diff --git a/assets/providers/NOTICE.md b/assets/providers/NOTICE.md index 6bdad16c3d..1ca03624a9 100644 --- a/assets/providers/NOTICE.md +++ b/assets/providers/NOTICE.md @@ -12,11 +12,11 @@ Checked 2026-11-18 against each upstream; where the source says "official artwor | grok.svg | Grok | The glyph (two paths) of the app icon https://grok.com/images/favicon.svg, cropped and rescaled to 24x24 without its tile, blur and shadow. Official artwork | No open licence found; xAI's trademark. Shown to identify the agent | | antigravity.svg | Antigravity | The arch of the favicon https://antigravity.google/favicon.svg, rescaled to 24x24 with its gradient and glow dropped (one tint). Official artwork | No open licence found; Google's trademark. Shown to identify the agent | | omp.svg | Oh My Pi | `assets/icon.svg` of https://github.com/can1357/oh-my-pi (a pi sign with a plug), redrawn as one path in one tint: the plug is a separate block under the right leg, where the original overlaps it in another colour | MIT (the repository, Copyright Mario Zechner and Can Bölük) | -| codex.svg | Codex | **Drawn for Backplane**: a terminal prompt (a chevron and an underscore) | Backplane's own. Not OpenAI's mark | +| codex.svg | Codex | OpenAI's blossom mark (`viewBox="0 0 256 260"`, single path) | OpenAI's trademark. Shown to identify the agent | ## What is not an official mark -- **Codex:** the `openai/codex` repository (Apache-2.0) ships no product mark: its only SVGs are skill icons (`openai-small.svg` is the OpenAI Docs skill's book), and OpenAI's blossom is not in simple-icons any more. Rather than borrow another OpenAI product's art, the row uses the prompt glyph above, which says "command-line agent". Swap in OpenAI's mark if OpenAI's brand terms are accepted for it. +- **Codex:** OpenAI's blossom mark is used as above (nominative identification of the Codex agent), as `openai/codex` ships no separate product mark. - **Muse Code:** the Meta AI orbit, as above. There is no Muse Code mark to use. ## Terms diff --git a/assets/providers/codex.svg b/assets/providers/codex.svg index 4950cf8c2b..106ce68ff5 100644 --- a/assets/providers/codex.svg +++ b/assets/providers/codex.svg @@ -1 +1 @@ -Codex +Codex diff --git a/docs/PHONE-DATA.md b/docs/PHONE-DATA.md index a9d3267de3..69b7a14202 100644 --- a/docs/PHONE-DATA.md +++ b/docs/PHONE-DATA.md @@ -22,10 +22,11 @@ Thread = {id, project, title, state, updatedAt, pinned, pinOrder, settled, sett pinOrder = where a pinned thread stands on its project's Pinned shelf (0 first: the order the pins were made, or a drag's), so a phone lists pins as the desktop does; 0 when not pinned mark? = {name, short, away, label, runs}: the machine the thread runs on when it is another one (see One project across machines); absent for this hub's state ∈ "idle" | "working" | "asking" | "failed"; preview ≤ 140 chars; waiting = open asks -Entry = {id, kind, text, at, clientId?, live?, agentOnly?, tool?, ask?, replyTo?} +Entry = {id, kind, text, at, clientId?, live?, agentOnly?, tool?, ask?, replyTo?, refs?} kind ∈ "user" | "assistant" | "tool" | "ask" | "note" | "step" replyTo: {id, quote} on the person's reply to a message (the desktop's Reply): `text` is what they wrote, `quote` the first line of the message answered. Draw "↩ In reply to: " (`gpui.b.in.reply.to`) over the bubble; a tap goes to `id` (read older pages until held). + refs: [{word, kind, id, label}] optional resolved mentions in a user message (currently resolved `&provider/model` tokens with `kind: "model"`, `id: ""`, concise `label`). agentOnly: true on a message only the agent reads (the hub's note about a quote it posted): a client does not show it; in a bot's conversation (the uberbot's chat) also everything the hub hands the bot: launched-thread and task reports, watched work, mailroom/triage input, wake/routine/webhook prompts, other threads' messages, `[Backplane]` notes and system notes (`present::thread::bot_private`). A launched thread that diff --git a/native/gpui/src/art.rs b/native/gpui/src/art.rs index fede498ae9..705134b5be 100644 --- a/native/gpui/src/art.rs +++ b/native/gpui/src/art.rs @@ -46,23 +46,39 @@ pub(crate) fn parse_d(d: &str) -> Vec { out } -/// A provider's mark as path segments in its 24x24 viewBox (assets/providers/.svg, sources in its NOTICE.md), None for a provider without one. -pub fn mark_path(provider: &str) -> Option<&'static [Seg]> { +/// A provider's vector mark: its path segments and SVG `viewBox` (`[min_x, min_y, width, height]`). +pub struct Mark { pub segs: Vec, pub vb: [f32; 4] } + +fn view_box(svg: &str) -> [f32; 4] { + let Some(v) = attr(svg, " = v.split(|c: char| c.is_whitespace() || c == ',').filter(|t| !t.is_empty()).filter_map(|t| t.parse().ok()).collect(); + if ns.len() == 4 && ns[2] > 0.0 && ns[3] > 0.0 { [ns[0], ns[1], ns[2], ns[3]] } else { [0.0, 0.0, 24.0, 24.0] } +} + +/// A provider's mark (segments + `viewBox`, from `assets/providers/.svg`, sources in its NOTICE.md), None for a provider without one. +pub fn mark_info(provider: &str) -> Option<&'static Mark> { macro_rules! marks { ($($name:literal),*) => {{ - static CELLS: [std::sync::OnceLock>; marks!(@n $($name),*)] = [const { std::sync::OnceLock::new() }; marks!(@n $($name),*)]; + static CELLS: [std::sync::OnceLock; marks!(@n $($name),*)] = [const { std::sync::OnceLock::new() }; marks!(@n $($name),*)]; let svgs = [$(include_str!(concat!("../../../assets/providers/", $name, ".svg"))),*]; let names = [$($name),*]; let i = names.iter().position(|n| *n == provider)?; - Some(CELLS[i].get_or_init(|| parse_d(attr(svgs[i], " { [$($name),*].len() } } marks!("claude", "codex", "grok", "muse", "antigravity", "opencode", "pi", "omp") } + +/// A provider's mark as path segments (`mark_info`), None for a provider without one. +pub fn mark_path(provider: &str) -> Option<&'static [Seg]> { mark_info(provider).map(|m| m.segs.as_slice()) } + /// The mark drawn plain in `color` in a `size` px box (one paint, no repaint loop). -pub fn mark(segs: &'static [Seg], size: f32, color: u32) -> impl IntoElement { +pub fn mark(m: &'static Mark, size: f32, color: u32) -> impl IntoElement { canvas(|_, _, _| (), move |b: Bounds, _, window: &mut Window, _| { - let (o, s) = (b.origin, size / 24.0); - let mut pb = PathBuilder::fill(); - trace(&mut pb, segs, 1.0, |x, y| point(o.x + px(x * s), o.y + px(y * s))); + let [vx, vy, vw, vh] = m.vb; + let s = size / vw.max(vh).max(1.0); + let (ox, oy) = ((size - vw * s) * 0.5 - vx * s, (size - vh * s) * 0.5 - vy * s); + let o = b.origin; + let mut pb = PathBuilder::fill().with_style(PathStyle::Fill(FillOptions::default().with_tolerance(0.02))); + trace(&mut pb, &m.segs, s, |x, y| point(o.x + px(ox + x * s), o.y + px(oy + y * s))); if let Ok(path) = pb.build() { window.paint_path(path, rgb(color)); } }).size(px(size)).flex_shrink_0() } @@ -478,3 +494,24 @@ mod cjk_font_tests { #[cfg(target_os = "linux")] assert_eq!(super::CJK_FACES.len(), 2, "the Linux client compiles both faces in"); } } + +#[cfg(test)] +mod provider_mark_tests { + use super::*; + use core::prelude::v1::test; + #[test] fn codex_uses_openai_viewbox_and_all_provider_marks_build_paths() { + let codex = mark_info("codex").expect("codex mark"); + assert_eq!(codex.vb, [0.0, 0.0, 256.0, 260.0]); + assert!(codex.segs.iter().any(|s| matches!(s, Seg::A(..))), "codex mark includes arc segments"); + for p in ["claude", "codex", "grok", "muse", "antigravity", "opencode", "pi", "omp"] { + let m = mark_info(p).unwrap_or_else(|| panic!("missing mark {p}")); + assert!(!m.segs.is_empty(), "{p} has segments"); + let [vx, vy, vw, vh] = m.vb; + let s = 16.0 / vw.max(vh).max(1.0); + let (ox, oy) = ((16.0 - vw * s) * 0.5 - vx * s, (16.0 - vh * s) * 0.5 - vy * s); + let mut pb = PathBuilder::fill().with_style(PathStyle::Fill(FillOptions::default().with_tolerance(0.02))); + trace(&mut pb, &m.segs, s, |x, y| point(px(ox + x * s), px(oy + y * s))); + assert!(pb.build().is_ok(), "{p} tessellates cleanly"); + } + } +} diff --git a/native/gpui/src/screens/md.rs b/native/gpui/src/screens/md.rs index 1556c9df81..8a36dab6c4 100644 --- a/native/gpui/src/screens/md.rs +++ b/native/gpui/src/screens/md.rs @@ -98,20 +98,67 @@ fn design_word(rest: &str) -> bool { } /// Where the whole words of `words` sit in `s`, as byte ranges in order: a word starts after a space or an opening bracket or quote, and ends at the end, a space or punctuation. pub fn word_ranges(s: &str, words: &[String]) -> Vec<(usize, usize)> { - let opens = |c: char| c.is_whitespace() || matches!(c, '(' | '[' | '"' | '\''); + let opens = |c: char| c.is_whitespace() || matches!(c, '(' | '[' | '"' | '\'' | '`'); let mut out: Vec<(usize, usize)> = vec![]; let mut at = 0; while at < s.len() { let hit = words.iter().filter(|w| !w.is_empty()).filter_map(|w| { let mut from = at; while let Some(i) = s[from..].find(w.as_str()) { let i = from + i; let end = i + w.len(); let before = i == 0 || s[..i].ends_with(opens); - let after = s[end..].chars().next().map_or(true, |c| !(c.is_alphanumeric() || matches!(c, '-' | '_' | '/' | ':' | '+')) && !(c == '.' && s[end + 1..].chars().next().map_or(false, |d| d.is_alphanumeric()))); - if before && after { return Some((i, end)) } from = i + 1; } + let after = s[end..].chars().next().map_or(true, |c| { + !(c.is_alphanumeric() || matches!(c, '-' | '_' | '/' | '+' | '[')) + && !(c == '.' && s[end + c.len_utf8()..].chars().next().map_or(false, |d| d.is_alphanumeric())) + && !(c == ':' && s[end + c.len_utf8()..].chars().next().map_or(false, |d| d.is_alphanumeric() || matches!(d, '-' | '_' | '/'))) + }); + if before && after { return Some((i, end)) } from = i + s[i..].chars().next().map_or(1, char::len_utf8); } None }).min_by_key(|(i, e)| (*i, std::cmp::Reverse(*e))); match hit { Some((i, e)) => { out.push((i, e)); at = e; } None => break } } out } +#[derive(Clone, Debug, PartialEq)] +pub struct ModelChip { pub word: String, pub label: String } + +#[derive(Clone, Debug, PartialEq)] +pub enum UserSeg { Span(Span), Model(ModelChip) } + +/// A person's message cut into styled text runs (`linkify` + `chips` for non-model references) and inline `ModelChip`s for resolved `&provider/model` mentions. +/// Preserves every character of `text` in order (`Span.text` and `ModelChip.word` concatenate to `text`). +pub fn user_segments(text: &str, other_refs: &[String], models: &[ModelChip]) -> Vec { + let linked = linkify(text); + if models.is_empty() { + return chips(linked, other_refs).into_iter().map(UserSeg::Span).collect(); + } + let model_words: Vec = models.iter().map(|m| m.word.clone()).collect(); + let mut out = Vec::new(); + for s in linked { + if s.style != Style::default() { + out.push(UserSeg::Span(s)); + continue; + } + let mut at = 0; + for (i, e) in word_ranges(&s.text, &model_words) { + if i > at { + let pre = vec![Span { text: s.text[at..i].to_string(), style: Style::default() }]; + out.extend(chips(pre, other_refs).into_iter().map(UserSeg::Span)); + } + let matched = &s.text[i..e]; + if let Some(m) = models.iter().find(|m| m.word == matched) { + out.push(UserSeg::Model(m.clone())); + } else { + let fallback = vec![Span { text: matched.to_string(), style: Style::default() }]; + out.extend(chips(fallback, other_refs).into_iter().map(UserSeg::Span)); + } + at = e; + } + if at < s.text.len() { + let tail = vec![Span { text: s.text[at..].to_string(), style: Style::default() }]; + out.extend(chips(tail, other_refs).into_iter().map(UserSeg::Span)); + } + } + out +} + /// The reference words of a message (`&claude/opus`, `@bot`...) set apart as chips: each whole word of `words` in a plain span becomes a code-styled span of its own. pub fn chips(spans: Vec, words: &[String]) -> Vec { if words.is_empty() { return spans } @@ -465,5 +512,21 @@ mod link_tests { assert!(links("x.rs main.c version 1.2 .kicad_pcb").is_empty(), "{:?}", links("x.rs main.c version 1.2 .kicad_pcb")); } #[test] fn the_spans_keep_every_character() { let t = "a https://x.io/p, b /tmp/q é"; assert_eq!(linkify(t).iter().map(|s| s.text.as_str()).collect::(), t); } + #[test] fn user_segments_embed_models_inline_and_keep_exact_text() { + let m1 = ModelChip { word: "&antigravity/gemini-4-neon".into(), label: "Gemini 4 Neon".into() }; + let m2 = ModelChip { word: "&claude/claude-fable-5-2[1m]".into(), label: "Fable 5.2 (1M)".into() }; + let m3 = ModelChip { word: "&claude/opus".into(), label: "Opus".into() }; + let m4 = ModelChip { word: "&claude/opus[1m]".into(), label: "Opus (1M)".into() }; + let txt = "swarm with &antigravity/gemini-4-neon, &claude/claude-fable-5-2[1m] and &antigravity/gemini-4-neon, plus @bot, &claude/opus[1m], Use &claude/opus: &provider/model, https://x.io?a=1&claude/opus"; + let segs = user_segments(txt, &["@bot".into()], &[m1.clone(), m2.clone(), m3.clone(), m4.clone()]); + let reconstructed: String = segs.iter().map(|s| match s { UserSeg::Span(sp) => sp.text.as_str(), UserSeg::Model(m) => m.word.as_str() }).collect(); + assert_eq!(reconstructed, txt); + let model_hits: Vec<&str> = segs.iter().filter_map(|s| match s { UserSeg::Model(m) => Some(m.label.as_str()), _ => None }).collect(); + assert_eq!(model_hits, ["Gemini 4 Neon", "Fable 5.2 (1M)", "Gemini 4 Neon", "Opus (1M)", "Opus"]); + assert!(segs.iter().any(|s| matches!(s, UserSeg::Span(sp) if sp.text == "@bot" && sp.style.code))); + assert!(segs.iter().any(|s| matches!(s, UserSeg::Span(sp) if sp.text == "https://x.io?a=1&claude/opus" && sp.style.link.is_some()))); + let tag_ref = ModelChip { word: "&opencode/llama3".into(), label: "Llama 3".into() }; + assert!(!user_segments("try &opencode/llama3:8b", &[], &[tag_ref]).iter().any(|s| matches!(s, UserSeg::Model(_)))); + } } diff --git a/native/gpui/src/screens/picker.rs b/native/gpui/src/screens/picker.rs index 1f8931d84a..d50a1caa4f 100644 --- a/native/gpui/src/screens/picker.rs +++ b/native/gpui/src/screens/picker.rs @@ -266,7 +266,7 @@ pub fn mark(provider: &str) -> (u32, &'static str) { pub fn logo(provider: &str) -> AnyElement { let provider = match bare(provider) { "agy" => "antigravity", p => p }; let (rgb_, letter) = mark(provider); - if let Some(segs) = crate::art::mark_path(provider) { return crate::art::mark(segs, 16., rgb_).into_any_element(); } + if let Some(m) = crate::art::mark_info(provider) { return crate::art::mark(m, 16., rgb_).into_any_element(); } div().w(px(16.)).h(px(16.)).flex_shrink_0().flex().items_center().justify_center().bg(rgb(rgb_)).text_color(rgb(0xffffff)).text_size(crate::scale::tpx(10.)).font_weight(FontWeight::BOLD).child(letter).into_any_element() } diff --git a/native/gpui/src/screens/timeline.rs b/native/gpui/src/screens/timeline.rs index fd5ad089e4..fc93811a83 100644 --- a/native/gpui/src/screens/timeline.rs +++ b/native/gpui/src/screens/timeline.rs @@ -1,7 +1,7 @@ //! The timeline's text: Markdown blocks drawn as styled, wrapped, selectable text (selection runs across blocks and //! messages), links, code blocks with Copy and light highlighting, tables, and images. What to draw comes from the hub's //! nodes (screens::md); this file only lays them out and answers the pointer. The pure rules are in md.rs and select.rs. -use super::{images::Slot, md::{self, Align, Block, Dim, Img, Inline, Link, Span, Tok}, select::{self, Pos, Selection, Text}}; +use super::{images::Slot, md::{self, Align, Block, Dim, Img, Inline, Link, ModelChip, Span, Tok, UserSeg}, select::{self, Pos, Selection, Text}}; use crate::{art, theme, Backplane}; use gpui::{prelude::*, *}; use serde_json::Value; @@ -26,7 +26,7 @@ pub struct Registry { } #[derive(Clone, Debug, PartialEq)] pub struct KPos { pub entry: String, pub idx: usize, pub off: usize } -pub struct Info { pub text: String, pub entry: usize, pub id: String, pub idx: usize, pub links: Vec<(Range, Link)>, pub layout: Option } +pub struct Info { pub text: String, pub entry: usize, pub id: String, pub idx: usize, pub links: Vec<(Range, Link)>, pub layout: Option } pub type Reg = Rc>; /// The viewer page's code blocks' Copy places are numbered from here (`copy:1000`...), the thread's rows' from 0: each part may draw without the other. pub const VIEWER_COPIES: usize = 1000; @@ -302,7 +302,629 @@ impl Element for SelText { if hot.iter().any(|(h, shown)| h.iter().any(|b| b.contains(&e.position)) != *shown) { window.refresh(); } }); } - let mut r = self.reg.borrow_mut(); if let Some(o) = r.at(&self.id, self.idx) { r.blocks[o].layout = Some(layout); } + let mut r = self.reg.borrow_mut(); if let Some(o) = r.at(&self.id, self.idx) { r.blocks[o].layout = Some(BlockLayout::Text(layout)); } + } +} + +/// Stored layout of one painted text block (plain `StyledText` or inline-chip `FlowText`). +#[derive(Clone)] +pub enum BlockLayout { + Text(TextLayout), + Flow(FlowLayout), +} + +impl BlockLayout { + pub fn bounds(&self) -> Bounds { + match self { Self::Text(l) => l.bounds(), Self::Flow(l) => l.bounds } + } + pub fn line_height(&self) -> Pixels { + match self { Self::Text(l) => l.line_height(), Self::Flow(l) => l.line_height } + } + pub fn index_for_position(&self, p: Point) -> Result { + match self { Self::Text(l) => l.index_for_position(p), Self::Flow(l) => l.index_for_position(p) } + } + pub fn position_for_index(&self, index: usize) -> Option> { + match self { Self::Text(l) => l.position_for_index(index), Self::Flow(l) => l.position_for_index(index) } + } +} + +#[derive(Clone)] +pub enum FlowItem { + Text { x: Pixels, text_y: Pixels, range: Range, shaped: ShapedLine }, + Chip { rect: Bounds, range: Range, amp: ShapedLine, label: ShapedLine, kind: ShapedLine, amp_x: Pixels, label_x: Pixels, kind_x: Pixels }, +} + +#[derive(Clone)] +pub struct FlowLine { + pub top: Pixels, + pub height: Pixels, + pub text_y: Pixels, + pub range: Range, + pub has_chip: bool, + pub items: Vec, +} + +#[derive(Clone)] +pub struct FlowLayout { + pub bounds: Bounds, + pub line_height: Pixels, + pub text_len: usize, + pub lines: Vec, +} + +impl FlowLayout { + pub fn index_for_position(&self, p: Point) -> Result { + if self.lines.is_empty() || p.y < self.bounds.top() { return Err(0) } + for vl in &self.lines { + if p.y <= vl.top + vl.height { + let Some(first) = vl.items.first() else { return Err(vl.range.start) }; + let first_x = match first { FlowItem::Text { x, .. } => *x, FlowItem::Chip { rect, .. } => rect.left() }; + if p.x < first_x { return Err(vl.range.start) } + for it in &vl.items { + match it { + FlowItem::Text { x, range, shaped, .. } => { + if p.x <= *x + shaped.width { + let off = shaped.closest_index_for_x((p.x - *x).max(px(0.))); + return Ok((range.start + off).min(range.end)); + } + } + FlowItem::Chip { rect, range, .. } => { + if p.x <= rect.right() { + let mid = rect.left() + rect.size.width / 2.; + return Ok(if p.x < mid { range.start } else { range.end }); + } + } + } + } + return Err(vl.range.end); + } + } + Err(self.text_len) + } + + pub fn position_for_index(&self, index: usize) -> Option> { + if index > self.text_len { return None } + for vl in &self.lines { + if index < vl.range.start { return Some(point(self.bounds.left(), vl.top + vl.text_y)) } + if index <= vl.range.end { + for it in &vl.items { + match it { + FlowItem::Text { x, text_y, range, shaped } if index >= range.start && index <= range.end => { + return Some(point(*x + shaped.x_for_index(index - range.start), vl.top + *text_y)); + } + FlowItem::Chip { rect, range, .. } if index >= range.start && index <= range.end => { + let x = if index == range.end { rect.right() } else { rect.left() }; + return Some(point(x, vl.top + vl.text_y)); + } + _ => {} + } + } + return Some(point(self.bounds.left(), vl.top + vl.text_y)); + } + } + None + } +} + +#[derive(Clone, Debug, PartialEq)] +struct WrapAtom { + width: f32, + is_space: bool, + is_chip: bool, + glue_prev: bool, +} + +/// Groups wrappable atoms into visual lines `(atom_range, has_chip)` under optional `wrap_w`, keeping +/// non-space clusters (e.g. a chip and adjacent punctuation or brackets) on one line and leaving +/// trailing spaces on the line before a soft wrap. +fn wrap_flow_lines(atoms: &[WrapAtom], wrap_w: Option) -> Vec<(Range, bool)> { + if atoms.is_empty() { return vec![(0..0, false)] } + let Some(max_w) = wrap_w else { + return vec![(0..atoms.len(), atoms.iter().any(|a| a.is_chip))]; + }; + struct Cluster { range: Range, width: f32, is_space: bool, has_chip: bool } + let mut clusters: Vec = Vec::new(); + for (i, a) in atoms.iter().enumerate() { + if a.glue_prev && clusters.last().is_some_and(|c| !c.is_space) && !a.is_space { + let c = clusters.last_mut().unwrap(); + c.range.end = i + 1; + c.width += a.width; + c.has_chip |= a.is_chip; + } else { + clusters.push(Cluster { range: i..i + 1, width: a.width, is_space: a.is_space, has_chip: a.is_chip }); + } + } + let mut out = Vec::new(); + let (mut line_start, mut line_end, mut cur_w, mut has_chip) = (0usize, 0usize, 0.0f32, false); + for cl in clusters { + let empty = line_start == line_end; + if empty { + line_start = cl.range.start; + line_end = cl.range.end; + cur_w = cl.width; + has_chip = cl.has_chip; + continue; + } + if cl.is_space { + line_end = cl.range.end; + cur_w += cl.width; + continue; + } + if cur_w + cl.width > max_w + 0.01 { + out.push((line_start..line_end, has_chip)); + line_start = cl.range.start; + line_end = cl.range.end; + cur_w = cl.width; + has_chip = cl.has_chip; + } else { + line_end = cl.range.end; + cur_w += cl.width; + has_chip |= cl.has_chip; + } + } + out.push((line_start..line_end, has_chip)); + out +} + +#[derive(Clone)] +enum RawPiece { + Span { text: String, style: md::Style, range: Range }, + Chip { label: String, range: Range }, +} + +#[derive(Clone)] +struct HardLine { + range: Range, + pieces: Vec, +} + +#[derive(Clone)] +enum AtomKind { + Text { text: String, style: md::Style, shaped: ShapedLine }, + Chip { amp: ShapedLine, label: ShapedLine, kind: ShapedLine, width: Pixels, height: Pixels, pad_x: Pixels, gap: Pixels }, +} + +#[derive(Clone)] +struct MeasuredAtom { + range: Range, + width: f32, + is_space: bool, + is_chip: bool, + glue_prev: bool, + kind: AtomKind, +} + +#[derive(Clone)] +enum BuiltItem { + Text { x: Pixels, range: Range, shaped: ShapedLine }, + Chip { x: Pixels, w: Pixels, h: Pixels, pad_x: Pixels, gap: Pixels, range: Range, amp: ShapedLine, label: ShapedLine, kind: ShapedLine }, +} + +#[derive(Clone)] +struct BuiltLine { + top: Pixels, + height: Pixels, + text_y: Pixels, + range: Range, + has_chip: bool, + items: Vec, +} + +#[derive(Clone)] +struct BuiltFlow { + wrap_w: Option, + size: Size, + lh: Pixels, + lines: Vec, +} + +fn span_run(style: &md::Style, base_font: &Font, light: bool) -> TextRun { + let c = |n: &str| theme::color(light, n); + let mut font = base_font.clone(); + if style.bold { font.weight = FontWeight::BOLD; } + if style.italic { font.style = FontStyle::Italic; } + if style.code { font = art::mono_font(); } + let button = style.link.as_ref().is_some_and(|l| l.href.starts_with("backplane://settings/") || l.href.starts_with("backplane://plan/")); + if button { font.weight = FontWeight::BOLD; } + let color = if style.link.is_some() { c("accent") } else if style.small { c("dim") } else { c("text") }; + TextRun { + len: 0, + font, + color: color.into(), + background_color: None, + underline: (style.link.is_some() && !button).then(|| UnderlineStyle { color: Some(color.into()), thickness: px(1.), wavy: false }), + strikethrough: style.strike.then(|| StrikethroughStyle { color: Some(color.into()), thickness: px(1.) }), + } +} + +fn shape_text_piece(text: &str, style: &md::Style, base_font: &Font, font_size: Pixels, light: bool, window: &Window) -> ShapedLine { + let mut run = span_run(style, base_font, light); + run.len = text.len(); + window.text_system().shape_line(SharedString::from(text.to_string()), font_size, &[run], None) +} + +fn shape_truncated_label(label: &str, max_w: Pixels, base_font: &Font, font_size: Pixels, color: Rgba, window: &Window) -> ShapedLine { + let make = |s: &str| { + let run = TextRun { len: s.len(), font: base_font.clone(), color: color.into(), background_color: None, underline: None, strikethrough: None }; + window.text_system().shape_line(SharedString::from(s.to_string()), font_size, &[run], None) + }; + let full = make(label); + if full.width <= max_w { return full; } + let chars: Vec = label.chars().collect(); + let mut lo = 1usize; + let mut hi = chars.len(); + let mut best = make("…"); + while lo <= hi { + let mid = (lo + hi) / 2; + let cand: String = chars[..mid].iter().collect::() + "…"; + let shaped = make(&cand); + if shaped.width <= max_w { + best = shaped; + lo = mid + 1; + } else { + if mid == 0 { break; } + hi = mid - 1; + } + } + best +} + +fn split_hard_lines(segs: &[UserSeg]) -> Vec { + let mut out = Vec::new(); + let mut cur = Vec::new(); + let mut byte_at = 0usize; + let mut line_start = 0usize; + for seg in segs { + match seg { + UserSeg::Model(m) => { + let len = m.word.len(); + cur.push(RawPiece::Chip { label: m.label.clone(), range: byte_at..byte_at + len }); + byte_at += len; + } + UserSeg::Span(sp) => { + for (i, part) in sp.text.split('\n').enumerate() { + if i > 0 { + out.push(HardLine { range: line_start..byte_at, pieces: std::mem::take(&mut cur) }); + byte_at += 1; + line_start = byte_at; + } + if !part.is_empty() { + let len = part.len(); + cur.push(RawPiece::Span { text: part.to_string(), style: sp.style.clone(), range: byte_at..byte_at + len }); + byte_at += len; + } + } + } + } + } + out.push(HardLine { range: line_start..byte_at, pieces: cur }); + out +} + +fn flow_range_rects(lines: &[FlowLine], r: &Range, lh: Pixels) -> Vec> { + let mut out = Vec::new(); + for vl in lines { + if r.end <= vl.range.start || r.start >= vl.range.end { continue } + for it in &vl.items { + match it { + FlowItem::Text { x, text_y, range, shaped } => { + let a = r.start.max(range.start); + let b = r.end.min(range.end); + if a < b { + let x0 = *x + shaped.x_for_index(a - range.start); + let x1 = *x + shaped.x_for_index(b - range.start); + out.push(Bounds::from_corners(point(x0, vl.top + *text_y), point(x1, vl.top + *text_y + lh))); + } + } + FlowItem::Chip { rect, range, .. } => { + if r.start < range.end && r.end > range.start { + out.push(*rect); + } + } + } + } + } + out +} + +/// Selectable, wrapping paragraph element that renders resolved `&provider/model` references as +/// inline bordered chips while keeping raw text selection/copy (`&provider/model`) and link hits intact. +pub struct FlowText { + raw_text: String, + hard_lines: Vec, + light: bool, + reg: Reg, + id: String, + idx: usize, + shaded: Vec>, + measured: Rc>>, + layout: Option, +} + +impl FlowText { + pub fn new(reg: &Reg, raw_text: &str, segs: Vec, light: bool) -> Self { + let mut r = reg.borrow_mut(); + let mut at = 0usize; + let mut links = Vec::new(); + let mut shaded = Vec::new(); + for seg in &segs { + match seg { + UserSeg::Span(sp) => { + if let Some(l) = &sp.style.link { links.push((at..at + sp.text.len(), l.clone())); } + let button = sp.style.link.as_ref().is_some_and(|l| l.href.starts_with("backplane://settings/") || l.href.starts_with("backplane://plan/")); + if !sp.text.is_empty() && (sp.style.code || sp.style.kbd || button) { shaded.push(at..at + sp.text.len()); } + at += sp.text.len(); + } + UserSeg::Model(m) => { at += m.word.len(); } + } + } + let entry = r.entry; + let (id, idx) = (r.entry_id.clone(), r.next_idx()); + r.blocks.push(Info { text: raw_text.to_string(), entry, id: id.clone(), idx, links, layout: None }); + drop(r); + let hard_lines = split_hard_lines(&segs); + Self { raw_text: raw_text.to_string(), hard_lines, light, reg: reg.clone(), id, idx, shaded, measured: Rc::new(RefCell::new(None)), layout: None } + } + + fn build(hard_lines: &[HardLine], light: bool, wrap_w: Option, style: &TextStyle, window: &Window) -> BuiltFlow { + let c = |n: &str| theme::color(light, n); + let sc = crate::scale::s(); + let font_size = style.font_size.to_pixels(window.rem_size()); + let lh = style.line_height.to_pixels(font_size.into(), window.rem_size()); + let base_font = style.font(); + let chip_fs = crate::scale::tpx(12.); + let kind_fs = crate::scale::tpx(10.); + let pad_x = px(6. * sc); + let gap = px(5. * sc); + let chip_h = lh.max(crate::scale::tpx(19.)); + let chip_line_h = lh + px(4. * sc); + let max_label_w = wrap_w.map_or(px(220. * sc), |w| px((w - 72. * sc).max(40. * sc)).min(px(220. * sc))); + let kind_word = crate::i18n::trs("model"); + + let mut built_lines = Vec::new(); + let mut y = px(0.); + let mut max_w = px(0.); + + for hl in hard_lines { + if hl.pieces.is_empty() { + built_lines.push(BuiltLine { top: y, height: lh, text_y: px(0.), range: hl.range.clone(), has_chip: false, items: Vec::new() }); + y += lh; + continue; + } + let mut atoms: Vec = Vec::new(); + for p in &hl.pieces { + match p { + RawPiece::Chip { label, range } => { + let mut amp_font = base_font.clone(); + amp_font.weight = FontWeight::BOLD; + let amp = window.text_system().shape_line("&".into(), chip_fs, &[TextRun { len: 1, font: amp_font, color: c("ok").into(), background_color: None, underline: None, strikethrough: None }], None); + let lbl = shape_truncated_label(label, max_label_w, &base_font, chip_fs, c("text"), window); + let kind = window.text_system().shape_line(SharedString::from(kind_word.clone()), kind_fs, &[TextRun { len: kind_word.len(), font: base_font.clone(), color: c("faint").into(), background_color: None, underline: None, strikethrough: None }], None); + let w = pad_x * 2. + amp.width + gap + lbl.width + gap + kind.width; + let glue_prev = atoms.last().is_some_and(|prev| !prev.is_space); + atoms.push(MeasuredAtom { + range: range.clone(), + width: f32::from(w), + is_space: false, + is_chip: true, + glue_prev, + kind: AtomKind::Chip { amp, label: lbl, kind, width: w, height: chip_h, pad_x, gap }, + }); + } + RawPiece::Span { text, style: sp_style, range } => { + let mut pos = 0usize; + while pos < text.len() { + let ws = text[pos..].chars().next().unwrap().is_whitespace(); + let mut end = pos; + for ch in text[pos..].chars() { + if ch.is_whitespace() != ws { break } + end += ch.len_utf8(); + } + let mut sub_start = pos; + let mut first_sub = true; + while sub_start < end { + let chunk = &text[sub_start..end]; + let shaped = shape_text_piece(chunk, sp_style, &base_font, font_size, light, window); + let glue_prev = first_sub && !ws && atoms.last().is_some_and(|prev| !prev.is_space); + if !ws && let Some(mw) = wrap_w && f32::from(shaped.width) > mw && chunk.chars().count() > 1 { + let mut cut = shaped.closest_index_for_x(px(mw)); + if cut == 0 { cut = chunk.chars().next().map_or(chunk.len(), char::len_utf8); } + while !chunk.is_char_boundary(cut) { cut += 1; } + let part = &chunk[..cut]; + let part_shaped = shape_text_piece(part, sp_style, &base_font, font_size, light, window); + let r = (range.start + sub_start)..(range.start + sub_start + cut); + atoms.push(MeasuredAtom { + range: r, + width: f32::from(part_shaped.width), + is_space: false, + is_chip: false, + glue_prev, + kind: AtomKind::Text { text: part.to_string(), style: sp_style.clone(), shaped: part_shaped }, + }); + sub_start += cut; + first_sub = false; + } else { + let r = (range.start + sub_start)..(range.start + end); + atoms.push(MeasuredAtom { + range: r, + width: f32::from(shaped.width), + is_space: ws, + is_chip: false, + glue_prev, + kind: AtomKind::Text { text: chunk.to_string(), style: sp_style.clone(), shaped }, + }); + sub_start = end; + } + } + pos = end; + } + } + } + } + + let wrap_atoms: Vec = atoms.iter().map(|a| WrapAtom { width: a.width, is_space: a.is_space, is_chip: a.is_chip, glue_prev: a.glue_prev }).collect(); + for (atom_range, has_chip) in wrap_flow_lines(&wrap_atoms, wrap_w) { + let line_h = if has_chip { chip_line_h } else { lh }; + let text_y = (line_h - lh) / 2.; + let line_atoms = &atoms[atom_range]; + let line_byte_range = line_atoms.first().map(|a| a.range.start).unwrap_or(hl.range.start)..line_atoms.last().map(|a| a.range.end).unwrap_or(hl.range.end); + + // Merge adjacent text atoms with identical style so prose keeps natural kerning and single ShapedLine layout per span. + let mut merged: Vec = Vec::new(); + let mut pending: Option<(String, md::Style, Range)> = None; + let mut x = px(0.); + let flush_pending = |pending: &mut Option<(String, md::Style, Range)>, x: &mut Pixels, merged: &mut Vec| { + if let Some((txt, st, rng)) = pending.take() { + let shaped = shape_text_piece(&txt, &st, &base_font, font_size, light, window); + let w = shaped.width; + merged.push(BuiltItem::Text { x: *x, range: rng, shaped }); + *x += w; + } + }; + for a in line_atoms { + match &a.kind { + AtomKind::Text { text, style: st, .. } => { + if let Some((ptxt, pst, prng)) = pending.as_mut() && *pst == *st && prng.end == a.range.start { + ptxt.push_str(text); + prng.end = a.range.end; + } else { + flush_pending(&mut pending, &mut x, &mut merged); + pending = Some((text.clone(), st.clone(), a.range.clone())); + } + } + AtomKind::Chip { amp, label, kind, width, height, pad_x, gap } => { + flush_pending(&mut pending, &mut x, &mut merged); + merged.push(BuiltItem::Chip { x, w: *width, h: *height, pad_x: *pad_x, gap: *gap, range: a.range.clone(), amp: amp.clone(), label: label.clone(), kind: kind.clone() }); + x += *width; + } + } + } + flush_pending(&mut pending, &mut x, &mut merged); + max_w = max_w.max(x.ceil()); + built_lines.push(BuiltLine { top: y, height: line_h, text_y, range: line_byte_range, has_chip, items: merged }); + y += line_h; + } + } + + let out_w = wrap_w.map_or(max_w, |mw| max_w.min(px(mw))); + BuiltFlow { wrap_w, size: size(out_w, y.max(lh)), lh, lines: built_lines } + } +} + +impl IntoElement for FlowText { type Element = Self; fn into_element(self) -> Self { self } } + +fn flow_needs_rebuild(cached_wrap_w: Option, cached_w: f32, cached_lines: usize, bounds_w: f32) -> bool { + cached_w > bounds_w + 0.5 || cached_wrap_w.is_some_and(|w| bounds_w > w + 0.5 && cached_lines > 1) +} + +impl Element for FlowText { + type RequestLayoutState = (); + type PrepaintState = Vec<(Hitbox, CursorStyle)>; + fn id(&self) -> Option { None } + fn source_location(&self) -> Option<&'static core::panic::Location<'static>> { None } + + fn request_layout(&mut self, _: Option<&GlobalElementId>, _: Option<&InspectorElementId>, window: &mut Window, _: &mut App) -> (LayoutId, ()) { + let style = window.text_style(); + let hard_lines = self.hard_lines.clone(); + let light = self.light; + let cache = self.measured.clone(); + let layout_id = window.request_measured_layout(Default::default(), move |known, avail, window, _| { + let wrap_w = known.width.or(match avail.width { AvailableSpace::Definite(x) => Some(x), _ => None }).map(f32::from); + let mut g = cache.borrow_mut(); + if g.as_ref().is_none_or(|b| b.wrap_w != wrap_w) { + *g = Some(FlowText::build(&hard_lines, light, wrap_w, &style, window)); + } + g.as_ref().unwrap().size + }); + (layout_id, ()) + } + + fn prepaint(&mut self, _: Option<&GlobalElementId>, _: Option<&InspectorElementId>, bounds: Bounds, _: &mut (), window: &mut Window, _: &mut App) -> Vec<(Hitbox, CursorStyle)> { + let style = window.text_style(); + let bounds_w = f32::from(bounds.size.width); + let built = { + let mut g = self.measured.borrow_mut(); + let need_rebuild = g.as_ref().is_none_or(|b| flow_needs_rebuild(b.wrap_w, f32::from(b.size.width), b.lines.len(), bounds_w)); + if need_rebuild { + *g = Some(FlowText::build(&self.hard_lines, self.light, Some(bounds_w), &style, window)); + } + g.as_ref().unwrap().clone() + }; + let lines = built.lines.into_iter().map(|vl| { + let top = bounds.top() + vl.top; + let items = vl.items.into_iter().map(|it| match it { + BuiltItem::Text { x, range, shaped } => FlowItem::Text { x: bounds.left() + x, text_y: vl.text_y, range, shaped }, + BuiltItem::Chip { x, w, h, pad_x, gap, range, amp, label, kind } => { + let chip_y = top + (vl.height - h) / 2.; + let rect = Bounds::new(point(bounds.left() + x, chip_y), size(w, h)); + let amp_x = rect.left() + pad_x; + let label_x = amp_x + amp.width + gap; + let kind_x = label_x + label.width + gap; + FlowItem::Chip { rect, range, amp, label, kind, amp_x, label_x, kind_x } + } + }).collect(); + FlowLine { top, height: vl.height, text_y: vl.text_y, range: vl.range, has_chip: vl.has_chip, items } + }).collect(); + let layout = FlowLayout { bounds, line_height: built.lh, text_len: self.raw_text.len(), lines }; + + let mut out = vec![(window.insert_hitbox(bounds, HitboxBehavior::Normal), CursorStyle::IBeam)]; + let links: Vec<(Range, String)> = { + let r = self.reg.borrow(); + r.at(&self.id, self.idx).map(|o| r.blocks[o].links.iter().map(|(r, l)| (r.clone(), l.href.clone())).collect()).unwrap_or_default() + }; + for (r, href) in links { + let rects = flow_range_rects(&layout.lines, &r, layout.line_height); + if let Some(first) = rects.first() { + /* i18n-ok: an e2e rect name */ crate::art::report(&format!("link:{}", href.replace(['"', '\\'], "")), *first, window.scale_factor()); + } + for rect in rects { + out.push((window.insert_hitbox(rect, HitboxBehavior::Normal), CursorStyle::PointingHand)); + } + } + self.layout = Some(layout); + out + } + + fn paint(&mut self, _: Option<&GlobalElementId>, _: Option<&InspectorElementId>, _: Bounds, _: &mut (), pre: &mut Vec<(Hitbox, CursorStyle)>, window: &mut Window, cx: &mut App) { + let Some(layout) = self.layout.clone() else { return }; + let c = |n: &str| theme::color(self.light, n); + let shade = c("raise"); + for r in &self.shaded { + for q in flow_range_rects(&layout.lines, r, layout.line_height) { window.paint_quad(fill(q, shade)); } + } + let panel = c("panel"); + let line_c = c("line"); + for vl in &layout.lines { + for it in &vl.items { + if let FlowItem::Chip { rect, .. } = it { + window.paint_quad(gpui::quad(*rect, Corners::default(), panel, Edges::all(px(1.)), line_c, BorderStyle::Solid)); + } + } + } + let sel_range = { let r = self.reg.borrow(); r.at(&self.id, self.idx).and_then(|o| r.sel.within(o, r.blocks[o].text.len())) }; + if let Some(range) = sel_range { + let tint = select::highlight(self.light); + for q in flow_range_rects(&layout.lines, &range, layout.line_height) { window.paint_quad(fill(q, tint)); } + } + for vl in &layout.lines { + for it in &vl.items { + match it { + FlowItem::Text { x, text_y, shaped, .. } => { + let _ = shaped.paint(point(*x, vl.top + *text_y), layout.line_height, window, cx); + } + FlowItem::Chip { rect, amp, label, kind, amp_x, label_x, kind_x, .. } => { + let h = rect.size.height; + let y = rect.top(); + let _ = amp.paint(point(*amp_x, y), h, window, cx); + let _ = label.paint(point(*label_x, y), h, window, cx); + let _ = kind.paint(point(*kind_x, y), h, window, cx); + } + } + } + } + for (h, style) in pre.iter() { window.set_cursor_style(*style, h); } + let mut r = self.reg.borrow_mut(); + if let Some(o) = r.at(&self.id, self.idx) { r.blocks[o].layout = Some(BlockLayout::Flow(layout)); } } } @@ -314,11 +936,32 @@ fn plain_spans(s: &str) -> Vec { vec![Span { text: s.to_string(), style: D /// A message of short lines never wraps and keeps its snug bubble. /// A message with pictures is laid out in blocks too: in the snug flex bubble the pictures' wrapping row was measured on one line and painted on /// two, so the second picture spilled out of the bubble over the rows below and the composer. -pub fn bubble_full_width(text: &str, attachments: &Value) -> bool { text.lines().any(|l| l.chars().count() > 60) || !split_attachments(attachments).0.is_empty() } +pub fn bubble_full_width(text: &str, attachments: &Value) -> bool { + text.lines().any(|l| l.chars().count() > 60) || !split_attachments(attachments).0.is_empty() +} + +/// [`bubble_full_width`] with a lower threshold when inline model chips add extra width beyond their raw `@`/`&` slug length. +pub fn bubble_full_width_with_chips(text: &str, attachments: &Value, has_model_chips: bool) -> bool { + bubble_full_width(text, attachments) || (has_model_chips && text.lines().any(|l| l.chars().count() > 40)) +} /// A user's message text. pub fn user_text(reg: &Reg, light: bool, s: &str, refs: &[String]) -> AnyElement { text(reg, light, md::chips(md::linkify(s), refs), Kind::Body) } +/// A user's message text with resolved `&provider/model` references embedded inline as chips, plus the set of model ref words embedded inline. +pub fn user_text_with_models(reg: &Reg, light: bool, s: &str, other_refs: &[String], models: &[ModelChip]) -> (AnyElement, std::collections::HashSet) { + if models.is_empty() { return (user_text(reg, light, s, other_refs), Default::default()) } + let segs = md::user_segments(s, other_refs, models); + let inline_words: std::collections::HashSet = segs.iter().filter_map(|seg| match seg { + UserSeg::Model(m) => Some(m.word.clone()), + _ => None, + }).collect(); + if inline_words.is_empty() { + return (user_text(reg, light, s, other_refs), inline_words); + } + (FlowText::new(reg, s, segs, light).into_any_element(), inline_words) +} + /// An invisible overlay that records where its parent was painted, for the check harness's control rectangles. fn copy_probe(reg: &Reg, ix: usize) -> impl IntoElement { let reg = reg.clone(); @@ -890,4 +1533,24 @@ mod tests { assert!(Rc::ptr_eq(&a, &b), "unchanged text is not parsed again"); let d = c.get("e1", "hi there", &n); assert!(!Rc::ptr_eq(&a, &d)); } + + #[test] fn wrap_flow_lines_keeps_chips_with_adjacent_punctuation_and_wraps_cleanly() { + let a = |w: f32, space: bool, chip: bool, glue: bool| WrapAtom { width: w, is_space: space, is_chip: chip, glue_prev: glue }; + // "use " (28 + 4), chip (120), "," (4, glued), " ok" (4 + 20) at max_w = 154: chip+comma = 124, 32 + 124 = 156 > 154 -> wraps before chip! + let atoms = vec![a(28., false, false, false), a(4., true, false, false), a(120., false, true, false), a(4., false, false, true), a(4., true, false, false), a(20., false, false, false)]; + assert_eq!(wrap_flow_lines(&atoms, Some(154.)), vec![(0..2, false), (2..6, true)]); + // Empty line still produces one line without a chip. + assert_eq!(wrap_flow_lines(&[], Some(200.)), vec![(0..0, false)]); + // "(" + chip + ")" stays together as one indivisible cluster. + let paren = vec![a(50., false, false, false), a(4., true, false, false), a(6., false, false, false), a(100., false, true, true), a(6., false, false, true)]; + assert_eq!(wrap_flow_lines(&paren, Some(150.)), vec![(0..2, false), (2..5, true)]); + } + + #[test] fn flow_needs_rebuild_reuses_snug_single_line_and_rebuilds_on_shrink_or_rewrap() { + assert!(!flow_needs_rebuild(None, 180., 1, 180.), "snug single-line chip keeps its layout width"); + assert!(!flow_needs_rebuild(Some(614.), 180., 1, 614.), "exact cached width never rebuilds"); + assert!(!flow_needs_rebuild(Some(300.), 180., 1, 500.), "single unwrapped line stays valid when wider"); + assert!(flow_needs_rebuild(Some(614.), 250., 1, 200.), "narrower bounds trigger wrap rebuild"); + assert!(flow_needs_rebuild(Some(300.), 290., 2, 420.), "wider bounds trigger unwrap rebuild for multi-line flow"); + } } diff --git a/native/gpui/src/ui.rs b/native/gpui/src/ui.rs index afc62c513e..2f3efba850 100644 --- a/native/gpui/src/ui.rs +++ b/native/gpui/src/ui.rs @@ -279,9 +279,17 @@ fn chip(light: bool, label: String) -> Div { div().px_3().py_1().flex().items_center().justify_center().border_1().border_color(c("line")).bg(c("panel")).text_size(crate::scale::tpx(12.)).whitespace_nowrap().child(label) } -/// A message's references as little cards under it: a bot, thread, project or room goes there on a click; a model is only named. -fn ref_cards(cx: &mut Context, light: bool, mid: &str, refs: &Value) -> Option
{ - let list = refs.as_array().filter(|r| !r.is_empty())?; +/// References kept as cards under a message (`bot`, `thread`, `project`, `room`, `skill`, `machine`, plus any model ref that was not rendered inline). +fn card_refs<'a>(refs: &'a Value, inline_models: &std::collections::HashSet) -> Vec<&'a Value> { + refs.as_array().into_iter().flatten().filter(|r| { + !(r["kind"].as_str() == Some("model") && r["word"].as_str().is_some_and(|w| inline_models.contains(w))) + }).collect() +} + +/// A message's references as little cards under it: a bot, thread, project or room goes there on a click; any non-inline model ref is named too. +fn ref_cards(cx: &mut Context, light: bool, mid: &str, refs: &Value, inline_models: &std::collections::HashSet) -> Option
{ + let list = card_refs(refs, inline_models); + if list.is_empty() { return None } let c = |n: &str| theme::color(light, n); let mut row = div().flex().flex_wrap().gap_2(); for (i, r) in list.iter().enumerate() { @@ -458,12 +466,23 @@ impl Backplane { let was_streamed = kind == "assistant" && !id.starts_with('@') && !self.screens.streamed.is_empty() && { let a: String = self.screens.streamed.trim().chars().take(60).collect(); text.trim_start().starts_with(&a) }; let row: AnyElement = match kind { "user" => { - let wide = crate::screens::timeline::bubble_full_width(&text, &e["attachments"]); - let ref_words: Vec = e["refs"].as_array().into_iter().flatten().map(|r| string(r, "word")).collect(); - let body = crate::screens::timeline::user_text(®, light, &text, &ref_words); + let mut model_chips = Vec::new(); + let mut other_ref_words = Vec::new(); + for r in e["refs"].as_array().into_iter().flatten() { + let word = string(r, "word"); + if word.is_empty() { continue } + if r["kind"].as_str() == Some("model") { + let label = string(r, "label"); + if !label.is_empty() { model_chips.push(crate::screens::md::ModelChip { word, label }); } + } else { + other_ref_words.push(word); + } + } + let (body, inline_models) = crate::screens::timeline::user_text_with_models(®, light, &text, &other_ref_words, &model_chips); + let wide = crate::screens::timeline::bubble_full_width_with_chips(&text, &e["attachments"], !inline_models.is_empty()); let atts = crate::screens::timeline::attachments(cx, light, &e["attachments"], &id, self.screens.attacher.target.as_ref(), &self.screens.images); let tools = msg_tools(cx, light, &id, &text); - let cards = ref_cards(cx, light, &id, &e["refs"]); + let cards = ref_cards(cx, light, &id, &e["refs"], &inline_models); // r05: a follow-up the agent has not read yet: its text a step dimmer, its time ("not read yet · 06:13") in the queued colour let unread = e["unread"] == true; let spoken = crate::screens::voice::bubble_mark(cx, light, &self.screens.voice, &id, &e["voice"]); @@ -1709,4 +1728,21 @@ mod home_tests { let fail = home_away_line(&json!({"kind":"peer","name":"desktop","online":true,"moving":{"to":"laptop","state":"failed","note":"disk full"}})); /* i18n-ok: test */ assert_eq!(fail, Some(("Home move failed: disk full".into(), true))); } + + #[test] + fn card_refs_excludes_inline_model_cards_and_keeps_others() { + let refs = json!([ + {"word": "&antigravity/gemini-4-neon", "kind": "model", "id": "", "label": "Gemini 4 Neon"}, + {"word": "&claude/unmatched", "kind": "model", "id": "", "label": "Unmatched"}, + {"word": "@designer", "kind": "bot", "id": "h|b1", "label": "Designer"}, + {"word": ">fix-bug", "kind": "thread", "id": "h|t1", "label": "Fix bug"} + ]); + let inline: std::collections::HashSet = ["&antigravity/gemini-4-neon".to_string()].into_iter().collect(); + let kept = super::card_refs(&refs, &inline); + assert_eq!(kept.len(), 3); + assert_eq!(kept[0]["word"], "&claude/unmatched"); + assert_eq!(kept[1]["kind"], "bot"); + assert_eq!(kept[2]["kind"], "thread"); + assert!(super::card_refs(&json!([{"word":"&claude/opus","kind":"model","id":"","label":"Opus"}]), &["&claude/opus".to_string()].into_iter().collect()).is_empty()); + } } diff --git a/native/host/src/data/mod.rs b/native/host/src/data/mod.rs index 18c63da773..51869ef059 100644 --- a/native/host/src/data/mod.rs +++ b/native/host/src/data/mod.rs @@ -281,7 +281,8 @@ fn far_entries(f: &Arc, th: &str, p: &Value, bot: bool) rows.sort_by_key(|r| r.ord); let backend = if bot { let o = oldest_ord(&page.rows); backend_of(&page.rows, if o > 1 { f.page(th, o, 32).map(|p| p.rows).unwrap_or_default() } else { vec![] }) } else { HashSet::new() }; let mut noise = crate::present::thread::Noise::default(); - let out: Vec = rows.iter().filter(|r| noise.shown(r.kind == "msg", &r.role, &r.akind, &r.text)).filter_map(|r| row_entry_hid(r, bot, &backend)).collect(); + let models_cat = std::cell::OnceCell::new(); + let out: Vec = rows.iter().filter(|r| noise.shown(r.kind == "msg", &r.role, &r.akind, &r.text)).filter_map(|r| row_entry_hid_with(r, bot, &backend, &models_cat)).collect(); let more = page.below > 0 || page.rows.iter().map(|r| r.ord).collect::>().len() > ids.len(); let next = if more { rows.first().map(|r| json!(r.ord.to_string())).unwrap_or(Value::Null) } else { Value::Null }; let title = rows.iter().find(|r| r.kind == "msg" && r.role == "user").map(|r| clip(&shown_text(&r.text), 60)).unwrap_or_default(); @@ -308,6 +309,10 @@ pub(crate) fn far_bot(hub: &Hub, th: &str) -> bool { hub.mirrors().shown(|far| m fn row_entry(r: &crate::model::Row, bot: bool) -> Option { row_entry_hid(r, bot, &HashSet::new()) } /// `backend`: the replies of turns that were not the person's (`present::thread::backend_replies`), agentOnly in a bot's conversation too fn row_entry_hid(r: &crate::model::Row, bot: bool, backend: &HashSet) -> Option { + row_entry_hid_with(r, bot, backend, &std::cell::OnceCell::new()) +} +/// `backend`: the replies of turns that were not the person's (`present::thread::backend_replies`), agentOnly in a bot's conversation too +fn row_entry_hid_with(r: &crate::model::Row, bot: bool, backend: &HashSet, catalog: &std::cell::OnceCell) -> Option { let at = ms(r.at); if r.kind == "msg" { let kind = match r.role.as_str() { "user" => "user", "assistant" => "assistant", _ => "note" }; @@ -315,8 +320,12 @@ fn row_entry_hid(r: &crate::model::Row, bot: bool, backend: &HashSet) -> let mut en = json!({"id":r.id,"kind":kind,"text":if kind == "user" { shown_text(&r.text) } else { crate::settings::order::pay_shown(&r.text) },"at":at}); // a reply (`` block, bots/reply.rs): its body as the text and the message it answers, as the desktop draws it (present/thread.rs) if let Some(v) = r.akind.strip_prefix("voice").and_then(|j| serde_json::from_str::(j).ok()) { en["voice"] = v } - if kind == "user" { if let Some((to, quote, body)) = crate::bots::reply::of(&r.text) { - en["text"] = json!(shown_text(&body)); en["replyTo"] = json!({"id": to, "quote": quote.lines().map(str::trim).find(|l| !l.is_empty()).unwrap_or("")}); } } + if kind == "user" { + if let Some((to, quote, body)) = crate::bots::reply::of(&r.text) { + en["text"] = json!(shown_text(&body)); en["replyTo"] = json!({"id": to, "quote": quote.lines().map(str::trim).find(|l| !l.is_empty()).unwrap_or("")}); + } + with_refs_catalog(&mut en, catalog); + } if crate::present::thread::hidden(bot, &r.id, &r.role, &r.text) || (bot && backend.contains(&r.id)) { en["agentOnly"] = json!(true) } if kind == "assistant" { with_images(&mut en, &r.text); with_files(&mut en, &r.text); with_copy(&mut en) } return Some(en); @@ -346,6 +355,27 @@ fn act_entry(thread: &str, id: &str, role: &str, akind: &str, text: &str, at: u6 if a["folds"] == true { n["folds"] = json!(true) } n } }) } +/// Resolved `&provider/model` references in a user entry's shown text (same shape as `present::thread`: `{word, kind, id, label}`). +fn with_refs_with(en: &mut Value, models_json: Option<&str>) { + let text = en["text"].as_str().unwrap_or(""); + if !text.contains('&') { return } + let refs = match models_json { + Some(raw) => crate::session::composer::mention::model_refs_in_with(text, raw), + None => crate::session::composer::mention::model_refs_in(text), + }; + if !refs.is_empty() { en["refs"] = Value::Array(refs); } +} + +fn with_refs_catalog(en: &mut Value, catalog: &std::cell::OnceCell) { + let text = en["text"].as_str().unwrap_or(""); + if !text.contains('&') { return } + let all = catalog.get_or_init(crate::session::composer::mention::models_catalog); + let refs = crate::session::composer::mention::model_refs_in_catalog(text, all); + if !refs.is_empty() { en["refs"] = Value::Array(refs); } +} + +fn with_refs(en: &mut Value) { with_refs_with(en, None); } + /// What of a message there is to copy (feature `copy`, md/copy.rs `spans`): `copy: [{text, cmd}]`, each fenced block and each inline code span with a /// kind, in order; left out when there is none. A phone that draws the Markdown itself gives a span a copy button when its text is listed. pub(crate) fn with_copy(en: &mut Value) { @@ -379,7 +409,8 @@ async fn entries(hub: &Hub, p: &Value) -> Result { let mut noise = crate::present::thread::Noise::default(); let quiet: HashSet<&str> = all.iter().filter(|r| !noise.shown(r.kind == "msg", &r.role, &r.akind, &r.text)).map(|r| r.id.as_str()).collect(); let points = crate::present::thread::restore_points(all.iter().map(|r| (r.id.as_str(), r.kind == "msg", r.role.as_str(), r.akind.as_str(), r.text.as_str()))); - let mut out: Vec = rows.iter().filter(|r| !quiet.contains(r.id.as_str())).filter_map(|r| { let mut e = row_entry_hid(r, bot, &backend)?; + let models_cat = std::cell::OnceCell::new(); + let mut out: Vec = rows.iter().filter(|r| !quiet.contains(r.id.as_str())).filter_map(|r| { let mut e = row_entry_hid_with(r, bot, &backend, &models_cat)?; // a user message's images are on its log line if r.kind == "msg" && r.role == "user" { if let Some(a) = attachments_of(hub, r.seq as usize - 1, &r.id) { e["attachments"] = a } if let Some(p) = points.get(&r.id) { e["restore"] = p.clone() } } Some(e) }).collect(); @@ -503,6 +534,7 @@ async fn send_message(hub: &Arc, c: &mut Conn, thread: &str, text: &str, cl if voice.is_object() { p["voice"] = voice.clone() } // dictated (voice/mark.rs): the agent is told rpc(hub, c, "turn.start", p).await?; let mut e = json!({"id":msg,"kind":"user","text":body,"at":now_ms()}); + with_refs(&mut e); if let Some((_, r)) = &rto { e["replyTo"] = r.clone() } if voice.is_object() { e["voice"] = voice.clone() } if !meta.is_empty() { e["attachments"] = json!(meta) } @@ -775,12 +807,12 @@ async fn deltas(hub: &Hub, lines: &[String], subs: &mut Subs) -> Vec { if crate::present::thread::hidden(bot, id, role, s(&e, "text")) || backend { en["agentOnly"] = json!(true) } if let Some(a) = e.get("attachments") { en["attachments"] = a.clone() } if kind == "assistant" { with_images(&mut en, s(&e, "text")); with_files(&mut en, s(&e, "text")); with_copy(&mut en) } - if kind == "user" { if let Some(x) = recalled(id) { if let Some(c) = x.get("clientId") { en["clientId"] = c.clone() } } } + if kind == "user" { with_refs(&mut en); if let Some(x) = recalled(id) { if let Some(c) = x.get("clientId") { en["clientId"] = c.clone() } } } let replaced = if kind == "assistant" { subs.live.get_mut(&th).and_then(|l| l.finished()) } else { None }; if let Some(n) = replaced { en["replaces"] = json!(Streams::id(&th, n)) } if replaced.is_some() || kind != "assistant" || !s(&e, "text").trim().is_empty() { entry = Some(en) } } - "MessageAttached" => { let id = s(&e, "msg"); let mut en = json!({"id":id,"kind":"user","text":"","at":ms(e["at"].as_u64().unwrap_or(0)),"attachments":e["attachments"]}); if let Some(x) = recalled(id) { en["text"] = x["text"].clone(); if let Some(c) = x.get("clientId") { en["clientId"] = c.clone() } } entry = Some(en) } + "MessageAttached" => { let id = s(&e, "msg"); let mut en = json!({"id":id,"kind":"user","text":"","at":ms(e["at"].as_u64().unwrap_or(0)),"attachments":e["attachments"]}); if let Some(x) = recalled(id) { en["text"] = x["text"].clone(); if let Some(c) = x.get("clientId") { en["clientId"] = c.clone() } } with_refs(&mut en); entry = Some(en) } "ActivityLogged" => entry = { let (tone, kind, sum) = (s(&e, "tone"), s(&e, "kind"), s(&e, "summary")); if crate::present::thread::snap_line(sum).is_some() { restore_push(hub, &th, s(&e, "act")).await } // the turn's snapshot: no row; its message gains Restore to before this diff --git a/native/host/src/data/tests.rs b/native/host/src/data/tests.rs index e4d3049676..6b881ba9ca 100644 --- a/native/host/src/data/tests.rs +++ b/native/host/src/data/tests.rs @@ -1552,3 +1552,17 @@ fn probed_models(installed: &[&str]) -> Value { let empty_create = ask(&mut ws, 3, "thread.create", json!({"project":"p1"})).await; assert_eq!(empty_create["ok"], true, "opening an empty thread remains allowed so user sees proactive banner: {empty_create}"); } + +#[test] fn data_user_message_carries_resolved_model_refs_only() { + let models_json = r#"{"claude":[{"value":"opus","label":"Opus 5.5","ok":true,"why":""},{"value":"claude-fable-5-2[1m]","label":"Fable 5.2","ok":true,"why":""}],"antigravity":[{"value":"gemini-4-neon","label":"Gemini 4 Neon","ok":true,"why":""}]}"#; + let mut en = json!({"id":"m1","kind":"user","text":"try &antigravity/gemini-4-neon, &claude/claude-fable-5-2[1m] and &provider/model","at":1}); + with_refs_with(&mut en, Some(models_json)); + assert_eq!(en["refs"], json!([ + {"word":"&antigravity/gemini-4-neon","kind":"model","id":"","label":"Gemini 4 Neon"}, + {"word":"&claude/claude-fable-5-2[1m]","kind":"model","id":"","label":"Fable 5.2"} + ])); + + let mut none = json!({"id":"m2","kind":"user","text":"try &provider/model only","at":2}); + with_refs_with(&mut none, Some(models_json)); + assert!(none.get("refs").is_none(), "unresolved model ref must not attach refs: {none}"); +} diff --git a/native/host/src/session/mention.rs b/native/host/src/session/mention.rs index 679039b439..b84a44e5b8 100644 --- a/native/host/src/session/mention.rs +++ b/native/host/src/session/mention.rs @@ -48,8 +48,8 @@ fn typing(w: &str) -> Option<(char, String)> { let mut cs = w.chars(); let sig = cs.next()?; if !matches!(sig, '@' | '>' | '%' | '#' | '&' | '~') { return None } let q: String = cs.collect(); - // a model id (`provider/model`) holds more than a slug does (settings/mentions.rs) - let ok = |c: char| c.is_ascii_alphanumeric() || c == '-' || c == '_' || (sig == '&' && matches!(c, '/' | '.' | ':' | '+')); + // a model id (`provider/model`) holds more than a slug does (settings/mentions.rs), including `[1m]` + let ok = |c: char| c.is_ascii_alphanumeric() || c == '-' || c == '_' || (sig == '&' && matches!(c, '/' | '.' | ':' | '+' | '[' | ']')); q.chars().all(ok).then(|| (sig, q.to_ascii_lowercase())) } @@ -150,13 +150,59 @@ pub fn rows(st: &State, here: &str, draft: &str) -> Vec { /// The words of a text that start with a sigil, its punctuation off, each once, in order. fn sigil_words(text: &str) -> Vec { let mut out: Vec = vec![]; - for w in text.split(|c: char| c.is_whitespace()) { - let w = w.trim_start_matches(|c| matches!(c, '(' | '[' | '"' | '\'' | '`')).trim_end_matches(|c| matches!(c, '.' | ',' | ':' | ';' | '!' | '?' | ')' | ']' | '"' | '\'' | '`')); + for raw in text.split(|c: char| c.is_whitespace()) { + let mut w = raw.trim_start_matches(|c| matches!(c, '(' | '[' | '"' | '\'' | '`')); + loop { + let trimmed = w.trim_end_matches(|c| matches!(c, '.' | ',' | ':' | ';' | '!' | '?' | ')' | '"' | '\'' | '`')); + if trimmed.len() < w.len() { w = trimmed; continue } + if w.ends_with(']') && w.bytes().filter(|&b| b == b']').count() > w.bytes().filter(|&b| b == b'[').count() { + w = &w[..w.len() - 1]; + continue; + } + break; + } if w.len() > 1 && matches!(w.chars().next(), Some('@' | '>' | '%' | '#' | '&' | '~')) && !out.iter().any(|x| x == w) { out.push(w.to_string()) } } out } +fn resolve_model(all: &Value, rest: &str) -> Option { + let (pr, m) = rest.split_once('/')?; + let rows = all[pr].as_array()?; + let r = rows.iter().find(|r| r["value"].as_str() == Some(m))?; + let raw = r["label"].as_str().unwrap_or(m); + let short = raw.split(" · ").next().map(str::trim).filter(|s| !s.is_empty()).unwrap_or(raw); + Some(short.to_string()) +} + +/// Parses the hub's current models catalog (`MODELS`) once as a JSON `Value`. +pub fn models_catalog() -> Value { + let raw = MODELS.get().map(|f| f()).unwrap_or_default(); + serde_json::from_str(&raw).unwrap_or(Value::Null) +} + +/// Resolved `&provider/model` references in `text`, in order, each once, against a pre-parsed `models` catalog. +pub fn model_refs_in_catalog(text: &str, all: &Value) -> Vec { + let words = sigil_words(text); + if !words.iter().any(|w| w.starts_with('&')) { return vec![] } + words.into_iter().filter(|w| w.starts_with('&')).filter_map(|w| { + resolve_model(all, &w[1..]).map(|label| json!({"word": w, "kind": "model", "id": "", "label": label})) + }).collect() +} + +/// Resolved `&provider/model` references in `text`, in order, each once, against `models_json` (`{provider: [{value, label, ..}]}`). +pub fn model_refs_in_with(text: &str, models_json: &str) -> Vec { + if !text.contains('&') { return vec![] } + let all: Value = serde_json::from_str(models_json).unwrap_or(Value::Null); + model_refs_in_catalog(text, &all) +} + +/// Resolved `&provider/model` references in `text`, in order, each once: `{word, kind: "model", id: "", label}`. +pub fn model_refs_in(text: &str) -> Vec { + if !text.contains('&') { return vec![] } + model_refs_in_catalog(text, &models_catalog()) +} + /// What a `/give` names: `(sigil, id, name)` for each `>thread`, `%project` and `@bot` the text points at, each once, in order. Lists are `(id, title)`; a slug two threads share takes the id's tail, as the popup writes it. pub fn give_hits(text: &str, threads: &[(String, String)], projects: &[(String, String)], bots: &[(String, String)]) -> Vec<(char, String, String)> { let mut out: Vec<(char, String, String)> = vec![]; @@ -198,7 +244,7 @@ pub fn refs_in(st: &State, hub: &str, text: &str) -> Vec { !s.is_empty() && (rest == s || (n > 1 && rest == format!("{s}-{}", id.rsplit('-').next().unwrap_or("")))) }).map(|(id, t)| ("thread", q(id), t.title.clone())), '%' => st.projects.iter().filter(|(_, p)| !p.removed).find(|(_, p)| slug(&p.title) == rest.to_ascii_lowercase()).map(|(id, p)| ("project", q(id), p.title.clone())), '#' => st.rooms_nav.iter().find(|(_, r)| !r.ephemeral && slug(&r.name) == rest.to_ascii_lowercase()).map(|(id, r)| ("room", q(id), r.name.clone())), - _ => rest.split_once('/').and_then(|(pr, m)| all[pr].as_array().and_then(|rows| rows.iter().find(|r| r["value"].as_str() == Some(m))).map(|r| ("model", String::new(), r["label"].as_str().unwrap_or(m).to_string()))), + _ => resolve_model(&all, rest).map(|label| ("model", String::new(), label)), } }; if let Some((kind, id, label)) = hit { out.push(json!({"word": w, "kind": kind, "id": id, "label": label})) } } @@ -258,6 +304,15 @@ mod tests { assert_eq!(words("&son"), ["&claude/sonnet", "&claude/claude-sonnet-5", "&claude/claude-sonnet-4-6"]); assert_eq!(words("&")[..3], ["&claude/opus", "&claude/claude-fable-5-2", "&claude/sonnet"]); assert!(rows(&st, "t", "&").last().unwrap()["desc"].as_str().unwrap().contains("not usable")); + let r = refs_in(&st, "h", "use [&claude/opus] and &provider/model."); + let got: Vec<(&str, &str, &str)> = r.iter().map(|x| (x["word"].as_str().unwrap(), x["kind"].as_str().unwrap(), x["label"].as_str().unwrap())).collect(); + assert_eq!(got, [("&claude/opus", "model", "Opus 5.5")]); + let cat = r#"{"claude":[{"value":"claude-fable-5-2[1m]","label":"Fable 5.2 · claude-fable-5-2","ok":true},{"value":"sonnet","label":"Sonnet 5.5 · claude-sonnet-5-5","ok":true}]}"#; + assert_eq!(model_refs_in_with("see &claude/claude-fable-5-2[1m], [&claude/sonnet] and &provider/model", cat), vec![ + json!({"word": "&claude/claude-fable-5-2[1m]", "kind": "model", "id": "", "label": "Fable 5.2"}), + json!({"word": "&claude/sonnet", "kind": "model", "id": "", "label": "Sonnet 5.5"}), + ]); + assert!(model_refs_in_with("see &provider/model", cat).is_empty()); } #[test] fn threads_and_projects_are_offered_best_match_first() { let mut st = State::new(); diff --git a/native/host/src/settings/mentions.rs b/native/host/src/settings/mentions.rs index 20c24bafa6..b2d08ba9b3 100644 --- a/native/host/src/settings/mentions.rs +++ b/native/host/src/settings/mentions.rs @@ -11,7 +11,7 @@ impl ModelRef { /// The agent's `` line. pub fn line(&self) -> String { format!("model {}/{}: {}", self.provider, self.model, match self.state { "ok" => "usable", "unavailable" => "listed but not usable now", _ => "not a model this hub lists" }) } } -fn slug(c: char) -> bool { c.is_alphanumeric() || matches!(c, '-' | '_' | '.' | '/' | ':' | '+') } +fn slug(c: char) -> bool { c.is_alphanumeric() || matches!(c, '-' | '_' | '.' | '/' | ':' | '+' | '[' | ']') } /// The `&word`s of a text, in order: a `&` that begins a word (start of text or after whitespace/an opening bracket or quote) then slug characters containing a `/` /// (a bare `&sonnet` has no provider: it is `unknown`, shown so, never guessed). Trailing `.`, `,`, `:`, `/` are punctuation, not the id. @@ -21,7 +21,15 @@ pub fn words(text: &str) -> Vec { let start = i == 0 || cs[i - 1].is_whitespace() || matches!(cs[i - 1], '(' | '[' | '{' | '"' | '\'' | '`' | ','); if cs[i] == '&' && start { let mut j = i + 1; while j < cs.len() && slug(cs[j]) { j += 1 } - while j > i + 1 && matches!(cs[j - 1], '.' | ',' | ':' | '/') { j -= 1 } + while j > i + 1 { + if matches!(cs[j - 1], '.' | ',' | ':' | '/') { j -= 1; continue } + if cs[j - 1] == ']' { + let opens = cs[i + 1..j].iter().filter(|&&c| c == '[').count(); + let closes = cs[i + 1..j].iter().filter(|&&c| c == ']').count(); + if closes > opens { j -= 1; continue } + } + break; + } if j > i + 1 { let w: String = cs[i..j].iter().collect(); if !out.contains(&w) { out.push(w) } } i = j.max(i + 1); } else { i += 1 } @@ -53,6 +61,7 @@ mod tests { assert_eq!(words("a&b rock&roll && &"), Vec::::new(), "mid-word and bare ampersands are text"); assert_eq!(words("&claude/opus &claude/opus"), ["&claude/opus"], "once each"); assert_eq!(words("see &opencode/openai/gpt-5."), ["&opencode/openai/gpt-5"], "the first slash splits, the last dot is punctuation"); + assert_eq!(words("try &claude/claude-fable-5-2[1m], [&claude/opus] and [&claude/claude-fable-5-2[1m]]."), ["&claude/claude-fable-5-2[1m]", "&claude/opus"]); } #[test] fn each_reference_is_ok_unknown_or_unavailable_and_none_changes_a_thread() { let r = resolve("use &claude/sonnet, &codex/gpt-6.1-sol, &claude/nope, &sonnet, &opencode/openai/gpt-5 and &zed/x", &all()); diff --git a/web/build.ts b/web/build.ts index 536ae7b414..3c247d04fc 100644 --- a/web/build.ts +++ b/web/build.ts @@ -9,8 +9,23 @@ const ROOT = resolve(WEB_DIR, ".."); const SRC_DIR = join(WEB_DIR, "src"); const DIST_DIR = join(WEB_DIR, "dist"); const STYLE_SRC = join(ROOT, "assets/web/style.css"); +const PROVIDERS_DIR = join(ROOT, "assets/providers"); const I18N_DIR = join(ROOT, "i18n"); const CHECK_ONLY = process.argv.includes("--check"); +const PROVIDER_MARK_NAMES = ["claude", "codex", "grok", "muse", "antigravity", "opencode", "pi", "omp"]; + +function buildProviderMarksBundle(): string { + const marks: Record = {}; + for (const name of PROVIDER_MARK_NAMES) { + const p = join(PROVIDERS_DIR, `${name}.svg`); + if (!existsSync(p)) continue; + const svg = readFileSync(p, "utf8"); + const vb = /\bviewBox="([^"]+)"/.exec(svg)?.[1] ?? "0 0 24 24"; + const d = /]*\bd="([^"]+)"/.exec(svg)?.[1] ?? ""; + if (d) marks[name] = { viewBox: vb, d }; + } + return `export const PROVIDER_MARKS: Record = ${JSON.stringify(marks)};\n`; +} function walkFiles(dir: string): string[] { if (!existsSync(dir)) return []; @@ -176,6 +191,21 @@ async function buildInto(outDir: string): Promise { }, }; + const providerMarksSource = buildProviderMarksBundle(); + const providerMarksPlugin: Bun.BunPlugin = { + name: "backplane-provider-marks", + setup(build) { + build.onResolve({ filter: /^virtual:provider-marks$/ }, () => ({ + path: "virtual:provider-marks", + namespace: "bp-provider-marks", + })); + build.onLoad({ filter: /.*/, namespace: "bp-provider-marks" }, () => ({ + contents: providerMarksSource, + loader: "ts", + })); + }, + }; + const viewerPanePath = join(SRC_DIR, "viewers/viewer-pane.ts"); const viewerPlugin: Bun.BunPlugin = { name: "backplane-viewer-pane", @@ -241,7 +271,7 @@ async function buildInto(outDir: string): Promise { sourcemap: "none", splitting: false, naming: "[name].[ext]", - plugins: [i18nPlugin, viewerPlugin, xtermCspPlugin], + plugins: [i18nPlugin, providerMarksPlugin, viewerPlugin, xtermCspPlugin], }); if (!res.success) { for (const log of res.logs) console.error(log); @@ -265,6 +295,7 @@ async function buildInto(outDir: string): Promise { ...walkFiles(SRC_DIR), ...walkFiles(join(WEB_DIR, "vendor")), join(WEB_DIR, "build.ts"), + ...PROVIDER_MARK_NAMES.map((n) => join(PROVIDERS_DIR, `${n}.svg`)), join(ROOT, "assets/web/favicon.svg"), join(ROOT, "assets/web/favicon-light.svg"), ]) { diff --git a/web/dist/assets/app.js b/web/dist/assets/app.js index e52b3f1ced..cfe9dd133d 100644 --- a/web/dist/assets/app.js +++ b/web/dist/assets/app.js @@ -1,15 +1,16 @@ -function qt(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 Dn(e){return e==="done"||e==="failed"||e==="cancelled"}function Fn(e,t){if(!e||e.id!==t.id)return!0;let n=Dn(e.state),i=Dn(t.state);if(n!==i)return i;return(t.ended??0)>=(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=(e.ended??0)}function On(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","native.thread.model":"Model","notify.settled":"Settled","palette.archive":"Archive thread","palette.command.placeholder":"Type a command or a thread","palette.diff":"Diff: what this thread changed","palette.newthread":"New thread","palette.settings":"Settings","palette.terminal":"Terminal","palette.unarchive":"Unarchive thread","phone.unsettle":"Unsettle","provider.notice.button":"Open Settings → Accounts","provider.notice.head":"No AI provider connected","provider.notice.senderr":"No AI provider connected yet. Open Settings → Accounts to connect Claude, Codex, Antigravity, or another provider.","provider.notice.senderr.remote":"No AI provider connected on {machine}. Open Settings → Accounts on {machine} to connect Claude, Codex, Antigravity, or another provider.","provider.notice.text.none":"Connect Claude, Codex, Antigravity, or another provider to start chatting.","provider.notice.text.signedout":"Sign in to Claude, Codex, or another provider in Settings → Accounts to start chatting.","reply.action":"Reply","reply.cancel":"Cancel reply","reply.to":"In reply to:","rooms.new":"New room","secret.you":"You","settings.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","native.thread.model":"Modelo","notify.settled":"Cerrado","palette.archive":"Archivar hilo","palette.command.placeholder":"Escribe un comando o un hilo","palette.diff":"Diff: qué cambió este hilo","palette.newthread":"Nuevo hilo","palette.settings":"Ajustes","palette.terminal":"Terminal","palette.unarchive":"Desarchivar hilo","phone.unsettle":"Reabrir","provider.notice.button":"Abrir Configuración → Cuentas","provider.notice.head":"No hay ningún proveedor de IA conectado","provider.notice.senderr":"Aún no hay ningún proveedor de IA conectado. Abre Configuración → Cuentas para conectar Claude, Codex, Antigravity u otro proveedor.","provider.notice.senderr.remote":"No hay ningún proveedor de IA conectado en {machine}. Abre Configuración → Cuentas en {machine} para conectar Claude, Codex, Antigravity u otro proveedor.","provider.notice.text.none":"Conecta Claude, Codex, Antigravity u otro proveedor para empezar a chatear.","provider.notice.text.signedout":"Inicia sesión en Claude, Codex u otro proveedor en Configuración → Cuentas para empezar a chatear.","reply.action":"Responder","reply.cancel":"Cancelar respuesta","reply.to":"En respuesta a:","rooms.new":"Nueva sala","secret.you":"Tú","settings.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":"エージェント","native.thread.model":"モデル","notify.settled":"完了","palette.archive":"スレッドをアーカイブ","palette.command.placeholder":"コマンドまたはスレッドを入力","palette.diff":"差分:このスレッドの変更","palette.newthread":"新しいスレッド","palette.settings":"設定","palette.terminal":"ターミナル","palette.unarchive":"スレッドのアーカイブを解除","phone.unsettle":"未完了に戻す","provider.notice.button":"設定 → アカウントを開く","provider.notice.head":"AI プロバイダーが接続されていません","provider.notice.senderr":"AI プロバイダーがまだ接続されていません。設定 → アカウントを開いて、Claude、Codex、Antigravity などのプロバイダーを接続してください。","provider.notice.senderr.remote":"{machine} に AI プロバイダーが接続されていません。{machine} で設定 → アカウントを開いて、Claude、Codex、Antigravity などのプロバイダーを接続してください。","provider.notice.text.none":"チャットを始めるには、Claude、Codex、Antigravity などのプロバイダーを接続してください。","provider.notice.text.signedout":"チャットを始めるには、設定 → アカウントで Claude、Codex などのプロバイダーにサインインしてください。","reply.action":"返信","reply.cancel":"返信をやめる","reply.to":"返信先:","rooms.new":"新しいルーム","secret.you":"あなた","settings.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=Es(),Jt=new Set,Yt=new Map;for(let[e,t]of Object.entries(vt.en||{}))if(typeof t==="string"&&!Yt.has(t))Yt.set(t,e);function Es(){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 Vn(){if(typeof document<"u"&&document.documentElement)document.documentElement.lang=yt}Vn();function jt(e){return Jt.add(e),()=>{Jt.delete(e)}}function Un(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,Vn(),i)for(let s of Jt)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=Yt.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 Cs(e){let t=e.replace(/[\\/]+$/,"");if(!t)return e||"/";let n=t.split(/[\\/]/);return n[n.length-1]||t}function xs(e,t){let n=e.includes("\\")&&!e.includes("/")?"\\":"/";return e.endsWith(n)?e+t:e+n+t}class Xt{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(xs(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(Cs(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 Zt{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 Xt(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 Xt(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=Kt();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=Kt(),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(!$n(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&&On(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 ks(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=ks(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(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.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 As=new Set(["(","[",'"',"'","`"]);function Ls(e){return/[\p{L}\p{N}\-_\/+\[]/u.test(e)}function Ss(e){return/[\p{L}\p{N}\-_\/]/u.test(e)}function Ns(e){return/[\p{L}\p{N}]/u.test(e)}function Wn(e,t){if(!e)return[];let n=(t??[]).filter((r)=>r.kind==="model"&&r.word&&r.label);if(n.length===0)return[{kind:"text",text:e}];let i=[],s=0;while(sa)r=d,a=p,o=c;break}m=d+1}}if(o===null)break;if(r>s)i.push({kind:"text",text:e.slice(s,r)});i.push({kind:"model",word:o.word,label:o.label}),s=a}if(s3600000)return"";let t=Math.max(1,Math.round(e/1000));if(t<60)return`${t}s`;let n=Math.floor(t/60),i=t%60;return i>0?`${n}m ${i}s`:`${n}m`}function Bs(e,t){let n=document.createDocumentFragment(),i=Wn(e,t),s=b("native.thread.model","Model").toLowerCase();for(let r of i){if(r.kind==="text"){n.appendChild(document.createTextNode(r.text));continue}let a=document.createElement("span");a.className="bp-ref-chip bp-ref-model",a.title=r.word,a.setAttribute("data-ref-word",r.word);let o=document.createElement("span");o.className="bp-ref-sigil",o.textContent="&";let c=document.createElement("span");c.className="bp-ref-label",c.textContent=r.label;let m=document.createElement("span");m.className="bp-ref-kind",m.textContent=s,a.append(o,c,m),n.appendChild(a)}return n}function Ts(e){e.addEventListener("copy",(t)=>{let n=typeof window<"u"?window.getSelection():null;if(!n||n.rangeCount===0||n.isCollapsed)return;let i=n.getRangeAt(0);if(!e.contains(i.commonAncestorContainer))return;let s=i.commonAncestorContainer,o=(s.nodeType===Node.ELEMENT_NODE?s:s.parentElement)?.closest(".bp-ref-chip[data-ref-word]")?.getAttribute("data-ref-word"),c;if(o)c=o;else{let m=i.cloneContents(),d=m.querySelectorAll(".bp-ref-chip[data-ref-word]");if(d.length===0)return;for(let l of d){let h=l.getAttribute("data-ref-word")||l.textContent||"";l.replaceWith(document.createTextNode(h))}let p=m.querySelectorAll(".bp-entry");for(let l=1;l{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",Ts(this.scrollEl),this.scrollEl.append(this.olderBtn,this.listEl),e.append(this.bannerEl,this.scrollEl)}setLoading(e){this.thread=e,this.entries=[],this.hasMore=!1,this.loadingOlder=!1,this.review=null,this.unanswered=null,this.btwNote=null,this.liveNodes.clear(),this.planExpanded.clear(),this.planRevisingId="",this.planReviseDrafts.clear(),this.renderBanners(),this.olderBtn.classList.add("bp-hidden");let t=document.createElement("div");t.className="bp-empty-state",t.textContent=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=Ps(e.at);if(t)d.textContent=p,i.append(s,...m?[o]:[],d);else{let l=n&&e.at?Ms(en(e.at)-en(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.appendChild(Bs(r.text||"",r.refs));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 P=g.value.trim();if(!P)return;this.planRevisingId="",this.planReviseDrafts.delete(e.id),this.cb.onAnswerAsk(e.id,`revise:${P}`)},x=()=>{this.closePlanRevise()};u.addEventListener("keydown",(P)=>{if(P.key==="Escape")P.preventDefault(),P.stopPropagation(),x()}),g.addEventListener("input",()=>{this.planReviseDrafts.set(e.id,g.value),f.disabled=g.value.trim().length===0}),g.addEventListener("keydown",(P)=>{if(P.key==="Enter"&&!P.shiftKey)P.preventDefault(),w()}),f.addEventListener("click",w);let L=document.createElement("button");L.type="button",L.className="bp-btn-ghost",L.textContent=b("common.cancel","Cancel"),L.addEventListener("click",x),u.append(g,f,L),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 zn={claude:{viewBox:"0 0 24 24",d:"m4.7144 15.9555 4.7174-2.6471.079-.2307-.079-.1275h-.2307l-.7893-.0486-2.6956-.0729-2.3375-.0971-2.2646-.1214-.5707-.1215-.5343-.7042.0546-.3522.4797-.3218.686.0608 1.5179.1032 2.2767.1578 1.6514.0972 2.4468.255h.3886l.0546-.1579-.1336-.0971-.1032-.0972L6.973 9.8356l-2.55-1.6879-1.3356-.9714-.7225-.4918-.3643-.4614-.1578-1.0078.6557-.7225.8803.0607.2246.0607.8925.686 1.9064 1.4754 2.4893 1.8336.3643.3035.1457-.1032.0182-.0728-.164-.2733-1.3539-2.4467-1.445-2.4893-.6435-1.032-.17-.6194c-.0607-.255-.1032-.4674-.1032-.7285L6.287.1335 6.6997 0l.9957.1336.419.3642.6192 1.4147 1.0018 2.2282 1.5543 3.0296.4553.8985.2429.8318.091.255h.1579v-.1457l.1275-1.706.2368-2.0947.2307-2.6957.0789-.7589.3764-.9107.7468-.4918.5828.2793.4797.686-.0668.4433-.2853 1.8517-.5586 2.9021-.3643 1.9429h.2125l.2429-.2429.9835-1.3053 1.6514-2.0643.7286-.8196.85-.9046.5464-.4311h1.0321l.759 1.1293-.34 1.1657-1.0625 1.3478-.8804 1.1414-1.2628 1.7-.7893 1.36.0729.1093.1882-.0183 2.8535-.607 1.5421-.2794 1.8396-.3157.8318.3886.091.3946-.3278.8075-1.967.4857-2.3072.4614-3.4364.8136-.0425.0304.0486.0607 1.5482.1457.6618.0364h1.621l3.0175.2247.7892.522.4736.6376-.079.4857-1.2142.6193-1.6393-.3886-3.825-.9107-1.3113-.3279h-.1822v.1093l1.0929 1.0686 2.0035 1.8092 2.5075 2.3314.1275.5768-.3218.4554-.34-.0486-2.2039-1.6575-.85-.7468-1.9246-1.621h-.1275v.17l.4432.6496 2.3436 3.5214.1214 1.0807-.17.3521-.6071.2125-.6679-.1214-1.3721-1.9246L14.38 17.959l-1.1414-1.9428-.1397.079-.674 7.2552-.3156.3703-.7286.2793-.6071-.4614-.3218-.7468.3218-1.4753.3886-1.9246.3157-1.53.2853-1.9004.17-.6314-.0121-.0425-.1397.0182-1.4328 1.9672-2.1796 2.9446-1.7243 1.8456-.4128.164-.7164-.3704.0667-.6618.4008-.5889 2.386-3.0357 1.4389-1.882.929-1.0868-.0062-.1579h-.0546l-6.3385 4.1164-1.1293.1457-.4857-.4554.0608-.7467.2307-.2429 1.9064-1.3114Z"},codex:{viewBox:"0 0 256 260",d:"M239.184 106.203a64.716 64.716 0 0 0-5.576-53.103C219.452 28.459 191 15.784 163.213 21.74A65.586 65.586 0 0 0 52.096 45.22a64.716 64.716 0 0 0-43.23 31.36c-14.31 24.602-11.061 55.634 8.033 76.74a64.665 64.665 0 0 0 5.525 53.102c14.174 24.65 42.644 37.324 70.446 31.36a64.72 64.72 0 0 0 48.754 21.744c28.481.025 53.714-18.361 62.414-45.481a64.767 64.767 0 0 0 43.229-31.36c14.137-24.558 10.875-55.423-8.083-76.483Zm-97.56 136.338a48.397 48.397 0 0 1-31.105-11.255l1.535-.87l51.67-29.825a8.595 8.595 0 0 0 4.247-7.367v-72.85l21.845 12.636c.218.111.37.32.409.563v60.367c-.056 26.818-21.783 48.545-48.601 48.601Zm-104.466-44.61a48.345 48.345 0 0 1-5.781-32.589l1.534.921l51.722 29.826a8.339 8.339 0 0 0 8.441 0l63.181-36.425v25.221a.87.87 0 0 1-.358.665l-52.335 30.184c-23.257 13.398-52.97 5.431-66.404-17.803ZM23.549 85.38a48.499 48.499 0 0 1 25.58-21.333v61.39a8.288 8.288 0 0 0 4.195 7.316l62.874 36.272l-21.845 12.636a.819.819 0 0 1-.767 0L41.353 151.53c-23.211-13.454-31.171-43.144-17.804-66.405v.256Zm179.466 41.695l-63.08-36.63L161.73 77.86a.819.819 0 0 1 .768 0l52.233 30.184a48.6 48.6 0 0 1-7.316 87.635v-61.391a8.544 8.544 0 0 0-4.4-7.213Zm21.742-32.69l-1.535-.922l-51.619-30.081a8.39 8.39 0 0 0-8.492 0L99.98 99.808V74.587a.716.716 0 0 1 .307-.665l52.233-30.133a48.652 48.652 0 0 1 72.236 50.391v.205ZM88.061 139.097l-21.845-12.585a.87.87 0 0 1-.41-.614V65.685a48.652 48.652 0 0 1 79.757-37.346l-1.535.87l-51.67 29.825a8.595 8.595 0 0 0-4.246 7.367l-.051 72.697Zm11.868-25.58L128.067 97.3l28.188 16.218v32.434l-28.086 16.218l-28.188-16.218l-.052-32.434Z"},grok:{viewBox:"0 0 24 24",d:"M9.497 15.122 L16.811 9.491 C17.169 9.215 17.682 9.323 17.852 9.751 C18.752 12.013 18.35 14.73 16.561 16.596 C14.772 18.462 12.283 18.871 10.007 17.939 L7.522 19.139 C11.087 21.68 15.416 21.052 18.121 18.229 C20.267 15.991 20.931 12.941 20.31 10.19 L20.315 10.196 C19.414 6.155 20.537 4.54 22.837 1.237 C22.891 1.159 22.946 1.08 23 1 L19.974 4.156 L19.974 4.146 L9.495 15.124 M7.987 16.49 C5.429 13.941 5.87 9.996 8.053 7.721 C9.667 6.037 12.313 5.35 14.622 6.361 L17.102 5.166 C16.655 4.829 16.082 4.467 15.425 4.213 C12.455 2.938 8.9 3.573 6.485 6.088 C4.163 8.51 3.433 12.234 4.687 15.411 C5.624 17.786 4.088 19.466 2.541 21.162 C1.993 21.763 1.443 22.364 1 23 L7.985 16.492"},muse:{viewBox:"0 0 24 24",d:"M10.73.032c-1.333 0-2.032 1.016-2.032 2.285 0 2.223 2.127 4.953 4.318 4.953 1.301 0 2-.953 2-2.254 0-2.254-2.095-4.984-4.286-4.984m8.413 2.984c-1.968 0-3.397 2.73-3.397 4.825 0 1.556.794 3.016 2.254 3.016 2 0 3.365-2.762 3.365-4.794 0-1.523-.762-3.047-2.222-3.047M4.857 4.159c-1.968 0-3.778 1.016-3.778 2.54 0 1.65 2.16 2.793 4.254 2.793 1.873 0 3.778-.92 3.778-2.508 0-1.682-2.159-2.825-4.254-2.825m-.222 6.476C2.413 10.635 0 13.175 0 15.397c0 1.301.825 2.159 2.095 2.159 2.19 0 4.603-2.508 4.603-4.794 0-1.27-.761-2.127-2.063-2.127m16.667.698c-2.223 0-5.016 1.62-5.016 3.651 0 1.238 1.047 2.19 2.698 2.19 2.159 0 5.016-1.587 5.016-3.682 0-1.302-1.08-2.159-2.698-2.159M7.619 16c-1.524 0-2.38 1.746-2.38 3.429 0 2.063 1.269 4.54 3.047 4.54 1.524 0 2.38-1.81 2.38-3.461C10.667 18.57 9.46 16 7.62 16m6.571 1.016c-1.333 0-2.476.667-2.476 2.032 0 2.095 2.667 4.063 4.92 4.063 1.366 0 2.54-.73 2.54-2.063 0-2.032-2.698-4.032-4.984-4.032"},antigravity:{viewBox:"0 0 24 24",d:"M20.197 20.618 C21.318 21.459 23 20.898 21.459 19.357 C16.834 14.873 17.815 2.541 12.07 2.541 C6.325 2.541 7.306 14.873 2.682 19.357 C1 21.038 2.822 21.459 3.943 20.618 C8.287 17.675 8.006 12.49 12.07 12.49 C16.134 12.49 15.853 17.675 20.197 20.618 Z"},opencode:{viewBox:"0 0 24 24",d:"M22 24H2V0h20zM17 4.8H7v14.4h10z"},pi:{viewBox:"0 0 24 24",d:"M0 0v24h6v-6h6v-6H6V6h6v6h6V0Zm18 12v12h6V12Z"},omp:{viewBox:"0 0 24 24",d:"M1.44 3.86 L22.56 3.86 C23 3.86 23 3.86 23 4.3 L23 6.06 C23 6.5 23 6.5 22.56 6.5 L1.44 6.5 C1 6.5 1 6.5 1 6.06 L1 4.3 C1 3.86 1 3.86 1.44 3.86 Z M4.74 6.5 L6.5 6.5 C6.94 6.5 6.94 6.5 6.94 6.94 L6.94 19.7 C6.94 20.14 6.94 20.14 6.5 20.14 L4.74 20.14 C4.3 20.14 4.3 20.14 4.3 19.7 L4.3 6.94 C4.3 6.5 4.3 6.5 4.74 6.5 Z M15.74 6.5 L17.5 6.5 C17.94 6.5 17.94 6.5 17.94 6.94 L17.94 13.32 C17.94 13.76 17.94 13.76 17.5 13.76 L15.74 13.76 C15.3 13.76 15.3 13.76 15.3 13.32 L15.3 6.94 C15.3 6.5 15.3 6.5 15.74 6.5 Z M15.08 14.64 L18.16 14.64 C18.82 14.64 18.82 14.64 18.82 15.3 L18.82 17.5 C18.82 18.16 18.82 18.16 18.16 18.16 L15.08 18.16 C14.42 18.16 14.42 18.16 14.42 17.5 L14.42 15.3 C14.42 14.64 14.42 14.64 15.08 14.64 Z"}};var Ht="http://www.w3.org/2000/svg",qn=4,Kn=new Set(["image/png","image/jpeg","image/webp","image/gif"]);function Dt(e){let t=document.createElementNS(Ht,"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(Ht,"path");i.setAttribute("d",n),t.appendChild(i)}return t}function nn(){return Dt(["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 Jn(){return Dt(["M6 4l14 8-14 8z"])}function Is(e){let t=(e||"").toLowerCase();if(t.includes("claude")||t.includes("anthropic"))return{mark:"claude",glyph:"A",color:"#d97757",title:"Claude"};if(t.includes("codex")||t.includes("openai"))return{mark:"codex",glyph:"O",color:"#10a37f",title:"Codex"};if(t.includes("gemini")||t.includes("antigravity")||t==="agy")return{mark:"antigravity",glyph:"G",color:"#4285f4",title:"Antigravity"};if(t.includes("grok"))return{mark:"grok",glyph:"X",color:"#6b7280",title:"Grok"};if(t.includes("muse"))return{mark:"muse",glyph:"M",color:"#8b5cf6",title:"Muse"};if(t.includes("opencode"))return{mark:"opencode",glyph:"C",color:"#2563eb",title:"OpenCode"};if(t.includes("omp")||t.includes("oh-my-pi"))return{mark:"omp",glyph:"Ω",color:"#c026d3",title:"Oh My Pi"};if(t==="pi"||t.startsWith("pi/")||t.startsWith("@pi"))return{mark:"pi",glyph:"π",color:"#db2777",title:"Pi"};return{glyph:"●",color:"var(--accent)",title:e||"Model"}}function Rs(e){let t=zn[e];if(!t||!t.d)return null;let n=document.createElementNS(Ht,"svg");n.setAttribute("viewBox",t.viewBox||"0 0 24 24"),n.setAttribute("width","14"),n.setAttribute("height","14"),n.setAttribute("fill","currentColor"),n.setAttribute("aria-hidden","true");let i=document.createElementNS(Ht,"path");return i.setAttribute("d",t.d),n.appendChild(i),n}class sn{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(nn()),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(Dt(["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(Dt(["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=Is(t),s=i.mark?Rs(i.mark):null;if(s)this.providerMarkEl.replaceChildren(s);else this.providerMarkEl.textContent=i.glyph;if(this.providerMarkEl.style.color=i.color,this.providerMarkEl.title=i.title,this.modelTextEl.textContent=e||"default",typeof n==="number"&&Number.isFinite(n)&&n>=0)this.ctxEl.textContent=`ctx ${Math.round(n)}%`,this.ctxEl.classList.remove("bp-hidden");else this.ctxEl.textContent="",this.ctxEl.classList.add("bp-hidden")}setFeatures(e,t){this.attachBtn.classList.toggle("bp-hidden",!e),this.voiceBtn.classList.toggle("bp-hidden",!t)}setVoiceRecording(e){this.voiceBtn.classList.toggle("recording",e),this.voiceBtn.setAttribute("aria-pressed",e?"true":"false")}setVoiceLevel(e){this.voiceBtn.setAttribute("data-level",String(e))}getDraft(){return this.textarea.value}getCaret(){return this.textarea.selectionStart??this.textarea.value.length}setMemory(e){if(this.memoryEl.classList.toggle("bp-hidden",!e),!e)return;let t=e.total??0,n=t>0?Math.min(1,(e.done??0)/t):1;this.memoryFill.style.width=`${Math.round(n*100)}%`,this.memoryFill.dataset.state=e.state??"",this.memoryText.textContent=e.line??"",this.memoryEl.title=[e.status,e.lines,e.viewLine].filter(Boolean).join(` +`)}setPlanMode(e){if(this.planMode=e,this.textarea.classList.remove("is-plan","is-plan-exec"),this.sendBtn.classList.remove("is-plan","is-plan-exec"),this.planChipBtn.classList.remove("is-plan","is-exec"),this.planBarEl.classList.remove("is-exec"),!e){this.planChipBtn.classList.add("bp-hidden"),this.planChipBtn.setAttribute("aria-pressed","false"),this.planBarEl.classList.add("bp-hidden"),this.planBarEl.replaceChildren(),this.sendBtn.textContent=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?Jn():nn()),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?Jn():nn());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(!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 +`)){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(!Kn.has(t.type)){this.showError(b("web.composer.unsupported","Unsupported image type: {type}",{type:t.type||t.name}));continue}if(this.attachments.length>=qn){this.showError(b("web.composer.maximages","At most {max} images per message.",{max:qn}));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 Yn(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 js=new Set(["bom","checks","life","plan","fab"]);function Ft(e){if(!e||!Array.isArray(e.panels))return[];return e.panels.filter((t)=>t&&typeof t.id==="string"&&js.has(t.id))}function ni(e){let t=e?.badge?.n??0;if(!Number.isFinite(t)||t<=0)return null;return{text:t>99?"99+":String(Math.floor(t)),tone:e?.badge?.tone==="bad"?"bad":"warn"}}function $t(e,t=22){let n=e.join(", ");if(n.length<=t)return n;let i="";for(let s=0;s0?` +${o}`.length:0)>t)return i?`${i} +${e.length-s}`:`${e[0]} +${e.length-1}`;i=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 Hs=new Set(["0201","0402","0603","0805","1206","1210","1812","2010","2512"]),Ds=new Set(["QFN","DFN","SOT","SOIC","SOP","SSOP","TSSOP","MSOP","QFP","LQFP","TQFP","BGA","WLCSP","SOD","TO","SON","LGA"]);function ii(e){if(!e)return"";let t=e.indexOf(":"),i=(t>=0?e.slice(t+1):e).split("_");for(let a of i)if(Hs.has(a))return a;let s=i[0]??"",r=s.replace(/[^a-zA-Z].*$/,"").toUpperCase();if(Ds.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 si(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 ri(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 ai(e,t){if(!t)return e;return e.filter((n)=>n.source===t)}function an(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 Ot(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 oi(e){return e.state==="routed"||e.state==="verified"}function li(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 ci(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 di(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 pi(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 mi(e){return e==="extra"?"costs-more limits":"base-price limits"}function on(e,t){return e.watchGen===t.watchGen&&e.editGen===t.editGen&&e.project!==""&&e.project===t.project&&e.editId!==""&&e.editId===t.editId}function ui(e){return{project:e.project,refs:e.refs.slice(),field:e.field,value:e.was}}function ln(e,t){return e.watchGen===t.watchGen&&e.project!==""&&e.project===t.project&&e.threadId!==""&&e.threadId===t.threadId&&e.threadGen===t.threadGen}var Xn=["#f59e0b","#38bdf8","#c084fc","#2dd4bf","#ef4444","#a3e635","#f97316","#ec4899"],Zn=["#14b8a6","#f59e0b","#c084fc","#22c55e","#38bdf8","#ef4444","#e879f9","#84cc16"];function hi(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 Xn[hi(i)%Xn.length]}function dt(e,t=""){let n=t.trim().toLowerCase();if(n&&n!=="#8a8a8a")return t;return Zn[hi(e)%Zn.length]}function bi(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 gi(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 fi(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 vi(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 cn(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 Fs(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 Qn(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 dn(e,t){return Math.max(5,Math.min(32,e*t))}function Vt(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(!Qn(d,p,v))continue;if(!(h.holes??[]).some((g)=>Qn(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 ei(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 yi(e,t,n){if(e==="split"&&n.length>0)return t.filter((i)=>n.includes(i.layer));return t}function rn(e,t){return!(e[2]<=t[0]||e[0]>=t[2]||e[3]<=t[1]||e[1]>=t[3])}function ti(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 wi(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(ti(m[0],m[1],e)&&!t.some((d)=>ti(m[0],m[1],d)))return m;return null}function Ei(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),L=15;for(let P of[0.5,0.35,0.65,0.22,0.78]){let A=ei(d.pts,P);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)=>rn(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=ei(d.pts,0.5);if(w){let[x,L]=Ve(t,w[0],w[1],n,i),P=Math.max(16,l.length*6.5+8),A=15,M=g(x,P);for(let T of[-18,18]){let R=f(L+T,15);if(!o.some((V)=>rn(m(M,R,P,15,2),V))){u={id:d.b.id,text:l,cx:M,cy:R,pw:P,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 Ci(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)=>rn(p,h)))c.push(p),m.push({text:d.text,cx:d.cx,cy:d.cy})}return m}function xi(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 Ut(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 ki(e,t,n,i,s,r,a,o){return e===t&&n===i&&s===r&&(o===void 0||a>=o)}var Ai="#111917",$s="#16201d",Os="rgba(212, 224, 219, 0.92)",Gs="rgba(61, 80, 73, 0.72)",Vs="rgba(82, 107, 97, 0.85)";var Li="#f59e0b",Us="#eef5f2",Si="#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 Ws(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 _s(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 zs(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 pn{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=Ut(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 bi(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=zs(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=Vt(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=cn(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=vi(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 L=this.getCam(t,c,m);this.setCam(t,gi(L,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((L)=>[L[0],L[1]]);this.patchLocalItem(this.drag.id,this.drag.isPlane,x),this.scheduleDraw();return}let d=this.getCam(t,c,m),p=Vt(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=Vt(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,fi(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=cn(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=Ai,e.fillRect(0,0,n,i);let o=(s.board.outline??[]).filter((u)=>u.length>=3);if(e.fillStyle=$s,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=_s(u.state||"proposed",f,w),L=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=wi(g,u.holes??[]);if(V){let[H,ae]=a(V[0],V[1]);e.fillStyle=rt(L,f?0.91:0.67),e.font="bold 10px ui-monospace, 'SFMono-Regular', Menlo, monospace",e.textAlign="center",e.textBaseline="middle",e.fillText(P,H,ae)}}}}if(e.strokeStyle=Os,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=Ei(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 Ci(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[L,P]=a(x[0],x[1]),[A,M]=a(x[2],x[3]);e.moveTo(L,P),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=Ws(u.state||"proposed",f,w),L=dt(u.name||u.id,u.color||""),P=dn(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 Ft(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=Ft(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=ni(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=ri(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=$t(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=si(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??"",ii(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=$t(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(!on(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(!on(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(ui(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=ai(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 L=document.createElement("div");if(L.textContent=pe(w.title??""),x.appendChild(L),w.names||this.checksSelectedId===w.id){let P=document.createElement("div");P.className="bp-mgmt-row-sub";let A=document.createElement("span");if(A.className="bp-dim bp-mgmt-flex1",A.textContent=w.names??"",P.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(!ln(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(!ln(R,H))return;this.checksStatus=V instanceof Error?V.message:"Could not send finding",this.render()})}),P.appendChild(M)}x.appendChild(P)}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=an(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 ${Ot(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 (${Ot(c[0])})`,s.appendChild(d)}for(let c of t.parts??[]){let m=this.lifeSelectedKey===c.key,d=an(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=$t(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?Ot(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=xi(q);if(!te)return;let D=typeof te.revision==="number"?te.revision:B;if(!ki(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?[]:di(t),v=h.reduce((E,k)=>E+k.count,0);if(!t.empty){let E=ci(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,L=document.createElement("div");if(L.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})),L.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",{})),L.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",{})),L.appendChild(E)}let P=document.createElement("span");if(P.className="bp-mgmt-flex1",L.appendChild(P),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()}),L.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()}),L.appendChild(A),e.appendChild(L);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}}),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}}),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=Ut(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 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})),q.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})),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 Ne=document.createElement("button");if(Ne.type="button",Ne.className="icon",Ne.textContent="×",Ne.addEventListener("click",()=>{this.planSelectedId="",this.planNoteOpen=!1,this.planMoveLayerOpen=!1,this.render()}),q.append(me,Ne),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=yi(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&&oi(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 Se=[];if(B.kind==="plane"){if(B.reference)Se.push(b("gpui.mgmt.plan.reference","over {layer}",{layer:B.reference}))}else{let Y=B.nets??0;Se.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))Se.push(`${B.width.toFixed(2)}mm`);if(B.impedance)Se.push(B.impedance);let me=Se.join(" · "),Ne=document.createElement("span");if(Ne.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"),Ne.textContent=li(B),D.append(K,je,Ne),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 pn({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: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,x={})=>{let L=this.watchGen,P=this.project;this.fabStatus="",this.cb.hub.rpc("fab.profile",{pro:P,action:w,...x}).catch((A)=>{if(L!==this.watchGen||P!==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}`:""} · ${mi(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=pi(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 L=document.createElement("div");L.className="bp-mgmt-row-line";let P=document.createElement("span");P.className="bp-mgmt-flex1 bp-tone-warn",P.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})),L.append(P,A),x.appendChild(L),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 L=t.stackup.by==="proposed",P=document.createElement("span");if(P.className="bp-mgmt-flex1 "+(L?"bp-tone-warn":"bp-dim"),P.textContent=`${L?"Proposed: ":""}${t.stackup.chosen}${t.stackup.outer_50_mm?` (50Ω ${t.stackup.outer_50_mm} mm)`:""}`,x.appendChild(P),L){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 L=document.createElement("span");L.className="bp-mgmt-flex1 bp-tone-warn",L.textContent=b("gpui.mgmt.fab.changed","Changed since you last looked");let P=document.createElement("button");P.type="button",P.className="bp-mgmt-btn",P.textContent=b("gpui.mgmt.fab.seen","Seen"),P.addEventListener("click",()=>n("seen")),x.append(L,P),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 L=document.createElement("span");L.className="bp-mgmt-col",L.textContent=b("gpui.mgmt.fab.free","Base price");let P=document.createElement("span");P.className="bp-mgmt-col",P.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,L,P,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??"",Le=Boolean(we)&&oe?.confidence!=="published",Me=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=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 qs={trs:(e)=>e,t:(e,t)=>t},Ks=new Set(["/settle"]);function Ni(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 Mi(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 Bi(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 Ti(e,t=qs){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=Ks.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}=Pi(o);s.push({label:o.title||"Untitled thread",place:o.project?r.get(o.project)??"":"",kind:"thread",urgency:c,want:m,dotClass:Mi(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 Ii(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}=Pi(v);c.push({label:v.title||"Untitled thread",place:v.project?l.get(v.project)??"":"",kind:"thread",urgency:u,want:g,dotClass:Mi(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=Ti(t,{t:b,trs:pe}),i=this.query.trim()===this.searchHitsQuery?this.searchHits:null;if(this.listed=Ii(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 Xs=new Set(["resume","raise","retry","move","signin"]);function Di(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 Wt(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(Xs.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 Fi(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 gn{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 fn(e){return Ee("pre","bp-context-code",e)}function Zs(e){return Ee("span",`bp-context-badge ${e==="Native"||e==="Enabled"?"active":e==="Untrusted"||e==="Invalid"?"warn":""}`,pe(e))}function _t(e,t){let n=Ee("div","bp-context-row");return n.append(Ee("strong",void 0,e),Zs(t)),n}class vn{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(_t(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,fn(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),fn(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(_t(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(_t(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(_t(s.name,s.status),fn(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 Qs(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 $i="http://www.w3.org/2000/svg";function at(e,t=14,n=""){let i=document.createElementNS($i,"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($i,"path");r.setAttribute("d",s),i.appendChild(r)}return i}function Oi(){return at(["M3 6h6l2 2h10v11H3z"],14,"bp-folder-icon")}function Gi(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 er(e=13){return at(["M6 6h12v12H6z","M9 2v4","M15 2v4","M9 18v4","M15 18v4","M2 9h4","M2 15h4","M18 9h4","M18 15h4"],e)}function tr(e=15){return at(["M4 10V4l4 3h8l4-3v6l-2 9H6z","M9 13h1","M14 13h1","M11 16h2"],e,"bp-cat-glyph")}function nr(e=11){return at(["M4 12l5 5 11-11"],e)}function ir(e=11){return at(["M12 22a10 10 0 1 0 0-20 10 10 0 0 0 0 20z","M12 6v6l4 2"],e)}function sr(e=11){return at(["M12 17v5","M8 4h8l-1 5 3 3v2H6v-2l3-3z"],e,"bp-pin-icon")}function Vi(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 rr(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 yn(e){if(e==="wait"||e==="error")return"bp-mood-wait";if(e==="work"||e==="talk")return"bp-mood-work";return"bp-mood-idle"}function Ze(e){let t=e.lastIndexOf("|");return t>=0?e.slice(t+1):e}class wn{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 ${yn(t.mood)}`,t.color)m.style.color=t.color;m.appendChild(tr(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 ${yn(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 ${yn(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=rr(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(ir(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(nr(11)),r.addEventListener("click",(a)=>{a.stopPropagation(),this.cb.onThreadAct(Ze(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||Ze(e.id)===this.selectedThreadId?" active":"")+(e.off?" bp-dim":""),i.setAttribute("data-thread-id",e.id),i.setAttribute("data-testid",`thread-row-${e.id}`);let s=Qs(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(Ze(a)));let o=this.snoozeMenuRowId===e.id&&Array.isArray(e.snooze)&&e.snooze.length>0,c=e.kind==="swarm"?Di(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(!Wt(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(Ze(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(Ze(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)?Gi(14):Oi();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(sr(11));let L=document.createElement("div");if(L.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(Gi(13,"")),A.addEventListener("click",(M)=>{M.stopPropagation(),this.cb.onQuickOpenViewer?.(Ze(l.id),"board")}),L.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(er(13)),A.addEventListener("click",(M)=>{M.stopPropagation(),this.cb.onQuickOpenViewer?.(Ze(l.id),"schematic")}),L.appendChild(A)}}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-${l.id}`),l.off)P.disabled=!0;if(P.addEventListener("click",(A)=>{A.stopPropagation(),this.cb.onNewThread(Ze(l.id))}),L.appendChild(P),v.append(u,x,L),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===Ze(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:Vi(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=Oi();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:Vi(l.updatedAt),pinned:l.pinned,nav:l.id},!0));t.appendChild(r)}}this.listEl.replaceChildren(t)}}function ar(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 or(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 En{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?ar(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=or(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 Ui=[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],Wi=[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],zi=[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],lr=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];function Lt(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 cr=(()=>{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),Lt(e,288)})(),dr=(()=>{let e=new Uint8Array(32);return e.fill(5),Lt(e,32)})();class Cn{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=cr,v=dr;if(l===2){let u=r(5)+257,g=r(5)+1,f=r(4)+4,w=new Uint8Array(19);for(let M=0;ML)throw Error("code length overflow");for(let V=0;VL)throw Error("code length overflow");A+=T}else if(M===18){let T=r(7)+11;if(A+T>L)throw Error("code length overflow");A+=T}else throw Error("invalid code length symbol")}h=Lt(P,u),v=Lt(P.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>=Ui.length)throw Error("invalid length symbol");let f=Ui[g]+(Wi[g]?r(Wi[g]):0),w=a(v);if(w>=_i.length)throw Error("invalid distance symbol");let x=_i[w]+(zi[w]?r(zi[w]):0);m(f);let L=this.winPos-x&32767;for(let P=0;P{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 Cn: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 St(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 pr=new TextDecoder;function qi(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 Ki(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=pr.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 Yi(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 Ji(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,L=-1/0;if(r===2)h=h+d.nextI32()|0,v=v+d.nextI32()|0,p.push(h,v),f=x=h,w=L=v;else{let A=Math.min(d.nextU32(),1048576);for(let M=0;Mx)x=h;if(vL)L=v}}let P=(p.length-g)/2;if(P>0){let A=r===2||P===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:L+M,at:g,n:P,kind:A})}}return{layer:n,color:i,alpha:s,mode:r,r:o,own:c,pts:new Float32Array(p),pieces:l}}function Xi(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 Zi(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 Qi=[["Enter","Enter"],["Tab","Tab"],["Bksp","Backspace"],["Esc","Escape"],["↑","ArrowUp"],["↓","ArrowDown"],["←","ArrowLeft"],["→","ArrowRight"]];function es(e){let t=e.trim();if(!t)return"";if(/^[a-zA-Z][a-zA-Z0-9+.-]*:/.test(t))return t;return`https://${t}`}class kn{tail=Promise.resolve();enqueue(e){let t=this.tail.then(e,e);return this.tail=t.catch(()=>{}),t}}function ts(e,t,n){let i=!0,s=!1,r=!1,a="",o=!1,c=!1,m=-1,d=null,p=new kn,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 L=v("Go","browser-go","Navigate");L.type="submit",w.append(x,L);let P=v("Take over","browser-takeover");P.classList.add("is-primary"),h.append(u,g,f,w,P);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 Qi){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 Le(X){H.textContent=X,H.hidden=!X}function Me(){A.hidden=!s,we.hidden=!s,P.textContent=s?"Hand back":"Take over",P.setAttribute("data-testid",s?"browser-handback":"browser-takeover"),P.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,Me()})}u.addEventListener("click",()=>be("back")),g.addEventListener("click",()=>be("forward")),f.addEventListener("click",()=>be("reload")),w.addEventListener("submit",(X)=>{X.preventDefault();let ce=es(x.value);if(!ce)return;if(x.value=ce,!s)he("takeover",{},()=>{s=!0,Me()});he("navigate",{url:ce},()=>{s=!0,Me()})}),P.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=Zi(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 zt(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 is(e){let t=e.lastIndexOf(".");return t>=0?e.slice(t+1).toLowerCase():""}function ur(e){return["png","jpg","jpeg","gif","webp","svg","bmp","ico"].includes(e)}function ns(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 hr(e){let t=is(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 ss(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 L of w){x=x?`${x}/${L}`:L;let P=x;m.append(z("span","bp-vh-sep","/"));let A=z("button","bp-crumb-btn",L);A.type="button",A.addEventListener("click",()=>void g(P)),m.append(A)}}async function u(f,w,x){a=f,h.replaceChildren();let L=z("div","bp-files-prev-head");L.append(z("span","bp-files-prev-name",f));let P=z("div","bp-files-prev-acts"),A=hr(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)),P.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,P.append(T),L.append(P),h.append(L);let R=is(w);if(ur(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&&!ns(R)){h.append(z("div","bp-pane-empty",`Binary file (${zt(x)}). Use Download to save.`));return}if(ns(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,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 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;neL.dir===P.dir?L.name.localeCompare(P.name):L.dir?-1:1),l.replaceChildren(),f){let L=z("button","bp-file-row is-dir");L.type="button",L.append(z("span","bp-file-icon","↰"),z("span","bp-file-name",".."));let P=f.includes("/")?f.slice(0,f.lastIndexOf("/")):"";L.addEventListener("click",()=>void g(P)),l.append(L)}if(x.length===0){l.append(z("div","bp-pane-empty","Empty folder"));return}for(let L of x){let P=f?`${f}/${L.name}`:L.name,A=z("button","bp-file-row"+(L.dir?" is-dir":"")+(P===a?" is-sel":""));A.type="button",A.setAttribute("data-testid",`file-row-${L.name}`),A.append(z("span","bp-file-icon",L.dir?"▸":"·"),z("span","bp-file-name",L.name),z("span","bp-file-size",L.dir?"":zt(L.size))),A.addEventListener("click",()=>{if(L.dir)g(P);else l.querySelectorAll(".bp-file-row.is-sel").forEach((M)=>M.classList.remove("is-sel")),A.classList.add("is-sel"),u(P,L.name,L.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 rs(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 as(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=P.value.trim();if(!T)return;A.disabled=!0,t.hub.rpc("review.comment",{thread:n,text:T}).then(()=>{P.value="",A.disabled=!1,u()},()=>{A.disabled=!1})}),l.append(L),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,L)=>{let P=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:L;A.addEventListener("change",()=>{t.hub.rpc("review.tick",{thread:n,index:M}).then(()=>void u(),()=>{})}),P.append(A,z("span",void 0,x.text||x.label||`Item ${L+1}`)),w.append(P)}),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 os(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 An{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,L=[],P=[];for(let M=0;M>>T&1)===1)continue;if(T===x)P.push(M);else L.push(M)}let A=L.concat(P);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=os(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 ls=[{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 cs(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 Ln(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 br=`#version 300 es precision highp float; out vec2 vUv; void main() { @@ -18,7 +19,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); } -`,or=`#version 300 es +`,gr=`#version 300 es precision highp float; in vec2 vUv; uniform vec3 uBgTop; @@ -35,7 +36,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); } -`,lr=`#version 300 es +`,fr=`#version 300 es precision highp float; layout(location = 0) in vec3 aPos; layout(location = 1) in vec3 aNrm; @@ -53,7 +54,7 @@ void main() { vCol = aCol; gl_Position = uMvp * vec4(aPos, 1.0); } -`,cr=`#version 300 es +`,vr=`#version 300 es precision highp float; in vec3 vPos; in vec3 vNrm; @@ -149,8 +150,8 @@ void main() { rgb = rgb / (vec3(1.0) + max(rgb - vec3(0.8), vec3(0.0)) * 0.28); outColor = vec4(linearToSrgb(clamp(rgb, 0.0, 1.0)), alpha * uFade); } -`;function ze(e){let t=e/255;return t<=0.04045?t/12.92:Math.pow((t+0.055)/1.055,2.4)}var 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(` +`;function ze(e){let t=e/255;return t<=0.04045?t/12.92:Math.pow((t+0.055)/1.055,2.4)}var yr=[ze(77),ze(83),ze(94)],wr=[ze(53),ze(58),ze(67)],Er=[ze(245),ze(246),ze(248)],Cr=[ze(225),ze(228),ze(233)];function ds(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 ps(e,t,n){let i=ds(e,e.VERTEX_SHADER,t),s=ds(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 xr(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 kr(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 ms(e){let t=Math.hypot(e[0],e[1],e[2])||1;return[e[0]/t,e[1]/t,e[2]/t]}function us(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 Nn(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=ps(n,br,gr),this.bgVao=n.createVertexArray(),this.uBgTop=n.getUniformLocation(this.bgProg,"uBgTop"),this.uBgBot=n.getUniformLocation(this.bgProg,"uBgBot"),this.prog=ps(n,fr,vr),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=Yi(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,L=1-x/255,P=(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]=P,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]=P,l[V+H*4+1]=A,l[V+H*4+2]=M,l[V+H*4+3]=L;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}=cs(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?Er:yr,V=this.lightTheme?Cr:wr;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=ms([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=ms(us(h,v)),g=us(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,-Nn(u,l),-Nn(g,l),Nn(h,l),1]),w=Math.max(0.05,this.dist*0.01),x=Math.max(this.dist*10,this.radius*20),L=kr(35*Math.PI/180,a/o,w,x),P=xr(L,f);t.useProgram(this.prog),t.uniformMatrix4fv(this.uMvp,!1,P),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 hs=64,Ar=16777216;function Lr(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 Nt(e){if(!e)return"";let t=e.replace(/\\/g,"/").replace(/\/+$/,""),n=t.lastIndexOf("/");return n>=0?t.slice(n+1):t}function bs(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 Mn(e){return e==="board"||e==="schematic"||e==="gerbers"}function Sr(e){return e==="files"||e==="diff"||e==="review"||e==="browser"||e==="terminal"}function Bn(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,L=new Set,P=[],A=0,M=new Map,T=new Map,R={},V=[],H="",ae="",ue=!1,oe=!1,we=0,Le=!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 ls){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(_),O=document.createElement("a");O.href=U;let Z=(He()||f||"view").replace(/[^a-zA-Z0-9._-]/g,"_");O.download=`${Z}-snap.png`,O.click(),setTimeout(()=>URL.revokeObjectURL(U),1000)})}),c.append(W)}async function Se(){if(!g||f!=="board"&&f!=="schematic")return;me();let F=E.compareRequest();if(!F){B="",q="",te="",D="",await Oe(!1);return}let W=`${f}|${F.commit}|${F.bits}|${ae}`;if(W===D&&L.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;L.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 O=await t.hub.rpc("viewer.compare",{thread:g,kind:f,commit:F.commit,bits:F.bits,...ae?{path:ae}:{}});if(_!==w)return;let Z=typeof O?.root==="string"?O.root:"",ee=f==="schematic"?"1":"0";B=Z?`${ee}|${Z}|diff +`:`${ee}|`,q=F.commit,te=U.startsWith("/")||/^[A-Za-z]:[\\/]/.test(U)||!Z?U:`${Z.replace(/\/+$/,"")}/${U.replace(/^\/+/,"")}`,x=!1;let Ce=P;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))Se()});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,Se();else me();k=window.setInterval(()=>{if(!E.playing||f!=="board"&&f!=="schematic"){K(),me();return}if(E.step(-1))Se();else K(),me()},1400)});let O=document.createElement("button");O.type="button",O.className="bp-v-btn",O.textContent=">",O.title="Newer snapshot",O.disabled=E.isLive(),O.setAttribute("data-testid","history-next"),O.addEventListener("click",()=>{if(K(),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(K(),E.goLive())ke("",!1),Se()});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,O,Z,ee);let xe=document.createElement("div");xe.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",()=>{K(),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=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);Se()}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(Pe,Re),u.replaceChildren(W,xe)}async function Ne(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 O=document.createElement("div");if(O.className="bp-v-state-msg",O.textContent=W,U.append(O),_){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 Oe(!0)),U.append(Z)}l.replaceChildren(U)}function ke(F,W){m.textContent=F,m.hidden=!F,m.classList.toggle("is-warn",W)}function He(){if(ae)return Nt(ae);if(f==="board"||f==="3d")return Nt(R.pcb);if(f==="schematic")return Nt(R.sch);if(f==="mech")return Nt(H);return""}function re(){s.textContent=bs(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 O=document.createElement("option");O.value=U,O.textContent=Nt(U),O.selected=U===H,_.append(O)}_.addEventListener("change",()=>{H=_.value,re(),Oe(!1)}),o.append(_)}if(Mn(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,h.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 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 Pe=document.createElement("button");Pe.type="button",Pe.className="bp-v-btn"+(I?.layerMode===xe?" is-on":""),Pe.textContent=Ce,Pe.addEventListener("click",()=>void _e("mode",String(xe))),ee.append(Pe)}),F.append(ee)}let U=le?.presentColors()??new Map,O=(I.layerList||[]).concat(I.layerMarks||[]),Z=document.createElement("div");Z.className="bp-v-layers-list";for(let ee of O){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 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=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(Pe,Re,Ie),Z.append(xe)}F.append(Z),h.replaceChildren(F)}async function _e(F,W){if(!Mn(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 O={off:Number(U.off)||0,dim:Number(U.dim)||0,lift:typeof U.lift==="number"?U.lift:255};if(le?.setLayers(O),re(),Le)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=[],O="",Z="";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")&&!O)O=qe;if(Be==="net"&&!Z)Z=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 Pe=document.createElement("div");Pe.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,Pe.append(Be)}return v.replaceChildren(ee,...U.length>0?[Pe]:[]),v.hidden=!1,{ref:O||void 0,net:Z||void 0}}async function Je(F){if(!F){de();return}let W=Array.from(L)[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 O=typeof U.info==="string"?U.info:"";if(!O){de();return}let{ref:Z,net:ee}=mt(O),Ce=[];if(Z)Ce.push(["ref",Z]);if(ee)Ce.push(["net",ee]);let xe=[[F.at,F.idx]];for(let[Pe,Re]of Ce){let ye=await t.hub.rpc("viewer.probe",{key:W,name:Pe,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(),Le=!1,h.hidden=!0,v.hidden=!0,v.replaceChildren(),ke("",!1),ie("none")}function Ye(){P=[],A=0}async function Oe(F){if(!g||!f)return;let W=++w;if(L.clear(),x=!1,Ye(),ut(),re(),je(),me(),(f==="board"||f==="schematic")&&g)Ne(g);if(Sr(f)){if(t.hub.rpc("viewer.watch",{thread:g,kind:""}).catch(()=>{}),f==="files")X=ss(p,t,g,(O,Z)=>{if(f=O,ae=Z,O==="mech")H=Z;Oe(!1)});else if(f==="diff")X=rs(p,t,g);else if(f==="review")X=as(p,t,g);else if(f==="browser")X=ts(p,t,g);else if(f==="terminal")ie("loading","Loading terminal…"),import("/assets/terminal.js").then((Z)=>{if(W!==w)return;if(ie("none"),Z?.mountTerminalPane)ce=Z.mountTerminalPane(p,t,g,Y());else ie("error","Terminal chunk missing",!0)},(Z)=>{if(W!==w)return;ie("error",Z instanceof Error?Z.message:String(Z),!0)});return}if(ie("loading","Loading…"),!R.root)try{let O=await t.hub.rpc("viewer.files",{thread:g});if(W!==w)return;R=O||{},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:(O,Z)=>{if(Z)ie("none"),ke(O,!1);else if(O)ie("loading",O);else ie("none"),ke("",!1)},onUserMove:()=>void Ue()}),ne.setTheme(_);else if(f==="board"||f==="schematic"||f==="gerbers")le=new An(p,{onPick:(O)=>void Je(O),onUserMove:()=>void Ue()}),le.setTheme(_);else{ie("empty",`${bs(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 O=await t.hub.rpc("mech.list",{thread:g});if(W!==w)return;if(V=Array.isArray(O.parts)?O.parts:[],!H)H=O.primary||V[0]||"";re()}catch(O){if(W!==w)return;ie("error",O instanceof Error?O.message:String(O),!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 O=ne.keptToken();if(O)U.kept=O}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 O=await t.hub.rpc("viewer.watch",U);if(W!==w)return;L=new Set(Array.isArray(O.keys)?O.keys:[]),x=!1;let Z=P;Ye();for(let ee of Z)if(ee.kind==="bin")$e(ee.buf);else We(ee.key,ee.none,ee.retryable)}catch(O){if(W!==w)return;x=!1,L.clear(),Ye();let Z=O instanceof Error?O.message:String(O),ee=/no gerbers|not in this project|another machine/i.test(Z);ie(ee?"empty":"error",Z,!ee)}}function We(F,W,_){if(x){if(P.length{if(F.t==="plot"&&typeof F.none==="string"&&typeof F.key==="string")We(F.key,F.none,F.retryable===!0)}),Ge=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="",Oe(!1)},reconcileHas(F){if(f&&!Lr(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="",L.clear(),ut()}}}var gs="http://www.w3.org/2000/svg";function Pt(e){let t=document.createElementNS(gs,"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(gs,"path");i.setAttribute("d",n),t.appendChild(i)}return t}function Nr(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 fs(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 vs(e){if(!e)return;let t=e==="light";document.documentElement.classList.toggle("light",t);try{localStorage.setItem("bp.theme",t?"light":"dark")}catch{}}function Pr(){return`web-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`}function ys(){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(Pt(["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(Pt(["M12 22a10 10 0 1 0 0-20 10 10 0 0 0 0 20z","M9 12l2 2 4-4"]),x);let L=document.createElement("div");L.className="bp-menu-wrap";let P=document.createElement("button");P.type="button",P.className="bp-btn-ghost bp-top-act",P.textContent="▾",P.title="Thread menu",P.setAttribute("aria-label","Thread menu"),P.setAttribute("data-testid","thread-menu-btn");let A=document.createElement("div");A.className="bp-popover bp-hidden",A.setAttribute("data-testid","thread-menu"),L.append(P,A),u.append(g,w,L);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(Pt(["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(Pt(["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(Pt(["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 Le=document.createElement("div");Le.className="bp-right-area bp-hidden",Le.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),Le.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,Le,be),e.append(t,ue);let I=new xn,le=null,ne=new Set,X=0,ce=null,E=[],k=[],j=[],B=[],q=[],te=[],D="",K=0,je=0,Se=null,me=null,Ne="",Y=null,ve=20,ie={},ke=new Map;function He(y,C){ke.delete(y),ke.set(y,C);while(ke.size>ve){let S=ke.keys().next().value;if(S!==void 0)ke.delete(S);else break}}let re=new wn(oe,{onSelectThread:(y)=>{if(y===D&&Se!==null){oe.classList.remove("bp-sidebar-open");return}Ie(y)},onNewThread:(y)=>{It(y)},onSelectBot:(y)=>{Ie(y.thread)},onQuickOpenViewer:(y,C)=>{let S=k.find((G)=>G.project===y&&!G.archived&&!G.swarm);(async()=>{if(S)await Ie(S.id);else await It(y);if(D)Ne=C,$e.setActive(C),Y?.open(C,D)})()},onThreadAct:(y,C)=>{Qe(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=Wt(y,!1);if(!C)return;if(C.kind==="thread"){Ie(C.id);return}if(C.kind!=="call")return;let S=Fi(await I.rpc(C.method,C.params));if(S?.kind==="thread")Ie(S.id);ye()},hasRoomView:!1,onAddProject:()=>We.open({mode:"folder"})}),ge=new tn(we,{onLoadOlder:()=>{Ke()},onGoToEntry:(y)=>{Tt(y)},onOpenAccounts:()=>{F()},onAnswerAsk:(y,C)=>{I.rpc("ask.answer",{ask:y,answer:C}).catch((S)=>{de.showError(S instanceof Error?S.message:"Could not send answer")})},onToggleReview:(y)=>{if(!D)return;let C=K;I.rpc("thread.review",{thread:D,on:y}).then((S)=>{if(C===K)ge.setReview(S.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(); +`);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 S={entry:y,path:C};if(I.hasFeature("blobs"))S.metaOnly=!0;let N=await I.rpc("message.image",S);if(N.blob&&N.blob.startsWith("/blob/"))return{url:N.blob};if(N.mime&&N.data)return{mime:N.mime,data:N.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 S=K,N=D;I.rpc(y,C).then((G)=>{if(S!==K||D!==N)return;if(G.thread){let Q=k.findIndex((fe)=>fe.id===G.thread.id);if(Q>=0)k[Q]=G.thread;else k.unshift(G.thread);re.setData(E,k,j,B),ge.updateThreadMeta(G.thread),O(),de.setState(!0,G.thread.state==="working")}}).catch((G)=>{if(S===K&&D===N)de.showError(G instanceof Error?G.message:"Could not change Plan mode")})}let nt,de=new sn(we,{onSend:(y,C)=>{In(y,C)},onRunCommand:(y)=>{Rn(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((S)=>S.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 En(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=Ne!=="",C=Je.isOpen();Le.classList.toggle("bp-hidden",!y&&!C),Le.classList.toggle("bp-has-viewer",y),Le.classList.toggle("bp-has-mgmt",C)}let Je=new mn(Me,Le,{hub:I,getThreadId:()=>D,getThreadGen:()=>K,onSendText:(y)=>{In(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((S)=>{if(S.thread)k=k.map((N)=>N.id===S.thread.id?S.thread:N),O(),ye()}).catch((S)=>{de.showError(S instanceof Error?S.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(Ne===y.id)Z();else ee(y.id);break;case"thread-act":if(D)Qe(D,y.action);break;case"new-thread":It(y.projectId);break;case"rename":{let C=k.find((S)=>S.id===D);if(C)ut(C);break}case"prev-thread":case"next-thread":{let C=k.filter((Q)=>!Q.archived&&!Q.swarm);if(C.length<2)break;let S=C.findIndex((Q)=>Q.id===D),N=y.type==="next-thread"?1:-1,G=C[(S<0?0:S+N+C.length)%C.length];if(G)Ie(G.id);break}case"command":if(y.runDirectly)Rn(y.word);else de.setDraft(`${y.word} `),de.focus();break;case"improvements":U();break;case"settings":Ge.open();break;case"sidebar":oe.classList.toggle("bp-sidebar-open"),oe.classList.toggle("bp-sidebar-collapsed");break}}let Oe=new un(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 Zt(e,{hub:I,onProjectAdded:(y)=>{if(ye(),y.id)It(y.id)},onCloneDone:(y)=>{if(ye(),y.thread)Ie(y.thread)}}),$e=new bn(be,(y)=>{if(y==="commands"){Oe.open();return}if(!D)return;if(Ne===y)Z();else ee(y)}),it=null,Mt=null,Ge=new gn(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:()=>Yn(()=>{I.disconnect(),window.location.replace("/")})});function Bt(y){if(Mt=y,ge.setNoProvider(y),Ge.isOpen())Ge.refresh()}function F(){Ge.openToAccounts()}function W(y,C){let S=y instanceof Error?y.message:C,N=y instanceof St?y:null,G=N?.code,Q=N?.machine,fe=G==="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):S;de.showError(fe,Ri(S,G)?{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)Qe(y.id,y.pinned?"unpin":"pin")}),w.addEventListener("click",()=>{let y=k.find((C)=>C.id===D);if(y)Qe(y.id,y.settled?"unsettle":"settle")});let _=new vn(e,(y,C)=>C?I.rpc("thread.context.mcp",{thread:y,...C}):I.rpc("thread.context",{thread:y}));P.addEventListener("click",(y)=>{y.stopPropagation();let C=k.find((G)=>G.id===D);if(!C)return;if(!A.classList.contains("bp-hidden")){A.classList.add("bp-hidden");return}let S=[{label:"Rename…",run:()=>ut(C)},{label:C.pinned?b("menu.unpin","Unpin"):b("menu.pin","Pin"),run:()=>{Qe(C.id,C.pinned?"unpin":"pin")}},{label:C.settled?b("phone.unsettle","Unsettle"):b("menu.settle","Settle"),run:()=>{Qe(C.id,C.settled?"unsettle":"settle")}},{label:C.archived?"Unarchive":"Archive",run:()=>{Qe(C.id,C.archived?"unarchive":"archive")}},{label:"Delete",danger:!0,run:()=>{if(window.confirm("Delete this thread?"))Qe(C.id,"delete")}}];if(I.hasFeature("threadContext"))S.unshift({label:b("thread.context.title","Context & Prompt"),run:()=>_.open(C.id)});let N=document.createDocumentFragment();for(let G of S){let Q=document.createElement("button");Q.type="button",Q.className="bp-popover-item"+(G.danger?" danger":""),Q.textContent=G.label,Q.addEventListener("click",()=>{A.classList.add("bp-hidden"),G.run()}),N.appendChild(Q)}A.replaceChildren(N),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 S=document.createElement("div");S.className="bp-modal-head";let N=document.createElement("h2");N.textContent=b("gpui.improvements","Improvements");let G=document.createElement("button");G.type="button",G.className="icon",G.textContent="×",G.addEventListener("click",()=>y.remove()),S.append(N,G);let Q=document.createElement("div");Q.className="bp-modal-body",Q.textContent="Loading…",C.append(S,Q),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){Q.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)}Q.replaceChildren(et)}catch(fe){Q.textContent=fe instanceof Error?fe.message:"Could not load Improvements."}}T.addEventListener("click",()=>{U()}),V.addEventListener("click",()=>Oe.open()),H.addEventListener("click",()=>Oe.open()),ae.addEventListener("click",()=>{Ge.open()}),n.addEventListener("click",()=>{oe.classList.toggle("bp-sidebar-open"),oe.classList.toggle("bp-sidebar-collapsed")});function O(){let y=k.find((N)=>N.id===D)??null,C=y?E.find((N)=>N.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 S=_e(y);if(de.setPlanMode(S),!S||S.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",S.phase==="executing"),d.title=b("gpui.planmode.tip","Plan before acting (1 turn, always, or off)"),d.textContent=S.phase==="armed"&&S.once?b("gpui.planmode.top.once","Plan (1 turn)"):S.phase==="armed"?b("gpui.mgmt.plan.tab","Plan"):S.phase==="planning"?b("gpui.planmode.top.planning","Planning"):S.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 ${Nr(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 N=y;de.setModelChip(y.chip||y.model||"default",y.provider,N.ctxPct??N.contextPct),de.setMemory(y.memory)}else de.setModelChip("default"),de.setMemory(null)}function Z(y=!0){if(je++,Ne="",$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++,Ne=y,$e.setActive(y),he.classList.remove("bp-hidden"),mt(),!Y&&typeof Bn==="function")Y=Bn(he,{hub:I,getThreadId:()=>D,closeViewer:()=>Z(!0)});if(Y)Y.open(y,D);else{let C=document.createElement("div");C.className="bp-viewer-placeholder";let S=document.createElement("div");S.className="bp-viewer-bar";let N=document.createElement("span");N.textContent=y.toUpperCase();let G=document.createElement("button");G.type="button",G.className="icon",G.textContent="×",G.addEventListener("click",()=>Z(!0)),S.append(N,G);let Q=document.createElement("div");Q.className="bp-dim bp-viewer-msg",Q.textContent=`Viewer pane (${y}).`,C.append(S,Q),he.replaceChildren(C)}}async function Ce(y,C){if(!y||!I.hasFeature("rail")){if(C===K)q=[],$e.setItems([]);return}let S=++je;try{let N=await I.rpc("viewer.rail",{thread:y,page:Ne});if(C!==K||S!==je)return;let G=Array.isArray(N.rail)?N.rail:Array.isArray(N.items)?N.items:[];if(q=G,$e.setItems(G),N.has){if(Y?.reconcileHas?.(N.has),Ne&&!fs(N.has,Ne))Z(!0)}}catch{if(C===K&&S===je)q=[],$e.setItems([])}}function xe(y){for(let C of y)if(C.kind==="threads"){for(let S of C.rows)if(!S.off&&(S.nav||S.id)&&!(S.nav||"").startsWith("@room:"))return S.nav||S.id}else if(C.kind==="projects"){for(let S of C.rows)for(let N of S.threads??[])if(!N.off&&(N.nav||N.id)&&!(N.nav||"").startsWith("@room:"))return N.nav||N.id}return""}function Pe(y,C){for(let S of y)if(S.kind==="threads"){if(S.rows.some((N)=>(N.nav||N.id)===C))return!0}else if(S.kind==="projects"){for(let N of S.rows)if((N.threads??[]).some((G)=>(G.nav||G.id)===C))return!0}return!1}function Re(y){let C=[];for(let S of y){if(S.kind!=="projects")continue;for(let N of S.rows)C.push({id:N.id,title:N.title,css:N.css,color:N.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 S=Array.isArray(C.sections)?C.sections:[];return le=S,Re(S),re.setData(E,k,j,B),re.setSections(S,j,B),O(),!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(Se=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}),S=new Set(C.removed??[]),N=new Set((C.projects??[]).map((G)=>G.id));if(S.size>0||N.size>0)E=[...E.filter((G)=>!S.has(G.id)&&!N.has(G.id)),...C.projects??[]],k=[...k.filter((G)=>!S.has(G.project)&&!N.has(G.project)),...C.threads??[]];else if(Array.isArray(C.threads)&&C.threads.length>0){let G=new Map(k.map((Q)=>[Q.id,Q]));for(let Q of C.threads)G.set(Q.id,Q);k=Array.from(G.values())}if(C.sections!==void 0){let G=Array.isArray(C.sections)?C.sections:Array.isArray(C.sections?.sections)?C.sections.sections:null;if(G)le=G,Re(G)}if(C.h)ie=C.h;re.setData(E,k,j,B),re.setSections(le,j,B)}else if(I.hasFeature("sections")){let[C,S]=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=S.threads??[],C&&Array.isArray(C.sections)){let N=C.sections;if(!N.some((Q)=>Q.kind==="projects"&&Q.rows.length>0)){let Q=N.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))N=fe.sections}}le=N,Re(N),re.setData(E,k,j,B),re.setSections(N,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,S]=await Promise.all([I.rpc("projects.list",{limit:100}),I.rpc("threads.list",{limit:200,archived:!1})]);E=C.projects??[],k=S.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&&Pe(le,C)||k.some((S)=>S.id===C)))y=C;else if(le)y=xe(le);if(!y)y=(k.find((N)=>!N.archived&&!N.swarm&&!N.settled)??k.find((N)=>!N.archived&&!N.swarm))?.id??""}if(y&&(le&&Pe(le,y)||k.some((C)=>C.id===y)))await Ie(y);else D="",q=[],$e.setItems([]),de.setState(!1,!1),O()}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 S=Se;if(Se=null,S!==null)I.rpc("unsubscribe",{sub:S}).catch(()=>{});D=y;let N=ke.get(y);me=N?.olderCursor??null;try{localStorage.setItem("bp.lastThread",y)}catch{}re.setSelected(y),oe.classList.remove("bp-sidebar-open"),O();let G=k.find((Ae)=>Ae.id===y)??null;if(N)ge.setThread(G,N.entries,Boolean(N.olderCursor),N.review,N.unanswered),q=N.rail,$e.setItems(N.rail);else ge.setLoading(G),q=[],$e.setItems([]);if(de.setState(!0,G?.state==="working"),I.hasFeature("open")){let Ae={};if(N){for(let[Te,ft]of Object.entries(N.hashes))Ae[Te]=ft;for(let Te of N.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(G,ft,()=>{Ie(y)})}return}if(C!==K){if(se.sub!==void 0&&se.sub!==null)I.rpc("unsubscribe",{sub:se.sub}).catch(()=>{});return}if(Se=se.sub??null,se.thread){G=se.thread;let Te=k.findIndex((ft)=>ft.id===se.thread.id);if(Te>=0)k[Te]=se.thread;else k.unshift(se.thread);O(),de.setState(!0,G.state==="working")}if("next"in se)me=se.next??null;let Xe=new Map;if(N)for(let Te of N.entries)Xe.set(Te.id,Te);for(let Te of se.entries??[])Xe.set(Te.id,Te);let tt=se.ids??N?.ids??(se.entries??[]).map((Te)=>Te.id),Hn=tt.map((Te)=>Xe.get(Te)).filter((Te)=>Boolean(Te)),gt=N?.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),Ne&&!fs(se.rail.has,Ne))Z(!0)}}q=gt,$e.setItems(gt);let qt=N?.review??null;if(I.hasFeature("reviewmode"))try{let Te=await I.rpc("thread.review",{thread:y});if(C!==K)return;qt=Te.review??null}catch{}if(C!==K)return;let Dn="unanswered"in se?se.unanswered??null:N?.unanswered??null,ws=se.h??N?.hashes??{};if(He(y,{entries:Hn,ids:tt,olderCursor:me,review:qt,unanswered:Dn,rail:gt,hashes:ws}),ge.setThread(G,Hn,Boolean(me),qt,Dn),ht(y,C),Ne)ee(Ne);return}let Q;try{Q=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(G,se,()=>{Ie(y)})}return}if(C!==K)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);O()}me=Q.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=Q.entries??[],et=Q.unanswered??null;He(y,{entries:De,ids:De.map((Ae)=>Ae.id),olderCursor:me,review:fe,unanswered:et,rail:N?.rail??[],hashes:N?.hashes??{}}),ge.setThread(G,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}Se=se}}catch{}if(C!==K)return;if(Ce(y,C),ht(y,C),Ne)ee(Ne)}async function ht(y,C){if(!y||!I.hasFeature("mgmt")){if(C===K)Je.clear();return}let S=k.find((G)=>G.id===y),N=S?.project?E.find((G)=>G.id===S.project)?.root??"":"";if(!N&&I.hasFeature("viewers"))try{let G=await I.rpc("viewer.files",{thread:y});if(C!==K)return;N=G.pcb||G.sch||G.root||""}catch{}if(C!==K)return;if(N)await Je.watchProject(N);else Je.clear()}async function Tt(y){let C=K;for(let S=0;S<25&&C===K;S++){if(ge.goTo(y))return;if(!me)return;let N=me;if(await Ke(),me===N)return}}async function Ke(){if(!D||!me){ge.clearLoadingOlder();return}let y=K,C=D,S=me;try{let N=await I.rpc("thread.entries",{thread:C,limit:40,before:S});if(y!==K||D!==C)return;me=N.next??null,ge.prependEntries(N.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((S)=>S.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 Tn(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:Tn(y.text)}:null,()=>{if(ot)Tt(ot.id)},()=>bt(null))}async function In(y,C=[]){if(!D)return;let S=K,N=D,G=Pr(),Q=`local-${G}`,fe=ot&&y.trim()&&I.hasFeature("reply")?ot:null;if(fe)bt(null);ge.upsertEntry({id:Q,kind:"user",text:y,at:Date.now(),clientId:G,...fe?{replyTo:{id:fe.id,quote:Tn(fe.text)}}:{},attachments:C.map((De)=>({name:De.name,mime:De.mime,previewUrl:`data:${De.mime};base64,${De.data}`}))});try{let De={thread:N,text:y,clientId:G};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(S!==K||D!==N)return;if(et.entry)ge.upsertEntry(et.entry)}catch(De){if(S===K&&D===N){if(ge.removeEntry(Q),de.setDraft(y),fe&&!ot)bt(fe);W(De,"Failed to send message")}}}async function Rn(y){if(!D)return;let C=K,S=D;try{let N=await I.rpc("composer.run",{thread:S,text:y});if(C!==K||D!==S)return;if(N.error)de.setDraft(y),W(new St(N.error,{code:N.errorCode,machine:N.machine}),N.error);else if(N.kind==="btw"&&typeof N.a==="string")ge.showBtw(N.q??"",N.a);else if(N.kind==="edit"&&typeof N.text==="string")de.setDraft(N.text);else if(N.kind==="project")We.open({mode:"folder"});else if(N.kind==="clone")We.open({mode:"clone",repo:N.repo??"",text:N.text??""})}catch(N){if(C===K&&D===S)de.setDraft(y),W(N,"Command refused")}}async function Qe(y,C){try{let S=await I.rpc("thread.act",{thread:y,action:C});if(S.thread){if(k=k.map((N)=>N.id===S.thread.id?S.thread:N),re.setData(E,k,j,B),S.thread.id===D)ge.updateThreadMeta(S.thread),O()}ye()}catch(S){de.showError(S instanceof Error?S.message:`Action "${C}" not allowed`)}}function jn(y,C){if(!y||!y.text||C-y.at>=300000)return"";let S=y.build.split("-").pop()??"";if(y.reason==="build"&&S)return b("hub.restarting.build",y.text,{build:S});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"&&jn(I.restarting,Date.now()))re.setConnStatus(jn(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")),O(),re.refreshLocale(),ge.refreshLocale(),de.refreshLocale(),$e.render(),Ge.refreshLocale(),We.refreshLocale()}),I.onState((y,C)=>{if(y==="connected"&&C){if(C.locale)Un(C.locale);if(C.theme)vs(C.theme);if(C.name)re.setHostName(C.name);if(it=C.home??null,re.setHome(it),Bt(hn(C.noProvider)),Ge.isOpen())Ge.refresh();Rt(y);let S=typeof C.hubBack==="string"?String(C.hubBack):"";if(S)try{let N=JSON.parse(S);if(N.reason==="crash")re.setConnStatus(b("hub.back.crash",N.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 S=y.info;if(Object.prototype.hasOwnProperty.call(S,"provider.notice"))Bt(hn(S["provider.notice"]));Je.handleInfo(S);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 S=C.project;if(!S)break;let N=E.findIndex((G)=>G.id===S.id);if(N>=0)E[N]=S;else E.unshift(S);re.setData(E,k,j,B),O(),Be();break}case"thread":{let S=C.thread;if(!S)break;let N=k.findIndex((G)=>G.id===S.id);if(N>=0)k[N]=S;else k.unshift(S);if(re.setData(E,k,j,B),S.id===D)ge.updateThreadMeta(S),O(),de.setState(!0,S.state==="working");Be();break}case"thread.removed":{let S=String(C.id??"");k=k.filter((N)=>N.id!==S),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 S=String(C.state??"idle");de.setState(!0,S==="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")vs(C.theme);break}case"home":{if(it=C.home??null,re.setHome(it),Ge.isOpen())Ge.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(),Oe.isOpen())Oe.close();else Oe.open();else if(y.key==="Escape"){if(Oe.isOpen())Oe.close();else if(We.isOpen())We.escape();else if(Ge.isOpen())Ge.close();else if(ge.closePlanRevise());else if(Je.isOpen())Je.closePanel()}}),I.connect()}if(document.readyState==="loading")document.addEventListener("DOMContentLoaded",ys);else ys(); diff --git a/web/dist/assets/pair.js b/web/dist/assets/pair.js index db0d012865..b68f31be74 100644 --- a/web/dist/assets/pair.js +++ b/web/dist/assets/pair.js @@ -1 +1 @@ -var U={en:{"agy.signout":"Sign out","android.hub.machines.approve":"Approve","android.load.earlier":"load earlier","approval.dismiss":"Dismiss","approval.implement":"Implement","ask.plan":"Proposed plan","bots.new":"New bot","bots.rooms":"Rooms","bots.tab.browser":"Browser","common.cancel":"Cancel","common.close":"Close","common.copy":"Copy","common.delete":"Delete","common.refresh":"Refresh","common.remove":"Remove","common.save":"Save","composer.placeholder":"Ask anything: @bot, >thread, %project, #room, $skill, /btw","composer.send":"Send","composer.stop":"Stop","gpui.acct.connected":"Connected","gpui.acct.not.connected":"Not connected","gpui.acct.sign.in.expired":"Sign-in expired","gpui.ask.plan.ready":"Ready for review","gpui.ask.plan.revise":"Revise","gpui.ask.plan.reviseph":"What should change in the plan?","gpui.ask.plan.sendrev":"Send revision","gpui.b.in.reply.to":"↩ In reply to: {quote}","gpui.b.replying.to":"↩ Replying to: {line}","gpui.bots.recall.off":"Off","gpui.bots.recall.on":"On","gpui.c.term.collapse":"Collapse","gpui.c.term.expand":"Expand","gpui.commands":"Commands","gpui.e.open.folder":"Open folder","gpui.filter.projects.and.threads":"Filter projects and threads","gpui.fold.or.unfold.the.sidebar":"Fold or unfold the sidebar","gpui.follow.paused":"Following paused","gpui.follow.wait":"Following: waiting for the agent's next edit","gpui.gerbers":"Gerbers","gpui.improvements":"Improvements","gpui.jump.to.a.thread.run":"Jump to a thread, run a command or find what was said","gpui.mgmt.bom.dnp":"DNP","gpui.mgmt.bom.nompn":"no MPN","gpui.mgmt.checks.all":"All","gpui.mgmt.checks.fix":"Fix with agent","gpui.mgmt.checks.run":"Run","gpui.mgmt.close":"Close the panel","gpui.mgmt.fab.apply":"Apply","gpui.mgmt.fab.changed":"Changed since you last looked","gpui.mgmt.fab.derived":"* worked out from the fab's page (a mil in mm, a ring from a diameter). Dimmed: the rigid board's value, where this board's page says nothing else. A date opens the page it was read from.","gpui.mgmt.fab.extra":"Costs more","gpui.mgmt.fab.findings":"Findings","gpui.mgmt.fab.free":"Base price","gpui.mgmt.fab.judge":"Datasheets","gpui.mgmt.fab.limit":"Limit","gpui.mgmt.fab.readcol":"Read","gpui.mgmt.fab.refresh":"Refresh","gpui.mgmt.fab.reviewbtn":"Review","gpui.mgmt.fab.seen":"Seen","gpui.mgmt.fab.thefab":"The fab","gpui.mgmt.fab.use":"Use","gpui.mgmt.life.nopart":"No reading of this part yet.","gpui.mgmt.life.reading":"Reading its history…","gpui.mgmt.plan.addnote":"Add note","gpui.mgmt.plan.all":"Approve all","gpui.mgmt.plan.before":"Plan before routing","gpui.mgmt.plan.compact":"Compact","gpui.mgmt.plan.done":"done","gpui.mgmt.plan.drawn":"The plan's corridors and planes are drawn on the board while this panel is open. Close it to hide them.","gpui.mgmt.plan.edited":"Edited","gpui.mgmt.plan.elsewhere":"A routing plan for {board} awaits your approval","gpui.mgmt.plan.emptysub":"Layers, corridors, and planes appear here once a plan is proposed.","gpui.mgmt.plan.expand":"Expand","gpui.mgmt.plan.fit":"Fit","gpui.mgmt.plan.grid.all":"All layers","gpui.mgmt.plan.grid.pair":"Side by side","gpui.mgmt.plan.grid.single":"Single","gpui.mgmt.plan.hide":"Hide done","gpui.mgmt.plan.hint":"Drag waypoints to steer · Click + on edge to insert · Right-click vertex to remove","gpui.mgmt.plan.keysnote":"On this KiCad version, approve from this panel: in plan view KiCad's A, R and W keys aren't the plan's yet (A opens Add Footprint). Update KiCad.","gpui.mgmt.plan.layer":"Approve layer","gpui.mgmt.plan.layer.short":"Layer","gpui.mgmt.plan.lock":"Lock","gpui.mgmt.plan.locked":"Locked","gpui.mgmt.plan.noboard":"No routing plan for this board.","gpui.mgmt.plan.noitems":"No corridors or planes on this layer","gpui.mgmt.plan.note.placeholder":"Steering note for router…","gpui.mgmt.plan.nothing":"Nothing awaits your approval","gpui.mgmt.plan.offwords":"Agents route as you ask. Turn it on to have them propose a routing plan first and route only what you approve here.","gpui.mgmt.plan.onwords":"Before routing a board with 4 or more copper layers or more than 60 nets, the agent proposes corridors and plane regions here. It routes only what you approve.","gpui.mgmt.plan.reading":"Reading the routing plan…","gpui.mgmt.plan.reference":"over {layer}","gpui.mgmt.plan.refused":"KiCad refused","gpui.mgmt.plan.reject":"Reject","gpui.mgmt.plan.rejectlayer":"Reject layer","gpui.mgmt.plan.reqplain":"Approval requested","gpui.mgmt.plan.requested":"Approval requested: {what}","gpui.mgmt.plan.saved":"saved plan","gpui.mgmt.plan.show":"Show done","gpui.mgmt.plan.st.approved":"Approved","gpui.mgmt.plan.st.awaiting":"Awaiting review","gpui.mgmt.plan.st.blocked":"Blocked","gpui.mgmt.plan.st.empty":"Empty","gpui.mgmt.plan.st.partial":"Partial","gpui.mgmt.plan.st.rejected":"Rejected","gpui.mgmt.plan.st.routed":"Routed","gpui.mgmt.plan.st.routing":"Routing","gpui.mgmt.plan.st.verified":"Verified","gpui.mgmt.plan.stackup.short":"Stackup","gpui.mgmt.plan.stop":"Stop routing","gpui.mgmt.plan.sync":"Link zoom","gpui.mgmt.plan.tab":"Plan","gpui.mgmt.plan.unlock":"Unlock","gpui.mgmt.plan.verify":"Verify","gpui.mgmt.plan.view.canvas":"Canvas","gpui.mgmt.plan.view.list":"List","gpui.mgmt.plan.view.split":"Split","gpui.mgmt.plan.width":"Width","gpui.next.thread":"Next thread","gpui.nothing.matches":"Nothing matches","gpui.planmode.bar.always":"Plan mode — explores and proposes a plan before editing","gpui.planmode.bar.executing":"Building the approved plan","gpui.planmode.bar.once":"Plan mode (1 turn) — explores and proposes a plan before editing","gpui.planmode.bar.pending":"Proposed plan awaits review below","gpui.planmode.bar.planning":"Planning — drafting a plan before edits","gpui.planmode.chip.building":"Building","gpui.planmode.chip.once":"Plan · 1t","gpui.planmode.scope.always":"Always","gpui.planmode.scope.once":"1 turn","gpui.planmode.tip":"Plan before acting (1 turn, always, or off)","gpui.planmode.top.executing":"Building plan","gpui.planmode.top.once":"Plan (1 turn)","gpui.planmode.top.pending":"Review plan","gpui.planmode.top.planning":"Planning","gpui.previous.thread":"Previous thread","gpui.rail.no.board":"No board in this project","gpui.rail.no.mech":"No mechanical parts in this project","gpui.rail.no.schematic":"No schematic in this project","gpui.rail.split.needs.both":"Split needs a board and a schematic","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(); +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","native.thread.model":"Model","notify.settled":"Settled","palette.archive":"Archive thread","palette.command.placeholder":"Type a command or a thread","palette.diff":"Diff: what this thread changed","palette.newthread":"New thread","palette.settings":"Settings","palette.terminal":"Terminal","palette.unarchive":"Unarchive thread","phone.unsettle":"Unsettle","provider.notice.button":"Open Settings → Accounts","provider.notice.head":"No AI provider connected","provider.notice.senderr":"No AI provider connected yet. Open Settings → Accounts to connect Claude, Codex, Antigravity, or another provider.","provider.notice.senderr.remote":"No AI provider connected on {machine}. Open Settings → Accounts on {machine} to connect Claude, Codex, Antigravity, or another provider.","provider.notice.text.none":"Connect Claude, Codex, Antigravity, or another provider to start chatting.","provider.notice.text.signedout":"Sign in to Claude, Codex, or another provider in Settings → Accounts to start chatting.","reply.action":"Reply","reply.cancel":"Cancel reply","reply.to":"In reply to:","rooms.new":"New room","secret.you":"You","settings.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","native.thread.model":"Modelo","notify.settled":"Cerrado","palette.archive":"Archivar hilo","palette.command.placeholder":"Escribe un comando o un hilo","palette.diff":"Diff: qué cambió este hilo","palette.newthread":"Nuevo hilo","palette.settings":"Ajustes","palette.terminal":"Terminal","palette.unarchive":"Desarchivar hilo","phone.unsettle":"Reabrir","provider.notice.button":"Abrir Configuración → Cuentas","provider.notice.head":"No hay ningún proveedor de IA conectado","provider.notice.senderr":"Aún no hay ningún proveedor de IA conectado. Abre Configuración → Cuentas para conectar Claude, Codex, Antigravity u otro proveedor.","provider.notice.senderr.remote":"No hay ningún proveedor de IA conectado en {machine}. Abre Configuración → Cuentas en {machine} para conectar Claude, Codex, Antigravity u otro proveedor.","provider.notice.text.none":"Conecta Claude, Codex, Antigravity u otro proveedor para empezar a chatear.","provider.notice.text.signedout":"Inicia sesión en Claude, Codex u otro proveedor en Configuración → Cuentas para empezar a chatear.","reply.action":"Responder","reply.cancel":"Cancelar respuesta","reply.to":"En respuesta a:","rooms.new":"Nueva sala","secret.you":"Tú","settings.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":"エージェント","native.thread.model":"モデル","notify.settled":"完了","palette.archive":"スレッドをアーカイブ","palette.command.placeholder":"コマンドまたはスレッドを入力","palette.diff":"差分:このスレッドの変更","palette.newthread":"新しいスレッド","palette.settings":"設定","palette.terminal":"ターミナル","palette.unarchive":"スレッドのアーカイブを解除","phone.unsettle":"未完了に戻す","provider.notice.button":"設定 → アカウントを開く","provider.notice.head":"AI プロバイダーが接続されていません","provider.notice.senderr":"AI プロバイダーがまだ接続されていません。設定 → アカウントを開いて、Claude、Codex、Antigravity などのプロバイダーを接続してください。","provider.notice.senderr.remote":"{machine} に AI プロバイダーが接続されていません。{machine} で設定 → アカウントを開いて、Claude、Codex、Antigravity などのプロバイダーを接続してください。","provider.notice.text.none":"チャットを始めるには、Claude、Codex、Antigravity などのプロバイダーを接続してください。","provider.notice.text.signedout":"チャットを始めるには、設定 → アカウントで Claude、Codex などのプロバイダーにサインインしてください。","reply.action":"返信","reply.cancel":"返信をやめる","reply.to":"返信先:","rooms.new":"新しいルーム","secret.you":"あなた","settings.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 dc300045fd..bbe7d4ff6f 100644 --- a/web/dist/assets/style.css +++ b/web/dist/assets/style.css @@ -857,6 +857,25 @@ button.bp-proj-quick:hover { color: var(--accent); } } .bp-entry-body { color: var(--text); word-break: break-word; } .bp-entry-user .bp-entry-body { white-space: pre-wrap; } +.bp-ref-chip { + display: inline-flex; + align-items: baseline; + gap: 5px; + padding: 0 6px; + margin: 0 1px; + border: 1px solid var(--line); + background: var(--bg); + font-size: 12px; + line-height: 1.45; + vertical-align: baseline; + white-space: nowrap; + max-width: 100%; + user-select: all; + -webkit-user-select: all; +} +.bp-ref-sigil { font-weight: 700; color: var(--ok); flex-shrink: 0; } +.bp-ref-label { color: var(--text); max-width: 220px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.bp-ref-kind { font-size: 10px; color: var(--faint); flex-shrink: 0; } .bp-entry-foot { display: flex; align-items: center; @@ -1093,7 +1112,16 @@ html.light .bp-code-block { background: var(--panel); } .bp-memory-fill { height: 100%; background: var(--accent); } .bp-memory-fill[data-state="held"] { background: var(--warn); } .bp-memory-fill[data-state="caught"] { background: var(--ok); } -.bp-provider-mark { font-weight: 700; flex-shrink: 0; } +.bp-provider-mark { + display: inline-flex; + align-items: center; + justify-content: center; + width: 15px; + height: 15px; + font-weight: 700; + flex-shrink: 0; +} +.bp-provider-mark svg { display: block; width: 14px; height: 14px; } .bp-model-text { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; flex: 1; min-width: 0; } .bp-ctx-pct { flex-shrink: 0; font-size: 11px; color: var(--faint); } .bp-composer-btns { display: flex; align-items: center; gap: 6px; flex-shrink: 0; } diff --git a/web/dist/manifest.json b/web/dist/manifest.json index ef348e11f5..003b15738f 100644 --- a/web/dist/manifest.json +++ b/web/dist/manifest.json @@ -1,6 +1,6 @@ { "version": 1, - "totalAssetGzipBytes": 208816, + "totalAssetGzipBytes": 213412, "styleTokensSha256": "a4fed1b1c7bc676acc328907343eb5dcf87e426383d05617c632e48c0c3f2b80", "i18nKeys": [ "agy.signout", @@ -163,6 +163,7 @@ "menu.unpin", "menu.wake", "model.col.agent", + "native.thread.model", "notify.settled", "palette.archive", "palette.command.placeholder", @@ -278,13 +279,13 @@ "web.settings.providers", "web.settings.providers.browser" ], - "i18nSubsetSha256": "793a000eb9d84d3f5a9b55032d5594e3be3404de25114af9144e4d39c6d4a810", + "i18nSubsetSha256": "db5f7133d01d755eead20f35efe2fd9a2f9e42834afde81b5bab3f244fb5b919", "inputs": { "web/src/addproject.ts": "06a7ff3e13cd78d993ebca7f638d5d623da06c0099186ad534bae8f184dbe44f", "web/src/app.ts": "4114b0fb1d9dd7e47db8222471213a64a9b60529c388196f0c79d08f15ca39c8", - "web/src/chat.ts": "27730f5adfcbb51eecf2f3a7cbd75562c964105dbb6a131697898977432c7892", + "web/src/chat.ts": "639e3af0791aedcde788c1a76aee6ea07cf96f5749d6a3564898c2beb8bd7337", "web/src/clone-model.ts": "d265df49436e14f415bbeb2a271ffa3552f9163be62bdc0158cecc10c3cdae45", - "web/src/composer.ts": "f351b271d59ae560ae57360a8a301fc7df7d4d3adbe2c8933577fd7201399dc0", + "web/src/composer.ts": "3269058fa1f8d65beee2cdc2429f91c2e748f3cbc968167eedffc459560fca40", "web/src/i18n-format.ts": "8561ca443ba371ad804b1cba75c144df666b1871a8250026c9806b66318c0c7b", "web/src/i18n.ts": "068561f33d911ed7c71d8c5f86d7a024b2ea9fe1dcd0bb766169cf19b82513b8", "web/src/index.html": "a661afef2f425bd880bccd134f90969b4d037cf455da827c921a99764ffd83a4", @@ -302,10 +303,11 @@ "web/src/qr.ts": "04b634557884b8f512a7b03ad9638c1c15a299ffaea0103d1bdeec6338d9b9d3", "web/src/rail.ts": "5fb391094992578cb6f54d35d53559951a584c43fcfc2ee6f4f2cc3897acfe46", "web/src/settings.ts": "4ec089580e4d2f04fb28462cb49cc164893c114af154d849c21ad5448a520433", - "web/src/shell.css": "ab269695b4c8486dfbbf54ad7372944da2b8d39fcd00ae58a7829f1d79ff69d7", + "web/src/shell.css": "98d9ed59251057a3f48708eddc0dea3b56b0766fbba560e62e6553388f3798e4", "web/src/sidebar.ts": "cc22668cddd8d039389fdd9637141c840d6ab8985de06a4268bb536d3a9588c1", "web/src/swarm-need.ts": "503bbf5ffe0389f068847571c792321b0ad5c8d26a18c73b8e41c0a8989e227f", "web/src/thread-context.ts": "b9fbd5b3ef0b1357b5a4444a1e9a0ac0606afe1c8a5377c4777752e918af0ac2", + "web/src/user-refs.ts": "56bcf0dc116d5f14260606f07cf9af9becbbd7cbb102dc9e0687a4ea5f894011", "web/src/viewers/browser-input.ts": "2be7672b8bfaded19f385ef56196793b9125130bffee7ac70afd493a3a91a9ab", "web/src/viewers/browser.ts": "44ba909e0e7d4c2d31672c97d41ad7e8039a8654e9929c2ba2650c7581f398ba", "web/src/viewers/cbor.ts": "0d2778a46998ab0c22c607dbca757494ad2ff6640b43a833356d227c09b80483", @@ -325,15 +327,23 @@ "web/vendor/xterm/addon-fit.js": "bdaefa370b1bfc42ee88d46fe6072400902a4d4b2d45cd93438dda9b23c97089", "web/vendor/xterm/xterm.css": "ba8e6985669488981ccf40c0cefe3aba80722cb6c92de7ad628b0bd717faf2b6", "web/vendor/xterm/xterm.js": "1f991ac3b4b283ebf96e60ae23a00a52765dd3a2e46fa6fdda9f1aab032f7495", - "web/build.ts": "40f837b7c23440ec7675bd5b7a472549c5a39eacc8fd2f2c2fe5abf1884d82c9", + "web/build.ts": "7f3d0d83a46bdea2e8cae217d0ae2cc5de83eac51c3b28e4d9c01a245bd3c7fd", + "assets/providers/claude.svg": "2d6fda79eb18ddccca35b799eeb3cece0dfabc22520ce3b10abd25668df9fa93", + "assets/providers/codex.svg": "71f7c8cae66142a92f69e2681dff60da996b64e1a64495a21e14c1ef40f3b277", + "assets/providers/grok.svg": "752909b823c8d6e0262a7495b76a09950bcd11652a46c5796b47499ada6226ec", + "assets/providers/muse.svg": "e2f652fcc1a28d4d089ea15b759498fbe231787bb0c10fd9853924b1d9b47340", + "assets/providers/antigravity.svg": "1d21b5a80382becbab7af32d3d08b721b5ae3d154942a85166963480a4fbf968", + "assets/providers/opencode.svg": "6f7d203200ba051cdbaa726c4de0a729cee3f1cec47953f189399d951af58c4c", + "assets/providers/pi.svg": "3f2a9abe50e8383f9fed6825301f2f7ebebf6bcd8185c2b281eb68109fe5ae73", + "assets/providers/omp.svg": "6e589681526bee6d4435e958d83a3e806f7a80350f1f7d1a2db627683d3065c3", "assets/web/favicon.svg": "5b0f22a3329f59809216aabe58d8dbbedbd46d29e4a2373a727529daa2441a2c", "assets/web/favicon-light.svg": "9aa4fb973f8a719c602e351c84d3344bac377db049f59eaa52d617e84eada5b6" }, "outputs": { "assets/app.js": { - "bytes": 357939, - "gzipBytes": 100335, - "sha256": "4744062db05b0ef354adacf4f312e3da4821574a4757373cf3479d035499e853" + "bytes": 367581, + "gzipBytes": 104772, + "sha256": "dfc9403ecb740c9b6bdaedf3fac1d674a9ba2f66a19b74e2e6c6bd3b9cf99a00" }, "assets/favicon-light.svg": { "bytes": 1207, @@ -351,14 +361,14 @@ "sha256": "123b6a27f255d339b505c8fd83609674f0bddf9b46c0e907fce23befa96b1eec" }, "assets/pair.js": { - "bytes": 53857, - "gzipBytes": 16286, - "sha256": "98b8a10c361338be615496f81432ad026af087e7fffa6b85f5165a7e87fc3aa7" + "bytes": 53952, + "gzipBytes": 16309, + "sha256": "a88ad06728d97dd0992bbae9a698789c9a2533d3a6d317b727305a15480a56ad" }, "assets/style.css": { - "bytes": 81620, - "gzipBytes": 13896, - "sha256": "5f5158b755ac3ac0646f7d6d7c5ebd5906a0e57170bd0ebbd190ae6097ec1257" + "bytes": 82388, + "gzipBytes": 14032, + "sha256": "5ff1bf13031144ecee3d2e7ddd3efadee95da2ed3c97cdfdbf910c1cbdfc6451" }, "assets/terminal.js": { "bytes": 296616, diff --git a/web/src/chat.ts b/web/src/chat.ts index 42717211a0..ea228777ae 100644 --- a/web/src/chat.ts +++ b/web/src/chat.ts @@ -6,6 +6,7 @@ import { t, trs } from "./i18n"; import { renderMarkdown } from "./md"; import type { NoProviderNotice } from "./provider-notice"; import type { ThreadItem } from "./sidebar"; +import { splitUserModelRefs, type MessageRef } from "./user-refs"; export interface EntryTool { name: string; summary?: string; state?: string; } export interface EntryAsk { @@ -37,6 +38,7 @@ export interface EntryItem { tool?: EntryTool; ask?: EntryAsk; replyTo?: { id: string; quote: string }; + refs?: MessageRef[]; images?: string[]; attachments?: EntryAttachment[]; } @@ -98,6 +100,72 @@ function formatDuration(deltaMs: number): string { return s > 0 ? `${m}m ${s}s` : `${m}m`; } +function renderUserBody(text: string, refs?: MessageRef[]): DocumentFragment { + const frag = document.createDocumentFragment(); + const segs = splitUserModelRefs(text, refs); + const modelLbl = t("native.thread.model", "Model").toLowerCase(); + for (const seg of segs) { + if (seg.kind === "text") { + frag.appendChild(document.createTextNode(seg.text)); + continue; + } + const chip = document.createElement("span"); + chip.className = "bp-ref-chip bp-ref-model"; + chip.title = seg.word; + chip.setAttribute("data-ref-word", seg.word); + + const sigil = document.createElement("span"); + sigil.className = "bp-ref-sigil"; + sigil.textContent = "&"; + + const label = document.createElement("span"); + label.className = "bp-ref-label"; + label.textContent = seg.label; + + const kind = document.createElement("span"); + kind.className = "bp-ref-kind"; + kind.textContent = modelLbl; + + chip.append(sigil, label, kind); + frag.appendChild(chip); + } + return frag; +} + +function attachTimelineCopyHandler(scrollEl: HTMLElement): void { + scrollEl.addEventListener("copy", (e) => { + const sel = typeof window !== "undefined" ? window.getSelection() : null; + if (!sel || sel.rangeCount === 0 || sel.isCollapsed) return; + const range = sel.getRangeAt(0); + if (!scrollEl.contains(range.commonAncestorContainer)) return; + const ancestor = range.commonAncestorContainer; + const el = ancestor.nodeType === Node.ELEMENT_NODE ? (ancestor as Element) : ancestor.parentElement; + const singleChip = el?.closest(".bp-ref-chip[data-ref-word]"); + const singleWord = singleChip?.getAttribute("data-ref-word"); + let textOut: string; + if (singleWord) { + textOut = singleWord; + } else { + const frag = range.cloneContents(); + const chips = frag.querySelectorAll(".bp-ref-chip[data-ref-word]"); + if (chips.length === 0) return; + for (const chip of chips) { + const raw = chip.getAttribute("data-ref-word") || chip.textContent || ""; + chip.replaceWith(document.createTextNode(raw)); + } + const entries = frag.querySelectorAll(".bp-entry"); + for (let i = 1; i < entries.length; i++) { + entries[i].before(document.createTextNode("\n")); + } + textOut = frag.textContent ?? ""; + } + if (e.clipboardData) { + e.preventDefault(); + e.clipboardData.setData("text/plain", textOut); + } + }); +} + function isHiddenSystemNote(e: EntryItem): boolean { if (e.agentOnly) return true; // Match desktop GPUI: routine git snapshot/repo-init notes are not drawn in the chat timeline. @@ -183,6 +251,7 @@ export class ChatView { this.listEl = document.createElement("div"); this.listEl.className = "bp-timeline-list"; + attachTimelineCopyHandler(this.scrollEl); this.scrollEl.append(this.olderBtn, this.listEl); container.append(this.bannerEl, this.scrollEl); } @@ -681,8 +750,11 @@ export class ChatView { if (hasBody || entry.live) { const body = document.createElement("div"); body.className = "bp-entry-body"; - if (entry.kind === "user") body.textContent = entry.text; - else body.appendChild(renderMarkdown(entry.text || "")); + if (entry.kind === "user") { + body.appendChild(renderUserBody(entry.text || "", entry.refs)); + } else { + body.appendChild(renderMarkdown(entry.text || "")); + } if (entry.live) this.liveNodes.set(entry.id, body); row.appendChild(body); } diff --git a/web/src/composer.ts b/web/src/composer.ts index bd4118f3e6..64ac1e1f51 100644 --- a/web/src/composer.ts +++ b/web/src/composer.ts @@ -4,6 +4,8 @@ // with model chip on the left and accent-blue Send / red Stop on the right. import { t, trs } from "./i18n"; import type { PlanModeInfo } from "./sidebar"; +// @ts-ignore virtual module injected by web/build.ts +import { PROVIDER_MARKS } from "virtual:provider-marks"; export interface SlashCommand { word: string; @@ -71,15 +73,34 @@ function makePlanPlayIcon(): SVGSVGElement { return makeComposerIcon(["M6 4l14 8-14 8z"]); } -function providerBadge(provider?: string): { glyph: string; color: string; title: string } { +function providerBadge(provider?: string): { mark?: string; glyph: string; color: string; title: string } { const p = (provider || "").toLowerCase(); - if (p.includes("claude") || p.includes("anthropic")) return { glyph: "A", color: "#d97706", title: "Claude" }; - if (p.includes("codex") || p.includes("openai")) return { glyph: "O", color: "#10b981", title: "Codex" }; - if (p.includes("gemini") || p.includes("antigravity")) return { glyph: "G", color: "#3b82f6", title: "Gemini" }; - if (p.includes("grok")) return { glyph: "X", color: "#94a3b8", title: "Grok" }; + if (p.includes("claude") || p.includes("anthropic")) return { mark: "claude", glyph: "A", color: "#d97757", title: "Claude" }; + if (p.includes("codex") || p.includes("openai")) return { mark: "codex", glyph: "O", color: "#10a37f", title: "Codex" }; + if (p.includes("gemini") || p.includes("antigravity") || p === "agy") return { mark: "antigravity", glyph: "G", color: "#4285f4", title: "Antigravity" }; + if (p.includes("grok")) return { mark: "grok", glyph: "X", color: "#6b7280", title: "Grok" }; + if (p.includes("muse")) return { mark: "muse", glyph: "M", color: "#8b5cf6", title: "Muse" }; + if (p.includes("opencode")) return { mark: "opencode", glyph: "C", color: "#2563eb", title: "OpenCode" }; + if (p.includes("omp") || p.includes("oh-my-pi")) return { mark: "omp", glyph: "Ω", color: "#c026d3", title: "Oh My Pi" }; + if (p === "pi" || p.startsWith("pi/") || p.startsWith("@pi")) return { mark: "pi", glyph: "π", color: "#db2777", title: "Pi" }; return { glyph: "●", color: "var(--accent)", title: provider || "Model" }; } +function makeProviderMarkSvg(mark: string): SVGSVGElement | null { + const info = PROVIDER_MARKS[mark]; + if (!info || !info.d) return null; + const svg = document.createElementNS(SVG_NS, "svg"); + svg.setAttribute("viewBox", info.viewBox || "0 0 24 24"); + svg.setAttribute("width", "14"); + svg.setAttribute("height", "14"); + svg.setAttribute("fill", "currentColor"); + svg.setAttribute("aria-hidden", "true"); + const path = document.createElementNS(SVG_NS, "path"); + path.setAttribute("d", info.d); + svg.appendChild(path); + return svg; +} + export class ComposerView { private popupEl: HTMLElement; private attachStripEl: HTMLElement; @@ -316,7 +337,9 @@ export class ComposerView { public setModelChip(chip: string, provider?: string, ctxPct?: number): void { const badge = providerBadge(provider); - this.providerMarkEl.textContent = badge.glyph; + const svg = badge.mark ? makeProviderMarkSvg(badge.mark) : null; + if (svg) this.providerMarkEl.replaceChildren(svg); + else this.providerMarkEl.textContent = badge.glyph; this.providerMarkEl.style.color = badge.color; this.providerMarkEl.title = badge.title; this.modelTextEl.textContent = chip || "default"; diff --git a/web/src/shell.css b/web/src/shell.css index ea478a936b..aac6594d13 100644 --- a/web/src/shell.css +++ b/web/src/shell.css @@ -764,6 +764,25 @@ button.bp-proj-quick:hover { color: var(--accent); } } .bp-entry-body { color: var(--text); word-break: break-word; } .bp-entry-user .bp-entry-body { white-space: pre-wrap; } +.bp-ref-chip { + display: inline-flex; + align-items: baseline; + gap: 5px; + padding: 0 6px; + margin: 0 1px; + border: 1px solid var(--line); + background: var(--bg); + font-size: 12px; + line-height: 1.45; + vertical-align: baseline; + white-space: nowrap; + max-width: 100%; + user-select: all; + -webkit-user-select: all; +} +.bp-ref-sigil { font-weight: 700; color: var(--ok); flex-shrink: 0; } +.bp-ref-label { color: var(--text); max-width: 220px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.bp-ref-kind { font-size: 10px; color: var(--faint); flex-shrink: 0; } .bp-entry-foot { display: flex; align-items: center; @@ -1000,7 +1019,16 @@ html.light .bp-code-block { background: var(--panel); } .bp-memory-fill { height: 100%; background: var(--accent); } .bp-memory-fill[data-state="held"] { background: var(--warn); } .bp-memory-fill[data-state="caught"] { background: var(--ok); } -.bp-provider-mark { font-weight: 700; flex-shrink: 0; } +.bp-provider-mark { + display: inline-flex; + align-items: center; + justify-content: center; + width: 15px; + height: 15px; + font-weight: 700; + flex-shrink: 0; +} +.bp-provider-mark svg { display: block; width: 14px; height: 14px; } .bp-model-text { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; flex: 1; min-width: 0; } .bp-ctx-pct { flex-shrink: 0; font-size: 11px; color: var(--faint); } .bp-composer-btns { display: flex; align-items: center; gap: 6px; flex-shrink: 0; } diff --git a/web/src/user-refs.ts b/web/src/user-refs.ts new file mode 100644 index 0000000000..350a650911 --- /dev/null +++ b/web/src/user-refs.ts @@ -0,0 +1,84 @@ +export interface MessageRef { + word: string; + kind: string; + id?: string; + label: string; +} + +export type UserSegment = + | { kind: "text"; text: string } + | { kind: "model"; word: string; label: string }; + +const OPENS = new Set(["(", "[", "\"", "'", "`"]); + +function isWordBoundaryExtra(ch: string): boolean { + return /[\p{L}\p{N}\-_\/+\[]/u.test(ch); +} + +function isColonIdentChar(ch: string): boolean { + return /[\p{L}\p{N}\-_\/]/u.test(ch); +} + +function isAlnum(ch: string): boolean { + return /[\p{L}\p{N}]/u.test(ch); +} + +/** + * Splits a user message's raw text into plain text and inline resolved model chip + * segments matching the backend/GPUI word boundary rules (`&provider/model`). + * Unresolved `&...` tokens stay as plain text. + */ +export function splitUserModelRefs(text: string, refs?: MessageRef[]): UserSegment[] { + if (!text) return []; + const models = (refs ?? []).filter((r) => r.kind === "model" && r.word && r.label); + if (models.length === 0) return [{ kind: "text", text }]; + + const out: UserSegment[] = []; + let at = 0; + while (at < text.length) { + let bestStart = -1; + let bestEnd = -1; + let bestModel: MessageRef | null = null; + + for (const m of models) { + let from = at; + while (from < text.length) { + const i = text.indexOf(m.word, from); + if (i < 0) break; + const end = i + m.word.length; + const before = i === 0 || /\s/.test(text[i - 1]) || OPENS.has(text[i - 1]); + const next = end < text.length ? text[end] : ""; + const after = + !next || + (!isWordBoundaryExtra(next) && + !(next === "." && end + 1 < text.length && isAlnum(text[end + 1])) && + !(next === ":" && end + 1 < text.length && isColonIdentChar(text[end + 1]))); + if (before && after) { + if ( + bestStart < 0 || + i < bestStart || + (i === bestStart && end > bestEnd) + ) { + bestStart = i; + bestEnd = end; + bestModel = m; + } + break; + } + from = i + 1; + } + } + + if (bestModel === null) break; + if (bestStart > at) { + out.push({ kind: "text", text: text.slice(at, bestStart) }); + } + out.push({ kind: "model", word: bestModel.word, label: bestModel.label }); + at = bestEnd; + } + + if (at < text.length) { + out.push({ kind: "text", text: text.slice(at) }); + } + return out; +} diff --git a/web/test/user-refs.test.ts b/web/test/user-refs.test.ts new file mode 100644 index 0000000000..25bf4ae2da --- /dev/null +++ b/web/test/user-refs.test.ts @@ -0,0 +1,64 @@ +import { describe, expect, test } from "bun:test"; +import { splitUserModelRefs, type MessageRef } from "../src/user-refs"; + +describe("splitUserModelRefs", () => { + const models: MessageRef[] = [ + { word: "&antigravity/gemini-4-neon", kind: "model", id: "", label: "Gemini 4 Neon" }, + { word: "&claude/claude-fable-5-2[1m]", kind: "model", id: "", label: "Fable 5.2 (1M)" }, + { word: "&claude/opus", kind: "model", id: "", label: "Opus" }, + { word: "&claude/opus[1m]", kind: "model", id: "", label: "Opus (1M)" }, + ]; + + test("returns plain text when no model refs exist", () => { + expect(splitUserModelRefs("hello &provider/model", [])).toEqual([ + { kind: "text", text: "hello &provider/model" }, + ]); + expect(splitUserModelRefs("ping @bot", [{ word: "@bot", kind: "bot", label: "Bot" }])).toEqual([ + { kind: "text", text: "ping @bot" }, + ]); + }); + + test("embeds single, multiple, repeated, and [1m] model refs inline", () => { + const input = + "swarm with &antigravity/gemini-4-neon and &claude/claude-fable-5-2[1m], then &antigravity/gemini-4-neon."; + expect(splitUserModelRefs(input, models)).toEqual([ + { kind: "text", text: "swarm with " }, + { kind: "model", word: "&antigravity/gemini-4-neon", label: "Gemini 4 Neon" }, + { kind: "text", text: " and " }, + { kind: "model", word: "&claude/claude-fable-5-2[1m]", label: "Fable 5.2 (1M)" }, + { kind: "text", text: ", then " }, + { kind: "model", word: "&antigravity/gemini-4-neon", label: "Gemini 4 Neon" }, + { kind: "text", text: "." }, + ]); + }); + + test("respects word boundaries and prefers longer [1m] suffix over bare prefix", () => { + const input = "(&claude/opus[1m]) [&claude/opus] foo&claude/opus https://x.io?a=1&claude/opus &provider/model"; + expect(splitUserModelRefs(input, models)).toEqual([ + { kind: "text", text: "(" }, + { kind: "model", word: "&claude/opus[1m]", label: "Opus (1M)" }, + { kind: "text", text: ") [" }, + { kind: "model", word: "&claude/opus", label: "Opus" }, + { kind: "text", text: "] foo&claude/opus https://x.io?a=1&claude/opus &provider/model" }, + ]); + }); + + test("preserves multiline text verbatim around chips", () => { + const input = "line 1 &antigravity/gemini-4-neon\n\nline 2"; + const segs = splitUserModelRefs(input, models); + expect(segs.map((s) => (s.kind === "text" ? s.text : s.word)).join("")).toBe(input); + expect(segs.filter((s) => s.kind === "model")).toHaveLength(1); + }); + + test("splits model ref before trailing colon while keeping colon tags non-chips", () => { + expect(splitUserModelRefs("Use &claude/opus: it's fast", models)).toEqual([ + { kind: "text", text: "Use " }, + { kind: "model", word: "&claude/opus", label: "Opus" }, + { kind: "text", text: ": it's fast" }, + ]); + const tagModels: MessageRef[] = [{ word: "&opencode/llama3", kind: "model", id: "", label: "Llama 3" }]; + expect(splitUserModelRefs("try &opencode/llama3:8b", tagModels)).toEqual([ + { kind: "text", text: "try &opencode/llama3:8b" }, + ]); + }); +});