From 5113cc106373afc46b16ef198a67d891c33cbee0 Mon Sep 17 00:00:00 2001 From: i2cjak Date: Tue, 24 Nov 2026 15:44:24 -0500 Subject: [PATCH] fix: watcher cmdline check and dismissible home move failed banner --- native/gpui/src/hub.rs | 3 +- native/gpui/src/ui.rs | 48 ++++++++++++- native/host/src/data/mod.rs | 32 +++++++-- native/host/src/data/webpolicy.rs | 4 +- native/host/src/net/home.rs | 3 +- native/host/src/net/homemove.rs | 97 +++++++++++++++++++++++-- native/host/src/restarting.rs | 16 ++++- web/dist/assets/app.js | 38 +++++----- web/dist/assets/style.css | 21 ++++++ web/dist/manifest.json | 20 +++--- web/src/app.ts | 11 +++ web/src/shell.css | 21 ++++++ web/src/sidebar.ts | 113 ++++++++++++++++++------------ web/test/sidebar.test.ts | 26 ++++++- 14 files changed, 364 insertions(+), 89 deletions(-) diff --git a/native/gpui/src/hub.rs b/native/gpui/src/hub.rs index ad7bd51c81..44c83c72d9 100644 --- a/native/gpui/src/hub.rs +++ b/native/gpui/src/hub.rs @@ -420,7 +420,7 @@ async fn session(config:&Config,commands:&mut mpsc::Receiver,queued:&mu continue; } if let Some(tag)=v.asks.remove(&id) {let _=events.send(Event::Answer(tag,x)).await;continue;} - if let Some(tag)=v.rpcs.remove(&id) {if tag=="hubupd" {if x["ok"]==true {let _=events.send(Event::Data("hubupd",x["result"].clone())).await;}continue;}if tag=="thread-context" {let _=events.send(Event::Data("thread-context",x)).await;continue;}if tag=="kicad" {let m=v.rpc_names.remove(&id).unwrap_or_default();let why=if x["ok"]==true {String::new()} else {rpc_error(&x)};eprintln!("GPUI_LOG {}",json!({"kicad_rpc_reply":m,"id":id,"at_ms":crate::screens::kcomment::epoch_ms() as u64,"ok":x["ok"]==true,"state":x["state"],"mode":x["mode"],"pid":x["pid"],"warm":x["warm"],"started":x["started"],"why":x["why"],"prewarming":x["prewarming"],"error":why.chars().take(160).collect::()}));let _=events.send(Event::KicadReply(m,x)).await;continue;}if tag=="star" {let _=events.send(Event::Star(if x["ok"]==true {x["result"]["offer"].clone()} else {Value::Null})).await;continue;}if tag=="tmnotice" {let _=events.send(Event::TmNotice(if x["ok"]==true {x["result"]["notice"].clone()} else {Value::Null})).await;continue;}if tag=="gpnotice" {let _=events.send(Event::GpNotice(if x["ok"]==true {x["result"]["notice"].clone()} else {Value::Null})).await;continue;}if tag==crate::streamer::TAG {if x["ok"]==true {let _=events.send(Event::Data(crate::streamer::TAG,x["result"].clone())).await;}continue;}if tag=="google" && x["ok"]==true {let _=events.send(Event::Data(tag.clone(),x["result"].clone())).await;}if tag=="acct" || (tag=="acct-moveall" && x["ok"]==true) {let _=events.send(Event::Data(tag.clone(),x["result"].clone())).await;}if tag=="steps" {let _=events.send(Event::Steps(if x["ok"]==true {x["result"].clone()} else {Value::Null})).await;continue;}if tag.starts_with("probe") {let slot:usize=tag[5..].parse().unwrap_or(0);let m=x["result"]["matches"].as_array().map(|a|a.iter().filter_map(|p|Some((p[0].as_u64()? as usize,p[1].as_u64()? as usize))).collect()).unwrap_or_default();let _=events.send(Event::Probe(slot,m)).await;continue;}if tag=="resolve" {let _=events.send(Event::Refs(serde_json::json!({"resolved":x["result"]["resolved"].clone(),"error":x["result"]["error"].clone()}))).await;continue;}if tag=="refs" {let _=events.send(Event::Refs(if x["ok"]==true {x["result"].clone()} else {Value::Null})).await;continue;}if tag=="names"||tag=="xsel"||tag=="xsel-tap" {let _=events.send(Event::Data(if tag=="names" {"names"} else if tag=="xsel" {"xsel"} else {"xsel-tap"},x)).await;continue;}if tag=="pick" {let _=events.send(Event::Pick(if x["ok"]==true {x["result"]["info"].as_str().unwrap_or("").to_string()} else {String::new()})).await;continue;}let ok=x["ok"]==true;let why=if ok&&tag.starts_with("hook"){crate::screens::bots::hook_answer(&x).to_string()}else if ok&&tag.starts_with("files"){x["result"].to_string()}else{crate::screens::settings::reply_error(&x)};let _=events.send(Event::Rpc(tag,ok,why)).await;continue;} + if let Some(tag)=v.rpcs.remove(&id) {if tag=="home-move-dismiss" {if x["ok"]==true {if !v.view_id.is_empty()&&v.pending.is_empty(){let request=v.request("view.update",json!({}));sink.send(Message::Binary(wire::encode(&request).into())).await?;}else{v.dirty=true;}}continue;}if tag=="hubupd" {if x["ok"]==true {let _=events.send(Event::Data("hubupd",x["result"].clone())).await;}continue;}if tag=="thread-context" {let _=events.send(Event::Data("thread-context",x)).await;continue;}if tag=="kicad" {let m=v.rpc_names.remove(&id).unwrap_or_default();let why=if x["ok"]==true {String::new()} else {rpc_error(&x)};eprintln!("GPUI_LOG {}",json!({"kicad_rpc_reply":m,"id":id,"at_ms":crate::screens::kcomment::epoch_ms() as u64,"ok":x["ok"]==true,"state":x["state"],"mode":x["mode"],"pid":x["pid"],"warm":x["warm"],"started":x["started"],"why":x["why"],"prewarming":x["prewarming"],"error":why.chars().take(160).collect::()}));let _=events.send(Event::KicadReply(m,x)).await;continue;}if tag=="star" {let _=events.send(Event::Star(if x["ok"]==true {x["result"]["offer"].clone()} else {Value::Null})).await;continue;}if tag=="tmnotice" {let _=events.send(Event::TmNotice(if x["ok"]==true {x["result"]["notice"].clone()} else {Value::Null})).await;continue;}if tag=="gpnotice" {let _=events.send(Event::GpNotice(if x["ok"]==true {x["result"]["notice"].clone()} else {Value::Null})).await;continue;}if tag==crate::streamer::TAG {if x["ok"]==true {let _=events.send(Event::Data(crate::streamer::TAG,x["result"].clone())).await;}continue;}if tag=="google" && x["ok"]==true {let _=events.send(Event::Data(tag.clone(),x["result"].clone())).await;}if tag=="acct" || (tag=="acct-moveall" && x["ok"]==true) {let _=events.send(Event::Data(tag.clone(),x["result"].clone())).await;}if tag=="steps" {let _=events.send(Event::Steps(if x["ok"]==true {x["result"].clone()} else {Value::Null})).await;continue;}if tag.starts_with("probe") {let slot:usize=tag[5..].parse().unwrap_or(0);let m=x["result"]["matches"].as_array().map(|a|a.iter().filter_map(|p|Some((p[0].as_u64()? as usize,p[1].as_u64()? as usize))).collect()).unwrap_or_default();let _=events.send(Event::Probe(slot,m)).await;continue;}if tag=="resolve" {let _=events.send(Event::Refs(serde_json::json!({"resolved":x["result"]["resolved"].clone(),"error":x["result"]["error"].clone()}))).await;continue;}if tag=="refs" {let _=events.send(Event::Refs(if x["ok"]==true {x["result"].clone()} else {Value::Null})).await;continue;}if tag=="names"||tag=="xsel"||tag=="xsel-tap" {let _=events.send(Event::Data(if tag=="names" {"names"} else if tag=="xsel" {"xsel"} else {"xsel-tap"},x)).await;continue;}if tag=="pick" {let _=events.send(Event::Pick(if x["ok"]==true {x["result"]["info"].as_str().unwrap_or("").to_string()} else {String::new()})).await;continue;}let ok=x["ok"]==true;let why=if ok&&tag.starts_with("hook"){crate::screens::bots::hook_answer(&x).to_string()}else if ok&&tag.starts_with("files"){x["result"].to_string()}else{crate::screens::settings::reply_error(&x)};let _=events.send(Event::Rpc(tag,ok,why)).await;continue;} if dock_watch.as_ref().is_some_and(|(rid, _)| *rid == id) { let (_, mut watch) = dock_watch.take().unwrap(); watch["tiles"] = x["result"]["tiles"].clone(); @@ -555,6 +555,7 @@ async fn session(config:&Config,commands:&mut mpsc::Receiver,queued:&mu "gitpush.notice"=>{let _=events.send(Event::GpNotice(x["notice"].clone())).await;}, "browser.download"=>{let s=|k:&str|x[k].as_str().unwrap_or("").to_string();let _=events.send(Event::BrowserDownload(s("bot"),s("id"),s("name"),s("error"))).await;}, "info"=>{ + if x["info"].get("home.move").is_some() { v.dirty = true; } // the merged project rows moved with no log line (a machine's origins learned, it away or back): the view is asked for again if x["info"].get("mirrors.gen").is_some()&&!v.view_id.is_empty()&&v.pending.is_empty(){let request=v.request("view.update",json!({}));sink.send(Message::Binary(wire::encode(&request).into())).await?;} if let Some(m)=x["info"].as_object(){for(k,val) in m{if k=="hub.back"{if let Some(t)=val.as_str().and_then(|v|serde_json::from_str::(v).ok()).and_then(|v|v["text"].as_str().map(str::to_string)).filter(|t|!t.is_empty()){let _=events.send(Event::Note(crate::i18n::trs(&t))).await;}}if k=="hub.offer"{let _=events.send(Event::HubOffer(val.as_str().unwrap_or("").to_string())).await;}if k=="kicad.update"||k=="kicad.install"{let _=events.send(Event::KicadUpdate(k.clone(),val.as_str().unwrap_or("").to_string())).await;}if k.starts_with("kicad.progress."){let _=events.send(Event::KicadProgress(val.as_str().unwrap_or("").to_string())).await;}if k.starts_with("mgmt.")||k.starts_with("review.clicked."){let _=events.send(Event::Mgmt(k.clone(),val.as_str().unwrap_or("").to_string())).await;}if k.starts_with("kicad.comment."){let _=events.send(Event::KicadComment(val.as_str().unwrap_or("").to_string())).await;}if k.starts_with("kicad.reload."){let _=events.send(Event::KicadReload(val.as_str().unwrap_or("").to_string())).await;}if let Some(d)=k.strip_prefix("editor.kicad."){let _=events.send(Event::KicadEditor(d.to_string(),val.as_str().unwrap_or("").to_string())).await;}if let Some(owner)=k.strip_prefix("browser.tabs."){let _=events.send(Event::BrowserTabs(owner.to_string(),val.as_str().unwrap_or("").to_string())).await;}}}}, diff --git a/native/gpui/src/ui.rs b/native/gpui/src/ui.rs index e8e2939e2b..08153b323f 100644 --- a/native/gpui/src/ui.rs +++ b/native/gpui/src/ui.rs @@ -680,7 +680,24 @@ impl Backplane { crew.push(div().id("crew-rooms").flex().flex_wrap().items_center().px(px(7.)).pb(px(6.)).max_h(px(3. * 22. + 6.)).overflow_y_scroll().children(chips).into_any_element()); } if let Some((line, bad)) = home_away_line(&self.data["home"]) { - rows.push(div().id("home-away-row").px_3().py_1().border_b_1().border_color(c("line")).bg(c("panel")).text_size(crate::scale::tpx(11.)).text_color(if bad { c("bad") } else { c("dim") }).child(line).into_any_element()); + let dismissible = home_move_dismissible(&self.data["home"]); + let mut row = div().id("home-away-row").px_3().py_1().border_b_1().border_color(c("line")).bg(c("panel")) + .flex().items_center().gap_1() + .text_size(crate::scale::tpx(11.)).text_color(if bad { c("bad") } else { c("dim") }) + .child(div().flex_1().min_w_0().child(line)); + if dismissible { + row = row.child( + /* i18n-ok: a ui: id the drivers press */ with_rect(div().id("home-away-dismiss"), || "ui:Dismiss home move".to_string()) + .flex_shrink_0().px_1().cursor_pointer().text_color(c("dim")).hover(|s| s.text_color(c("text")).bg(c("raise"))) + .tooltip(crate::keys::tip_raw(&crate::i18n::t("approval.dismiss"), "", light)) + .on_click(cx.listener(|this, _, _, cx| { + let _ = this.tx.try_send(home_move_dismiss_cmd()); + cx.notify(); + })) + .child("×"), + ); + } + rows.push(row.into_any_element()); } let new_here = crate::keys::new_target(&self.data, &self.selected, self.project_page.as_deref()); // the hub's sections (Needs you, Pinned, Active, groups, Quiet: screens/sections.rs); an older hub sends projects and the Active view @@ -1715,9 +1732,20 @@ pub(crate) fn home_away_line(home: &Value) -> Option<(String, bool)> { Some((s, false)) } +/// Whether the sidebar home status banner represents a failed move that the user can dismiss. +pub(crate) fn home_move_dismissible(home: &Value) -> bool { + home.get("moving").and_then(|m| m["state"].as_str()) == Some("failed") +} + +/// Command sent when the user dismisses a failed home-move banner. +pub(crate) fn home_move_dismiss_cmd() -> Command { + Command::Rpc("home.move.dismiss".into(), crate::screens::settings::Secret(serde_json::json!({})), "home-move-dismiss") +} + #[cfg(test)] mod home_tests { - use super::home_away_line; + use super::{home_away_line, home_move_dismiss_cmd, home_move_dismissible}; + use crate::hub::Command; use serde_json::{json, Value}; #[test] @@ -1733,6 +1761,22 @@ mod home_tests { /* i18n-ok: test */ assert_eq!(fail, Some(("Home move failed: disk full".into(), true))); } + #[test] + fn home_move_dismiss_only_applies_to_failed_moves() { + assert!(!home_move_dismissible(&Value::Null)); + assert!(!home_move_dismissible(&json!({"kind":"local","name":"desk","online":true}))); + assert!(!home_move_dismissible(&json!({"kind":"peer","name":"desk","online":false}))); + assert!(!home_move_dismissible(&json!({"kind":"peer","name":"desk","online":true,"moving":{"to":"laptop","state":"moving","step":"copying"}}))); + assert!(home_move_dismissible(&json!({"kind":"peer","name":"desk","online":true,"moving":{"to":"laptop","state":"failed","note":"that machine is away"}}))); + match home_move_dismiss_cmd() { + Command::Rpc(method, _, tag) => { + assert_eq!(method, "home.move.dismiss"); + assert_eq!(tag, "home-move-dismiss"); + } + other => panic!("unexpected command: {other:?}"), + } + } + #[test] fn card_refs_excludes_inline_model_cards_and_keeps_others() { let refs = json!([ diff --git a/native/host/src/data/mod.rs b/native/host/src/data/mod.rs index 5f680f0f4b..65efab7d51 100644 --- a/native/host/src/data/mod.rs +++ b/native/host/src/data/mod.rs @@ -741,7 +741,7 @@ async fn call(hub: &Arc, c: &mut Conn, m: &str, p: &Value, is_browser: bool "ask.answer" => { rpc(hub, c, "ask.answer", json!({"id":s(p, "ask"),"answer":s(p, "answer")})).await?; Ok(json!({})) } // the same answer every client gets (its `result`, not the reply around it); the phones draw it "update.status" | "update.check" | "app.update" | "update.now" => Ok(rpc(hub, c, m, json!({})).await?["result"].clone()), - "hub.offer.take" | "hub.offer.done" => Ok(rpc(hub, c, m, p.clone()).await?["result"].clone()), + "hub.offer.take" | "hub.offer.done" | "home.move.dismiss" => Ok(rpc(hub, c, m, p.clone()).await?["result"].clone()), "update.channel" => { let ch = s(p, "channel"); if !["stable", "beta", "nightly"].contains(&ch) { return Err(err("no such channel")) } rpc(hub, c, "setting.set", json!({"key":"update.channel","value":ch})).await?; Ok(rpc(hub, c, "update.status", json!({})).await?["result"].clone()) } // Improvements: the projects of every machine a request may go to (searched on the hub) and the last one chosen, as the desktop gets them "improvements.projects" | "improvements.project" => Ok(rpc(hub, c, m, p.clone()).await?["result"].clone()), @@ -1196,10 +1196,21 @@ async fn socket_with_reg( let lines = hub.store.range(seen, len.min(seen + 2000)).unwrap_or_default(); seen += lines.len(); let inv_changed = lines.iter().any(|l| l.contains("\"accounts.inventory\"")); + let home_changed = lines.iter().any(|l| l.contains("\"home.moving\"") || l.contains("\"home.at\"")); for f in deltas(&hub, &lines, &mut subs).await { if !send_frame(&mut tx, &hub, browser.as_ref(), conn.client, pack(&f, json_mode)).await? { return Ok(()) } sent = true; } + if home_changed && !subs.lists().is_empty() { + let h = crate::net::home::now(&hub).await; + if h != home_sent { + home_sent = h.clone(); + for sub in subs.lists() { + if !send_frame(&mut tx, &hub, browser.as_ref(), conn.client, pack(&d(sub, "home", json!({"home": h})), json_mode)).await? { return Ok(()) } + } + sent = true; + } + } if inv_changed { let cur = crate::settings::provider_notice::for_hub(&hub).await.map_or(Value::Null, |n| n.json()); if cur != no_provider_sent { @@ -1239,11 +1250,22 @@ async fn socket_with_reg( if !send_frame(&mut tx, &hub, browser.as_ref(), conn.client, pack(&f, json_mode)).await? { return Ok(()) } }, // hub info (set_info): what a phone draws of it (phone_info), as `{"t":"info","info":{...}}` - Out::Value(v) if v["t"] == "info" => if let Some(f) = phone_info_frame(&v) { - if let Some(raw) = f["info"].get(crate::settings::provider_notice::INFO_KEY) { - no_provider_sent = raw.as_str().and_then(|s| if s.is_empty() { None } else { serde_json::from_str(s).ok() }).unwrap_or(Value::Null); + Out::Value(v) if v["t"] == "info" => { + if v["info"].get("home.move").is_some() && !subs.lists().is_empty() { + let h = crate::net::home::now(&hub).await; + if h != home_sent { + home_sent = h.clone(); + for sub in subs.lists() { + if !send_frame(&mut tx, &hub, browser.as_ref(), conn.client, pack(&d(sub, "home", json!({"home": h})), json_mode)).await? { return Ok(()) } + } + } + } + if let Some(f) = phone_info_frame(&v) { + if let Some(raw) = f["info"].get(crate::settings::provider_notice::INFO_KEY) { + no_provider_sent = raw.as_str().and_then(|s| if s.is_empty() { None } else { serde_json::from_str(s).ok() }).unwrap_or(Value::Null); + } + if !send_frame(&mut tx, &hub, browser.as_ref(), conn.client, pack(&f, json_mode)).await? { return Ok(()) } } - if !send_frame(&mut tx, &hub, browser.as_ref(), conn.client, pack(&f, json_mode)).await? { return Ok(()) } }, Out::Value(v) => if ext::wants_value(&v) { // a plot's "none" is binary like the plots (one decoder in the app); a browser frame's announcement is JSON diff --git a/native/host/src/data/webpolicy.rs b/native/host/src/data/webpolicy.rs index edfd854202..d4abed5b8d 100644 --- a/native/host/src/data/webpolicy.rs +++ b/native/host/src/data/webpolicy.rs @@ -72,7 +72,8 @@ fn classify(method: &str, params: &Value) -> Option { | "clone.start" | "clone.cancel" | "clone.retry" - | "clone.signin" => Activity, + | "clone.signin" + | "home.move.dismiss" => Activity, "attachment.get" | "badge.list" | "bot.cat" @@ -232,6 +233,7 @@ mod tests { assert_eq!(policy("ring.hear", &json!({"note":"n1","engine":"local"})), Policy::Activity); for m in ["ring.page", "ring.page.act", "ring.setup", "ring.send", "ring.get", "ring.search"] { assert_eq!(policy(m, &Value::Null), Policy::Denied, "{m}"); } assert_eq!(policy("project.home", &json!({"project":"p1"})), Policy::Passive); + assert_eq!(policy("home.move.dismiss", &Value::Null), Policy::Activity); assert_eq!(policy("devices.page", &Value::Null), Policy::Devices); assert_eq!(policy("devices.page.act", &Value::Null), Policy::Denied); } diff --git a/native/host/src/net/home.rs b/native/host/src/net/home.rs index 2ad5cbbf84..4b6dd264a7 100644 --- a/native/host/src/net/home.rs +++ b/native/host/src/net/home.rs @@ -67,9 +67,10 @@ pub async fn read(hub: &Arc) -> Facts { let home_id = at["mid"].as_str().filter(|id| !id.is_empty()).map(str::to_string) .or_else(|| bots.as_ref().and_then(|b| b.mid_known(&link))).unwrap_or_default(); let queued = if link.is_empty() { 0 } else { crate::net::farsend::global().map_or(0, |o| o.items().iter().filter(|h| h.link == link).count()) }; + let now = crate::hub::now_ms() / 1000; // the machine coming home says so in `home.moving`; the one sending has the job (net/homemove.rs `home.status`) let here: Value = serde_json::from_str(&hub.setting("home.moving").await.unwrap_or_default()).unwrap_or(Value::Null); - let moving = if here.is_object() { here } else { crate::net::homemove::job() }; + let moving = crate::net::homemove::active_move(&here, now).unwrap_or_else(|| crate::net::homemove::job_at(now)); Facts { away_since: if link.is_empty() { None } else { hub.mirrors().away_since(&link) }, at, boat_link: boat["link"].as_str().unwrap_or("").to_string(), me_id, me_name: NAME.get_or_init(crate::net::botnet::name).await.clone(), home_id, queued, moving } } diff --git a/native/host/src/net/homemove.rs b/native/host/src/net/homemove.rs index 94279a111b..0f860131a0 100644 --- a/native/host/src/net/homemove.rs +++ b/native/host/src/net/homemove.rs @@ -4,7 +4,7 @@ //! receiver holds it all, and a move whose check fails is undone at once. //! //! Requests (this hub's clients): `home.move {to}` (a linked machine's link id or name; "back" asks the machine that holds the home now to move -//! it here), `home.status`, `hub.offer.take {id}`, `hub.offer.done {id, ok}`. Far requests (an owner's machine, signed): `home.state`, +//! it here), `home.move.dismiss`, `home.status`, `hub.offer.take {id}`, `hub.offer.done {id, ok}`. Far requests (an owner's machine, signed): `home.state`, //! `home.adopt`, `home.secret`, `home.file`, `home.import`, `home.finish`, `home.retire`, `home.mint`, `home.pull`. //! Settings: `home.at` (JSON `{link, name, url, at}`: the machine that holds the home now; "" when this one does), `home.here` (on the holder: //! `{from, at}`). Info: `home.move` (the job's state), `hub.offer` (docs/PHONE-DATA.md: a client adds the holder to its hubs by itself). @@ -308,7 +308,7 @@ pub fn moving_note(v: &str, now: u64) -> Option<(&'static str, String)> { _ => None, } } -const FAILED_SHOWN_S: u64 = 3600; +pub(crate) const FAILED_SHOWN_S: u64 = 600; /// The thread a client asked for, when the home moved away and took it: `~` on the new home (the same id there), drawn in its place. /// `at` the setting `home.at`; `project` the local thread's project (a project's thread never moves); `there` whether the mirror has an id. pub fn moved_thread(at: &str, thread: &str, project: Option<&str>, there: &dyn Fn(&str) -> bool) -> Option { @@ -580,8 +580,47 @@ pub async fn check(hub: &Arc, link: &str) -> Result { // ---- the sending side ---- static STATE: Mutex> = Mutex::new(None); +/// Returns `v` when it represents a live move or a non-expired failed move at unix seconds `now`. +pub(crate) fn active_move(v: &Value, now: u64) -> Option { + match gs(v, "state") { + "moving" => Some(v.clone()), + "failed" => { + let at = v["at"].as_u64().unwrap_or(0); + if now > 0 && now > at.saturating_add(FAILED_SHOWN_S) { None } else { Some(v.clone()) } + } + _ => None, + } +} +/// The sending side's move job at unix seconds `now` while it runs or before a failed state expires, else null. +pub fn job_at(now: u64) -> Value { + STATE.lock().unwrap().as_ref().and_then(|v| active_move(v, now)).unwrap_or(Value::Null) +} /// The sending side's move job while it runs or after it failed (`{state, step, note}`), else null: the home object's `moving` (net/home.rs). -pub fn job() -> Value { STATE.lock().unwrap().clone().filter(|v| v["state"] == "moving" || v["state"] == "failed").unwrap_or(Value::Null) } +pub fn job() -> Value { job_at(now_s()) } +/// Dismiss a failed home move banner/state on this hub. Leaves an active `"moving"` job untouched. +pub async fn dismiss(hub: &Arc) -> Value { + let cleared_state = { + let mut g = STATE.lock().unwrap(); + if g.as_ref().is_some_and(|v| v["state"] != "moving") { + *g = None; + WARN.lock().unwrap().clear(); + true + } else { + false + } + }; + if cleared_state { + hub.set_info("home.move", "").await; + } + let moving_setting = hub.setting("home.moving").await.unwrap_or_default(); + if !moving_setting.is_empty() { + let parsed: Value = serde_json::from_str(&moving_setting).unwrap_or(Value::Null); + if parsed["state"] != "moving" { + set_moving(hub, Value::Null).await; + } + } + json!({"home": crate::net::home::now(hub).await}) +} /// The check's warnings for the move running now (or the last one), shown with its state: what the bots there wait for (`warnings`). static WARN: Mutex> = Mutex::new(Vec::new()); async fn tell(hub: &Arc, state: &str, step: &str, note: &str) { @@ -897,7 +936,7 @@ pub fn rows(uber: bool, at: &str, mv: &str, linked: &Value) -> Vec { } pub struct HomeRpc; impl RpcHandler for HomeRpc { - fn methods(&self) -> &'static [&'static str] { &["home.move", "home.check", "home.status", "hub.offer.take", "hub.offer.done", "ring.front.use"] } + fn methods(&self) -> &'static [&'static str] { &["home.move", "home.move.dismiss", "home.check", "home.status", "hub.offer.take", "hub.offer.done", "ring.front.use"] } fn call<'a>(&'a self, hub: &'a Arc, _who: &'a Caller, id: &'a Value, m: &'a str, p: &'a Value) -> Fut<'a, Vec> { Box::pin(async move { let reply = |v: Value| vec![json!({"t":"reply","id":id,"ok":true,"result":v})]; @@ -905,6 +944,7 @@ impl RpcHandler for HomeRpc { match m { "home.status" => reply(STATE.lock().unwrap().clone().unwrap_or(json!({"state":"idle"}))), "home.move" => match start(hub, gs(p, "to")).await { Ok(v) => reply(v), Err(e) => fail(&e) }, + "home.move.dismiss" => reply(dismiss(hub).await), // the dry check alone (Settings, Machines and scripts/home-move-check.sh): what a move there would find, nothing moved "home.check" => { let to = gs(p, "to"); match hub.far_machines().into_iter().find(|(lid, n, _)| lid == to || n.eq_ignore_ascii_case(to)).map(|(lid, _, _)| lid) { Some(l) => match check(hub, &l).await { Ok(v) => reply(v), Err(e) => fail(&e) }, None => fail("no machine of yours by that name is linked") } } "hub.offer.take" => { @@ -1127,4 +1167,53 @@ mod tests { deliver_held(&hub2, m2, false).await; assert!(!path2.exists(), "successful delivery removes held file"); } + + #[test] + fn active_move_expires_failed_and_keeps_running() { + let moving = json!({"state":"moving","step":"copying","at":100}); + assert_eq!(active_move(&moving, 100 + FAILED_SHOWN_S + 10_000), Some(moving)); + let failed = json!({"state":"failed","note":"that machine is away","at":100}); + assert_eq!(active_move(&failed, 110), Some(failed.clone())); + assert_eq!(active_move(&failed, 100 + FAILED_SHOWN_S), Some(failed.clone())); + assert_eq!(active_move(&failed, 100 + FAILED_SHOWN_S + 1), None); + assert_eq!(active_move(&json!({"state":"failed","note":"no ts"}), FAILED_SHOWN_S + 1), None); + assert_eq!(active_move(&json!({"state":"done","at":100}), 110), None); + assert_eq!(active_move(&json!({"state":"idle"}), 110), None); + assert_eq!(active_move(&Value::Null, 110), None); + } + + #[tokio::test(flavor = "multi_thread")] + async fn failed_move_expires_and_dismiss_clears_state_and_setting() { + let home = crate::plat::tmp::dir("hm-dismiss"); + let hub = Hub::start( + crate::hub::Cfg { home: home.to_path_buf(), version: "0.1.0-dev".into(), commit: "c".into(), listen: "x".into(), os: "linux".into(), arch: "x64".into() }, + Arc::new(crate::presenter::Canned { reply: json!({}) }), + ).await.unwrap(); + + let ts = now_s(); + tell(&hub, "failed", "checking", "that machine is away").await; + set_moving(&hub, json!({"to":"boat","state":"failed","why":"that machine is away","at":ts})).await; + + assert_eq!(job()["state"], "failed"); + assert_eq!(crate::net::home::now(&hub).await["moving"]["state"], "failed"); + assert_eq!(job_at(ts + FAILED_SHOWN_S + 1), Value::Null); + + let reply = HomeRpc.call(&hub, &Caller { gen: "test".into(), client: 1 }, &json!(7), "home.move.dismiss", &json!({})).await; + assert_eq!(reply.len(), 1); + assert_eq!(reply[0]["ok"], true); + assert!(reply[0]["result"]["home"].is_object()); + assert!(reply[0]["result"]["home"].get("moving").is_none()); + assert_eq!(job(), Value::Null); + assert!(hub.setting("home.moving").await.unwrap_or_default().is_empty()); + assert!(hub.info_now().get("home.move").is_none()); + assert!(crate::net::home::now(&hub).await.get("moving").is_none()); + + // Dismiss must not clobber an active in-flight move. + tell(&hub, "moving", "copying", "boat").await; + let active_reply = HomeRpc.call(&hub, &Caller { gen: "test".into(), client: 1 }, &json!(8), "home.move.dismiss", &json!({})).await; + assert_eq!(active_reply[0]["result"]["home"]["moving"]["state"], "moving"); + + *STATE.lock().unwrap() = None; + WARN.lock().unwrap().clear(); + } } diff --git a/native/host/src/restarting.rs b/native/host/src/restarting.rs index 6935743af6..385925c796 100644 --- a/native/host/src/restarting.rs +++ b/native/host/src/restarting.rs @@ -66,13 +66,19 @@ pub fn announce() { /// What runs on SIGTERM, SIGINT, SIGHUP (and Ctrl+C on Windows): the clients told, then the KiCad sessions ended. pub fn on_exit() { announce(); crate::files::kicad::embed::shutdown_all(); } +/// Whether `/proc//cmdline` bytes belong to `fresh-watch.sh`. +pub fn cmdline_is_watcher(cmdline: &[u8]) -> bool { + const NEEDLE: &[u8] = b"fresh-watch"; + cmdline.windows(NEEDLE.len()).any(|w| w == NEEDLE) +} + /// Whether the auto-update watcher (scripts/fresh-watch.sh) runs for this home: None when the home is not a fresh one (`/.fresh` beside `/home`), else /// whether the pid in `/watch.pid` is alive and (where /proc says) a fresh-watch.sh. Nov 20: a watcher gone for a day left the person's app on one build, unsaid. pub fn watcher(home: &std::path::Path) -> Option { let d = home.parent()?; if !d.join(".fresh").exists() { return None } let pid: u32 = std::fs::read_to_string(d.join("watch.pid")).ok().and_then(|p| p.trim().parse().ok()).unwrap_or(0); if pid <= 1 || !crate::plat::proc::alive(pid) { return Some(false) } - Some(std::fs::read(format!("/proc/{pid}/cmdline")).map_or(true, |c| c.windows(10).any(|w| w == b"fresh-watch"))) + Some(std::fs::read(format!("/proc/{pid}/cmdline")).map_or(true, |c| cmdline_is_watcher(&c))) } /// The words for a missing watcher (guard::notice). pub const NO_WATCHER: &str = "Auto-update watcher not running: new builds will not reach this app"; @@ -97,6 +103,14 @@ pub const NO_WATCHER: &str = "Auto-update watcher not running: new builds will n std::fs::write(t.join("watch.pid"), format!("{}\n", std::process::id())).unwrap(); assert_eq!(watcher(&home), Some(!std::path::Path::new("/proc/self/cmdline").exists()), "alive, but not a fresh-watch.sh where /proc can tell"); } + #[test] fn cmdline_matches_fresh_watch_bytes() { + assert!(cmdline_is_watcher(b"/bin/bash\0/home/user/Backplane/scripts/fresh-watch.sh\0")); + assert!(cmdline_is_watcher(b"bash\0scripts/fresh-watch.sh\0--dir\0/home/user/.backplane-gpui-fresh\0")); + assert!(cmdline_is_watcher(b"fresh-watch")); + assert!(!cmdline_is_watcher(b"")); + assert!(!cmdline_is_watcher(b"fresh-watc")); + assert!(!cmdline_is_watcher(b"/usr/bin/backplane-hub\0--home\0/home/user\0")); + } #[test] fn only_a_crash_is_said_after_the_start() { let b: Value = serde_json::from_str(&back("crash", 5)).unwrap(); assert_eq!((b["reason"].as_str(), b["at"].as_u64()), (Some("crash"), Some(5))); diff --git a/web/dist/assets/app.js b/web/dist/assets/app.js index 8ac8e1819e..10afd868c0 100644 --- a/web/dist/assets/app.js +++ b/web/dist/assets/app.js @@ -1,17 +1,17 @@ -function En(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 Pi(e){return e==="done"||e==="failed"||e==="cancelled"}function Si(e,t){if(!e||e.id!==t.id)return!0;let n=Pi(e.state),i=Pi(t.state);if(n!==i)return i;return(t.ended??0)>=(e.ended??0)}function Li(e){if(e.state!=="done")return!1;if(typeof e.hold==="boolean")return!e.hold;return(e.notes??[]).length===0}var Ft={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","chats.move":"Move to project…","chats.move.none":"No project to move it to. Add a project first.","chats.new.noproject":"New chat (no project)","chats.title":"Chats","common.cancel":"Cancel","common.close":"Close","common.copy":"Copy","common.delete":"Delete","common.refresh":"Refresh","common.remove":"Remove","common.save":"Save","common.search":"Search","composer.model.tip":"Choose the model and effort","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.assembly":"Assembly","gpui.b.in.reply.to":"↩ In reply to: {quote}","gpui.b.replying.to":"↩ Replying to: {line}","gpui.bots.recall.off":"Off","gpui.bots.recall.on":"On","gpui.c.solid.big.next":"Loading it may take a while and a lot of memory.","gpui.c.solid.load.big":"Load it anyway","gpui.c.solid.loading.big":"Loading it anyway…","gpui.c.term.collapse":"Collapse","gpui.c.term.expand":"Expand","gpui.commands":"Commands","gpui.e.open.folder":"Open folder","gpui.filter.projects.and.threads":"Filter projects and threads","gpui.fold.or.unfold.the.sidebar":"Fold or unfold the sidebar","gpui.follow.paused":"Following paused","gpui.follow.wait":"Following: waiting for the agent's next edit","gpui.gerbers":"Gerbers","gpui.goal.notes":"GOAL & NOTES","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.no.goal.yet.ask.an":"No goal yet. Ask an agent to write what this project is for, or edit .backplane/intent.md.","gpui.no.models":"No models","gpui.no.threads.yet":"No threads yet.","gpui.nothing.matches":"Nothing matches","gpui.picker.favorite.add":"Add to favorites","gpui.picker.favorite.remove":"Remove from favorites","gpui.picker.favorites":"Favorites","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.projects.boards":"BOARDS ({n})","gpui.projects.mech":"MECHANICAL ({n})","gpui.projects.threads":"THREADS ({n})","gpui.projects.to.order":"TO ORDER ({n})","gpui.rail.no.board":"No board in this project","gpui.rail.no.mech":"No mechanical parts in this project","gpui.rail.no.schematic":"No schematic in this project","gpui.rail.split.needs.both":"Split needs a board and a schematic","gpui.search.models":"Search models","gpui.settings.group.agents":"Agents and tools","gpui.settings.group.general":"General","home.away":"Home ({name}) is away","home.away.queued":"Home ({name}) is away · {n} queued","home.away.since":"Home ({name}) is away since {time}","home.away.since.queued":"Home ({name}) is away since {time} · {n} queued","home.machine":"Home machine","home.move.failed":"Home move failed","home.move.failed.note":"Home move failed: {note}","home.move.here":"Make this machine the home","home.moving":"Moving home to {to}…","home.moving.step":"Moving home to {to}: {step}","hub.back.crash":"Backplane is back after it stopped unexpectedly","hub.restarting":"Restarting Backplane…","hub.restarting.build":"Restarting Backplane… (new build {build})","hub.stopped":"Backplane stopped","ios.hub.address.field":"Hub address","menu.pin":"Pin","menu.settle":"Settle","menu.unpin":"Unpin","menu.wake":"Wake","model.col.agent":"Agent","model.col.effort":"Effort","native.pair.connect":"Connect","native.thread.model":"Model","notify.settled":"Settled","palette.archive":"Archive thread","palette.command.placeholder":"Type a command or a thread","palette.diff":"Diff: what this thread changed","palette.newthread":"New thread","palette.settings":"Settings","palette.terminal":"Terminal","palette.unarchive":"Unarchive thread","phone.unsettle":"Unsettle","provider.notice.button":"Open Settings → Accounts","provider.notice.head":"No AI provider connected","provider.notice.senderr":"No AI provider connected yet. Open Settings → Accounts to connect Claude, Codex, Antigravity, or another provider.","provider.notice.senderr.remote":"No AI provider connected on {machine}. Open Settings → Accounts on {machine} to connect Claude, Codex, Antigravity, or another provider.","provider.notice.text.none":"Connect Claude, Codex, Antigravity, or another provider to start chatting.","provider.notice.text.signedout":"Sign in to Claude, Codex, or another provider in Settings → Accounts to start chatting.","reply.action":"Reply","reply.cancel":"Cancel reply","reply.to":"In reply to:","ring.hear.again.local":"Hear again (local)","ring.hear.again.openai":"Hear again (OpenAI)","ring.no.recordings.yet":"No recordings yet.","ring.recordings":"Recordings","ring.ring":"Ring","ring.search.what.you.said":"Search what you said","ring.show.all":"Show all","ring.what.happened":"What happened","rooms.new":"New room","secret.you":"You","settings.appearance":"Appearance","settings.lang":"Language","settings.lang.auto":"Automatic","settings.lang.en":"English","settings.lang.es":"Español","settings.lang.ja":"日本語","settings.theme":"Theme","settings.theme.dark":"Dark","settings.theme.light":"Light","sheet.rename":"Rename thread","sidebar.add.project":"Add project","sidebar.search.projects":"Search projects","thread.context.base":"Backplane","thread.context.copied":"Prompt copied.","thread.context.copy":"Copy prompt","thread.context.disable":"Disable","thread.context.enable":"Enable","thread.context.index":"Available skills index","thread.context.injected.label":"Injected project instructions","thread.context.instructions":"Instructions","thread.context.mcp":"Project MCPs","thread.context.native.note":"Backplane’s launch prompt. Native files are loaded by the provider.","thread.context.none.instructions":"No project instructions found.","thread.context.none.mcp":"No project MCP configurations found.","thread.context.reading":"Reading thread context…","thread.context.size":"{bytes} B · ≈{tokens} tokens","thread.context.skills":"Skills","thread.context.system":"System Prompt","thread.context.title":"Context & Prompt","thread.context.trust":"Trust and enable","thread.new":"New thread","tools.pinned":"Pinned","tools.retry":"Retry","tour.title.bots":"Bots","viewer.board":"Board","viewer.diff":"Diff","viewer.files":"Files","viewer.mech":"Mech","viewer.review":"Review","viewer.schematic":"Schematic","viewer.solid":"3D","web.chat.answer.btn":"Answer","web.chat.answer.placeholder":"Type answer…","web.chat.answered":"Answered: {answer}","web.chat.choose":"Choose a project thread on the left to begin.","web.chat.empty":"No messages yet. Type below to start a turn.","web.chat.finished":"Finished {time}","web.chat.finished.dur":"Finished {time} · {dur}","web.chat.loading":"Loading messages…","web.chat.review.mode":"Review mode","web.chat.streaming":"Streaming…","web.clone.add.dir":"Add {dir}","web.clone.back":"Back","web.clone.change.folder":"Change folder","web.clone.cloned":"Cloned {repo} into {dest}","web.clone.cloning":"Cloning {repo} into {dest}","web.clone.copied":"Copied","web.clone.first":"First message: {text}","web.clone.folder.name":"Folder name","web.clone.go":"Clone","web.clone.loading":"Loading…","web.clone.no.folders":"No folders here","web.clone.open.project":"Open the project","web.clone.open.thread":"Open the thread","web.clone.private":"private","web.clone.repo.placeholder":"https or ssh URL, or owner/repo","web.clone.retry":"Try again","web.clone.same":"Already cloned there: it is added as it is.","web.clone.signin":"Sign in to GitHub","web.clone.signin.done":"Signed in to GitHub","web.clone.signin.enter":"Enter this code on GitHub:","web.clone.signin.wait":"Starting GitHub sign-in…","web.clone.start.thread":"Start a thread","web.clone.stopped":"Stopped cloning {repo}","web.clone.tab":"Clone from git","web.clone.up":"Up","web.clone.use.dir":"Use {dir}","web.composer.attach":"Attach image","web.composer.maximages":"At most {max} images per message.","web.composer.unsupported":"Unsupported image type: {type}","web.composer.voice":"Voice dictation","web.home.error":"Could not load this project.","web.home.fold":"Hide threads","web.home.lead":"Lead time: {n} days","web.home.lead.one":"Lead time: 1 day","web.home.loading":"Loading project…","web.home.open":"Open project home","web.home.unfold":"Show threads","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.ring.app.words":"The Pebble app's words","web.ring.count":"{n} recordings","web.ring.count.one":"1 recording","web.ring.error":"Could not load recordings.","web.ring.found":"{found} of {total} have “{q}”.","web.ring.heard.by":"Heard by {model}","web.ring.heard.by.sure":"Heard by {model}, {conf}% sure","web.ring.loading":"Loading recordings…","web.ring.no.words":"(no words)","web.ring.not.heard":"Not heard","web.ring.state.busy":"being heard now","web.ring.state.failed":"not given to Pebble","web.ring.state.heard":"waiting to go to Pebble","web.ring.state.new":"waiting to be heard","web.ring.state.sent":"given to Pebble","web.ring.unavailable":"This hub does not show ring notes to a browser yet. Update it, or open Settings › Ring in the desktop app.","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","chats.move":"Mover a un proyecto…","chats.move.none":"No hay ningún proyecto al que moverlo. Añade uno primero.","chats.new.noproject":"Chat nuevo (sin proyecto)","chats.title":"Chats","common.cancel":"Cancelar","common.close":"Cerrar","common.copy":"Copiar","common.delete":"Eliminar","common.refresh":"Actualizar","common.remove":"Quitar","common.save":"Guardar","common.search":"Buscar","composer.model.tip":"Elegir el modelo y el esfuerzo","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.assembly":"Ensamblaje","gpui.b.in.reply.to":"↩ En respuesta a: {quote}","gpui.b.replying.to":"↩ Respondiendo a: {line}","gpui.bots.recall.off":"Desactivado","gpui.bots.recall.on":"Activado","gpui.c.solid.big.next":"Cargarlo puede tardar y usar mucha memoria.","gpui.c.solid.load.big":"Cargarlo de todos modos","gpui.c.solid.loading.big":"Cargándolo de todos modos…","gpui.c.term.collapse":"Contraer","gpui.c.term.expand":"Expandir","gpui.commands":"Comandos","gpui.e.open.folder":"Abrir carpeta","gpui.filter.projects.and.threads":"Filtrar proyectos e hilos","gpui.fold.or.unfold.the.sidebar":"Plegar o desplegar la barra lateral","gpui.follow.paused":"Seguimiento en pausa","gpui.follow.wait":"Siguiendo: esperando la próxima edición del agente","gpui.gerbers":"Gerbers","gpui.goal.notes":"OBJETIVO Y NOTAS","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.no.goal.yet.ask.an":"Sin objetivo aún. Pide a un agente que escriba para qué es este proyecto, o edita .backplane/intent.md.","gpui.no.models":"Sin modelos","gpui.no.threads.yet":"Sin hilos aún.","gpui.nothing.matches":"Nada coincide","gpui.picker.favorite.add":"Añadir a favoritos","gpui.picker.favorite.remove":"Quitar de favoritos","gpui.picker.favorites":"Favoritos","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.projects.boards":"PLACAS ({n})","gpui.projects.mech":"MECÁNICO ({n})","gpui.projects.threads":"HILOS ({n})","gpui.projects.to.order":"POR PEDIR ({n})","gpui.rail.no.board":"Este proyecto no tiene placa","gpui.rail.no.mech":"Este proyecto no tiene piezas mecánicas","gpui.rail.no.schematic":"Este proyecto no tiene esquema","gpui.rail.split.needs.both":"La vista dividida requiere una placa y un esquema","gpui.search.models":"Buscar modelos","gpui.settings.group.agents":"Agentes y herramientas","gpui.settings.group.general":"General","home.away":"El inicio ({name}) no está disponible","home.away.queued":"El inicio ({name}) no está disponible · {n} en cola","home.away.since":"El inicio ({name}) no está disponible desde las {time}","home.away.since.queued":"El inicio ({name}) no está disponible desde las {time} · {n} en cola","home.machine":"Máquina de inicio","home.move.failed":"No se pudo mover el inicio","home.move.failed.note":"No se pudo mover el inicio: {note}","home.move.here":"Hacer de esta máquina el inicio","home.moving":"Moviendo el inicio a {to}…","home.moving.step":"Moviendo el inicio a {to}: {step}","hub.back.crash":"Backplane volvió tras detenerse de forma inesperada","hub.restarting":"Reiniciando Backplane…","hub.restarting.build":"Reiniciando Backplane… (nueva compilación {build})","hub.stopped":"Backplane se detuvo","ios.hub.address.field":"Dirección del hub","menu.pin":"Fijar","menu.settle":"Cerrar","menu.unpin":"Desfijar","menu.wake":"Despertar","model.col.agent":"Agente","model.col.effort":"Esfuerzo","native.pair.connect":"Conectar","native.thread.model":"Modelo","notify.settled":"Cerrado","palette.archive":"Archivar hilo","palette.command.placeholder":"Escribe un comando o un hilo","palette.diff":"Diff: qué cambió este hilo","palette.newthread":"Nuevo hilo","palette.settings":"Ajustes","palette.terminal":"Terminal","palette.unarchive":"Desarchivar hilo","phone.unsettle":"Reabrir","provider.notice.button":"Abrir Configuración → Cuentas","provider.notice.head":"No hay ningún proveedor de IA conectado","provider.notice.senderr":"Aún no hay ningún proveedor de IA conectado. Abre Configuración → Cuentas para conectar Claude, Codex, Antigravity u otro proveedor.","provider.notice.senderr.remote":"No hay ningún proveedor de IA conectado en {machine}. Abre Configuración → Cuentas en {machine} para conectar Claude, Codex, Antigravity u otro proveedor.","provider.notice.text.none":"Conecta Claude, Codex, Antigravity u otro proveedor para empezar a chatear.","provider.notice.text.signedout":"Inicia sesión en Claude, Codex u otro proveedor en Configuración → Cuentas para empezar a chatear.","reply.action":"Responder","reply.cancel":"Cancelar respuesta","reply.to":"En respuesta a:","ring.hear.again.local":"Escuchar de nuevo (local)","ring.hear.again.openai":"Escuchar de nuevo (OpenAI)","ring.no.recordings.yet":"Sin grabaciones aún.","ring.recordings":"Grabaciones","ring.ring":"Anillo","ring.search.what.you.said":"Buscar lo que dijiste","ring.show.all":"Mostrar todo","ring.what.happened":"Qué ocurrió","rooms.new":"Nueva sala","secret.you":"Tú","settings.appearance":"Apariencia","settings.lang":"Idioma","settings.lang.auto":"Automático","settings.lang.en":"English","settings.lang.es":"Español","settings.lang.ja":"日本語","settings.theme":"Tema","settings.theme.dark":"Oscuro","settings.theme.light":"Claro","sheet.rename":"Renombrar hilo","sidebar.add.project":"Añadir proyecto","sidebar.search.projects":"Buscar proyectos","thread.context.base":"Backplane","thread.context.copied":"Se copiaron las instrucciones.","thread.context.copy":"Copiar instrucciones","thread.context.disable":"Desactivar","thread.context.enable":"Activar","thread.context.index":"Índice de habilidades disponibles","thread.context.injected.label":"Instrucciones del proyecto añadidas","thread.context.instructions":"Instrucciones","thread.context.mcp":"MCP del proyecto","thread.context.native.note":"Instrucciones de inicio de Backplane. El proveedor carga los archivos nativos.","thread.context.none.instructions":"No se encontraron instrucciones del proyecto.","thread.context.none.mcp":"No se encontraron configuraciones MCP del proyecto.","thread.context.reading":"Leyendo el contexto del hilo…","thread.context.size":"{bytes} B · ≈{tokens} tokens","thread.context.skills":"Habilidades","thread.context.system":"Instrucciones del sistema","thread.context.title":"Contexto e instrucciones","thread.context.trust":"Confiar y activar","thread.new":"Nuevo hilo","tools.pinned":"Fijado","tools.retry":"Reintentar","tour.title.bots":"Bots","viewer.board":"Placa","viewer.diff":"Diff","viewer.files":"Archivos","viewer.mech":"Mech","viewer.review":"Revisión","viewer.schematic":"Esquemático","viewer.solid":"3D","web.chat.answer.btn":"Responder","web.chat.answer.placeholder":"Escribe una respuesta…","web.chat.answered":"Respondido: {answer}","web.chat.choose":"Elige un hilo de proyecto a la izquierda para empezar.","web.chat.empty":"Aún no hay mensajes. Escribe abajo para iniciar un turno.","web.chat.finished":"Terminado {time}","web.chat.finished.dur":"Terminado {time} · {dur}","web.chat.loading":"Cargando mensajes…","web.chat.review.mode":"Modo de revisión","web.chat.streaming":"Transmitiendo…","web.clone.add.dir":"Añadir {dir}","web.clone.back":"Atrás","web.clone.change.folder":"Cambiar carpeta","web.clone.cloned":"{repo} clonado en {dest}","web.clone.cloning":"Clonando {repo} en {dest}","web.clone.copied":"Copiado","web.clone.first":"Primer mensaje: {text}","web.clone.folder.name":"Nombre de la carpeta","web.clone.go":"Clonar","web.clone.loading":"Cargando…","web.clone.no.folders":"No hay carpetas aquí","web.clone.open.project":"Abrir el proyecto","web.clone.open.thread":"Abrir el hilo","web.clone.private":"privado","web.clone.repo.placeholder":"URL https o ssh, o propietario/repositorio","web.clone.retry":"Reintentar","web.clone.same":"Ya está clonado ahí: se añade tal cual.","web.clone.signin":"Iniciar sesión en GitHub","web.clone.signin.done":"Sesión iniciada en GitHub","web.clone.signin.enter":"Introduce este código en GitHub:","web.clone.signin.wait":"Iniciando sesión en GitHub…","web.clone.start.thread":"Empezar un hilo","web.clone.stopped":"Se detuvo la clonación de {repo}","web.clone.tab":"Clonar desde git","web.clone.up":"Subir","web.clone.use.dir":"Usar {dir}","web.composer.attach":"Adjuntar imagen","web.composer.maximages":"Como máximo {max} imágenes por mensaje.","web.composer.unsupported":"Tipo de imagen no compatible: {type}","web.composer.voice":"Dictado por voz","web.home.error":"No se pudo cargar este proyecto.","web.home.fold":"Ocultar hilos","web.home.lead":"Plazo de entrega: {n} días","web.home.lead.one":"Plazo de entrega: 1 día","web.home.loading":"Cargando el proyecto…","web.home.open":"Abrir la página del proyecto","web.home.unfold":"Mostrar hilos","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.ring.app.words":"Las palabras de la aplicación Pebble","web.ring.count":"{n} grabaciones","web.ring.count.one":"1 grabación","web.ring.error":"No se pudieron cargar las grabaciones.","web.ring.found":"{found} de {total} contienen “{q}”.","web.ring.heard.by":"Transcrito por {model}","web.ring.heard.by.sure":"Transcrito por {model}, {conf}% de certeza","web.ring.loading":"Cargando grabaciones…","web.ring.no.words":"(sin palabras)","web.ring.not.heard":"Sin transcribir","web.ring.state.busy":"transcribiéndose ahora","web.ring.state.failed":"no entregada a Pebble","web.ring.state.heard":"en espera de entrega a Pebble","web.ring.state.new":"en espera de transcripción","web.ring.state.sent":"entregada a Pebble","web.ring.unavailable":"Este hub aún no muestra las notas del anillo en un navegador. Actualízalo o abre Configuración › Anillo en la aplicación de escritorio.","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":"ブラウザ","chats.move":"プロジェクトに移動…","chats.move.none":"移動先のプロジェクトがありません。先にプロジェクトを追加してください。","chats.new.noproject":"新しいチャット(プロジェクトなし)","chats.title":"チャット","common.cancel":"キャンセル","common.close":"閉じる","common.copy":"コピー","common.delete":"削除","common.refresh":"更新","common.remove":"削除","common.save":"保存","common.search":"検索","composer.model.tip":"モデルと推論の強さを選択","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.assembly":"アセンブリ","gpui.b.in.reply.to":"↩ 返信先:{quote}","gpui.b.replying.to":"↩ 返信中:{line}","gpui.bots.recall.off":"オフ","gpui.bots.recall.on":"オン","gpui.c.solid.big.next":"読み込みには時間と多くのメモリがかかることがあります。","gpui.c.solid.load.big":"それでも読み込む","gpui.c.solid.loading.big":"それでも読み込み中…","gpui.c.term.collapse":"折りたたむ","gpui.c.term.expand":"展開","gpui.commands":"コマンド","gpui.e.open.folder":"フォルダを開く","gpui.filter.projects.and.threads":"プロジェクトとスレッドを絞り込む","gpui.fold.or.unfold.the.sidebar":"サイドバーを折りたたむ/開く","gpui.follow.paused":"追従を一時停止中","gpui.follow.wait":"追従中: エージェントの次の編集を待っています","gpui.gerbers":"ガーバー","gpui.goal.notes":"目標とメモ","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.no.goal.yet.ask.an":"目標はまだありません。このプロジェクトの目的をエージェントに書いてもらうか、.backplane/intent.md を編集してください。","gpui.no.models":"モデルがありません","gpui.no.threads.yet":"スレッドはまだありません。","gpui.nothing.matches":"一致するものはありません","gpui.picker.favorite.add":"お気に入りに追加","gpui.picker.favorite.remove":"お気に入りから外す","gpui.picker.favorites":"お気に入り","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.projects.boards":"基板({n})","gpui.projects.mech":"機構部品({n})","gpui.projects.threads":"スレッド({n})","gpui.projects.to.order":"注文するもの({n})","gpui.rail.no.board":"このプロジェクトには基板がありません","gpui.rail.no.mech":"このプロジェクトには機械部品がありません","gpui.rail.no.schematic":"このプロジェクトには回路図がありません","gpui.rail.split.needs.both":"分割表示には基板と回路図が必要です","gpui.search.models":"モデルを検索","gpui.settings.group.agents":"エージェントとツール","gpui.settings.group.general":"一般","home.away":"ホーム({name})はオフラインです","home.away.queued":"ホーム({name})はオフラインです · {n} 件待機中","home.away.since":"ホーム({name})は {time} からオフラインです","home.away.since.queued":"ホーム({name})は {time} からオフラインです · {n} 件待機中","home.machine":"ホームマシン","home.move.failed":"ホームの移動に失敗しました","home.move.failed.note":"ホームの移動に失敗しました: {note}","home.move.here":"このマシンをホームにする","home.moving":"ホームを {to} へ移動中…","home.moving.step":"ホームを {to} へ移動中: {step}","hub.back.crash":"予期せず停止したBackplaneが戻りました","hub.restarting":"Backplaneを再起動しています…","hub.restarting.build":"Backplaneを再起動しています…(新しいビルド {build})","hub.stopped":"Backplaneは停止しました","ios.hub.address.field":"ハブのアドレス","menu.pin":"ピン留め","menu.settle":"完了","menu.unpin":"ピン留めを解除","menu.wake":"再開","model.col.agent":"エージェント","model.col.effort":"推論の強さ","native.pair.connect":"接続","native.thread.model":"モデル","notify.settled":"完了","palette.archive":"スレッドをアーカイブ","palette.command.placeholder":"コマンドまたはスレッドを入力","palette.diff":"差分:このスレッドの変更","palette.newthread":"新しいスレッド","palette.settings":"設定","palette.terminal":"ターミナル","palette.unarchive":"スレッドのアーカイブを解除","phone.unsettle":"未完了に戻す","provider.notice.button":"設定 → アカウントを開く","provider.notice.head":"AI プロバイダーが接続されていません","provider.notice.senderr":"AI プロバイダーがまだ接続されていません。設定 → アカウントを開いて、Claude、Codex、Antigravity などのプロバイダーを接続してください。","provider.notice.senderr.remote":"{machine} に AI プロバイダーが接続されていません。{machine} で設定 → アカウントを開いて、Claude、Codex、Antigravity などのプロバイダーを接続してください。","provider.notice.text.none":"チャットを始めるには、Claude、Codex、Antigravity などのプロバイダーを接続してください。","provider.notice.text.signedout":"チャットを始めるには、設定 → アカウントで Claude、Codex などのプロバイダーにサインインしてください。","reply.action":"返信","reply.cancel":"返信をやめる","reply.to":"返信先:","ring.hear.again.local":"もう一度聞き取る (ローカル)","ring.hear.again.openai":"もう一度聞き取る (OpenAI)","ring.no.recordings.yet":"録音はまだありません。","ring.recordings":"録音","ring.ring":"リング","ring.search.what.you.said":"話した内容を検索","ring.show.all":"すべて表示","ring.what.happened":"どうなったか","rooms.new":"新しいルーム","secret.you":"あなた","settings.appearance":"外観","settings.lang":"言語","settings.lang.auto":"自動","settings.lang.en":"English","settings.lang.es":"Español","settings.lang.ja":"日本語","settings.theme":"テーマ","settings.theme.dark":"ダーク","settings.theme.light":"ライト","sheet.rename":"スレッド名を変更","sidebar.add.project":"プロジェクトを追加","sidebar.search.projects":"プロジェクトを検索","thread.context.base":"Backplane","thread.context.copied":"プロンプトをコピーしました。","thread.context.copy":"プロンプトをコピー","thread.context.disable":"無効にする","thread.context.enable":"有効にする","thread.context.index":"利用可能なスキルの一覧","thread.context.injected.label":"追加されたプロジェクトの指示","thread.context.instructions":"指示","thread.context.mcp":"プロジェクトの MCP","thread.context.native.note":"Backplane が起動時に渡すプロンプトです。ネイティブファイルはプロバイダーが読み込みます。","thread.context.none.instructions":"プロジェクトの指示が見つかりません。","thread.context.none.mcp":"プロジェクトの MCP 設定が見つかりません。","thread.context.reading":"スレッドのコンテキストを読み込み中…","thread.context.size":"{bytes} B・約{tokens}トークン","thread.context.skills":"スキル","thread.context.system":"システムプロンプト","thread.context.title":"コンテキストとプロンプト","thread.context.trust":"承認して有効にする","thread.new":"新しいスレッド","tools.pinned":"固定中","tools.retry":"再試行","tour.title.bots":"ボット","viewer.board":"基板","viewer.diff":"差分","viewer.files":"ファイル","viewer.mech":"Mech","viewer.review":"レビュー","viewer.schematic":"回路図","viewer.solid":"3D","web.chat.answer.btn":"回答","web.chat.answer.placeholder":"回答を入力…","web.chat.answered":"回答済み: {answer}","web.chat.choose":"左側からプロジェクトのスレッドを選んで開始してください。","web.chat.empty":"まだメッセージはありません。下に入力して開始してください。","web.chat.finished":"完了 {time}","web.chat.finished.dur":"完了 {time} · {dur}","web.chat.loading":"メッセージを読み込んでいます…","web.chat.review.mode":"レビューモード","web.chat.streaming":"受信中…","web.clone.add.dir":"{dir} を追加","web.clone.back":"戻る","web.clone.change.folder":"フォルダを変更","web.clone.cloned":"{repo} を {dest} にクローンしました","web.clone.cloning":"{repo} を {dest} にクローン中","web.clone.copied":"コピーしました","web.clone.first":"最初のメッセージ: {text}","web.clone.folder.name":"フォルダ名","web.clone.go":"クローン","web.clone.loading":"読み込み中…","web.clone.no.folders":"フォルダがありません","web.clone.open.project":"プロジェクトを開く","web.clone.open.thread":"スレッドを開く","web.clone.private":"非公開","web.clone.repo.placeholder":"https / ssh の URL、または owner/repo","web.clone.retry":"もう一度","web.clone.same":"すでにそこにクローンされています: そのまま追加します。","web.clone.signin":"GitHub にサインイン","web.clone.signin.done":"GitHub にサインインしました","web.clone.signin.enter":"このコードを GitHub に入力してください:","web.clone.signin.wait":"GitHub のサインインを開始しています…","web.clone.start.thread":"スレッドを開始","web.clone.stopped":"{repo} のクローンを中止しました","web.clone.tab":"git からクローン","web.clone.up":"上へ","web.clone.use.dir":"{dir} を使う","web.composer.attach":"画像を添付","web.composer.maximages":"1 件のメッセージに添付できる画像は最大 {max} 枚です。","web.composer.unsupported":"未対応の画像形式です: {type}","web.composer.voice":"音声入力","web.home.error":"このプロジェクトを読み込めませんでした。","web.home.fold":"スレッドを隠す","web.home.lead":"リードタイム: {n} 日","web.home.lead.one":"リードタイム: 1 日","web.home.loading":"プロジェクトを読み込み中…","web.home.open":"プロジェクトホームを開く","web.home.unfold":"スレッドを表示","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.ring.app.words":"Pebble アプリの文字起こし","web.ring.count":"録音 {n} 件","web.ring.count.one":"録音 1 件","web.ring.error":"録音を読み込めませんでした。","web.ring.found":"{total} 件中 {found} 件に「{q}」があります。","web.ring.heard.by":"{model} が認識","web.ring.heard.by.sure":"{model} が認識、確度 {conf}%","web.ring.loading":"録音を読み込み中…","web.ring.no.words":"(言葉なし)","web.ring.not.heard":"未認識","web.ring.state.busy":"認識中","web.ring.state.failed":"Pebble に渡せませんでした","web.ring.state.heard":"Pebble への受け渡し待ち","web.ring.state.new":"認識待ち","web.ring.state.sent":"Pebble に渡しました","web.ring.unavailable":"このハブはまだブラウザーにリングのメモを表示しません。ハブを更新するか、デスクトップアプリの設定 › リングを開いてください。","web.settings.providers":"AI プロバイダー","web.settings.providers.browser":"Backplane のデスクトップまたはモバイルアプリの設定 → アカウントからプロバイダーを接続してください。"}};function Ai(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 Ct=Br(),Cn=new Set,kn=new Map;for(let[e,t]of Object.entries(Ft.en||{}))if(typeof t==="string"&&!kn.has(t))kn.set(t,e);function Br(){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 Ni(){if(typeof document<"u"&&document.documentElement)document.documentElement.lang=Ct}Ni();function rn(e){return Cn.add(e),()=>{Cn.delete(e)}}function kt(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!==Ct;if(Ct=n,Ni(),i)for(let s of Cn)s(Ct);return i}function Mi(){return Ct}function u(e,t,n){let s=(Ft[Ct]||Ft.en||{})[e]??Ft.en?.[e]??t??e;return Ai(s,n)}function he(e){if(!e)return"";let t=kn.get(e);if(!t)return e;return u(t,e)}function X(e,t="",n=""){let i=document.createElement(e);if(t)i.className=t;if(n)i.textContent=n;return i}function _e(e,t="",n){let i=X("button",t,e);if(i.type="button",n)i.addEventListener("click",n);return i}function Ir(e){let t=e.replace(/[\\/]+$/,"");if(!t)return e||"/";let n=t.split(/[\\/]/);return n[n.length-1]||t}function Rr(e,t){let n=e.includes("\\")&&!e.includes("/")?"\\":"/";return e.endsWith(n)?e+t:e+n+t}class xn{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=X("div","bp-fb"),this.root.setAttribute("data-testid","folder-browser");let s=X("div","bp-fb-head");this.upBtn=_e("↑","bp-btn-ghost bp-fb-up",()=>{if(this.parent)this.go(this.parent)}),this.upBtn.title=u("web.clone.up","Up"),this.upBtn.setAttribute("aria-label",u("web.clone.up","Up")),this.pathInput=X("input","bp-input bp-fb-path"),this.pathInput.spellcheck=!1,this.pathInput.setAttribute("data-testid","folder-path"),this.pathInput.addEventListener("keydown",(o)=>{if(o.key==="Enter"){o.preventDefault();let a=this.pathInput.value.trim();if(a)this.go(a)}}),s.append(this.upBtn,this.pathInput),this.listEl=X("div","bp-fb-list"),this.errEl=X("div","bp-ap-err bp-hidden");let r=X("div","bp-ap-foot");this.actBtn=_e("","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(X("div","bp-fb-empty",u("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(he(n instanceof Error?n.message:String(n))),this.render(null)}}refreshLocale(){this.upBtn.title=u("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(X("div","bp-fb-empty",u("web.clone.no.folders","No folders here")));return}let t=document.createDocumentFragment();for(let n of e){let i=_e("","bp-fb-row",()=>{this.go(Rr(this.path,n))});i.append(X("span","bp-fb-icon","▸"),X("span","bp-fb-name",n)),t.appendChild(i)}this.listEl.replaceChildren(t),this.listEl.scrollTop=0}updateAct(){this.actBtn.textContent=this.path?this.actionLabel(Ir(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(he(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 Pn{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=X("div","bp-modal-backdrop");e.setAttribute("data-testid","add-project");let t=X("div","bp-modal bp-ap"),n=X("div","bp-modal-head"),i=X("h2","",u("sidebar.add.project","Add project")),s=_e("×","icon",()=>this.close());s.title=u("common.close","Close"),s.setAttribute("aria-label",u("common.close","Close")),n.append(i,s),this.tabsEl=X("div","bp-ap-tabs"),this.bodyEl=X("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=u("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=_e(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",u("gpui.e.open.folder","Open folder")),e("clone",u("web.clone.tab","Clone from git")))}renderFolder(){let e=new xn(this.host.hub,(t)=>u("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=X("div","bp-ap-form"),n=X("div","bp-ap-repo"),i=X("input","bp-input");i.type="text",i.spellcheck=!1,i.autocomplete="off",i.placeholder=u("web.clone.repo.placeholder","https or ssh URL, or owner/repo"),i.setAttribute("aria-label",u("web.clone.repo.placeholder","https or ssh URL, or owner/repo")),i.setAttribute("data-testid","clone-repo"),i.value=this.repoText,i.addEventListener("input",()=>{if(this.repoText=i.value,this.repoValue="",this.showSuggest=!0,this.suggestIdx=-1,this.startErr="",!this.nameTouched)this.nameText="";this.askRepos(200),this.askDest(250)}),i.addEventListener("focus",()=>{if(this.showSuggest=!0,this.repos===null)this.askRepos(0);else this.renderSuggest()}),i.addEventListener("blur",()=>{window.setTimeout(()=>{if(document.activeElement!==i)this.showSuggest=!1,this.renderSuggest()},120)}),i.addEventListener("keydown",(p)=>this.repoKey(p)),this.repoInput=i,this.suggestEl=X("div","bp-ap-suggest bp-hidden"),this.suggestEl.setAttribute("data-testid","clone-suggest"),n.append(i,this.suggestEl),this.signinEl=X("div","bp-ap-signin bp-hidden"),this.signinEl.setAttribute("data-testid","clone-signin"),this.destEl=X("div","bp-ap-dest"),this.destEl.setAttribute("data-testid","clone-dest");let s=X("label","bp-ap-check"),r=X("input");r.type="checkbox",r.checked=this.wantThread,r.setAttribute("data-testid","clone-thread"),r.addEventListener("change",()=>{this.wantThread=r.checked}),s.append(r,X("span","",u("web.clone.start.thread","Start a thread")));let o=[n,this.signinEl,this.destEl,s];if(this.firstText)o.push(X("div","bp-ap-first bp-dim",u("web.clone.first","First message: {text}",{text:this.firstText})));let a=X("div","bp-ap-err"+(this.startErr?"":" bp-hidden"),this.startErr);a.setAttribute("data-testid","clone-start-error");let c=X("div","bp-ap-foot");this.cloneBtn=_e(u("web.clone.go","Clone"),"primary",()=>{this.startClone()}),this.cloneBtn.setAttribute("data-testid","clone-go"),c.append(this.cloneBtn),o.push(a,c),t.append(...o),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 o=_e("","bp-ap-sug"+(r===this.suggestIdx?" active":""));o.setAttribute("data-testid","clone-suggestion"),o.addEventListener("mousedown",(c)=>c.preventDefault()),o.addEventListener("click",()=>this.pickRepo(s));let a=X("div","bp-ap-sug-top");if(a.append(X("span","bp-ap-sug-name",s.name)),s.private)a.append(X("span","bp-ap-tag",u("web.clone.private","private")));if(o.append(a),s.description)o.append(X("div","bp-ap-sug-desc",s.description));i.push(o)}),n.length===0&&t){if(t.loading)i.push(X("div","bp-ap-sug-note",u("web.clone.loading","Loading…")));else if(t.hint){let s=X("div","bp-ap-sug-note");if(s.append(X("span","",he(t.hint))),t.state==="signedout"){let r=_e(u("web.clone.signin","Sign in to GitHub"),"bp-btn-line",()=>{this.startSignin()});r.addEventListener("mousedown",(o)=>o.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(he(t.error)))}else if(t){let o=X("div","bp-ap-where"),a=X("span","bp-ap-dest-path",t.destShown||t.dest||t.defaultParentShown||"");a.setAttribute("data-testid","clone-dest-shown");let c=_e(u("web.clone.change.folder","Change folder"),"bp-btn-line",()=>{this.picking=!0,this.render()});c.setAttribute("data-testid","clone-change-folder"),o.append(a,c),n.push(o);let p=X("label","bp-ap-name");p.append(X("span","bp-ap-lbl",u("web.clone.folder.name","Folder name")));let l=X("input","bp-input");if(l.type="text",l.spellcheck=!1,l.value=this.nameText,l.setAttribute("data-testid","clone-name"),l.addEventListener("input",()=>{this.nameText=l.value,this.nameTouched=l.value.trim()!=="",this.startErr="",this.askDest(250)}),l.addEventListener("keydown",(h)=>{if(h.key==="Enter"&&this.canStart())h.preventDefault(),this.startClone()}),p.append(l),n.push(p),!t.ok&&t.error)n.push(this.errLine(he(t.error)));else if(t.same)n.push(X("div","bp-ap-note bp-dim",u("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 o=e.querySelector('[data-testid="clone-name"]');if(o){if(o.focus(),r!==null)o.setSelectionRange(r,r)}}this.updateCloneBtn()}errLine(e){let t=X("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=_e(u("web.clone.back","Back"),"bp-btn-line",()=>{this.picking=!1,this.render()}),n=new xn(this.host.hub,(i)=>u("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=En();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=he(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=En(),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 o=he(r instanceof Error?r.message:String(r));if(this.jobId!==i)return;if(!this.job||this.job.id!==i){let a=await this.host.hub.rpc("clone.status",{id:i}).catch(()=>null);if(a&&a.id===i){this.apply(a);return}}if(this.jobId===i&&(!this.job||this.job.id!==i))this.jobId=s,t.disabled=!1,this.showJobError(o)}}apply(e){if(!e||e.id!==this.jobId)return;if(!Si(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&&Li(e))this.goTo(e)}renderJobView(){this.jobEl=X("div","bp-ap-job"),this.jobEl.setAttribute("data-testid","clone-job"),this.signinEl=X("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"?u("web.clone.cloned","Cloned {repo} into {dest}",{repo:i,dest:n}):t.state==="cancelled"?u("web.clone.stopped","Stopped cloning {repo}",{repo:i}):u("web.clone.cloning","Cloning {repo} into {dest}",{repo:i,dest:n}),r=[X("div","bp-ap-job-title",s)];if(t.state==="running"){let o=X("div","bp-ap-phase",he(t.phase||""));o.setAttribute("data-testid","clone-phase");let a=X("div","bp-ap-bar"+(typeof t.pct==="number"?"":" indeterminate")),c=X("div","bp-ap-bar-fill");if(typeof t.pct==="number")c.style.width=`${Math.max(0,Math.min(100,t.pct))}%`;if(a.appendChild(c),a.setAttribute("role","progressbar"),typeof t.pct==="number")a.setAttribute("aria-valuenow",String(t.pct));if(r.push(o,a),t.detail)r.push(X("div","bp-ap-detail bp-dim",t.detail));let p=X("div","bp-ap-foot"),l=_e(u("common.cancel","Cancel"),"bp-btn-line",()=>{this.host.hub.rpc("clone.cancel",{id:t.id}).then((h)=>this.apply(h)).catch(()=>{})});l.setAttribute("data-testid","clone-cancel"),p.append(l),r.push(p)}else if(t.state==="failed"||t.state==="cancelled"){if(t.state==="failed"&&t.error){let p=X("div","bp-ap-err",he(t.error));p.setAttribute("data-testid","clone-error"),r.push(p)}let o=X("div","bp-ap-foot"),a=_e(u("web.clone.back","Back"),"bp-btn-line",()=>{this.jobId="",this.job=null,this.signin=null,this.render(),this.askDest()});if(o.append(a),t.signin){let p=_e(u("web.clone.signin","Sign in to GitHub"),"bp-btn-line",()=>{this.startSignin()});p.setAttribute("data-testid","clone-signin-btn"),o.append(p)}let c=_e(u("web.clone.retry","Try again"),"primary",()=>{this.retry(t,c)});c.setAttribute("data-testid","clone-retry"),o.append(c),r.push(o)}else if(t.state==="done"){let o=t.notes??[];if(o.length>0){let l=X("ul","bp-ap-notes");l.setAttribute("data-testid","clone-notes");for(let h of o)l.appendChild(X("li","",he(h)));r.push(l)}let a=X("div","bp-ap-foot"),c=t.thread?u("web.clone.open.thread","Open the thread"):u("web.clone.open.project","Open the project"),p=_e(c,"primary",()=>this.goTo(t));p.setAttribute("data-testid","clone-open"),a.append(p),r.push(a)}e.replaceChildren(...r)}showJobError(e){if(!this.jobEl)return;this.jobEl.querySelector(".bp-ap-job-err")?.remove();let t=X("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(X("div","bp-dim",u("web.clone.signin.wait","Starting GitHub sign-in…")));else if(t.state==="waiting"){n.push(X("div","",u("web.clone.signin.enter","Enter this code on GitHub:")));let i=X("div","bp-ap-code-row"),s=X("span","bp-ap-code",t.code||"");s.setAttribute("data-testid","clone-signin-code");let r=_e(this.copied?u("web.clone.copied","Copied"):u("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 o=X("a","bp-ap-link",t.url);o.href=t.url,o.target="_blank",o.rel="noopener noreferrer",o.setAttribute("data-testid","clone-signin-url"),n.push(o)}}else if(t.state==="done")n.push(X("div","bp-ok",u("web.clone.signin.done","Signed in to GitHub")));else if(t.state==="failed")n.push(X("div","bp-ap-err",he(t.error||"")))}e.replaceChildren(...n),e.classList.toggle("bp-hidden",n.length===0)}}function jr(e){try{let t=new URL(e,window.location.origin);if(t.protocol==="https:"||t.protocol==="http:")return t.href}catch{}return null}function $t(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 o=document.createElement("code");o.className="bp-code-inline",o.textContent=r.slice(1,-1),e.appendChild(o)}else if(r.startsWith("**")&&r.endsWith("**")){let o=document.createElement("strong");o.textContent=r.slice(2,-2),e.appendChild(o)}else if(r.startsWith("*")&&r.endsWith("*")){let o=document.createElement("em");o.textContent=r.slice(1,-1),e.appendChild(o)}else if(r.startsWith("[")){let o=s[2]??"",a=jr(s[3]??"");if(a){let c=document.createElement("a");c.href=a,c.target="_blank",c.rel="noopener noreferrer",c.textContent=o,e.appendChild(c)}else e.appendChild(document.createTextNode(o))}i=n.lastIndex}if(i=(e.ended??0)}function Li(e){if(e.state!=="done")return!1;if(typeof e.hold==="boolean")return!e.hold;return(e.notes??[]).length===0}var Ft={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","chats.move":"Move to project…","chats.move.none":"No project to move it to. Add a project first.","chats.new.noproject":"New chat (no project)","chats.title":"Chats","common.cancel":"Cancel","common.close":"Close","common.copy":"Copy","common.delete":"Delete","common.refresh":"Refresh","common.remove":"Remove","common.save":"Save","common.search":"Search","composer.model.tip":"Choose the model and effort","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.assembly":"Assembly","gpui.b.in.reply.to":"↩ In reply to: {quote}","gpui.b.replying.to":"↩ Replying to: {line}","gpui.bots.recall.off":"Off","gpui.bots.recall.on":"On","gpui.c.solid.big.next":"Loading it may take a while and a lot of memory.","gpui.c.solid.load.big":"Load it anyway","gpui.c.solid.loading.big":"Loading it anyway…","gpui.c.term.collapse":"Collapse","gpui.c.term.expand":"Expand","gpui.commands":"Commands","gpui.e.open.folder":"Open folder","gpui.filter.projects.and.threads":"Filter projects and threads","gpui.fold.or.unfold.the.sidebar":"Fold or unfold the sidebar","gpui.follow.paused":"Following paused","gpui.follow.wait":"Following: waiting for the agent's next edit","gpui.gerbers":"Gerbers","gpui.goal.notes":"GOAL & NOTES","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.no.goal.yet.ask.an":"No goal yet. Ask an agent to write what this project is for, or edit .backplane/intent.md.","gpui.no.models":"No models","gpui.no.threads.yet":"No threads yet.","gpui.nothing.matches":"Nothing matches","gpui.picker.favorite.add":"Add to favorites","gpui.picker.favorite.remove":"Remove from favorites","gpui.picker.favorites":"Favorites","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.projects.boards":"BOARDS ({n})","gpui.projects.mech":"MECHANICAL ({n})","gpui.projects.threads":"THREADS ({n})","gpui.projects.to.order":"TO ORDER ({n})","gpui.rail.no.board":"No board in this project","gpui.rail.no.mech":"No mechanical parts in this project","gpui.rail.no.schematic":"No schematic in this project","gpui.rail.split.needs.both":"Split needs a board and a schematic","gpui.search.models":"Search models","gpui.settings.group.agents":"Agents and tools","gpui.settings.group.general":"General","home.away":"Home ({name}) is away","home.away.queued":"Home ({name}) is away · {n} queued","home.away.since":"Home ({name}) is away since {time}","home.away.since.queued":"Home ({name}) is away since {time} · {n} queued","home.machine":"Home machine","home.move.failed":"Home move failed","home.move.failed.note":"Home move failed: {note}","home.move.here":"Make this machine the home","home.moving":"Moving home to {to}…","home.moving.step":"Moving home to {to}: {step}","hub.back.crash":"Backplane is back after it stopped unexpectedly","hub.restarting":"Restarting Backplane…","hub.restarting.build":"Restarting Backplane… (new build {build})","hub.stopped":"Backplane stopped","ios.hub.address.field":"Hub address","menu.pin":"Pin","menu.settle":"Settle","menu.unpin":"Unpin","menu.wake":"Wake","model.col.agent":"Agent","model.col.effort":"Effort","native.pair.connect":"Connect","native.thread.model":"Model","notify.settled":"Settled","palette.archive":"Archive thread","palette.command.placeholder":"Type a command or a thread","palette.diff":"Diff: what this thread changed","palette.newthread":"New thread","palette.settings":"Settings","palette.terminal":"Terminal","palette.unarchive":"Unarchive thread","phone.unsettle":"Unsettle","provider.notice.button":"Open Settings → Accounts","provider.notice.head":"No AI provider connected","provider.notice.senderr":"No AI provider connected yet. Open Settings → Accounts to connect Claude, Codex, Antigravity, or another provider.","provider.notice.senderr.remote":"No AI provider connected on {machine}. Open Settings → Accounts on {machine} to connect Claude, Codex, Antigravity, or another provider.","provider.notice.text.none":"Connect Claude, Codex, Antigravity, or another provider to start chatting.","provider.notice.text.signedout":"Sign in to Claude, Codex, or another provider in Settings → Accounts to start chatting.","reply.action":"Reply","reply.cancel":"Cancel reply","reply.to":"In reply to:","ring.hear.again.local":"Hear again (local)","ring.hear.again.openai":"Hear again (OpenAI)","ring.no.recordings.yet":"No recordings yet.","ring.recordings":"Recordings","ring.ring":"Ring","ring.search.what.you.said":"Search what you said","ring.show.all":"Show all","ring.what.happened":"What happened","rooms.new":"New room","secret.you":"You","settings.appearance":"Appearance","settings.lang":"Language","settings.lang.auto":"Automatic","settings.lang.en":"English","settings.lang.es":"Español","settings.lang.ja":"日本語","settings.theme":"Theme","settings.theme.dark":"Dark","settings.theme.light":"Light","sheet.rename":"Rename thread","sidebar.add.project":"Add project","sidebar.search.projects":"Search projects","thread.context.base":"Backplane","thread.context.copied":"Prompt copied.","thread.context.copy":"Copy prompt","thread.context.disable":"Disable","thread.context.enable":"Enable","thread.context.index":"Available skills index","thread.context.injected.label":"Injected project instructions","thread.context.instructions":"Instructions","thread.context.mcp":"Project MCPs","thread.context.native.note":"Backplane’s launch prompt. Native files are loaded by the provider.","thread.context.none.instructions":"No project instructions found.","thread.context.none.mcp":"No project MCP configurations found.","thread.context.reading":"Reading thread context…","thread.context.size":"{bytes} B · ≈{tokens} tokens","thread.context.skills":"Skills","thread.context.system":"System Prompt","thread.context.title":"Context & Prompt","thread.context.trust":"Trust and enable","thread.new":"New thread","tools.pinned":"Pinned","tools.retry":"Retry","tour.title.bots":"Bots","viewer.board":"Board","viewer.diff":"Diff","viewer.files":"Files","viewer.mech":"Mech","viewer.review":"Review","viewer.schematic":"Schematic","viewer.solid":"3D","web.chat.answer.btn":"Answer","web.chat.answer.placeholder":"Type answer…","web.chat.answered":"Answered: {answer}","web.chat.choose":"Choose a project thread on the left to begin.","web.chat.empty":"No messages yet. Type below to start a turn.","web.chat.finished":"Finished {time}","web.chat.finished.dur":"Finished {time} · {dur}","web.chat.loading":"Loading messages…","web.chat.review.mode":"Review mode","web.chat.streaming":"Streaming…","web.clone.add.dir":"Add {dir}","web.clone.back":"Back","web.clone.change.folder":"Change folder","web.clone.cloned":"Cloned {repo} into {dest}","web.clone.cloning":"Cloning {repo} into {dest}","web.clone.copied":"Copied","web.clone.first":"First message: {text}","web.clone.folder.name":"Folder name","web.clone.go":"Clone","web.clone.loading":"Loading…","web.clone.no.folders":"No folders here","web.clone.open.project":"Open the project","web.clone.open.thread":"Open the thread","web.clone.private":"private","web.clone.repo.placeholder":"https or ssh URL, or owner/repo","web.clone.retry":"Try again","web.clone.same":"Already cloned there: it is added as it is.","web.clone.signin":"Sign in to GitHub","web.clone.signin.done":"Signed in to GitHub","web.clone.signin.enter":"Enter this code on GitHub:","web.clone.signin.wait":"Starting GitHub sign-in…","web.clone.start.thread":"Start a thread","web.clone.stopped":"Stopped cloning {repo}","web.clone.tab":"Clone from git","web.clone.up":"Up","web.clone.use.dir":"Use {dir}","web.composer.attach":"Attach image","web.composer.maximages":"At most {max} images per message.","web.composer.unsupported":"Unsupported image type: {type}","web.composer.voice":"Voice dictation","web.home.error":"Could not load this project.","web.home.fold":"Hide threads","web.home.lead":"Lead time: {n} days","web.home.lead.one":"Lead time: 1 day","web.home.loading":"Loading project…","web.home.open":"Open project home","web.home.unfold":"Show threads","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.ring.app.words":"The Pebble app's words","web.ring.count":"{n} recordings","web.ring.count.one":"1 recording","web.ring.error":"Could not load recordings.","web.ring.found":"{found} of {total} have “{q}”.","web.ring.heard.by":"Heard by {model}","web.ring.heard.by.sure":"Heard by {model}, {conf}% sure","web.ring.loading":"Loading recordings…","web.ring.no.words":"(no words)","web.ring.not.heard":"Not heard","web.ring.state.busy":"being heard now","web.ring.state.failed":"not given to Pebble","web.ring.state.heard":"waiting to go to Pebble","web.ring.state.new":"waiting to be heard","web.ring.state.sent":"given to Pebble","web.ring.unavailable":"This hub does not show ring notes to a browser yet. Update it, or open Settings › Ring in the desktop app.","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","chats.move":"Mover a un proyecto…","chats.move.none":"No hay ningún proyecto al que moverlo. Añade uno primero.","chats.new.noproject":"Chat nuevo (sin proyecto)","chats.title":"Chats","common.cancel":"Cancelar","common.close":"Cerrar","common.copy":"Copiar","common.delete":"Eliminar","common.refresh":"Actualizar","common.remove":"Quitar","common.save":"Guardar","common.search":"Buscar","composer.model.tip":"Elegir el modelo y el esfuerzo","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.assembly":"Ensamblaje","gpui.b.in.reply.to":"↩ En respuesta a: {quote}","gpui.b.replying.to":"↩ Respondiendo a: {line}","gpui.bots.recall.off":"Desactivado","gpui.bots.recall.on":"Activado","gpui.c.solid.big.next":"Cargarlo puede tardar y usar mucha memoria.","gpui.c.solid.load.big":"Cargarlo de todos modos","gpui.c.solid.loading.big":"Cargándolo de todos modos…","gpui.c.term.collapse":"Contraer","gpui.c.term.expand":"Expandir","gpui.commands":"Comandos","gpui.e.open.folder":"Abrir carpeta","gpui.filter.projects.and.threads":"Filtrar proyectos e hilos","gpui.fold.or.unfold.the.sidebar":"Plegar o desplegar la barra lateral","gpui.follow.paused":"Seguimiento en pausa","gpui.follow.wait":"Siguiendo: esperando la próxima edición del agente","gpui.gerbers":"Gerbers","gpui.goal.notes":"OBJETIVO Y NOTAS","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.no.goal.yet.ask.an":"Sin objetivo aún. Pide a un agente que escriba para qué es este proyecto, o edita .backplane/intent.md.","gpui.no.models":"Sin modelos","gpui.no.threads.yet":"Sin hilos aún.","gpui.nothing.matches":"Nada coincide","gpui.picker.favorite.add":"Añadir a favoritos","gpui.picker.favorite.remove":"Quitar de favoritos","gpui.picker.favorites":"Favoritos","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.projects.boards":"PLACAS ({n})","gpui.projects.mech":"MECÁNICO ({n})","gpui.projects.threads":"HILOS ({n})","gpui.projects.to.order":"POR PEDIR ({n})","gpui.rail.no.board":"Este proyecto no tiene placa","gpui.rail.no.mech":"Este proyecto no tiene piezas mecánicas","gpui.rail.no.schematic":"Este proyecto no tiene esquema","gpui.rail.split.needs.both":"La vista dividida requiere una placa y un esquema","gpui.search.models":"Buscar modelos","gpui.settings.group.agents":"Agentes y herramientas","gpui.settings.group.general":"General","home.away":"El inicio ({name}) no está disponible","home.away.queued":"El inicio ({name}) no está disponible · {n} en cola","home.away.since":"El inicio ({name}) no está disponible desde las {time}","home.away.since.queued":"El inicio ({name}) no está disponible desde las {time} · {n} en cola","home.machine":"Máquina de inicio","home.move.failed":"No se pudo mover el inicio","home.move.failed.note":"No se pudo mover el inicio: {note}","home.move.here":"Hacer de esta máquina el inicio","home.moving":"Moviendo el inicio a {to}…","home.moving.step":"Moviendo el inicio a {to}: {step}","hub.back.crash":"Backplane volvió tras detenerse de forma inesperada","hub.restarting":"Reiniciando Backplane…","hub.restarting.build":"Reiniciando Backplane… (nueva compilación {build})","hub.stopped":"Backplane se detuvo","ios.hub.address.field":"Dirección del hub","menu.pin":"Fijar","menu.settle":"Cerrar","menu.unpin":"Desfijar","menu.wake":"Despertar","model.col.agent":"Agente","model.col.effort":"Esfuerzo","native.pair.connect":"Conectar","native.thread.model":"Modelo","notify.settled":"Cerrado","palette.archive":"Archivar hilo","palette.command.placeholder":"Escribe un comando o un hilo","palette.diff":"Diff: qué cambió este hilo","palette.newthread":"Nuevo hilo","palette.settings":"Ajustes","palette.terminal":"Terminal","palette.unarchive":"Desarchivar hilo","phone.unsettle":"Reabrir","provider.notice.button":"Abrir Configuración → Cuentas","provider.notice.head":"No hay ningún proveedor de IA conectado","provider.notice.senderr":"Aún no hay ningún proveedor de IA conectado. Abre Configuración → Cuentas para conectar Claude, Codex, Antigravity u otro proveedor.","provider.notice.senderr.remote":"No hay ningún proveedor de IA conectado en {machine}. Abre Configuración → Cuentas en {machine} para conectar Claude, Codex, Antigravity u otro proveedor.","provider.notice.text.none":"Conecta Claude, Codex, Antigravity u otro proveedor para empezar a chatear.","provider.notice.text.signedout":"Inicia sesión en Claude, Codex u otro proveedor en Configuración → Cuentas para empezar a chatear.","reply.action":"Responder","reply.cancel":"Cancelar respuesta","reply.to":"En respuesta a:","ring.hear.again.local":"Escuchar de nuevo (local)","ring.hear.again.openai":"Escuchar de nuevo (OpenAI)","ring.no.recordings.yet":"Sin grabaciones aún.","ring.recordings":"Grabaciones","ring.ring":"Anillo","ring.search.what.you.said":"Buscar lo que dijiste","ring.show.all":"Mostrar todo","ring.what.happened":"Qué ocurrió","rooms.new":"Nueva sala","secret.you":"Tú","settings.appearance":"Apariencia","settings.lang":"Idioma","settings.lang.auto":"Automático","settings.lang.en":"English","settings.lang.es":"Español","settings.lang.ja":"日本語","settings.theme":"Tema","settings.theme.dark":"Oscuro","settings.theme.light":"Claro","sheet.rename":"Renombrar hilo","sidebar.add.project":"Añadir proyecto","sidebar.search.projects":"Buscar proyectos","thread.context.base":"Backplane","thread.context.copied":"Se copiaron las instrucciones.","thread.context.copy":"Copiar instrucciones","thread.context.disable":"Desactivar","thread.context.enable":"Activar","thread.context.index":"Índice de habilidades disponibles","thread.context.injected.label":"Instrucciones del proyecto añadidas","thread.context.instructions":"Instrucciones","thread.context.mcp":"MCP del proyecto","thread.context.native.note":"Instrucciones de inicio de Backplane. El proveedor carga los archivos nativos.","thread.context.none.instructions":"No se encontraron instrucciones del proyecto.","thread.context.none.mcp":"No se encontraron configuraciones MCP del proyecto.","thread.context.reading":"Leyendo el contexto del hilo…","thread.context.size":"{bytes} B · ≈{tokens} tokens","thread.context.skills":"Habilidades","thread.context.system":"Instrucciones del sistema","thread.context.title":"Contexto e instrucciones","thread.context.trust":"Confiar y activar","thread.new":"Nuevo hilo","tools.pinned":"Fijado","tools.retry":"Reintentar","tour.title.bots":"Bots","viewer.board":"Placa","viewer.diff":"Diff","viewer.files":"Archivos","viewer.mech":"Mech","viewer.review":"Revisión","viewer.schematic":"Esquemático","viewer.solid":"3D","web.chat.answer.btn":"Responder","web.chat.answer.placeholder":"Escribe una respuesta…","web.chat.answered":"Respondido: {answer}","web.chat.choose":"Elige un hilo de proyecto a la izquierda para empezar.","web.chat.empty":"Aún no hay mensajes. Escribe abajo para iniciar un turno.","web.chat.finished":"Terminado {time}","web.chat.finished.dur":"Terminado {time} · {dur}","web.chat.loading":"Cargando mensajes…","web.chat.review.mode":"Modo de revisión","web.chat.streaming":"Transmitiendo…","web.clone.add.dir":"Añadir {dir}","web.clone.back":"Atrás","web.clone.change.folder":"Cambiar carpeta","web.clone.cloned":"{repo} clonado en {dest}","web.clone.cloning":"Clonando {repo} en {dest}","web.clone.copied":"Copiado","web.clone.first":"Primer mensaje: {text}","web.clone.folder.name":"Nombre de la carpeta","web.clone.go":"Clonar","web.clone.loading":"Cargando…","web.clone.no.folders":"No hay carpetas aquí","web.clone.open.project":"Abrir el proyecto","web.clone.open.thread":"Abrir el hilo","web.clone.private":"privado","web.clone.repo.placeholder":"URL https o ssh, o propietario/repositorio","web.clone.retry":"Reintentar","web.clone.same":"Ya está clonado ahí: se añade tal cual.","web.clone.signin":"Iniciar sesión en GitHub","web.clone.signin.done":"Sesión iniciada en GitHub","web.clone.signin.enter":"Introduce este código en GitHub:","web.clone.signin.wait":"Iniciando sesión en GitHub…","web.clone.start.thread":"Empezar un hilo","web.clone.stopped":"Se detuvo la clonación de {repo}","web.clone.tab":"Clonar desde git","web.clone.up":"Subir","web.clone.use.dir":"Usar {dir}","web.composer.attach":"Adjuntar imagen","web.composer.maximages":"Como máximo {max} imágenes por mensaje.","web.composer.unsupported":"Tipo de imagen no compatible: {type}","web.composer.voice":"Dictado por voz","web.home.error":"No se pudo cargar este proyecto.","web.home.fold":"Ocultar hilos","web.home.lead":"Plazo de entrega: {n} días","web.home.lead.one":"Plazo de entrega: 1 día","web.home.loading":"Cargando el proyecto…","web.home.open":"Abrir la página del proyecto","web.home.unfold":"Mostrar hilos","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.ring.app.words":"Las palabras de la aplicación Pebble","web.ring.count":"{n} grabaciones","web.ring.count.one":"1 grabación","web.ring.error":"No se pudieron cargar las grabaciones.","web.ring.found":"{found} de {total} contienen “{q}”.","web.ring.heard.by":"Transcrito por {model}","web.ring.heard.by.sure":"Transcrito por {model}, {conf}% de certeza","web.ring.loading":"Cargando grabaciones…","web.ring.no.words":"(sin palabras)","web.ring.not.heard":"Sin transcribir","web.ring.state.busy":"transcribiéndose ahora","web.ring.state.failed":"no entregada a Pebble","web.ring.state.heard":"en espera de entrega a Pebble","web.ring.state.new":"en espera de transcripción","web.ring.state.sent":"entregada a Pebble","web.ring.unavailable":"Este hub aún no muestra las notas del anillo en un navegador. Actualízalo o abre Configuración › Anillo en la aplicación de escritorio.","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":"ブラウザ","chats.move":"プロジェクトに移動…","chats.move.none":"移動先のプロジェクトがありません。先にプロジェクトを追加してください。","chats.new.noproject":"新しいチャット(プロジェクトなし)","chats.title":"チャット","common.cancel":"キャンセル","common.close":"閉じる","common.copy":"コピー","common.delete":"削除","common.refresh":"更新","common.remove":"削除","common.save":"保存","common.search":"検索","composer.model.tip":"モデルと推論の強さを選択","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.assembly":"アセンブリ","gpui.b.in.reply.to":"↩ 返信先:{quote}","gpui.b.replying.to":"↩ 返信中:{line}","gpui.bots.recall.off":"オフ","gpui.bots.recall.on":"オン","gpui.c.solid.big.next":"読み込みには時間と多くのメモリがかかることがあります。","gpui.c.solid.load.big":"それでも読み込む","gpui.c.solid.loading.big":"それでも読み込み中…","gpui.c.term.collapse":"折りたたむ","gpui.c.term.expand":"展開","gpui.commands":"コマンド","gpui.e.open.folder":"フォルダを開く","gpui.filter.projects.and.threads":"プロジェクトとスレッドを絞り込む","gpui.fold.or.unfold.the.sidebar":"サイドバーを折りたたむ/開く","gpui.follow.paused":"追従を一時停止中","gpui.follow.wait":"追従中: エージェントの次の編集を待っています","gpui.gerbers":"ガーバー","gpui.goal.notes":"目標とメモ","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.no.goal.yet.ask.an":"目標はまだありません。このプロジェクトの目的をエージェントに書いてもらうか、.backplane/intent.md を編集してください。","gpui.no.models":"モデルがありません","gpui.no.threads.yet":"スレッドはまだありません。","gpui.nothing.matches":"一致するものはありません","gpui.picker.favorite.add":"お気に入りに追加","gpui.picker.favorite.remove":"お気に入りから外す","gpui.picker.favorites":"お気に入り","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.projects.boards":"基板({n})","gpui.projects.mech":"機構部品({n})","gpui.projects.threads":"スレッド({n})","gpui.projects.to.order":"注文するもの({n})","gpui.rail.no.board":"このプロジェクトには基板がありません","gpui.rail.no.mech":"このプロジェクトには機械部品がありません","gpui.rail.no.schematic":"このプロジェクトには回路図がありません","gpui.rail.split.needs.both":"分割表示には基板と回路図が必要です","gpui.search.models":"モデルを検索","gpui.settings.group.agents":"エージェントとツール","gpui.settings.group.general":"一般","home.away":"ホーム({name})はオフラインです","home.away.queued":"ホーム({name})はオフラインです · {n} 件待機中","home.away.since":"ホーム({name})は {time} からオフラインです","home.away.since.queued":"ホーム({name})は {time} からオフラインです · {n} 件待機中","home.machine":"ホームマシン","home.move.failed":"ホームの移動に失敗しました","home.move.failed.note":"ホームの移動に失敗しました: {note}","home.move.here":"このマシンをホームにする","home.moving":"ホームを {to} へ移動中…","home.moving.step":"ホームを {to} へ移動中: {step}","hub.back.crash":"予期せず停止したBackplaneが戻りました","hub.restarting":"Backplaneを再起動しています…","hub.restarting.build":"Backplaneを再起動しています…(新しいビルド {build})","hub.stopped":"Backplaneは停止しました","ios.hub.address.field":"ハブのアドレス","menu.pin":"ピン留め","menu.settle":"完了","menu.unpin":"ピン留めを解除","menu.wake":"再開","model.col.agent":"エージェント","model.col.effort":"推論の強さ","native.pair.connect":"接続","native.thread.model":"モデル","notify.settled":"完了","palette.archive":"スレッドをアーカイブ","palette.command.placeholder":"コマンドまたはスレッドを入力","palette.diff":"差分:このスレッドの変更","palette.newthread":"新しいスレッド","palette.settings":"設定","palette.terminal":"ターミナル","palette.unarchive":"スレッドのアーカイブを解除","phone.unsettle":"未完了に戻す","provider.notice.button":"設定 → アカウントを開く","provider.notice.head":"AI プロバイダーが接続されていません","provider.notice.senderr":"AI プロバイダーがまだ接続されていません。設定 → アカウントを開いて、Claude、Codex、Antigravity などのプロバイダーを接続してください。","provider.notice.senderr.remote":"{machine} に AI プロバイダーが接続されていません。{machine} で設定 → アカウントを開いて、Claude、Codex、Antigravity などのプロバイダーを接続してください。","provider.notice.text.none":"チャットを始めるには、Claude、Codex、Antigravity などのプロバイダーを接続してください。","provider.notice.text.signedout":"チャットを始めるには、設定 → アカウントで Claude、Codex などのプロバイダーにサインインしてください。","reply.action":"返信","reply.cancel":"返信をやめる","reply.to":"返信先:","ring.hear.again.local":"もう一度聞き取る (ローカル)","ring.hear.again.openai":"もう一度聞き取る (OpenAI)","ring.no.recordings.yet":"録音はまだありません。","ring.recordings":"録音","ring.ring":"リング","ring.search.what.you.said":"話した内容を検索","ring.show.all":"すべて表示","ring.what.happened":"どうなったか","rooms.new":"新しいルーム","secret.you":"あなた","settings.appearance":"外観","settings.lang":"言語","settings.lang.auto":"自動","settings.lang.en":"English","settings.lang.es":"Español","settings.lang.ja":"日本語","settings.theme":"テーマ","settings.theme.dark":"ダーク","settings.theme.light":"ライト","sheet.rename":"スレッド名を変更","sidebar.add.project":"プロジェクトを追加","sidebar.search.projects":"プロジェクトを検索","thread.context.base":"Backplane","thread.context.copied":"プロンプトをコピーしました。","thread.context.copy":"プロンプトをコピー","thread.context.disable":"無効にする","thread.context.enable":"有効にする","thread.context.index":"利用可能なスキルの一覧","thread.context.injected.label":"追加されたプロジェクトの指示","thread.context.instructions":"指示","thread.context.mcp":"プロジェクトの MCP","thread.context.native.note":"Backplane が起動時に渡すプロンプトです。ネイティブファイルはプロバイダーが読み込みます。","thread.context.none.instructions":"プロジェクトの指示が見つかりません。","thread.context.none.mcp":"プロジェクトの MCP 設定が見つかりません。","thread.context.reading":"スレッドのコンテキストを読み込み中…","thread.context.size":"{bytes} B・約{tokens}トークン","thread.context.skills":"スキル","thread.context.system":"システムプロンプト","thread.context.title":"コンテキストとプロンプト","thread.context.trust":"承認して有効にする","thread.new":"新しいスレッド","tools.pinned":"固定中","tools.retry":"再試行","tour.title.bots":"ボット","viewer.board":"基板","viewer.diff":"差分","viewer.files":"ファイル","viewer.mech":"Mech","viewer.review":"レビュー","viewer.schematic":"回路図","viewer.solid":"3D","web.chat.answer.btn":"回答","web.chat.answer.placeholder":"回答を入力…","web.chat.answered":"回答済み: {answer}","web.chat.choose":"左側からプロジェクトのスレッドを選んで開始してください。","web.chat.empty":"まだメッセージはありません。下に入力して開始してください。","web.chat.finished":"完了 {time}","web.chat.finished.dur":"完了 {time} · {dur}","web.chat.loading":"メッセージを読み込んでいます…","web.chat.review.mode":"レビューモード","web.chat.streaming":"受信中…","web.clone.add.dir":"{dir} を追加","web.clone.back":"戻る","web.clone.change.folder":"フォルダを変更","web.clone.cloned":"{repo} を {dest} にクローンしました","web.clone.cloning":"{repo} を {dest} にクローン中","web.clone.copied":"コピーしました","web.clone.first":"最初のメッセージ: {text}","web.clone.folder.name":"フォルダ名","web.clone.go":"クローン","web.clone.loading":"読み込み中…","web.clone.no.folders":"フォルダがありません","web.clone.open.project":"プロジェクトを開く","web.clone.open.thread":"スレッドを開く","web.clone.private":"非公開","web.clone.repo.placeholder":"https / ssh の URL、または owner/repo","web.clone.retry":"もう一度","web.clone.same":"すでにそこにクローンされています: そのまま追加します。","web.clone.signin":"GitHub にサインイン","web.clone.signin.done":"GitHub にサインインしました","web.clone.signin.enter":"このコードを GitHub に入力してください:","web.clone.signin.wait":"GitHub のサインインを開始しています…","web.clone.start.thread":"スレッドを開始","web.clone.stopped":"{repo} のクローンを中止しました","web.clone.tab":"git からクローン","web.clone.up":"上へ","web.clone.use.dir":"{dir} を使う","web.composer.attach":"画像を添付","web.composer.maximages":"1 件のメッセージに添付できる画像は最大 {max} 枚です。","web.composer.unsupported":"未対応の画像形式です: {type}","web.composer.voice":"音声入力","web.home.error":"このプロジェクトを読み込めませんでした。","web.home.fold":"スレッドを隠す","web.home.lead":"リードタイム: {n} 日","web.home.lead.one":"リードタイム: 1 日","web.home.loading":"プロジェクトを読み込み中…","web.home.open":"プロジェクトホームを開く","web.home.unfold":"スレッドを表示","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.ring.app.words":"Pebble アプリの文字起こし","web.ring.count":"録音 {n} 件","web.ring.count.one":"録音 1 件","web.ring.error":"録音を読み込めませんでした。","web.ring.found":"{total} 件中 {found} 件に「{q}」があります。","web.ring.heard.by":"{model} が認識","web.ring.heard.by.sure":"{model} が認識、確度 {conf}%","web.ring.loading":"録音を読み込み中…","web.ring.no.words":"(言葉なし)","web.ring.not.heard":"未認識","web.ring.state.busy":"認識中","web.ring.state.failed":"Pebble に渡せませんでした","web.ring.state.heard":"Pebble への受け渡し待ち","web.ring.state.new":"認識待ち","web.ring.state.sent":"Pebble に渡しました","web.ring.unavailable":"このハブはまだブラウザーにリングのメモを表示しません。ハブを更新するか、デスクトップアプリの設定 › リングを開いてください。","web.settings.providers":"AI プロバイダー","web.settings.providers.browser":"Backplane のデスクトップまたはモバイルアプリの設定 → アカウントからプロバイダーを接続してください。"}};function Ai(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 Ct=Br(),Cn=new Set,kn=new Map;for(let[e,t]of Object.entries(Ft.en||{}))if(typeof t==="string"&&!kn.has(t))kn.set(t,e);function Br(){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 Ni(){if(typeof document<"u"&&document.documentElement)document.documentElement.lang=Ct}Ni();function rn(e){return Cn.add(e),()=>{Cn.delete(e)}}function kt(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!==Ct;if(Ct=n,Ni(),i)for(let s of Cn)s(Ct);return i}function Mi(){return Ct}function m(e,t,n){let s=(Ft[Ct]||Ft.en||{})[e]??Ft.en?.[e]??t??e;return Ai(s,n)}function he(e){if(!e)return"";let t=kn.get(e);if(!t)return e;return m(t,e)}function X(e,t="",n=""){let i=document.createElement(e);if(t)i.className=t;if(n)i.textContent=n;return i}function _e(e,t="",n){let i=X("button",t,e);if(i.type="button",n)i.addEventListener("click",n);return i}function Ir(e){let t=e.replace(/[\\/]+$/,"");if(!t)return e||"/";let n=t.split(/[\\/]/);return n[n.length-1]||t}function Rr(e,t){let n=e.includes("\\")&&!e.includes("/")?"\\":"/";return e.endsWith(n)?e+t:e+n+t}class xn{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=X("div","bp-fb"),this.root.setAttribute("data-testid","folder-browser");let s=X("div","bp-fb-head");this.upBtn=_e("↑","bp-btn-ghost bp-fb-up",()=>{if(this.parent)this.go(this.parent)}),this.upBtn.title=m("web.clone.up","Up"),this.upBtn.setAttribute("aria-label",m("web.clone.up","Up")),this.pathInput=X("input","bp-input bp-fb-path"),this.pathInput.spellcheck=!1,this.pathInput.setAttribute("data-testid","folder-path"),this.pathInput.addEventListener("keydown",(o)=>{if(o.key==="Enter"){o.preventDefault();let a=this.pathInput.value.trim();if(a)this.go(a)}}),s.append(this.upBtn,this.pathInput),this.listEl=X("div","bp-fb-list"),this.errEl=X("div","bp-ap-err bp-hidden");let r=X("div","bp-ap-foot");this.actBtn=_e("","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(X("div","bp-fb-empty",m("web.clone.loading","Loading…")));try{let n=await this.hub.rpc("dirs.list",{path:e});if(t!==this.gen)return;this.path=n.path,this.parent=n.parent??null,this.render(n.dirs??[])}catch(n){if(t!==this.gen)return;this.setError(he(n instanceof Error?n.message:String(n))),this.render(null)}}refreshLocale(){this.upBtn.title=m("web.clone.up","Up"),this.updateAct()}render(e){if(this.pathInput.value=this.path,this.upBtn.disabled=!this.parent,this.updateAct(),e===null){this.listEl.replaceChildren();return}if(e.length===0){this.listEl.replaceChildren(X("div","bp-fb-empty",m("web.clone.no.folders","No folders here")));return}let t=document.createDocumentFragment();for(let n of e){let i=_e("","bp-fb-row",()=>{this.go(Rr(this.path,n))});i.append(X("span","bp-fb-icon","▸"),X("span","bp-fb-name",n)),t.appendChild(i)}this.listEl.replaceChildren(t),this.listEl.scrollTop=0}updateAct(){this.actBtn.textContent=this.path?this.actionLabel(Ir(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(he(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 Pn{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=X("div","bp-modal-backdrop");e.setAttribute("data-testid","add-project");let t=X("div","bp-modal bp-ap"),n=X("div","bp-modal-head"),i=X("h2","",m("sidebar.add.project","Add project")),s=_e("×","icon",()=>this.close());s.title=m("common.close","Close"),s.setAttribute("aria-label",m("common.close","Close")),n.append(i,s),this.tabsEl=X("div","bp-ap-tabs"),this.bodyEl=X("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=m("sidebar.add.project","Add project");if(this.renderTabs(),this.repoInput=null,this.suggestEl=null,this.destEl=null,this.signinEl=null,this.cloneBtn=null,this.jobEl=null,this.mode==="folder")this.renderFolder();else if(this.jobId&&this.job)this.renderJobView();else if(this.picking)this.renderPickParent();else this.renderCloneForm()}renderTabs(){if(!this.tabsEl)return;if(!this.host.hub.hasFeature("clone")){this.tabsEl.classList.add("bp-hidden");return}this.tabsEl.classList.remove("bp-hidden");let e=(t,n)=>{let i=_e(n,"bp-ap-tab"+(this.mode===t?" on":""),()=>{if(this.mode===t)return;if(this.mode=t,this.render(),t==="clone"&&!this.jobId&&this.repos===null)this.askRepos(0)});return i.setAttribute("data-testid",`ap-tab-${t}`),i.setAttribute("aria-pressed",String(this.mode===t)),i};this.tabsEl.replaceChildren(e("folder",m("gpui.e.open.folder","Open folder")),e("clone",m("web.clone.tab","Clone from git")))}renderFolder(){let e=new xn(this.host.hub,(t)=>m("web.clone.add.dir","Add {dir}",{dir:t}),async(t)=>{let n=await this.host.hub.rpc("project.add",{path:t},30000);if(this.close(),n.project)this.host.onProjectAdded(n.project)});this.bodyEl.replaceChildren(e.root),e.go("")}renderCloneForm(){let e=this.bodyEl,t=X("div","bp-ap-form"),n=X("div","bp-ap-repo"),i=X("input","bp-input");i.type="text",i.spellcheck=!1,i.autocomplete="off",i.placeholder=m("web.clone.repo.placeholder","https or ssh URL, or owner/repo"),i.setAttribute("aria-label",m("web.clone.repo.placeholder","https or ssh URL, or owner/repo")),i.setAttribute("data-testid","clone-repo"),i.value=this.repoText,i.addEventListener("input",()=>{if(this.repoText=i.value,this.repoValue="",this.showSuggest=!0,this.suggestIdx=-1,this.startErr="",!this.nameTouched)this.nameText="";this.askRepos(200),this.askDest(250)}),i.addEventListener("focus",()=>{if(this.showSuggest=!0,this.repos===null)this.askRepos(0);else this.renderSuggest()}),i.addEventListener("blur",()=>{window.setTimeout(()=>{if(document.activeElement!==i)this.showSuggest=!1,this.renderSuggest()},120)}),i.addEventListener("keydown",(p)=>this.repoKey(p)),this.repoInput=i,this.suggestEl=X("div","bp-ap-suggest bp-hidden"),this.suggestEl.setAttribute("data-testid","clone-suggest"),n.append(i,this.suggestEl),this.signinEl=X("div","bp-ap-signin bp-hidden"),this.signinEl.setAttribute("data-testid","clone-signin"),this.destEl=X("div","bp-ap-dest"),this.destEl.setAttribute("data-testid","clone-dest");let s=X("label","bp-ap-check"),r=X("input");r.type="checkbox",r.checked=this.wantThread,r.setAttribute("data-testid","clone-thread"),r.addEventListener("change",()=>{this.wantThread=r.checked}),s.append(r,X("span","",m("web.clone.start.thread","Start a thread")));let o=[n,this.signinEl,this.destEl,s];if(this.firstText)o.push(X("div","bp-ap-first bp-dim",m("web.clone.first","First message: {text}",{text:this.firstText})));let a=X("div","bp-ap-err"+(this.startErr?"":" bp-hidden"),this.startErr);a.setAttribute("data-testid","clone-start-error");let c=X("div","bp-ap-foot");this.cloneBtn=_e(m("web.clone.go","Clone"),"primary",()=>{this.startClone()}),this.cloneBtn.setAttribute("data-testid","clone-go"),c.append(this.cloneBtn),o.push(a,c),t.append(...o),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 o=_e("","bp-ap-sug"+(r===this.suggestIdx?" active":""));o.setAttribute("data-testid","clone-suggestion"),o.addEventListener("mousedown",(c)=>c.preventDefault()),o.addEventListener("click",()=>this.pickRepo(s));let a=X("div","bp-ap-sug-top");if(a.append(X("span","bp-ap-sug-name",s.name)),s.private)a.append(X("span","bp-ap-tag",m("web.clone.private","private")));if(o.append(a),s.description)o.append(X("div","bp-ap-sug-desc",s.description));i.push(o)}),n.length===0&&t){if(t.loading)i.push(X("div","bp-ap-sug-note",m("web.clone.loading","Loading…")));else if(t.hint){let s=X("div","bp-ap-sug-note");if(s.append(X("span","",he(t.hint))),t.state==="signedout"){let r=_e(m("web.clone.signin","Sign in to GitHub"),"bp-btn-line",()=>{this.startSignin()});r.addEventListener("mousedown",(o)=>o.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(he(t.error)))}else if(t){let o=X("div","bp-ap-where"),a=X("span","bp-ap-dest-path",t.destShown||t.dest||t.defaultParentShown||"");a.setAttribute("data-testid","clone-dest-shown");let c=_e(m("web.clone.change.folder","Change folder"),"bp-btn-line",()=>{this.picking=!0,this.render()});c.setAttribute("data-testid","clone-change-folder"),o.append(a,c),n.push(o);let p=X("label","bp-ap-name");p.append(X("span","bp-ap-lbl",m("web.clone.folder.name","Folder name")));let l=X("input","bp-input");if(l.type="text",l.spellcheck=!1,l.value=this.nameText,l.setAttribute("data-testid","clone-name"),l.addEventListener("input",()=>{this.nameText=l.value,this.nameTouched=l.value.trim()!=="",this.startErr="",this.askDest(250)}),l.addEventListener("keydown",(h)=>{if(h.key==="Enter"&&this.canStart())h.preventDefault(),this.startClone()}),p.append(l),n.push(p),!t.ok&&t.error)n.push(this.errLine(he(t.error)));else if(t.same)n.push(X("div","bp-ap-note bp-dim",m("web.clone.same","Already cloned there: it is added as it is.")))}let i=document.activeElement,s=i&&e.contains(i)&&i.getAttribute("data-testid")==="clone-name",r=s?i.selectionStart:null;if(e.replaceChildren(...n),e.classList.toggle("bp-hidden",n.length===0),s){let o=e.querySelector('[data-testid="clone-name"]');if(o){if(o.focus(),r!==null)o.setSelectionRange(r,r)}}this.updateCloneBtn()}errLine(e){let t=X("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=_e(m("web.clone.back","Back"),"bp-btn-line",()=>{this.picking=!1,this.render()}),n=new xn(this.host.hub,(i)=>m("web.clone.use.dir","Use {dir}",{dir:i}),async(i)=>{this.userParent=i,this.picking=!1,this.render(),this.askDest()},[t]);this.bodyEl.replaceChildren(n.root),n.go(e)}async startClone(){if(!this.canStart()||!this.dest)return;this.starting=!0,this.startErr="",this.updateCloneBtn();let e={repo:this.repoArg(),thread:this.wantThread,text:this.firstText},t=En();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=he(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=En(),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 o=he(r instanceof Error?r.message:String(r));if(this.jobId!==i)return;if(!this.job||this.job.id!==i){let a=await this.host.hub.rpc("clone.status",{id:i}).catch(()=>null);if(a&&a.id===i){this.apply(a);return}}if(this.jobId===i&&(!this.job||this.job.id!==i))this.jobId=s,t.disabled=!1,this.showJobError(o)}}apply(e){if(!e||e.id!==this.jobId)return;if(!Si(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&&Li(e))this.goTo(e)}renderJobView(){this.jobEl=X("div","bp-ap-job"),this.jobEl.setAttribute("data-testid","clone-job"),this.signinEl=X("div","bp-ap-signin bp-hidden"),this.signinEl.setAttribute("data-testid","clone-signin"),this.bodyEl.replaceChildren(this.jobEl,this.signinEl),this.renderJob(),this.renderSignin()}renderJob(){let e=this.jobEl,t=this.job;if(!e||!t)return;let n=t.destShown||t.dest||"",i=t.repo||"",s=t.state==="done"?m("web.clone.cloned","Cloned {repo} into {dest}",{repo:i,dest:n}):t.state==="cancelled"?m("web.clone.stopped","Stopped cloning {repo}",{repo:i}):m("web.clone.cloning","Cloning {repo} into {dest}",{repo:i,dest:n}),r=[X("div","bp-ap-job-title",s)];if(t.state==="running"){let o=X("div","bp-ap-phase",he(t.phase||""));o.setAttribute("data-testid","clone-phase");let a=X("div","bp-ap-bar"+(typeof t.pct==="number"?"":" indeterminate")),c=X("div","bp-ap-bar-fill");if(typeof t.pct==="number")c.style.width=`${Math.max(0,Math.min(100,t.pct))}%`;if(a.appendChild(c),a.setAttribute("role","progressbar"),typeof t.pct==="number")a.setAttribute("aria-valuenow",String(t.pct));if(r.push(o,a),t.detail)r.push(X("div","bp-ap-detail bp-dim",t.detail));let p=X("div","bp-ap-foot"),l=_e(m("common.cancel","Cancel"),"bp-btn-line",()=>{this.host.hub.rpc("clone.cancel",{id:t.id}).then((h)=>this.apply(h)).catch(()=>{})});l.setAttribute("data-testid","clone-cancel"),p.append(l),r.push(p)}else if(t.state==="failed"||t.state==="cancelled"){if(t.state==="failed"&&t.error){let p=X("div","bp-ap-err",he(t.error));p.setAttribute("data-testid","clone-error"),r.push(p)}let o=X("div","bp-ap-foot"),a=_e(m("web.clone.back","Back"),"bp-btn-line",()=>{this.jobId="",this.job=null,this.signin=null,this.render(),this.askDest()});if(o.append(a),t.signin){let p=_e(m("web.clone.signin","Sign in to GitHub"),"bp-btn-line",()=>{this.startSignin()});p.setAttribute("data-testid","clone-signin-btn"),o.append(p)}let c=_e(m("web.clone.retry","Try again"),"primary",()=>{this.retry(t,c)});c.setAttribute("data-testid","clone-retry"),o.append(c),r.push(o)}else if(t.state==="done"){let o=t.notes??[];if(o.length>0){let l=X("ul","bp-ap-notes");l.setAttribute("data-testid","clone-notes");for(let h of o)l.appendChild(X("li","",he(h)));r.push(l)}let a=X("div","bp-ap-foot"),c=t.thread?m("web.clone.open.thread","Open the thread"):m("web.clone.open.project","Open the project"),p=_e(c,"primary",()=>this.goTo(t));p.setAttribute("data-testid","clone-open"),a.append(p),r.push(a)}e.replaceChildren(...r)}showJobError(e){if(!this.jobEl)return;this.jobEl.querySelector(".bp-ap-job-err")?.remove();let t=X("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(X("div","bp-dim",m("web.clone.signin.wait","Starting GitHub sign-in…")));else if(t.state==="waiting"){n.push(X("div","",m("web.clone.signin.enter","Enter this code on GitHub:")));let i=X("div","bp-ap-code-row"),s=X("span","bp-ap-code",t.code||"");s.setAttribute("data-testid","clone-signin-code");let r=_e(this.copied?m("web.clone.copied","Copied"):m("common.copy","Copy"),"bp-btn-line",()=>{navigator.clipboard?.writeText(t.code||"").then(()=>{this.copied=!0,this.renderSignin()}).catch(()=>{})});if(i.append(s,r),n.push(i),t.url){let o=X("a","bp-ap-link",t.url);o.href=t.url,o.target="_blank",o.rel="noopener noreferrer",o.setAttribute("data-testid","clone-signin-url"),n.push(o)}}else if(t.state==="done")n.push(X("div","bp-ok",m("web.clone.signin.done","Signed in to GitHub")));else if(t.state==="failed")n.push(X("div","bp-ap-err",he(t.error||"")))}e.replaceChildren(...n),e.classList.toggle("bp-hidden",n.length===0)}}function jr(e){try{let t=new URL(e,window.location.origin);if(t.protocol==="https:"||t.protocol==="http:")return t.href}catch{}return null}function $t(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 o=document.createElement("code");o.className="bp-code-inline",o.textContent=r.slice(1,-1),e.appendChild(o)}else if(r.startsWith("**")&&r.endsWith("**")){let o=document.createElement("strong");o.textContent=r.slice(2,-2),e.appendChild(o)}else if(r.startsWith("*")&&r.endsWith("*")){let o=document.createElement("em");o.textContent=r.slice(1,-1),e.appendChild(o)}else if(r.startsWith("[")){let o=s[2]??"",a=jr(s[3]??"");if(a){let c=document.createElement("a");c.href=a,c.target="_blank",c.rel="noopener noreferrer",c.textContent=o,e.appendChild(c)}else e.appendChild(document.createTextNode(o))}i=n.lastIndex}if(i{navigator.clipboard?.writeText(l).then(()=>{f.textContent="✓",window.setTimeout(()=>{f.textContent=b},1200)}).catch(()=>{})}),d.append(m,f);let v=document.createElement("pre"),w=document.createElement("code");w.textContent=l,v.appendChild(w),h.append(d,v),t.appendChild(h);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",$t(c,r[2]),t.appendChild(c),i++;continue}if(s.startsWith("> ")){let c=document.createElement("blockquote");c.className="bp-md-quote";let p=[];while(i "))p.push(n[i].slice(2)),i++;$t(c,p.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]))o.push(n[i]),i++;let a=document.createElement("p");a.className="bp-md-p";for(let c=0;c0)a.appendChild(document.createElement("br"));$t(a,o[c])}t.appendChild(a)}return t}var Hr=new Set(["(","[",'"',"'","`"]);function Dr(e){return/[\p{L}\p{N}\-_\/+\[]/u.test(e)}function Fr(e){return/[\p{L}\p{N}\-_\/]/u.test(e)}function $r(e){return/[\p{L}\p{N}]/u.test(e)}function Ti(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(so)r=l,o=h,a=c;break}p=l+1}}if(a===null)break;if(r>s)i.push({kind:"text",text:e.slice(s,r)});i.push({kind:"model",word:a.word,label:a.label}),s=o}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 Vr(e,t){let n=document.createDocumentFragment(),i=Ti(e,t),s=u("native.thread.model","Model").toLowerCase();for(let r of i){if(r.kind==="text"){n.appendChild(document.createTextNode(r.text));continue}let o=document.createElement("span");o.className="bp-ref-chip bp-ref-model",o.title=r.word,o.setAttribute("data-ref-word",r.word);let a=document.createElement("span");a.className="bp-ref-sigil",a.textContent="&";let c=document.createElement("span");c.className="bp-ref-label",c.textContent=r.label;let p=document.createElement("span");p.className="bp-ref-kind",p.textContent=s,o.append(a,c,p),n.appendChild(o)}return n}function Ur(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,a=(s.nodeType===Node.ELEMENT_NODE?s:s.parentElement)?.closest(".bp-ref-chip[data-ref-word]")?.getAttribute("data-ref-word"),c;if(a)c=a;else{let p=i.cloneContents(),l=p.querySelectorAll(".bp-ref-chip[data-ref-word]");if(l.length===0)return;for(let d of l){let m=d.getAttribute("data-ref-word")||d.textContent||"";d.replaceWith(document.createTextNode(m))}let h=p.querySelectorAll(".bp-entry");for(let d=1;d{if(!this.loadingOlder&&this.hasMore)this.loadingOlder=!0,this.cb.onLoadOlder()}),this.scrollEl.addEventListener("scroll",()=>{if(this.pinnedToBottom=this.isNearBottom(),this.hasMore&&!this.loadingOlder&&this.scrollEl.scrollTop<48)this.loadingOlder=!0,this.cb.onLoadOlder()}),typeof ResizeObserver<"u"){let n=0;new ResizeObserver(()=>{let s=this.scrollEl.clientHeight;if(n>0&&s!==n&&this.pinnedToBottom)this.scrollToBottom();n=s}).observe(this.scrollEl)}this.listEl=document.createElement("div"),this.listEl.className="bp-timeline-list",Ur(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=u("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=u("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=u("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)=>!Sn(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)=>!Sn(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(Sn(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((o)=>o.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(Ot(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=he(this.noProvider.head),n.appendChild(i),this.noProvider.text){let o=document.createElement("span");o.className="bp-dim",o.textContent=he(this.noProvider.text),n.appendChild(o)}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=he(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||u("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(Ot(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=u("common.copy","Copy"),o=document.createElement("span");o.textContent=r,s.append(Gt(["M9 9h11v11H9z","M5 15H4a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1h10a1 1 0 0 1 1 1v1"]),o),s.addEventListener("click",()=>{navigator.clipboard?.writeText(e.text||"").then(()=>{o.textContent="✓",window.setTimeout(()=>{o.textContent=r},1000)}).catch(()=>{})});let a=document.createElement("button");a.type="button",a.className="bp-entry-act";let c=document.createElement("span");c.textContent=u("reply.action","Reply"),a.append(Gt(["M9 17l-5-5 5-5","M20 18v-2a4 4 0 0 0-4-4H4"]),c),a.addEventListener("click",()=>this.cb.onReplyEntry(e));let p=!e.live&&!e.id.startsWith("local-")&&!e.id.startsWith("live:"),l=document.createElement("span");l.className="bp-entry-time";let h=Or(e.at);if(t)l.textContent=h,i.append(s,...p?[a]:[],l);else{let d=n&&e.at?Gr(Ln(e.at)-Ln(n)):"",m=h?d?u("web.chat.finished.dur","Finished {time} · {dur}",{time:h,dur:d}):u("web.chat.finished","Finished {time}",{time:h}):"";l.textContent=e.live?u("web.chat.streaming","Streaming…"):m,i.append(l,s,...p?[a]:[])}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=u("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=u("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 o=document.createElement("article");if(o.className=`bp-entry bp-entry-${r.kind}`+(r.live?" is-live":""),o.setAttribute("data-entry-id",r.id),r.kind==="tool"&&r.tool){let l=document.createElement("div");l.className=`bp-tool-pill bp-tool-${r.tool.state||"done"}`;let h=document.createElement("span");if(h.className="bp-tool-name",h.textContent=r.tool.name,l.appendChild(h),r.tool.summary){let d=document.createElement("span");d.className="bp-tool-summary",d.textContent=r.tool.summary,l.appendChild(d)}o.appendChild(l),i.appendChild(o);continue}if(r.kind==="ask"&&r.ask){let l=r.ask;if(l.kind==="plan"){o.appendChild(this.renderPlanAsk(l)),i.appendChild(o);continue}let h=document.createElement("div");h.className="bp-ask-card",h.setAttribute("data-testid",`ask-${l.id}`);let d=document.createElement("div");if(d.className="bp-ask-q",d.textContent=l.question,h.appendChild(d),l.state==="open"){let m=document.createElement("div");if(m.className="bp-ask-opts",l.options&&l.options.length>0)for(let f of l.options){let b=document.createElement("button");b.type="button",b.textContent=f.label,b.addEventListener("click",()=>this.cb.onAnswerAsk(l.id,f.id)),m.appendChild(b)}else{let f=document.createElement("input");f.type="text",f.className="bp-input",f.placeholder=u("web.chat.answer.placeholder","Type answer…");let b=document.createElement("button");b.type="button",b.className="primary",b.textContent=u("web.chat.answer.btn","Answer"),b.addEventListener("click",()=>{if(f.value.trim())this.cb.onAnswerAsk(l.id,f.value.trim())}),m.append(f,b)}h.appendChild(m)}else{let m=document.createElement("div");m.className="bp-ask-answered",m.textContent=u("web.chat.answered","Answered: {answer}",{answer:l.answered??""}),h.appendChild(m)}o.appendChild(h),i.appendChild(o);continue}let a=Boolean(r.text&&r.text.trim().length>0),c=Boolean(r.images&&r.images.length>0),p=Boolean(r.attachments&&r.attachments.length>0);if(!a&&!c&&!p&&!r.live)continue;if(r.replyTo?.quote){let l=document.createElement("div");l.className="bp-reply-quote",l.textContent=u("gpui.b.in.reply.to","↩ In reply to: {quote}",{quote:r.replyTo.quote});let h=r.replyTo.id;l.setAttribute("role","button"),l.tabIndex=0,l.setAttribute("data-testid","entry-reply-quote");let d=()=>{if(this.cb.onGoToEntry)this.cb.onGoToEntry(h);else this.goTo(h)};l.addEventListener("click",d),l.addEventListener("keydown",(m)=>{if(m.key==="Enter"||m.key===" ")m.preventDefault(),d()}),o.appendChild(l)}if(a||r.live){let l=document.createElement("div");if(l.className="bp-entry-body",r.kind==="user")l.appendChild(Vr(r.text||"",r.refs));else l.appendChild(Ot(r.text||""));if(r.live)this.liveNodes.set(r.id,l);o.appendChild(l)}if(p&&r.attachments){let l=document.createElement("div");l.className="bp-entry-images";for(let h of r.attachments)if(h.previewUrl){let d=document.createElement("img");d.className="bp-reply-img",d.src=h.previewUrl,d.alt=h.name||"attachment",l.appendChild(d)}else if(h.path||h.name){let d=document.createElement("span");d.className="bp-tool-pill",d.textContent=h.name||h.path||"image",l.appendChild(d)}if(l.childElementCount>0)o.appendChild(l)}if(r.images&&r.images.length>0){let l=document.createElement("div");l.className="bp-entry-images";for(let h of r.images){let d=document.createElement("img");d.className="bp-reply-img",d.alt=h;let m=`${r.id}|${h}`,f=this.imageCache.get(m);if(f)d.src=f;else this.cb.onLoadImage(r.id,h).then((b)=>{if(!b)return;let v=b.url??(b.mime&&b.data?`data:${b.mime};base64,${b.data}`:"");if(!v)return;this.imageCache.set(m,v),d.src=v});l.appendChild(d)}o.appendChild(l)}o.appendChild(this.makeEntryActions(r,r.kind==="user",r.kind==="assistant"?s:void 0)),i.appendChild(o)}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=Gt(["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 o=document.createElement("span");if(o.className="bp-plan-title",o.textContent=!e.head||e.head==="Proposed plan"?u("ask.plan","Proposed plan"):he(e.head),s.append(r,o),e.state==="open"){let l=document.createElement("span");l.className="bp-plan-badge",l.textContent=u("gpui.ask.plan.ready","Ready for review"),s.appendChild(l)}let a=document.createElement("span");if(a.className="bp-mgmt-flex1",s.appendChild(a),e.question){let l=document.createElement("button");l.type="button",l.className="bp-plan-head-btn";let h=u("common.copy","Copy"),d=document.createElement("span");d.textContent=h,l.append(Gt(["M9 9h11v11H9z","M5 15H4a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1h10a1 1 0 0 1 1 1v1"]),d),l.addEventListener("click",()=>{navigator.clipboard?.writeText(e.question).then(()=>{l.classList.add("copied"),d.textContent=u("web.clone.copied","Copied"),window.setTimeout(()=>{l.classList.remove("copied"),d.textContent=h},1200)}).catch(()=>{})}),s.appendChild(l)}let c=document.createElement("button");c.type="button",c.className="bp-plan-head-btn",c.setAttribute("data-testid","plan-expand"),c.textContent=t?u("gpui.c.term.collapse","Collapse"):u("gpui.c.term.expand","Expand"),c.addEventListener("click",()=>{if(this.planExpanded.has(e.id))this.planExpanded.delete(e.id);else this.planExpanded.add(e.id);let l=this.scrollEl.scrollTop;this.renderEntries(!1),this.scrollEl.scrollTop=l}),s.appendChild(c),i.appendChild(s);let p=document.createElement("div");if(p.className="bp-plan-body"+(t?" is-expanded":""),p.setAttribute("data-testid","plan-body"),p.appendChild(Ot(e.question||"")),i.appendChild(p),e.state==="open"){let l=document.createElement("div");l.className="bp-plan-actions";let h=e.options?.find((b)=>b.id==="implement"||b.id.endsWith("|implement")),d=document.createElement("button");if(d.type="button",d.className="primary",d.setAttribute("data-testid","plan-implement"),d.textContent=h?.label&&h.label!=="Implement"?he(h.label):u("approval.implement","Implement"),d.addEventListener("click",()=>{this.planRevisingId="",this.planReviseDrafts.delete(e.id),this.cb.onAnswerAsk(e.id,h?.id??"implement")}),l.appendChild(d),e.revise!==!1){let b=document.createElement("button");b.type="button",b.className="bp-plan-revise-btn"+(n?" active":""),b.setAttribute("data-testid","plan-revise"),b.append(Gt(["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(u("gpui.ask.plan.revise","Revise"))),b.addEventListener("click",()=>{let v=this.planRevisingId!==e.id;this.planRevisingId=v?e.id:"";let w=this.scrollEl.scrollTop;if(this.renderEntries(!1),this.scrollEl.scrollTop=w,v)this.listEl.querySelector(`[data-testid="ask-${CSS.escape(e.id)}"] .bp-plan-revise-input`)?.focus()}),l.appendChild(b)}let m=e.options?.find((b)=>b.id==="dismiss"||b.id.endsWith("|dismiss")),f=document.createElement("button");if(f.type="button",f.className="bp-plan-dismiss-btn",f.setAttribute("data-testid","plan-dismiss"),f.textContent=m?.label&&m.label!=="Dismiss"?he(m.label):u("approval.dismiss","Dismiss"),f.addEventListener("click",()=>{this.planRevisingId="",this.planReviseDrafts.delete(e.id),this.cb.onAnswerAsk(e.id,m?.id??"dismiss")}),l.appendChild(f),i.appendChild(l),n){let b=document.createElement("div");b.className="bp-plan-revise",b.setAttribute("data-testid","plan-revise-drawer");let v=document.createElement("textarea");v.rows=2,v.className="bp-input bp-plan-revise-input",v.placeholder=u("gpui.ask.plan.reviseph","What should change in the plan?"),v.value=this.planReviseDrafts.get(e.id)??"";let w=document.createElement("button");w.type="button",w.className="bp-plan-revise-send",w.setAttribute("data-testid","plan-revise-send"),w.textContent=u("gpui.ask.plan.sendrev","Send revision"),w.disabled=v.value.trim().length===0;let E=()=>{let M=v.value.trim();if(!M)return;this.planRevisingId="",this.planReviseDrafts.delete(e.id),this.cb.onAnswerAsk(e.id,`revise:${M}`)},k=()=>{this.closePlanRevise()};b.addEventListener("keydown",(M)=>{if(M.key==="Escape")M.preventDefault(),M.stopPropagation(),k()}),v.addEventListener("input",()=>{this.planReviseDrafts.set(e.id,v.value),w.disabled=v.value.trim().length===0}),v.addEventListener("keydown",(M)=>{if(M.key==="Enter"&&!M.shiftKey)M.preventDefault(),E()}),w.addEventListener("click",E);let L=document.createElement("button");L.type="button",L.className="bp-btn-ghost",L.textContent=u("common.cancel","Cancel"),L.addEventListener("click",k),b.append(v,w,L),i.appendChild(b)}}else{let l=document.createElement("div");l.className="bp-ask-answered",l.textContent=u("web.chat.answered","Answered: {answer}",{answer:e.answered??""}),i.appendChild(l)}return i}}var Wr={claude:"Claude Code",codex:"Codex CLI",grok:"Grok CLI",muse:"Muse Code",antigravity:"Google Antigravity",opencode:"OpenCode",pi:"Pi",omp:"Oh My Pi"};var Ii=/[\x00-\x1f\x7f]/,_r=/\s/;function Pt(e){return e.trim().replace(/^@+/,"").toLowerCase()}function ft(e,t){if(Ii.test(e)||Ii.test(t))return"";let n=Pt(e),i=t.trim();if(!n||!i||n.includes("/")||_r.test(n))return"";if(n.length+1+i.length>200)return"";return`${n}/${i}`}function Ri(e){let t=e.indexOf("/");if(t<=0)return null;let n=e.slice(0,t),i=e.slice(t+1);if(!ft(n,i))return null;return{provider:Pt(n),model:i.trim()}}function dt(e){if(!Array.isArray(e))return[];let t=[],n=new Set;for(let i of e){if(typeof i!=="string")continue;let s=Ri(i);if(!s)continue;let r=`${s.provider}/${s.model}`;if(!n.has(r)){if(n.add(r),t.push(r),t.length>=64)break}}return t}function Nn(e,t,n,i){let s=ft(t,n),r=dt(e);if(!s)return{keys:r,starred:!1};let o=r.indexOf(s),a=i!==void 0?i:o<0;if(a&&o<0){if(r.length>=64)return{keys:r,starred:!1};r.push(s)}else if(!a&&o>=0)r.splice(o,1);return{keys:r,starred:a}}function nt(e){return e&&typeof e==="object"&&!Array.isArray(e)?e:null}function xt(e){return Array.isArray(e)?e:[]}function Se(e){return typeof e==="string"?e:""}function zr(e){return Wr[e]??e}function ji(e,t,n,i){let s=new Map;for(let o of e)s.set(o.provider,o);let r=[];for(let o of dt(t)){let a=Ri(o);if(!a)continue;let c=s.get(a.provider),p=Boolean(c&&c.models.some((m)=>m.value!=="")),l=c?.models.find((m)=>m.value===a.model),h=l?l.ok&&(c?.ok??!0):c?.ok??!0,d=l?.why||c?.why||"";if(h&&p&&!l)h=!1,d="not available on this machine";r.push({key:o,provider:a.provider,model:a.model,label:l?.label||a.model,note:l?.note||"",on:a.provider===n&&a.model===i,ok:h,why:d})}return r}function Hi(e,t=[]){let n=nt(e),i=nt(n?.picker)??n??{},s=xt(i.sections).map(nt).filter((P)=>Boolean(P)),r=(P)=>s.find((Y)=>Se(Y.action)===P),o=r("provider"),a=r("model"),c=r("effort"),p=xt(o?.choices).map(nt).filter((P)=>Boolean(P)),l=xt(a?.choices).map(nt).filter((P)=>Boolean(P)),h=xt(c?.choices).map(nt).filter((P)=>Boolean(P)),d=Se(i.chip),m=Se(p.find((P)=>P.on===!0)?.value)||d.split("/")[0]?.trim()||"claude",f=Pt(m)||"claude",b=Se(l.find((P)=>P.on===!0)?.value),v=Se(h.find((P)=>P.on===!0)?.value),w=h.map((P)=>({value:Se(P.value),label:Se(P.label)||"auto",on:P.on===!0})),E=nt(i.agents),k=[],L=new Set,M=(P)=>{let Y=Pt(P);if(Y&&!L.has(Y))L.add(Y),k.push(Y)};for(let P of p)M(Se(P.value)||Se(P.label));if(E)for(let P of Object.keys(E))M(P);M(f);let A=k.map((P)=>{let Y=p.find((te)=>Pt(Se(te.value)||Se(te.label))===P),re=nt(E?.[P]),ie=re?re.ok!==!1:Y?Y.ok!==!1:!0,ue=Se(re?.why)||Se(Y?.why),Pe=xt(re?.models).map(nt).filter((te)=>Boolean(te)),Ce;if(Pe.length>0)Ce=Pe.map((te)=>{let oe=Se(te.value),R=Se(te.label)||(oe===""?"default":oe),me=Se(te.note);return{value:oe,label:R,note:me,on:P===f&&oe===b,ok:te.ok!==!1&&ie,why:Se(te.why)||ue}});else if(P===f&&l.length>0)Ce=l.map((te)=>{let oe=Se(te.value),R=Se(te.label);return{value:oe,label:oe===""?"default":oe,note:R&&R!==oe?R:"",on:te.on===!0,ok:te.ok!==!1&&ie,why:Se(te.why)||ue}});else if(ie)Ce=[{value:"",label:"default",note:"",on:P===f&&b==="",ok:!0,why:""}];else Ce=[];if(P===f&&b&&!Ce.some((te)=>te.value===b)){let te=l.find((R)=>Se(R.value)===b),oe=Se(te?.label);Ce.push({value:b,label:b,note:oe&&oe!==b?oe:"",on:!0,ok:!0,why:""})}return{provider:P,label:zr(P),ok:ie,why:ue,models:Ce}}),B=Array.isArray(i.favoriteKeys),T=xt(i.favorites).map(nt).filter((P)=>Boolean(P)),H=B?dt(i.favoriteKeys):T.length>0?dt(T.map((P)=>Se(P.key)||ft(Se(P.provider),Se(P.model)))):dt(t),O=T.length>0?T.map((P)=>{let Y=Pt(Se(P.provider)),re=Se(P.model).trim(),ie=ft(Y,re);if(!ie)return null;return{key:ie,provider:Y,model:re,label:Se(P.label)||re,note:Se(P.note),on:P.on===!0||Y===f&&re===b,ok:P.ok!==!1,why:Se(P.why)}}).filter((P)=>Boolean(P)):ji(A,H,f,b);return{chip:d,provider:f,model:b,effort:v,efforts:w,providers:A,favoriteKeys:H,favorites:O}}function Vt(e,t){let n=dt(t);return{...e,favoriteKeys:n,favorites:ji(e.providers,n,e.provider,e.model)}}function Di(e,t){let n=t.trim().toLowerCase().split(/\s+/).filter(Boolean),i=(a)=>{if(n.length===0)return!0;let c=a.toLowerCase();return n.every((p)=>c.includes(p))},s=new Set(e.favoriteKeys),r=e.favorites.filter((a)=>i(`${a.provider} ${a.model} ${a.label} ${a.note}`)),o=[];for(let a of e.providers){let c=a.models.filter((p)=>i(`${a.provider} ${a.label} ${p.value} ${p.label} ${p.note}`)).map((p)=>{let l=p.value?ft(a.provider,p.value):"";return{...p,provider:a.provider,starrable:p.value!=="",starred:Boolean(l&&s.has(l))}});if(c.length>0||n.length===0&&!a.ok&&a.why)o.push({provider:a.provider,label:a.label,ok:a.ok,why:a.why,models:c})}return{favorites:r,groups:o,efforts:e.efforts}}var Fi={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 St="http://www.w3.org/2000/svg",$i=4,Oi=new Set(["image/png","image/jpeg","image/webp","image/gif"]);function on(e){let t=document.createElementNS(St,"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(St,"path");i.setAttribute("d",n),t.appendChild(i)}return t}function Mn(){return on(["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 Gi(){return on(["M6 4l14 8-14 8z"])}function Vi(e){let t=document.createElementNS(St,"svg");t.setAttribute("viewBox","0 0 24 24"),t.setAttribute("width","13"),t.setAttribute("height","13"),t.setAttribute("fill",e?"currentColor":"none"),t.setAttribute("stroke","currentColor"),t.setAttribute("stroke-width","1.8"),t.setAttribute("stroke-linejoin","round"),t.setAttribute("aria-hidden","true");let n=document.createElementNS(St,"path");return n.setAttribute("d","M12 2.5l2.9 6 6.6.9-4.8 4.6 1.2 6.5L12 17.4l-5.9 3.1 1.2-6.5-4.8-4.6 6.6-.9z"),t.appendChild(n),t}function Ui(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 Wi(e){let t=Fi[e];if(!t||!t.d)return null;let n=document.createElementNS(St,"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(St,"path");return i.setAttribute("d",t.d),n.appendChild(i),n}class Tn{popupEl;attachStripEl;planBarEl;fileInput;textarea;memoryEl;memoryFill;memoryText;modelBtn;providerMarkEl;modelTextEl;ctxEl;modelPickerEl;modelSearchInput;modelPickerBodyEl;modelPickerEffortsEl;modelPickerOpen=!1;modelPickerLoading=!1;modelPickerSnap=null;modelPickerQuery="";modelPickerFocusIdx=-1;onDocMouseDown;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=u("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("button");r.type="button",r.className="bp-composer-model",r.setAttribute("data-testid","composer-model-chip"),r.setAttribute("aria-haspopup","dialog"),r.setAttribute("aria-expanded","false"),r.title=u("composer.model.tip","Choose the model and effort"),this.modelBtn=r,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");let o=document.createElement("span");o.className="bp-model-caret",o.textContent="▾",r.append(this.providerMarkEl,this.modelTextEl,this.ctxEl,o),r.addEventListener("click",()=>{this.toggleModelPicker()}),this.modelPickerEl=document.createElement("div"),this.modelPickerEl.className="bp-model-picker bp-hidden",this.modelPickerEl.setAttribute("data-testid","model-picker"),this.modelPickerEl.setAttribute("role","dialog");let a=document.createElement("div");a.className="bp-mp-search-wrap",this.modelSearchInput=document.createElement("input"),this.modelSearchInput.type="search",this.modelSearchInput.className="bp-mp-search",this.modelSearchInput.placeholder=u("gpui.search.models","Search models"),this.modelSearchInput.setAttribute("data-testid","model-picker-search"),this.modelSearchInput.addEventListener("input",()=>{this.modelPickerQuery=this.modelSearchInput.value,this.modelPickerFocusIdx=-1,this.renderModelPicker()}),this.modelSearchInput.addEventListener("keydown",(l)=>{if(l.key==="Escape"){l.preventDefault(),l.stopPropagation(),this.closeModelPicker(),this.textarea.focus();return}if(l.key==="ArrowDown"||l.key==="ArrowUp"){let h=this.modelPickerFocusableButtons();if(h.length===0)return;l.preventDefault();let d=l.key==="ArrowDown"?1:-1;this.modelPickerFocusIdx=this.modelPickerFocusIdx<0?d>0?0:h.length-1:(this.modelPickerFocusIdx+d+h.length)%h.length,this.updateModelPickerKbdFocus(h);return}if(l.key==="Enter"){let h=this.modelPickerFocusableButtons(),d=this.modelPickerFocusIdx>=0&&this.modelPickerFocusIdxthis.cb.onCyclePlanMode?.()),this.memoryEl=document.createElement("div"),this.memoryEl.className="bp-composer-memory bp-hidden",this.memoryEl.setAttribute("data-testid","composer-memory");let c=document.createElement("div");c.className="bp-memory-meter",this.memoryFill=document.createElement("div"),this.memoryFill.className="bp-memory-fill",c.appendChild(this.memoryFill),this.memoryText=document.createElement("span"),this.memoryEl.append(c,this.memoryText);let p=document.createElement("div");p.className="bp-composer-btns",this.attachBtn=document.createElement("button"),this.attachBtn.type="button",this.attachBtn.className="icon bp-composer-tool",this.attachBtn.title=u("web.composer.attach","Attach image"),this.attachBtn.setAttribute("aria-label",u("web.composer.attach","Attach image")),this.attachBtn.setAttribute("data-testid","composer-attach"),this.attachBtn.appendChild(on(["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=u("web.composer.voice","Voice dictation"),this.voiceBtn.setAttribute("aria-label",u("web.composer.voice","Voice dictation")),this.voiceBtn.setAttribute("data-testid","composer-voice"),this.voiceBtn.appendChild(on(["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=u("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=u("composer.send","Send"),this.sendBtn.setAttribute("data-testid","composer-send"),this.sendBtn.addEventListener("click",()=>this.submit()),p.append(this.attachBtn,this.voiceBtn,this.stopBtn,this.sendBtn),s.append(r,this.planChipBtn,this.memoryEl,p),i.append(this.modelPickerEl,this.popupEl,this.errorEl,this.replyEl,this.attachStripEl,this.planBarEl,this.fileInput,this.textarea,s),n.appendChild(i),e.appendChild(n),this.onDocMouseDown=(l)=>{if(!this.modelPickerEl.isConnected){document.removeEventListener("mousedown",this.onDocMouseDown);return}if(!this.modelPickerOpen)return;let h=l.target;if(h&&(this.modelPickerEl.contains(h)||this.modelBtn.contains(h)))return;this.closeModelPicker()},document.addEventListener("mousedown",this.onDocMouseDown),this.textarea.addEventListener("paste",(l)=>{let h=l.clipboardData?.items;if(!h)return;let d=[];for(let m=0;m0)l.preventDefault(),this.addFiles(d)}),this.textarea.addEventListener("input",()=>{this.autoGrow(),this.clearError(),this.updatePopups()}),this.textarea.addEventListener("keydown",(l)=>{if(this.popupMode!=="none"){let h=this.popupMode==="slash"?this.filteredSlash.length:this.mentionItems.length;if(l.key==="ArrowDown"){l.preventDefault(),this.popupIdx=(this.popupIdx+1)%Math.max(1,h),this.renderPopup();return}if(l.key==="ArrowUp"){l.preventDefault(),this.popupIdx=(this.popupIdx-1+Math.max(1,h))%Math.max(1,h),this.renderPopup();return}if(l.key==="Tab"||l.key==="Enter"&&!l.shiftKey&&this.shouldCompleteOnEnter()){l.preventDefault(),this.applyPopupChoice(this.popupIdx);return}if(l.key==="Escape"){l.preventDefault(),this.closePopup();return}}if(l.key==="Tab"&&l.shiftKey&&this.planMode!==null){l.preventDefault(),this.cb.onCyclePlanMode?.();return}if(l.key==="Enter"&&!l.shiftKey)l.preventDefault(),this.submit()})}setCommands(e){this.commands=e.map((t)=>({...t,word:t.word.replace(/^\//,"")}))}setModelChip(e,t,n){let i=Ui(t),s=i.mark?Wi(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=u("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=`${u("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?Gi():Mn()),this.planChipLbl.textContent=s?u("gpui.planmode.chip.building","Building"):t==="pending"?u("gpui.mgmt.fab.reviewbtn","Review"):i&&e.once?u("gpui.planmode.chip.once","Plan · 1t"):u("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?u("gpui.mgmt.plan.tab","Plan"):u("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 o=document.createElement("span");o.className="bp-plan-bar-ic",o.appendChild(s?Gi():Mn());let a=document.createElement("span");a.className="bp-plan-bar-text",a.textContent=t==="armed"&&e.once?u("gpui.planmode.bar.once","Plan mode (1 turn) — explores and proposes a plan before editing"):t==="armed"?u("gpui.planmode.bar.always","Plan mode — explores and proposes a plan before editing"):t==="planning"?u("gpui.planmode.bar.planning","Planning — drafting a plan before edits"):t==="pending"?u("gpui.planmode.bar.pending","Proposed plan awaits review below"):u("gpui.planmode.bar.executing","Building the approved plan");let c=[o,a];if(t==="armed"||t==="planning"){let p=document.createElement("div");p.className="bp-plan-scopes";let l=(h,d,m,f)=>{let b=document.createElement("button");return b.type="button",b.className="bp-plan-scope-btn"+(d?" active":""),b.textContent=h,b.disabled=!this.enabled,b.setAttribute("data-testid",f),b.addEventListener("click",()=>this.cb.onSetPlanMode?.(m)),b};p.append(l(u("gpui.planmode.scope.once","1 turn"),e.once,"once","plan-scope-once"),l(u("gpui.planmode.scope.always","Always"),!e.once,"always","plan-scope-always"),l(u("gpui.bots.recall.off","Off"),!1,"off","plan-scope-off")),c.push(p)}this.planBarEl.replaceChildren(...c)}setState(e,t){if(this.enabled=e,this.textarea.disabled=!e,this.sendBtn.disabled=!e,this.attachBtn.disabled=!e,this.voiceBtn.disabled=!e,this.modelBtn.disabled=!e,!e)this.closeModelPicker();this.planChipBtn.disabled=!e,this.planBarEl.querySelectorAll(".bp-plan-scope-btn").forEach((n)=>{n.disabled=!e}),this.stopBtn.classList.toggle("bp-hidden",!t)}destroy(){document.removeEventListener("mousedown",this.onDocMouseDown)}isModelPickerOpen(){return this.modelPickerOpen}closeModelPicker(){if(!this.modelPickerOpen)return;this.modelPickerOpen=!1,this.modelPickerFocusIdx=-1,this.modelPickerEl.classList.add("bp-hidden"),this.modelBtn.classList.remove("is-open"),this.modelBtn.setAttribute("aria-expanded","false")}modelPickerFocusableButtons(){return Array.from(this.modelPickerBodyEl.querySelectorAll(".bp-mp-row-main:not(:disabled)"))}updateModelPickerKbdFocus(e){e.forEach((t,n)=>{let i=n===this.modelPickerFocusIdx;if(t.classList.toggle("is-kbd",i),i)t.scrollIntoView({block:"nearest"})})}updateFavoriteModels(e){if(!this.modelPickerSnap)return;if(this.modelPickerSnap=Vt(this.modelPickerSnap,e),this.modelPickerOpen)this.renderModelPicker()}async toggleModelPicker(){if(!this.enabled)return;if(this.modelPickerOpen){this.closeModelPicker();return}this.closePopup(),this.modelPickerOpen=!0,this.modelPickerQuery="",this.modelPickerFocusIdx=-1,this.modelSearchInput.value="",this.modelPickerEl.classList.remove("bp-hidden"),this.modelBtn.classList.add("is-open"),this.modelBtn.setAttribute("aria-expanded","true"),this.modelPickerLoading=!0,this.renderModelPicker(),this.modelSearchInput.focus(),await this.reloadModelPicker()}async reloadModelPicker(){if(!this.cb.onLoadModelPicker){this.modelPickerLoading=!1,this.renderModelPicker();return}try{let e=await this.cb.onLoadModelPicker();if(!this.modelPickerOpen)return;this.modelPickerSnap=Hi(e,this.cb.getFavoriteModels?.()??[])}catch{}finally{if(this.modelPickerLoading=!1,this.modelPickerOpen)this.renderModelPicker()}}async toggleFavoriteInPicker(e,t){if(!this.modelPickerSnap)return;let n=this.modelPickerSnap,i=ft(e,t);if(!i)return;let s=n.favoriteKeys.includes(i),r=Nn(n.favoriteKeys,e,t);if(r.keys.length===n.favoriteKeys.length&&r.starred===s)return;if(this.modelPickerSnap=Vt(n,r.keys),this.renderModelPicker(),!this.cb.onToggleFavorite)return;try{let o=await this.cb.onToggleFavorite(e,t,r.starred);if(Array.isArray(o)&&this.modelPickerSnap){if(this.modelPickerSnap=Vt(this.modelPickerSnap,dt(o)),this.modelPickerOpen)this.renderModelPicker()}}catch(o){if(this.modelPickerSnap){let a=this.cb.getFavoriteModels?.(),c=Array.isArray(a)?dt(a):Nn(this.modelPickerSnap.favoriteKeys,e,t,!r.starred).keys;if(this.modelPickerSnap=Vt(this.modelPickerSnap,c),this.modelPickerOpen)this.renderModelPicker()}this.showError(o instanceof Error&&o.message?o.message:"Could not update favorite model")}}renderProviderGlyph(e){let t=Ui(e),n=document.createElement("span");n.className="bp-mp-mark",n.style.color=t.color,n.title=t.title;let i=t.mark?Wi(t.mark):null;if(i)n.appendChild(i);else n.textContent=t.glyph;return n}makeStarButton(e,t,n,i="model-star"){let s=document.createElement("button");s.type="button",s.className="bp-mp-star"+(n?" is-starred":"");let r=n?u("gpui.picker.favorite.remove","Remove from favorites"):u("gpui.picker.favorite.add","Add to favorites");return s.title=r,s.setAttribute("aria-label",r),s.setAttribute("aria-pressed",n?"true":"false"),s.setAttribute("data-testid",`${i}-${e}-${t}`),s.appendChild(Vi(n)),s.addEventListener("click",(o)=>{o.preventDefault(),o.stopPropagation(),this.toggleFavoriteInPicker(e,t)}),s}renderModelPicker(){if(!this.modelPickerOpen)return;if(this.modelPickerFocusIdx=-1,!this.modelPickerSnap){let i=document.createElement("div");i.className="bp-mp-empty",i.textContent=this.modelPickerLoading?"…":u("gpui.no.models","No models"),this.modelPickerBodyEl.replaceChildren(i),this.modelPickerEffortsEl.classList.add("bp-hidden"),this.modelPickerEffortsEl.replaceChildren();return}let e=Di(this.modelPickerSnap,this.modelPickerQuery),t=document.createDocumentFragment();if(e.favorites.length>0){let i=document.createElement("div");i.className="bp-mp-section bp-mp-favorites",i.setAttribute("data-testid","model-picker-favorites");let s=document.createElement("div");s.className="bp-mp-head";let r=document.createElement("span");r.className="bp-mp-head-star",r.appendChild(Vi(!0));let o=document.createElement("span");o.textContent=u("gpui.picker.favorites","Favorites"),s.append(r,o),i.appendChild(s);for(let a of e.favorites){let c=document.createElement("div");c.className="bp-mp-row"+(a.on?" is-active":"")+(!a.ok?" is-disabled":""),c.setAttribute("data-testid",`model-fav-row-${a.provider}-${a.model}`);let p=document.createElement("button");if(p.type="button",p.className="bp-mp-row-main",p.disabled=!a.ok,!a.ok&&a.why)p.title=a.why;let l=document.createElement("span");l.className="bp-mp-check",l.textContent=a.on?"✓":"";let h=document.createElement("span");h.className="bp-mp-name",h.textContent=a.label;let d=document.createElement("span");d.className="bp-mp-note",d.textContent=!a.ok&&a.why?he(a.why):a.note&&a.note!==a.label?he(a.note):a.provider,p.append(l,this.renderProviderGlyph(a.provider),h,d),p.addEventListener("click",()=>{if(!a.ok)return;this.closeModelPicker(),this.textarea.focus(),this.cb.onSelectModel?.(a.provider,a.model)}),c.append(p,this.makeStarButton(a.provider,a.model,!0,"model-fav-star")),i.appendChild(c)}t.appendChild(i)}let n=document.createElement("div");if(n.className="bp-mp-groups",n.setAttribute("data-testid","model-picker-groups"),e.groups.length===0){let i=document.createElement("div");i.className="bp-mp-empty",i.textContent=this.modelPickerQuery.trim()?u("gpui.nothing.matches","Nothing matches"):u("gpui.no.models","No models"),n.appendChild(i)}else for(let i of e.groups){let s=document.createElement("div");s.className="bp-mp-group";let r=document.createElement("div");r.className="bp-mp-group-head";let o=document.createElement("span");if(o.className="bp-mp-group-title",o.textContent=i.label,r.append(this.renderProviderGlyph(i.provider),o),!i.ok&&i.why){let a=document.createElement("span");a.className="bp-mp-group-why",a.textContent=he(i.why),r.appendChild(a)}s.appendChild(r);for(let a of i.models){let c=document.createElement("div");c.className="bp-mp-row"+(a.on?" is-active":"")+(!a.ok?" is-disabled":""),c.setAttribute("data-testid",`model-row-${i.provider}-${a.value||"default"}`);let p=document.createElement("button");if(p.type="button",p.className="bp-mp-row-main",p.disabled=!a.ok,!a.ok&&a.why)p.title=a.why;let l=document.createElement("span");l.className="bp-mp-check",l.textContent=a.on?"✓":"";let h=document.createElement("span");h.className="bp-mp-name",h.textContent=a.label;let d=document.createElement("span");if(d.className="bp-mp-note",d.textContent=a.note&&a.note!==a.label?he(a.note):"",p.append(l,h,d),p.addEventListener("click",()=>{if(!a.ok)return;this.closeModelPicker(),this.textarea.focus(),this.cb.onSelectModel?.(i.provider,a.value)}),c.appendChild(p),a.starrable)c.appendChild(this.makeStarButton(i.provider,a.value,a.starred));s.appendChild(c)}n.appendChild(s)}if(t.appendChild(n),this.modelPickerBodyEl.replaceChildren(t),e.efforts.length>0){let i=document.createDocumentFragment(),s=document.createElement("span");s.className="bp-mp-efforts-lbl",s.textContent=u("model.col.effort","Effort"),i.appendChild(s);for(let r of e.efforts){let o=document.createElement("button");o.type="button",o.className="bp-mp-effort"+(r.on?" active":""),o.textContent=r.label,o.addEventListener("click",()=>{Promise.resolve(this.cb.onSelectEffort?.(r.value)).then(()=>{if(this.modelPickerOpen)this.reloadModelPicker()})}),i.appendChild(o)}this.modelPickerEffortsEl.replaceChildren(i),this.modelPickerEffortsEl.classList.remove("bp-hidden")}else this.modelPickerEffortsEl.classList.add("bp-hidden"),this.modelPickerEffortsEl.replaceChildren()}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=u("gpui.b.replying.to","↩ Replying to: {line}",{line:e.line}),i.append(s,r),t)i.addEventListener("click",t);let o=document.createElement("button");o.type="button",o.className="icon bp-reply-strip-drop",o.textContent="×";let a=u("reply.cancel","Cancel reply");if(o.title=a,o.setAttribute("aria-label",a),o.setAttribute("data-testid","composer-reply-drop"),n)o.addEventListener("click",n);this.replyEl.replaceChildren(i,o),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=he(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(){if(this.textarea.placeholder=u("composer.placeholder","Ask anything: @bot, >thread, %project, #room, $skill, /btw"),this.attachBtn.title=u("web.composer.attach","Attach image"),this.attachBtn.setAttribute("aria-label",u("web.composer.attach","Attach image")),this.voiceBtn.title=u("web.composer.voice","Voice dictation"),this.voiceBtn.setAttribute("aria-label",u("web.composer.voice","Voice dictation")),this.modelBtn.title=u("composer.model.tip","Choose the model and effort"),this.modelSearchInput.placeholder=u("gpui.search.models","Search models"),this.sendBtn.textContent=u("composer.send","Send"),this.stopBtn.textContent=u("composer.stop","Stop"),this.setPlanMode(this.planMode),this.modelPickerOpen)this.renderModelPicker()}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",(o)=>{o.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",(o)=>{o.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(!Oi.has(t.type)){this.showError(u("web.composer.unsupported","Unsupported image type: {type}",{type:t.type||t.name}));continue}if(this.attachments.length>=$i){this.showError(u("web.composer.maximages","At most {max} images per message.",{max:$i}));break}let n=await new Promise((s,r)=>{let o=new FileReader;o.onload=()=>s(String(o.result||"")),o.onerror=()=>r(Error("read failed")),o.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=u("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 _i(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 qr=new Set(["bom","checks","life","plan","fab"]);function an(e){if(!e||!Array.isArray(e.panels))return[];return e.panels.filter((t)=>t&&typeof t.id==="string"&&qr.has(t.id))}function Xi(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 ln(e,t=22){let n=e.join(", ");if(n.length<=t)return n;let i="";for(let s=0;s0?` +${a}`.length:0)>t)return i?`${i} +${e.length-s}`:`${e[0]} +${e.length-1}`;i=o}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 At(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 Kr=new Set(["0201","0402","0603","0805","1206","1210","1812","2010","2512"]),Jr=new Set(["QFN","DFN","SOT","SOIC","SOP","SSOP","TSSOP","MSOP","QFP","LQFP","TQFP","BGA","WLCSP","SOD","TO","SON","LGA"]);function Qi(e){if(!e)return"";let t=e.indexOf(":"),i=(t>=0?e.slice(t+1):e).split("_");for(let o of i)if(Kr.has(o))return o;let s=i[0]??"",r=s.replace(/[^a-zA-Z].*$/,"").toUpperCase();if(Jr.has(r)){let o=s.split("-");if(o.length>=2&&/^\d+$/.test(o[1]))return`${o[0]}-${o[1]}`;return o[0]}return i.slice(0,2).join("_")}function Zi(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 es(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 ts(e,t){if(!t)return e;return e.filter((n)=>n.source===t)}function In(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 cn(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 ns(e){return e.state==="routed"||e.state==="verified"}function is(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 ss(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 rs(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 o of e.layers??[])for(let a of o.items??[])if(a.state==="routed"||a.state==="verified")t+=1;else if(a.state==="routing")r+=1;else if(a.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 os(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 as(e){return e==="extra"?"costs-more limits":"base-price limits"}function Rn(e,t){return e.watchGen===t.watchGen&&e.editGen===t.editGen&&e.project!==""&&e.project===t.project&&e.editId!==""&&e.editId===t.editId}function ls(e){return{project:e.project,refs:e.refs.slice(),field:e.field,value:e.was}}function jn(e,t){return e.watchGen===t.watchGen&&e.project!==""&&e.project===t.project&&e.threadId!==""&&e.threadId===t.threadId&&e.threadGen===t.threadGen}var zi=["#f59e0b","#38bdf8","#c084fc","#2dd4bf","#ef4444","#a3e635","#f97316","#ec4899"],qi=["#14b8a6","#f59e0b","#c084fc","#22c55e","#38bdf8","#ef4444","#e879f9","#84cc16"];function cs(e){let t=2166136261;for(let n=0;n>>0;return t}function Ut(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 zi[cs(i)%zi.length]}function Nt(e,t=""){let n=t.trim().toLowerCase();if(n&&n!=="#8a8a8a")return t;return qi[cs(e)%qi.length]}function ds(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])),o=Math.max(20,t-i*2),a=Math.max(20,n-i*2),c=Math.max(0.05,Math.min(200,Math.min(o/s,a/r)));return{cx:(e[0]+e[2])*0.5,cy:(e[1]+e[3])*0.5,scale:c,fitted:c,touched:!1}}function Ke(e,t,n,i,s){return[i*0.5+(t-e.cx)*e.scale,s*0.5+(n-e.cy)*e.scale]}function dn(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 ps(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 hs(e,t,n,i,s,r){let o=Math.max(0.02,e.fitted*0.35),a=Math.max(40,e.fitted*24),c=Math.max(o,Math.min(a,e.scale*t)),[p,l]=dn(e,n,i,s,r);return{...e,cx:p-(n-s*0.5)/c,cy:l-(i-r*0.5)/c,scale:c,touched:!0}}function us(e,t,n,i){let s=e.map((o)=>[o[0],o[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 Hn(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 Yr(e,t,n,i,s,r){let o=s-n,a=r-i,c=o*o+a*a;if(c<0.000001)return(e-n)*(e-n)+(t-i)*(t-i);let p=Math.max(0,Math.min(1,((e-n)*o+(t-i)*a)/c)),l=n+p*o,h=i+p*a;return(e-l)*(e-l)+(t-h)*(t-h)}function Ki(e,t,n){if(n.length<3)return!1;let i=!1;for(let s=0,r=n.length-1;st!==p>t&&e<(c-o)*(t-a)/(p-a+0.000000000001)+o)i=!i}return i}function Dn(e,t){return Math.max(5,Math.min(32,e*t))}function pn(e,t,n,i,s,r,o,a,c){if(i){for(let d of e){if(d.layer!==n||d.id!==i||d.locked)continue;let m=d.path??[];for(let f=0;f=3)for(let f=0;f=0;d--){let m=t[d];if(m.layer!==n)continue;let f=m.outline??[];if(!Ki(l,h,f))continue;if(!(m.holes??[]).some((v)=>Ki(l,h,v)))return{kind:"region",id:m.id}}return null}function Mt(e){let t=null,n=null,i=[];for(let r of e){if(!r.layer)continue;i.push(r.layer);let o=r.items??[],a=o.filter((p)=>p.kind==="corridor").length,c=o.filter((p)=>p.kind==="plane").length;if((a>0||r.role==="signal")&&(!t||a>t.count))t={count:a,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 Ji(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 o=1;o=s&&a>0.000000001){let c=(s-r)/a;return[e[o-1][0]+(e[o][0]-e[o-1][0])*c,e[o-1][1]+(e[o][1]-e[o-1][1])*c]}r+=a}return e[e.length-1]}function vt(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 ms(e,t,n){if(e==="split"&&n.length>0)return t.filter((i)=>n.includes(i.layer));return t}function Bn(e,t){return!(e[2]<=t[0]||e[0]>=t[2]||e[3]<=t[1]||e[1]>=t[3])}function Yi(e,t,n){if(n.length<3)return!1;let i=!1;for(let s=0,r=n.length-1;st!==p>t&&e<(c-o)*(t-a)/(p-a+0.000000000001)+o)i=!i}return i}function bs(e,t){if(e.length<3)return null;let n=1/0,i=1/0,s=-1/0,r=-1/0,o=0,a=0;for(let p of e)n=Math.min(n,p[0]),i=Math.min(i,p[1]),s=Math.max(s,p[0]),r=Math.max(r,p[1]),o+=p[0],a+=p[1];let c=[[(n+s)*0.5,(i+r)*0.5],[o/e.length,a/e.length]];for(let p of[0.5,0.25,0.75,0.125,0.875])for(let l of[0.5,0.25,0.75,0.125,0.875])c.push([n+(s-n)*l,i+(r-i)*p]);for(let p of c)if(Yi(p[0],p[1],e)&&!t.some((l)=>Yi(p[0],p[1],l)))return p;return null}function gs(e,t,n,i,s,r){let o=[];for(let l of e){let h=l.nets??0,d=l.path??[];if(h<=0||d.length<2)continue;let m=0;for(let f=1;f{let d=l.sel||l.hov?1:0,m=h.sel||h.hov?1:0;if(m!==d)return m-d;if(h.nets!==l.nets)return h.nets-l.nets;return l.b.id.localeCompare(h.b.id)});let a=[],c=[],p=(l,h,d,m,f)=>[l-d*0.5-f,h-m*0.5-f,l+d*0.5+f,h+m*0.5+f];for(let l of o){let h=l.b.name||"",d=String(l.nets),m=h?`${h} · ${l.nets}`:d,f=(l.sel||l.hov||l.pxLen>=95)&&h?[m,d]:[d],b=null,v=(E,k)=>Math.max(k*0.5+3,Math.min(Math.max(k*0.5+3,n-k*0.5-3),E)),w=(E,k)=>Math.max(k*0.5+3,Math.min(Math.max(k*0.5+3,i-k*0.5-3),E));e:for(let E of f){let k=Math.max(16,E.length*5.9+10),L=15;for(let M of[0.5,0.35,0.65,0.22,0.78]){let A=Ji(l.pts,M);if(!A)continue;let[B,T]=Ke(t,A[0],A[1],n,i),H=v(B,k),O=w(T,15),P=p(H,O,k,15,2);if(!a.some((Y)=>Bn(P,Y))){b={id:l.b.id,text:E,cx:H,cy:O,pw:k,ph:15,col:l.col,sel:l.sel};break e}}}if(!b){let E=Ji(l.pts,0.5);if(E){let[k,L]=Ke(t,E[0],E[1],n,i),M=Math.max(16,d.length*6.5+8),A=15,B=v(k,M);for(let T of[-18,18]){let H=w(L+T,15);if(!a.some((O)=>Bn(p(B,H,M,15,2),O))){b={id:l.b.id,text:d,cx:B,cy:H,pw:M,ph:15,col:l.col,sel:l.sel};break}}}}if(b)a.push(p(b.cx,b.cy,b.pw,b.ph,2)),c.push(b)}return c}function fs(e,t,n,i,s,r=[]){let o=new Set(s),a=[];for(let l of e){if(!l.r||!l.b||l.b.length!==4)continue;let[h,d]=Ke(t,l.b[0],l.b[1],n,i),[m,f]=Ke(t,l.b[2],l.b[3],n,i),b=Math.abs(m-h),v=Math.abs(f-d);if(b<13||v<9)continue;let w=(h+m)*0.5,E=(d+f)*0.5;if(w<8||w>n-8||E<8||E>i-8)continue;a.push({text:l.r,cx:w,cy:E,bw:l.r.length*5.8+4,bh:11,score:b*v+(o.has(l.r)?1e4:0)})}a.sort((l,h)=>h.score-l.score);let c=[...r],p=[];for(let l of a){let h=[l.cx-l.bw*0.5,l.cy-l.bh*0.5,l.cx+l.bw*0.5,l.cy+l.bh*0.5];if(!c.some((m)=>Bn(h,m)))c.push(h),p.push({text:l.text,cx:l.cx,cy:l.cy})}return p}function vs(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 hn(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 o=n.get(r.layer);if(o)i.push(o);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 ws(e,t,n,i,s,r,o,a){return e===t&&n===i&&s===r&&(a===void 0||o>=a)}var ys="#111917",Xr="#16201d",Qr="rgba(212, 224, 219, 0.92)",Zr="rgba(61, 80, 73, 0.72)",eo="rgba(82, 107, 97, 0.85)";var Es="#f59e0b",to="#eef5f2",Cs="#ef4444";function wt(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 no(e,t,n){let i=0.14,s=0.45,r=0.85,o=!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,o=!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:o}}function io(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 so(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 Fn{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=hn(e.layers,e.copperLayers);if(t.length===0)return[];if(e.gridMode==="all")return t;if(e.gridMode==="single"){let s=e.shownLayers.find((o)=>t.some((a)=>a.layer===o))??Mt(t)[0]??t[0]?.layer,r=t.find((o)=>o.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):Mt(t),i=[];for(let s of n){let r=t.find((o)=>o.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 ds(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((E)=>E.kind==="plane");s.className="bp-plan-card-bar "+(r?"pwr":"sig");let o=document.createElement("span");o.className="bp-plan-card-title";let a=document.createElement("span");a.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=u("gpui.mgmt.plan.layer","Approve layer"),c.addEventListener("click",(E)=>{E.stopPropagation(),this.cb.onApproveLayer(e.layer,!0)});let p=document.createElement("button");p.type="button",p.className="bp-mgmt-btn bp-plan-mini-btn",p.textContent="✗",p.title=u("gpui.mgmt.plan.rejectlayer","Reject layer"),p.addEventListener("click",(E)=>{E.stopPropagation(),this.cb.onApproveLayer(e.layer,!1)}),i.append(s,o,a,c,p);let l=document.createElement("div");l.className="bp-plan-card-sub",n.append(i,l);let h=document.createElement("div");h.className="bp-plan-card-canvas-wrap";let d=document.createElement("canvas");d.className="bp-plan-card-canvas",d.setAttribute("data-testid",`mgmt-plan-canvas-${e.layer}`);let m=document.createElement("div");m.className="bp-plan-hover-hud bp-hidden",h.append(d,m);let f=document.createElement("div");f.className="bp-plan-legend bp-hidden",t.append(n,h,f);let b=d.getContext("2d"),v=new ResizeObserver(()=>this.scheduleDraw());v.observe(h),this.attachPointerListeners(d,e.layer);let w={layer:e.layer,el:t,canvas:d,ctx:b,legendEl:f,okBtn:c,noBtn:p,statusEl:a,titleEl:o,subtitleEl:l,hoverHudEl:m,ro:v};return this.syncCardHeaderAndLegend(w,e),w}syncCardHeaderAndLegend(e,t){e.titleEl.textContent=vt(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=so(t);e.statusEl.className=`bp-plan-card-status tone-${s.tone==="warn"?"dim":s.tone}`,e.statusEl.textContent=i.length>0?u(s.key,s.label):"",e.statusEl.classList.toggle("bp-hidden",i.length===0);let r=i.some((a)=>a.state==="proposed"||a.state==="edited");if(e.okBtn)e.okBtn.classList.toggle("bp-hidden",!r);if(e.noBtn)e.noBtn.classList.toggle("bp-hidden",!r);let o=(this.state?.regions??[]).filter((a)=>a.layer===t.layer);if(o.length===0)e.legendEl.classList.add("bp-hidden"),e.legendEl.replaceChildren();else{e.legendEl.classList.remove("bp-hidden");let a=document.createDocumentFragment();for(let c of o){let p=document.createElement("button");p.type="button";let l=this.state?.selectedId===c.id;p.className="bp-plan-legend-chip"+(l?" active":"");let h=document.createElement("span");h.className="bp-plan-legend-sw",h.style.background=Ut(c.net||c.id,c.color||"");let d=document.createElement("span");d.textContent=c.net||c.id,p.append(h,d),p.addEventListener("click",()=>{this.cb.onSelect(c.id),this.cb.onFocusItem(c.id)}),a.appendChild(p)}e.legendEl.replaceChildren(a)}}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(),o=i.clientX-r.left,a=i.clientY-r.top,c=Math.max(1,r.width),p=Math.max(1,r.height),l=this.getCam(t,c,p),h=pn(s.bands,s.regions,t,s.selectedId,l,c,p,o,a);if(i.button===2){if(h?.kind==="vertex"){let d=this.getItemPts(h.id,h.isPlane),m=Hn(d,h.idx,h.isPlane);if(m)this.selectedVertex=null,this.cb.onCommitFields(h.id,{[h.isPlane?"outline":"path"]:m})}return}if(i.button!==0)return;if(e.setPointerCapture(i.pointerId),this.downPos={x:i.clientX,y:i.clientY},h?.kind==="vertex"){let d=this.getItemPts(h.id,h.isPlane),m=d.map((f)=>[f[0],f[1]]);this.selectedVertex={id:h.id,idx:h.idx},this.drag={layer:t,kind:"vertex",id:h.id,isPlane:h.isPlane,idx:h.idx,pts:d.map((f)=>[f[0],f[1]]),origPts:m,moved:!1},this.scheduleDraw()}else if(h?.kind==="midpoint"){let d=this.getItemPts(h.id,h.isPlane),m=d.map((v)=>[v[0],v[1]]),f=us(d,h.segIdx,h.pos,h.isPlane),b=h.isPlane&&h.segIdx+1>=d.length?f.length-1:Math.min(h.segIdx+1,f.length-1);this.selectedVertex={id:h.id,idx:b},this.patchLocalItem(h.id,h.isPlane,f),this.drag={layer:t,kind:"vertex",id:h.id,isPlane:h.isPlane,idx:b,pts:f,origPts:m,moved:!0},this.scheduleDraw()}else this.selectedVertex=null,this.drag={layer:t,kind:"pan",lastX:o,lastY:a}}),e.addEventListener("pointermove",(i)=>{let s=this.state;if(!s)return;let r=e.getBoundingClientRect(),o=i.clientX-r.left,a=i.clientY-r.top,c=Math.max(1,r.width),p=Math.max(1,r.height);if(this.drag&&this.drag.layer===t){if(this.drag.kind==="pan"){let L=this.getCam(t,c,p);this.setCam(t,ps(L,o-this.drag.lastX,a-this.drag.lastY)),this.drag.lastX=o,this.drag.lastY=a,this.scheduleDraw();return}if(this.downPos&&Math.hypot(i.clientX-this.downPos.x,i.clientY-this.downPos.y)<1.5&&!this.drag.moved)return;let b=this.getCam(t,c,p),[v,w]=dn(b,o,a,c,p),E=[Math.round(v*1000)/1000,Math.round(w*1000)/1000];this.drag.moved=!0,this.drag.pts[this.drag.idx]=E;let k=this.drag.pts.map((L)=>[L[0],L[1]]);this.patchLocalItem(this.drag.id,this.drag.isPlane,k),this.scheduleDraw();return}let l=this.getCam(t,c,p),h=pn(s.bands,s.regions,t,s.selectedId,l,c,p,o,a),d=this.hover?.hit?"id"in this.hover.hit?this.hover.hit.id:"":"",m=this.hover?.hit.kind??"",f=h?h.id:"";if(this.hover=h?{layer:t,hit:h}:null,e.style.cursor=h?"pointer":"crosshair",d!==f||(h?.kind??"")!==m)this.syncHoverHud(t),this.scheduleDraw()}),e.addEventListener("pointerleave",()=>{if(this.hover?.layer===t)this.hover=null,this.syncHoverHud(t),this.scheduleDraw()});let n=()=>{let i=this.drag;if(!i||i.layer!==t)return;if(this.drag=null,this.downPos=null,i.kind==="vertex"&&i.moved){let s=i.origPts.map((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,o=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&&o&&Math.hypot(i.clientX-o.x,i.clientY-o.y)<4.5){let a=e.getBoundingClientRect(),c=i.clientX-a.left,p=i.clientY-a.top,l=Math.max(1,a.width),h=Math.max(1,a.height),d=this.getCam(t,l,h),m=pn(s.bands,s.regions,t,s.selectedId,d,l,h,c,p);if(m&&(m.kind==="band"||m.kind==="region")){this.cb.onSelect(m.id),this.cb.onFocusItem(m.id);return}if(!m&&s.selectedId){this.cb.onSelect("");return}}this.cb.onDragEnd?.()}),e.addEventListener("wheel",(i)=>{i.preventDefault();let s=e.getBoundingClientRect(),r=i.clientX-s.left,o=i.clientY-s.top,a=Math.max(1,s.width),c=Math.max(1,s.height),p=this.getCam(t,a,c),l=Math.max(0.65,Math.min(1.55,1-i.deltaY*0.002));this.setCam(t,hs(p,l,r,o,a,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((a)=>a.id===i),r=n.regions.find((a)=>a.id===i),o="";if(s)o=`${s.name||i} · ${s.nets??0}n · ${(s.width??1.5).toFixed(2)}mm`;else if(r)o=r.reference?`${r.net||i} · ${r.reference}`:r.net||i;if(!o)t.hoverHudEl.classList.add("bp-hidden");else t.hoverHudEl.classList.remove("bp-hidden"),t.hoverHudEl.textContent=o}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((o)=>o.id===t.selectedId),i=t.regions.find((o)=>o.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 o=e.shiftKey?-0.25:0.25,a=Math.round(Math.max(0.15,Math.min(25,(n.width??1.5)+o))*100)/100;this.cb.onCommitFields(t.selectedId,{width:a})}else if((e.key==="Delete"||e.key==="Backspace")&&!s&&this.selectedVertex?.id===t.selectedId){e.preventDefault();let o=Boolean(i),a=this.getItemPts(t.selectedId,o),c=Hn(a,this.selectedVertex.idx,o);if(c)this.selectedVertex=null,this.cb.onCommitFields(t.selectedId,{[o?"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 o=Math.max(1,window.devicePixelRatio||1),a=Math.round(s*o),c=Math.round(r*o);if(n.canvas.width!==a||n.canvas.height!==c)n.canvas.width=a,n.canvas.height=c;n.ctx.setTransform(o,0,0,o,0,0),this.drawLayer(n.ctx,n.layer,s,r,e)}}drawLayer(e,t,n,i,s){let r=this.getCam(t,n,i),o=(b,v)=>Ke(r,b,v,n,i);e.fillStyle=ys,e.fillRect(0,0,n,i);let a=(s.board.outline??[]).filter((b)=>b.length>=3);if(e.fillStyle=Xr,a.length>0){e.beginPath();for(let b of a){for(let v=0;vb.layer===t),p=this.hover?.layer===t?this.hover.hit:null;for(let b of c){let v=b.outline??[];if(v.length<3)continue;let w=s.selectedId===b.id,E=p?.id===b.id,k=io(b.state||"proposed",w,E),L=Ut(b.net||b.id,b.color||"");e.beginPath();for(let A=0;AT)T=P;if(Y>H)H=Y}if(Math.abs(T-A)>=38&&Math.abs(H-B)>=18){let O=bs(v,b.holes??[]);if(O){let[P,Y]=o(O[0],O[1]);e.fillStyle=wt(L,w?0.91:0.67),e.font="bold 10px ui-monospace, 'SFMono-Regular', Menlo, monospace",e.textAlign="center",e.textBaseline="middle",e.fillText(M,P,Y)}}}}if(e.strokeStyle=Qr,e.lineWidth=1.25,e.lineCap="round",e.lineJoin="round",a.length>0){e.beginPath();for(let b of a){for(let v=0;vb.layer===t),d=gs(h,r,n,i,s.selectedId,p?.id??""),m=d.map((b)=>[b.cx-b.pw*0.5-1,b.cy-b.ph*0.5-1,b.cx+b.pw*0.5+1,b.cy+b.ph*0.5+1]),f=[];for(let b of h){for(let v of b.from??[])f.push(v);for(let v of b.to??[])f.push(v)}e.fillStyle="rgba(143, 163, 155, 0.72)",e.font="9.5px ui-monospace, 'SFMono-Regular', Menlo, monospace",e.textAlign="center",e.textBaseline="middle";for(let b of fs(l,r,n,i,f,m))e.fillText(b.text,b.cx,b.cy);for(let b of h){let v=b.guides??[];if(v.length===0)continue;let w=s.selectedId===b.id||p?.id===b.id,E=Nt(b.name||b.id,b.color||"");e.strokeStyle=wt(E,w?0.38:0.17),e.lineWidth=w?1:0.7,e.beginPath();for(let k of v){let[L,M]=o(k[0],k[1]),[A,B]=o(k[2],k[3]);e.moveTo(L,M),e.lineTo(A,B)}e.stroke()}for(let b of h){let v=b.path??[];if(v.length<2)continue;let w=s.selectedId===b.id,E=p?.id===b.id,k=no(b.state||"proposed",w,E),L=Nt(b.name||b.id,b.color||""),M=Dn(b.width??1.5,r.scale),A=()=>{e.beginPath();for(let B=0;B{let E=w?v.length:Math.max(0,v.length-1);for(let k=0;kn.id===e))return;if(this.openPanel!==e)this.togglePanel(e)}getTabs(){return an(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=an(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 o of t){let a=document.createElement("button");a.type="button";let c=this.openPanel===o.id;a.className="bp-mgmt-tab"+(c?" active":""),a.setAttribute("data-testid",`mgmt-tab-${o.id}`),a.setAttribute("aria-pressed",c?"true":"false");let p=document.createElement("span");p.textContent=he(o.label),a.appendChild(p);let l=this.getPanelData(o.id),h=Xi(l);if(h){let d=document.createElement("span");d.className=`bp-mgmt-badge bp-tone-${h.tone}`,d.textContent=h.text,a.appendChild(d)}a.addEventListener("click",()=>this.togglePanel(o.id)),i.appendChild(a)}if(n.appendChild(i),this.openPanel){let o=document.createElement("button");o.type="button",o.className="icon bp-mgmt-close",o.textContent="×",o.title=u("gpui.mgmt.close","Close the panel"),o.setAttribute("aria-label",u("gpui.mgmt.close","Close the panel")),o.setAttribute("data-testid","mgmt-close"),o.addEventListener("click",()=>this.closePanel()),n.appendChild(o)}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 o=document.createElement("div");o.className="bp-mgmt-note bp-tone-bad",o.textContent=this.errorMsg,r.appendChild(o)}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"),o=t.source==="kicad";if(r.className="bp-mgmt-pill"+(o?" accent":""),r.textContent=o?"live":"saved",i.append(s,r),(t.priced??0)>0&&(t.checking??0)===0&&typeof t.cost==="number"){let p=document.createElement("span");p.className="bp-dim",p.textContent=(t.priced??0)<(t.lookups??0)?`≥ ${At(t.cost)}/board`:`${At(t.cost)}/board`,i.appendChild(p)}if(t.paused){let p=document.createElement("span");p.className="bp-mgmt-faint",p.textContent="Stock check paused",i.appendChild(p)}if(e.appendChild(i),t.stock_note){let p=document.createElement("div");p.className="bp-mgmt-note bp-mgmt-faint",p.textContent=he(t.stock_note),e.appendChild(p)}let a=this.bomEditingId?n.find((p)=>p.id===this.bomEditingId)??null:null;if(a)e.appendChild(this.renderBomEditor(a));else{let p=document.createElement("div");p.className="bp-mgmt-filter-row";let l=document.createElement("input");l.type="text",l.className="bp-mgmt-filter",l.placeholder="Filter BOM (ref, value, footprint, MPN, dnp)…",l.value=this.bomFilter,l.setAttribute("data-testid","mgmt-bom-filter"),l.addEventListener("input",()=>{this.bomFilter=l.value,this.renderBomRows(c,n)}),p.appendChild(l),e.appendChild(p)}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=es(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 o=Array.isArray(r.refs)?r.refs:[],a=document.createElement("div");a.className="bp-mgmt-row"+(this.bomSelectedId===r.id?" active":"")+(r.dnp?" faint":""),a.setAttribute("data-testid",`mgmt-bom-row-${r.id}`);let c=document.createElement("div");c.className="bp-mgmt-row-line";let p=document.createElement("span");if(p.className="bp-mgmt-strong bp-mgmt-flex1",p.textContent=ln(o,24),c.appendChild(p),r.dnp){let b=document.createElement("span");b.className="bp-mgmt-pill",b.textContent=u("gpui.mgmt.bom.dnp","DNP"),c.appendChild(b)}else{let b=Zi(r.stock);if(b){let v=document.createElement("span");v.className=`bp-tone-${b.tone}`,v.textContent=b.text,c.appendChild(v)}}let l=document.createElement("button");l.type="button",l.className="bp-mgmt-btn",l.textContent="Edit",l.addEventListener("click",(b)=>{b.stopPropagation(),this.bomEditGen++,this.bomEditingId=r.id,this.bomEditDraft=r.mpn??"",this.bomEditStatus="",this.bomLastUndo=null,this.render()}),c.appendChild(l);let h=document.createElement("div");h.className="bp-mgmt-row-sub";let d=[`${r.qty??o.length}×`,r.value??"",Qi(r.footprint??"")].filter(Boolean).join(" · "),m=document.createElement("span");m.className="bp-dim",m.textContent=d;let f=document.createElement("span");if(f.className="bp-mgmt-flex1",r.mpn)f.textContent=r.mpn;else if(i&&!r.dnp)f.className+=" bp-tone-warn",f.textContent=u("gpui.mgmt.bom.nompn","no MPN");if(h.append(m,f),!r.dnp&&typeof r.stock?.price==="number"){let b=document.createElement("span");b.className="bp-dim",b.textContent=At(r.stock.price),h.appendChild(b)}if(!r.dnp&&r.stock?.class){let b=document.createElement("span");b.className="bp-mgmt-faint",b.textContent=he(r.stock.class),h.appendChild(b)}a.append(c,h),a.addEventListener("click",()=>{this.bomSelectedId=r.id,this.renderBomRows(e,t)}),s.appendChild(a)}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=ln(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 o=document.createElement("input");o.type="text",o.className="bp-mgmt-filter",o.placeholder="MPN",o.value=this.bomEditDraft,o.addEventListener("input",()=>{this.bomEditDraft=o.value});let a=()=>({watchGen:this.watchGen,editGen:this.bomEditGen,project:this.project,editId:this.bomEditingId}),c=async(d,m=!1)=>{let f=a();this.bomEditStatus="Writing…",this.render();try{let b=await this.cb.hub.rpc("mgmt.bom.edit",d);if(!Rn(f,a()))return;this.bomLastUndo=!m&&(b.changed??0)>0?{project:d.project,editId:f.editId,refs:d.refs.slice(),field:d.field,was:typeof b.was==="string"?b.was:d.field==="mpn"?e.mpn??"":e.dnp?"yes":"no"}:null,this.bomEditStatus=m?"Restored":(b.changed??0)===0?"No change":b.via==="kicad"?"Updated in KiCad":"Saved to schematic"}catch(b){if(!Rn(f,a()))return;this.bomEditStatus=b instanceof Error?b.message:"Could not save edit"}this.render()},p=document.createElement("div");p.className="bp-mgmt-btn-row";let l=document.createElement("button");l.type="button",l.className="primary bp-mgmt-btn",l.textContent="Save MPN",l.addEventListener("click",()=>{c({project:this.project,refs:n.slice(),field:"mpn",value:this.bomEditDraft.trim()})});let h=document.createElement("button");if(h.type="button",h.className="bp-mgmt-btn",h.textContent=e.dnp?"Clear DNP":"Mark DNP",h.addEventListener("click",()=>{c({project:this.project,refs:n.slice(),field:"dnp",value:e.dnp?"no":"yes"})}),p.append(l,h),this.bomLastUndo&&this.bomLastUndo.project===this.project&&this.bomLastUndo.editId===this.bomEditingId){let d=this.bomLastUndo,m=document.createElement("button");m.type="button",m.className="bp-mgmt-btn",m.textContent="Undo",m.addEventListener("click",()=>{c(ls(d),!0)}),p.appendChild(m)}if(t.append(i,o,p),this.bomEditStatus){let d=document.createElement("div");d.className="bp-mgmt-faint",d.textContent=this.bomEditStatus,t.appendChild(d)}return t}renderChecks(){let e=document.createElement("div");e.className="bp-mgmt-body";let t=this.getPanelData("checks");if(!t)return e.appendChild(this.makeEmpty("Reading checks…")),e;let n=Array.isArray(t.groups)?t.groups:[],i=Array.from(new Set(n.map((d)=>d.source).filter(Boolean))),s=(d)=>t.sources?.[d]?.label||d.toUpperCase(),r=(d)=>t.sources?.[d]?.judged===!0,o=document.createElement("div");o.className="bp-mgmt-head bp-mgmt-scroll-x";let a=document.createElement("button");a.type="button",a.className="bp-mgmt-btn"+(this.checksSource===""?" active":""),a.textContent=u("gpui.mgmt.checks.all","All"),a.addEventListener("click",()=>{this.checksSource="",this.render()}),o.appendChild(a);for(let d of i){let m=document.createElement("button");m.type="button",m.className="bp-mgmt-btn"+(this.checksSource===d?" active":""),m.textContent=s(d)+(r(d)?" · judged":""),m.addEventListener("click",()=>{this.checksSource=this.checksSource===d?"":d,this.render()}),o.appendChild(m)}let c=document.createElement("span");c.className="bp-mgmt-flex1";let p=document.createElement("button");if(p.type="button",p.className="bp-mgmt-btn",p.textContent=u("gpui.mgmt.checks.run","Run"),p.addEventListener("click",()=>{let d=this.watchGen,m=this.project;this.checksStatus="Running checks…",this.render(),this.cb.hub.rpc("kicad.checks.run",{project:m}).then(()=>{if(d!==this.watchGen||m!==this.project)return;this.checksStatus="",this.render()}).catch((f)=>{if(d!==this.watchGen||m!==this.project)return;this.checksStatus=f instanceof Error?f.message:"Could not run checks",this.render()})}),o.append(c,p),e.appendChild(o),this.checksStatus){let d=document.createElement("div");d.className="bp-mgmt-note bp-dim",d.textContent=this.checksStatus,e.appendChild(d)}let l=document.createElement("div");l.className="bp-mgmt-rows",l.setAttribute("data-testid","mgmt-checks-rows");let h=ts(n,this.checksSource);if(h.length===0)l.appendChild(this.makeEmpty("No check findings."));else for(let d of h){let m=d.severity==="error"?"bad":d.severity==="warning"?"warn":"faint",f=document.createElement("div");f.className="bp-mgmt-group-head";let b=document.createElement("span");b.className=`bp-mgmt-dot bp-tone-bg-${m}`;let v=document.createElement("span");v.className="bp-mgmt-flex1",v.textContent=`${s(d.source)} · ${d.rule}`;let w=document.createElement("span");w.className=`bp-tone-${m}`,w.textContent=String(d.n),f.append(b,v,w),l.appendChild(f);for(let E of d.rows??[]){let k=document.createElement("div");k.className="bp-mgmt-row"+(this.checksSelectedId===E.id?" active":"");let L=document.createElement("div");if(L.textContent=he(E.title??""),k.appendChild(L),E.names||this.checksSelectedId===E.id){let M=document.createElement("div");M.className="bp-mgmt-row-sub";let A=document.createElement("span");if(A.className="bp-dim bp-mgmt-flex1",A.textContent=E.names??"",M.appendChild(A),this.checksSelectedId===E.id){let B=document.createElement("button");B.type="button",B.className="bp-mgmt-btn accent",B.textContent=u("gpui.mgmt.checks.fix","Fix with agent"),B.addEventListener("click",(T)=>{T.stopPropagation();let H={watchGen:this.watchGen,project:this.project,threadId:this.cb.getThreadId(),threadGen:this.cb.getThreadGen()};this.cb.hub.rpc("kicad.checks.fix",{project:H.project,id:E.id}).then((O)=>{let P={watchGen:this.watchGen,project:this.project,threadId:this.cb.getThreadId(),threadGen:this.cb.getThreadGen()};if(!jn(H,P))return;if(O.text)this.cb.onSendText(O.text),this.checksStatus="Sent to agent",this.render()}).catch((O)=>{let P={watchGen:this.watchGen,project:this.project,threadId:this.cb.getThreadId(),threadGen:this.cb.getThreadGen()};if(!jn(H,P))return;this.checksStatus=O instanceof Error?O.message:"Could not send finding",this.render()})}),M.appendChild(B)}k.appendChild(M)}k.addEventListener("click",()=>{this.checksSelectedId=E.id,this.cb.hub.rpc("kicad.checks.focus",{project:this.project,id:E.id}).catch(()=>{}),this.render()}),l.appendChild(k)}}return e.appendChild(l),e}renderLife(){let e=document.createElement("div");e.className="bp-mgmt-body";let t=this.getPanelData("life");if(!t)return e.appendChild(this.makeEmpty("Reading lifecycle…")),e;let n=document.createElement("div");n.className="bp-mgmt-head";let i=t.counts??{};for(let c of["active","nrnd","eol"]){let p=i[c]??0,l=In(c),h=document.createElement("span");h.className=p>0?`bp-tone-${l.tone}`:"bp-mgmt-faint",h.textContent=`${l.label} ${p}`,n.appendChild(h)}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 p=document.createElement("span");p.className="bp-mgmt-faint",p.textContent=`since ${cn(t.since)} (${t.samples??0})`,n.append(c,p)}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??[],o=t.bom?.instock??[],a=t.bom?.lines??0;if(r.length===0)s.appendChild(this.makeEmpty(a===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],p=o[o.length-1],l=document.createElement("div");l.className="bp-mgmt-note bp-dim",l.textContent=`Parts/board: ${At(c[1])} · ${Math.round(p?.[1]??0)}/${a} lines in stock (${cn(c[0])})`,s.appendChild(l)}for(let c of t.parts??[]){let p=this.lifeSelectedKey===c.key,l=In(c.lifecycle??"unknown"),h=document.createElement("div");h.className="bp-mgmt-row"+(p?" active":"");let d=document.createElement("div");d.className="bp-mgmt-row-line";let m=document.createElement("span");m.className="bp-mgmt-strong",m.textContent=ln(c.refs??[],14);let f=document.createElement("span");f.className="bp-mgmt-flex1 bp-dim",f.textContent=c.mpn||c.key;let b=document.createElement("span");if(b.className=`bp-tone-${l.tone}`,b.textContent=l.label,d.append(m,f,b),typeof c.stock==="number"){let v=document.createElement("span");v.className="bp-dim",v.textContent=Lt(c.stock),d.appendChild(v)}if(h.appendChild(d),p){let v=document.createElement("div");if(v.className="bp-mgmt-row-sub bp-mgmt-faint",this.lifePartLoading)v.textContent=u("gpui.mgmt.life.reading","Reading its history…");else if(this.lifePartSamples&&this.lifePartSamples.length>0){let w=this.lifePartSamples[this.lifePartSamples.length-1];v.textContent=`${this.lifePartSamples.length} samples · latest ${w.at?cn(w.at):""}`+(typeof w.stock==="number"?` · stock ${Lt(w.stock)}`:"")+(typeof w.price==="number"?` · ${At(w.price)}`:"")}else v.textContent=u("gpui.mgmt.life.nopart","No reading of this part yet.");h.appendChild(v)}h.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((v)=>{if(this.lifeSelectedKey!==c.key)return;this.lifePartLoading=!1,this.lifePartSamples=Array.isArray(v.samples)?v.samples:[],this.render()}).catch(()=>{if(this.lifeSelectedKey!==c.key)return;this.lifePartLoading=!1,this.lifePartSamples=[],this.render()})}),s.appendChild(h)}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(u("gpui.mgmt.plan.reading","Reading the routing plan…"))),e;let n=(C,x)=>{let F=this.watchGen,I=this.project;this.planStatus="",this.cb.hub.rpc(C,{pro:I,...x}).catch((J)=>{if(F!==this.watchGen||I!==this.project)return;this.planOptimistic.clear(),this.planStatus=J instanceof Error?J.message:u("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 C=this.watchGen,x=++this.planHydrateGen,F=this.project,I=t.revision??0;this.cb.hub.rpc("plan.get",{pro:F,board:!0}).then((J)=>{let se=vs(J);if(!se)return;let ye=typeof se.revision==="number"?se.revision:I;if(!ws(C,this.watchGen,x,this.planHydrateGen,F,this.project,ye,this.planHydratedRev))return;this.planHydratedRev=ye,this.planHydratedKey=`${F}:${ye}`,this.planHydratedBoard=se.board??null,this.planHydratedDraw=se.draw??null,this.render()}).catch(()=>{})}let s=t.on===!0,r=document.createElement("div");r.className="bp-plan-header";let o=document.createElement("div");o.className="bp-plan-toggle";let a=document.createElement("span");a.className="bp-mgmt-strong",a.textContent=u("gpui.mgmt.plan.before","Plan before routing"),a.title=s?u("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."):u("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."),o.appendChild(a);let c=t.awaiting??0,p=t.blocked??0,l=t.done??0,h=t.total??0,d=t.revision??0,m=t.empty?[]:rs(t),f=m.reduce((C,x)=>C+x.count,0);if(!t.empty){let C=ss(t),x=document.createElement("span");if(x.className=`bp-plan-status-badge tone-${C.tone}`,x.textContent=u(C.key,C.label),o.appendChild(x),d>0){let I=document.createElement("span");I.className="bp-dim",I.textContent=`v${d}`,o.appendChild(I)}let F=document.createElement("span");if(F.className="bp-plan-header-counts bp-mgmt-flex1 "+(c>0?"bp-tone-warn":p>0?"bp-tone-bad":"bp-dim"),F.textContent=h>0?`${l}/${h} ${u("gpui.mgmt.plan.done","done")}`:c>0?u("web.plan.awaiting","{n} awaiting approval",{n:c}):u("gpui.mgmt.plan.nothing","Nothing awaits your approval"),o.appendChild(F),!t.live){let I=document.createElement("span");I.className="bp-mgmt-pill",I.textContent=u("gpui.mgmt.plan.saved","saved plan"),o.appendChild(I)}}else{let C=document.createElement("span");C.className="bp-mgmt-flex1",o.appendChild(C)}let b=document.createElement("button");b.type="button",b.className="bp-mgmt-btn bp-plan-chip-btn"+(s?" active":""),b.setAttribute("data-testid","mgmt-plan-on"),b.setAttribute("aria-pressed",s?"true":"false"),b.textContent=u("gpui.bots.recall.on","On"),b.addEventListener("click",()=>n("plan.enable",{on:!0}));let v=document.createElement("button");if(v.type="button",v.className="bp-mgmt-btn bp-plan-chip-btn"+(!s?" active":""),v.setAttribute("data-testid","mgmt-plan-off"),v.setAttribute("aria-pressed",!s?"true":"false"),v.textContent=u("gpui.bots.recall.off","Off"),v.addEventListener("click",()=>n("plan.enable",{on:!1})),o.append(b,v),r.appendChild(o),f>0){let C=document.createElement("div");C.className="bp-plan-segbar";for(let x of m){if(x.count<=0)continue;let F=document.createElement("div");F.className=`bp-plan-seg bp-tone-bg-${x.tone}`,F.style.flexGrow=String(x.count),C.appendChild(F)}r.appendChild(C)}e.appendChild(r);for(let C of t.elsewhere??[]){let x=document.createElement("div");x.className="bp-plan-elsewhere";let F=document.createElement("span");F.className="bp-tone-warn bp-mgmt-flex1",F.textContent=u("gpui.mgmt.plan.elsewhere","A routing plan for {board} awaits your approval",{board:C.name||C.rel||""}),x.appendChild(F),e.appendChild(x)}if(t.empty){let C=document.createElement("div");C.className="bp-mgmt-note";let x=document.createElement("div");x.className="bp-dim",x.textContent=u("gpui.mgmt.plan.noboard","No routing plan for this board.");let F=document.createElement("div");return F.className="bp-mgmt-faint",F.textContent=u("gpui.mgmt.plan.emptysub","Layers, corridors, and planes appear here once a plan is proposed."),C.append(x,F),e.appendChild(C),e}let w=t.stackup_summary??"",E=Array.isArray(t.impedances)?t.impedances:[],k=Boolean(w)||E.length>0,L=document.createElement("div");if(L.className="bp-mgmt-head",c>0){let C=document.createElement("button");C.type="button",C.className="primary bp-mgmt-btn",C.setAttribute("data-testid","mgmt-plan-approve-all"),C.textContent=u("gpui.mgmt.plan.all","Approve all"),C.addEventListener("click",()=>n("plan.approve",{layer:"",ids:[],approve:!0})),L.appendChild(C)}if(t.routing){let C=document.createElement("button");C.type="button",C.className="bp-mgmt-btn",C.setAttribute("data-testid","mgmt-plan-stop"),C.textContent=u("gpui.mgmt.plan.stop","Stop routing"),C.addEventListener("click",()=>n("plan.stop",{})),L.appendChild(C)}if(t.live&&l>0){let C=document.createElement("button");C.type="button",C.className="bp-mgmt-btn",C.setAttribute("data-testid","mgmt-plan-verify"),C.textContent=u("gpui.mgmt.plan.verify","Verify"),C.addEventListener("click",()=>n("plan.verify",{})),L.appendChild(C)}let M=document.createElement("span");if(M.className="bp-mgmt-flex1",L.appendChild(M),k){let C=document.createElement("button");C.type="button",C.className="bp-mgmt-btn bp-plan-chip-btn"+(this.planStackupOpen?" active":""),C.setAttribute("data-testid","mgmt-plan-stackup-toggle"),C.setAttribute("aria-expanded",this.planStackupOpen?"true":"false"),C.textContent=`${u("gpui.mgmt.plan.stackup.short","Stackup")} ${this.planStackupOpen?"▾":"▸"}`,C.addEventListener("click",()=>{this.planStackupOpen=!this.planStackupOpen,this.render()}),L.appendChild(C)}let A=document.createElement("button");A.type="button",A.className="bp-mgmt-btn",A.setAttribute("data-testid","mgmt-plan-hide"),A.textContent=this.planHideDone?u("gpui.mgmt.plan.show","Show done"):u("gpui.mgmt.plan.hide","Hide done"),A.addEventListener("click",()=>{this.planHideDone=!this.planHideDone,this.render()}),L.appendChild(A),e.appendChild(L);let B=Array.isArray(t.asks)?t.asks:[];if(B.length>0){let C=B.map((se)=>se.what||"").filter(Boolean).join(", "),x=B[0]?.note||"",F=document.createElement("div");F.className="bp-plan-elsewhere";let I=document.createElement("div");I.className="bp-plan-ask-col";let J=document.createElement("div");if(J.className="bp-tone-warn",J.textContent=C?u("gpui.mgmt.plan.requested","Approval requested: {what}",{what:C}):u("gpui.mgmt.plan.reqplain","Approval requested"),I.appendChild(J),x){let se=document.createElement("div");se.className="bp-dim",se.textContent=x,I.appendChild(se)}F.appendChild(I),e.appendChild(F)}if(this.planStatus){let C=document.createElement("div");C.className="bp-mgmt-note bp-plan-err bp-tone-bad";let x=document.createElement("span");x.className="bp-mgmt-flex1",x.textContent=this.planStatus==="KiCad refused"?u("gpui.mgmt.plan.refused","KiCad refused"):he(this.planStatus);let F=document.createElement("button");F.type="button",F.className="icon",F.textContent="×",F.title=u("common.close","Close"),F.addEventListener("click",()=>{this.planStatus="",this.render()}),C.append(x,F),e.appendChild(C)}if(t.keys_note){let C=document.createElement("div");C.className="bp-mgmt-note bp-dim";let x="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.";C.textContent=t.keys_note===x?u("gpui.mgmt.plan.keysnote",x):he(t.keys_note),e.appendChild(C)}if(k&&this.planStackupOpen){let C=document.createElement("div");if(C.className="bp-plan-stackup-body",C.setAttribute("data-testid","mgmt-plan-stackup-body"),w){let x=document.createElement("div");x.className="bp-dim",x.textContent=w,C.appendChild(x)}for(let x of E){let F=document.createElement("div");F.className="bp-mgmt-faint",F.textContent=`· ${x}`,C.appendChild(F)}e.appendChild(C)}let T=(C,x,F,I)=>{let J=document.createElement("button");return J.type="button",J.className="bp-mgmt-btn bp-plan-chip-btn"+(x?" active":""),J.setAttribute("data-testid",F),J.setAttribute("aria-pressed",x?"true":"false"),J.textContent=C,J.addEventListener("click",I),J},H=document.createElement("div");if(H.className="bp-plan-viewbar",H.append(T(u("gpui.mgmt.plan.view.canvas","Canvas"),this.planViewMode==="canvas","mgmt-plan-view-canvas",()=>{this.planViewMode="canvas",this.render()}),T(u("gpui.mgmt.plan.view.split","Split"),this.planViewMode==="split","mgmt-plan-view-split",()=>{this.planViewMode="split",this.render()}),T(u("gpui.mgmt.plan.view.list","List"),this.planViewMode==="list","mgmt-plan-view-list",()=>{this.planViewMode="list",this.render()})),this.planViewMode!=="list"){let C=document.createElement("span");C.className="bp-plan-sep";let x=document.createElement("span");x.className="bp-plan-sep";let F=document.createElement("button");F.type="button",F.className="bp-mgmt-btn bp-plan-mini-btn",F.setAttribute("data-testid","mgmt-plan-fit"),F.textContent=u("gpui.mgmt.plan.fit","Fit"),F.addEventListener("click",()=>this.planCanvas?.fitAll()),H.append(C,T(u("gpui.mgmt.plan.grid.pair","Side by side"),this.planGridMode==="pair","mgmt-plan-grid-pair",()=>{this.planGridMode="pair",this.render()}),T(u("gpui.mgmt.plan.grid.all","All layers"),this.planGridMode==="all","mgmt-plan-grid-all",()=>{this.planGridMode="all",this.render()}),T(u("gpui.mgmt.plan.grid.single","Single"),this.planGridMode==="single","mgmt-plan-grid-single",()=>{this.planGridMode="single",this.render()}),x,T(u("gpui.mgmt.plan.sync","Link zoom"),this.planSyncZoom,"mgmt-plan-sync",()=>{this.planSyncZoom=!this.planSyncZoom,this.render()}),F)}let O=document.createElement("span");O.className="bp-mgmt-flex1";let P=document.createElement("button");P.type="button",P.className="bp-mgmt-btn bp-plan-mini-btn",P.setAttribute("data-testid","mgmt-plan-expand"),P.textContent=this.planExpanded?u("gpui.mgmt.plan.compact","Compact"):u("gpui.mgmt.plan.expand","Expand"),P.addEventListener("click",()=>{this.planExpanded=!this.planExpanded,this.render()}),H.append(O,P),e.appendChild(H);let Y=Boolean(this.planHydratedBoard)&&this.planHydratedKey.startsWith(`${this.project}:`)&&(this.planHydratedKey===i||this.planHydratedRev!==void 0&&this.planHydratedRev>=(t.revision??0)),re=Y&&this.planHydratedBoard?this.planHydratedBoard:t.board??{bbox:[0,0,100,70],outline:[],parts:[]},ie=Y&&this.planHydratedDraw?this.planHydratedDraw:t.draw??{bands:[],regions:[]},ue=(ie.bands??[]).map((C)=>{let x=this.planOptimistic.get(C.id);if(!x)return{...C};return{...C,...x,edited:!0,state:C.state==="proposed"?"edited":C.state}}),Pe=(ie.regions??[]).map((C)=>{let x=this.planOptimistic.get(C.id);if(!x)return{...C};return{...C,...x,edited:!0,state:C.state==="proposed"?"edited":C.state}}),Ce=[],te=(t.layers??[]).map((C)=>{let x=[];for(let F of C.items??[]){let I=this.planOptimistic.get(F.id);if(!I){x.push(F);continue}let J={...F,width:typeof I.width==="number"?I.width:F.width,locked:typeof I.locked==="boolean"?I.locked:F.locked,edited:!0,state:F.state==="proposed"?"edited":F.state};if(typeof I.layer==="string"&&I.layer!==C.layer)Ce.push({target:I.layer,item:J});else x.push(J)}return{...C,items:x}});for(let C of Ce){let x=te.find((F)=>F.layer===C.target);if(x)x.items=[...x.items??[],C.item]}let oe=hn(te,t.copper_layers),R=this.planGridMode==="all"?oe.map((C)=>C.layer):this.planGridMode==="single"?[this.planShownLayers.find((C)=>oe.some((x)=>x.layer===C))??Mt(oe)[0]??oe[0]?.layer??""].filter(Boolean):this.planShownLayers.length>0&&this.planShownLayers.every((C)=>oe.some((x)=>x.layer===C))?this.planShownLayers.slice(0,2):Mt(oe);if(this.planViewMode!=="list"&&this.planGridMode!=="all"&&oe.length>1){let C=document.createElement("div");C.className="bp-plan-layerbar";for(let x of oe){let F=R.includes(x.layer),I=(x.items??[]).length,J=vt(x.layer,t.copper_layers,oe)||x.title||x.layer,se=I>0?`${J} · ${I}`:J,ye=T(se,F,`mgmt-plan-layerpill-${x.layer}`,()=>{if(this.planGridMode==="single")this.planShownLayers=[x.layer];else if(this.planGridMode==="pair"){if(!R.includes(x.layer))this.planShownLayers=R.length>=2?[R[0],x.layer]:[...R,x.layer]}else this.planGridMode="single",this.planShownLayers=[x.layer];this.render()});if(I===0&&!F)ye.classList.add("empty-layer");C.appendChild(ye)}e.appendChild(C)}let me=(C,x)=>{let F=this.planOptimistic.get(C)??{};if(this.planOptimistic.set(C,{...F,...x}),typeof x.layer==="string"){if(this.planGridMode==="single")this.planShownLayers=[x.layer];else if(this.planGridMode==="pair"&&!R.includes(x.layer))this.planShownLayers=R.length>=2?[R[0],x.layer]:[...R,x.layer]}let I=typeof t.revision==="number"?t.revision:void 0;this.render(),n("plan.update",{ops:[{op:"set",id:C,fields:x}],...I!==void 0?{base:I}:{}})};if(this.planCommitFields=me,this.planSelectedId){let C="",x=null;for(let F of te){let I=(F.items??[]).find((J)=>J.id===this.planSelectedId);if(I){C=F.layer,x=I;break}}if(x){let F=vt(C,t.copper_layers,oe),I=document.createElement("div");I.className="bp-plan-inspector",I.setAttribute("data-testid","mgmt-plan-inspector");let J=document.createElement("div");J.className="bp-plan-ins-row";let se=document.createElement("span");se.className="bp-plan-ins-sw",se.style.background=x.kind==="corridor"?Nt(x.name||x.id,x.color||""):Ut(x.name||x.id,x.color||"");let ye=document.createElement("span");ye.className="bp-mgmt-strong",ye.textContent=x.name||x.id;let D=document.createElement("span");if(D.className="bp-dim",D.textContent=F,J.append(se,ye,D),x.edited||x.state==="edited"){let q=document.createElement("span");q.className="bp-plan-ins-pill warn",q.textContent=u("gpui.mgmt.plan.edited","Edited"),J.appendChild(q)}if(x.locked){let q=document.createElement("span");q.className="bp-plan-ins-pill",q.textContent=u("gpui.mgmt.plan.locked","Locked"),J.appendChild(q)}let ne=document.createElement("span");ne.className="bp-mgmt-flex1",J.appendChild(ne);let Te=document.createElement("button");if(Te.type="button",Te.className="bp-mgmt-btn bp-plan-mini-btn",Te.setAttribute("data-testid","mgmt-plan-lock"),Te.textContent=x.locked?u("gpui.mgmt.plan.unlock","Unlock"):u("gpui.mgmt.plan.lock","Lock"),Te.addEventListener("click",()=>me(x.id,{locked:!x.locked})),J.appendChild(Te),x.state==="proposed"||x.state==="edited"){let q=document.createElement("button");q.type="button",q.className="primary bp-mgmt-btn bp-plan-mini-btn",q.textContent=u("android.hub.machines.approve","Approve"),q.addEventListener("click",()=>n("plan.approve",{layer:"",ids:[x.id],approve:!0}));let fe=document.createElement("button");fe.type="button",fe.className="bp-mgmt-btn bp-plan-mini-btn",fe.textContent=u("gpui.mgmt.plan.reject","Reject"),fe.addEventListener("click",()=>n("plan.approve",{layer:"",ids:[x.id],approve:!1})),J.append(q,fe)}let Le=document.createElement("button");Le.type="button",Le.className="bp-mgmt-btn bp-plan-mini-btn",Le.setAttribute("data-testid","mgmt-plan-note-toggle"),Le.textContent=u("gpui.mgmt.plan.addnote","Add note"),Le.addEventListener("click",()=>{this.planNoteOpen=!this.planNoteOpen,this.render()});let Be=document.createElement("button");if(Be.type="button",Be.className="icon",Be.textContent="×",Be.addEventListener("click",()=>{this.planSelectedId="",this.planNoteOpen=!1,this.planMoveLayerOpen=!1,this.render()}),J.append(Le,Be),I.appendChild(J),!x.locked){let q=document.createElement("div");if(q.className="bp-plan-ins-row",x.kind==="corridor"){let le=typeof x.width==="number"?x.width:1.5,He=document.createElement("span");He.className="bp-dim",He.textContent=u("gpui.mgmt.plan.width","Width");let $e=document.createElement("button");$e.type="button",$e.className="bp-mgmt-btn bp-plan-mini-btn",$e.setAttribute("data-testid","mgmt-plan-w-down"),$e.textContent="-",$e.addEventListener("click",()=>{let ze=Math.round(Math.max(0.15,le-0.25)*100)/100;me(x.id,{width:ze})});let Oe=document.createElement("span");Oe.className="bp-plan-ins-val",Oe.textContent=`${le.toFixed(2)}mm`;let Ne=document.createElement("button");Ne.type="button",Ne.className="bp-mgmt-btn bp-plan-mini-btn",Ne.setAttribute("data-testid","mgmt-plan-w-up"),Ne.textContent="+",Ne.addEventListener("click",()=>{let ze=Math.round(Math.min(25,le+0.25)*100)/100;me(x.id,{width:ze})});let We=document.createElement("span");We.className="bp-plan-sep",q.append(He,$e,Oe,Ne,We)}let fe=(t.copper_layers??[]).length>0?(t.copper_layers??[]).map((le)=>le.layer):te.map((le)=>le.layer);if(fe.length>0){let le=document.createElement("span");le.className="bp-dim",le.textContent=u("gpui.mgmt.plan.layer.short","Layer"),q.appendChild(le),q.appendChild(T(`${F} ${this.planMoveLayerOpen?"▴":"▾"}`,this.planMoveLayerOpen,"mgmt-plan-move-toggle",()=>{this.planMoveLayerOpen=!this.planMoveLayerOpen,this.render()}))}if(I.appendChild(q),this.planMoveLayerOpen&&fe.length>0){let le=document.createElement("div");le.className="bp-plan-ins-row";for(let He of fe){let $e=vt(He,t.copper_layers,oe);le.appendChild(T($e,He===C,`mgmt-plan-move-${He}`,()=>{if(this.planMoveLayerOpen=!1,He!==C)me(x.id,{layer:He});else this.render()}))}I.appendChild(le)}}if(this.planNoteOpen){let q=document.createElement("form");q.className="bp-plan-note-form";let fe=document.createElement("input");fe.type="text",fe.className="bp-plan-note-input",fe.setAttribute("data-testid","mgmt-plan-note-input"),fe.placeholder=u("gpui.mgmt.plan.note.placeholder","Steering note for router…");let le=document.createElement("button");le.type="submit",le.className="primary bp-mgmt-btn bp-plan-mini-btn",le.setAttribute("data-testid","mgmt-plan-note-submit"),le.textContent=u("gpui.mgmt.plan.addnote","Add note"),q.append(fe,le),q.addEventListener("submit",(He)=>{He.preventDefault();let $e=fe.value.trim();if(!$e)return;fe.value="",this.planNoteOpen=!1;let Oe=typeof t.revision==="number"?t.revision:void 0;this.render(),n("plan.update",{ops:[{op:"note",target:x.id,text:$e}],...Oe!==void 0?{base:Oe}:{}})}),I.appendChild(q)}if(this.planViewMode!=="list"&&!x.locked){let q=document.createElement("div");q.className="bp-plan-hint",q.textContent=u("gpui.mgmt.plan.hint","Drag waypoints to steer · Click + on edge to insert · Right-click vertex to remove"),I.appendChild(q)}e.appendChild(I)}}let de=document.createElement("div");de.className="bp-mgmt-rows"+(this.planViewMode==="split"?" bp-plan-split-list":""),de.setAttribute("data-testid","mgmt-plan-rows");let ee=u("gpui.mgmt.plan.done","done"),ge=ms(this.planViewMode,te,R);if(this.planViewMode==="split"&&ge.length===0){let C=document.createElement("div");C.className="bp-dim",C.style.padding="6px 8px",C.style.fontSize="11px",C.textContent=u("gpui.mgmt.plan.noitems","No corridors or planes on this layer"),de.appendChild(C)}for(let C of ge){let x=C.items??[],F=vt(C.layer,t.copper_layers,oe)||C.layer;if(this.planViewMode==="split"){if(ge.length>1){let I=document.createElement("div");I.className="bp-plan-split-divider";let J=C.role==="power"||C.role==="plane",se=document.createElement("span");se.className="bp-plan-card-bar "+(J?"pwr":"sig");let ye=document.createElement("span");ye.className="bp-mgmt-strong",ye.textContent=F;let D=document.createElement("span");D.className="bp-dim",D.textContent=`${C.done??0}/${x.length} ${ee}`,I.append(se,ye,D),de.appendChild(I)}}else{let I=document.createElement("div");I.className="bp-mgmt-group-head bp-plan-layer-head";let J=document.createElement("div");J.className="bp-mgmt-row-line";let se=document.createElement("span");se.className="bp-mgmt-strong",se.textContent=F;let ye=document.createElement("span");if(ye.className="bp-dim bp-mgmt-flex1",ye.textContent=`${C.role?`${C.role} · `:""}${C.done??0}/${x.length} ${ee}`,J.append(se,ye),C.status!=="approved"&&x.length>0){let D=document.createElement("button");D.type="button",D.className="bp-mgmt-btn",D.textContent=u("gpui.mgmt.plan.layer","Approve layer"),D.addEventListener("click",()=>n("plan.approve",{layer:C.layer,ids:[],approve:!0}));let ne=document.createElement("button");ne.type="button",ne.className="bp-mgmt-btn",ne.textContent=u("gpui.mgmt.plan.reject","Reject"),ne.addEventListener("click",()=>n("plan.approve",{layer:C.layer,ids:[],approve:!1})),J.append(D,ne)}if(I.appendChild(J),C.stackup){let D=document.createElement("div");D.className="bp-plan-layer-stackup",D.textContent=C.stackup,I.appendChild(D)}de.appendChild(I)}for(let I of x){if(this.planHideDone&&ns(I))continue;let J=this.planSelectedId===I.id,se=document.createElement("div");se.className="bp-mgmt-row bp-plan-row"+(J?" active":""),se.setAttribute("data-testid",`mgmt-plan-row-${I.id}`);let ye=document.createElement("div");ye.className="bp-mgmt-row-line";let D=document.createElement("span");D.className=`bp-plan-swatch bp-plan-st-${I.state||"proposed"}`,D.style.setProperty("--swatch-color",I.color||"#8a8a8a");let ne=document.createElement("span");ne.className="bp-mgmt-flex1"+(I.state==="blocked"||I.state==="failed"?" bp-tone-bad":I.state==="edited"?" bp-tone-warn":I.state==="rejected"||I.state==="routed"||I.state==="verified"?" bp-dim":""),ne.textContent=`${I.name||I.id}${I.locked?" \uD83D\uDD12":""}`;let Te=[];if(I.kind==="plane"){if(I.reference)Te.push(u("gpui.mgmt.plan.reference","over {layer}",{layer:I.reference}))}else{let q=I.nets??0;Te.push(q===1?u("web.plan.net.one","1 net"):u("web.plan.nets","{n} nets",{n:q}))}if(typeof I.width==="number"&&Number.isFinite(I.width))Te.push(`${I.width.toFixed(2)}mm`);if(I.impedance)Te.push(I.impedance);let Le=Te.join(" · "),Be=document.createElement("span");if(Be.className="bp-plan-mark "+(I.state==="blocked"||I.state==="failed"?"bp-tone-bad":I.state==="verified"||I.state==="routed"?"bp-tone-ok":I.state==="approved"?"bp-tone-accent":"bp-dim"),Be.textContent=is(I),ye.append(D,ne,Be),I.state==="proposed"||I.state==="edited"){let q=document.createElement("button");q.type="button",q.className="bp-mgmt-btn",q.textContent="✓",q.title=u("gpui.mgmt.plan.layer","Approve layer"),q.addEventListener("click",(le)=>{le.stopPropagation(),n("plan.approve",{layer:"",ids:[I.id],approve:!0})});let fe=document.createElement("button");fe.type="button",fe.className="bp-mgmt-btn",fe.textContent="✗",fe.title=u("gpui.mgmt.plan.reject","Reject"),fe.addEventListener("click",(le)=>{le.stopPropagation(),n("plan.approve",{layer:"",ids:[I.id],approve:!1})}),ye.append(q,fe)}if(se.appendChild(ye),Le){let q=document.createElement("div");q.className="bp-mgmt-row-sub bp-plan-detail bp-dim",q.textContent=Le,se.appendChild(q)}if(I.state==="routing"&&typeof I.total==="number"&&I.total>0){let q=document.createElement("div");q.className="bp-plan-microbar";let fe=document.createElement("div");fe.className="bp-plan-microbar-fill";let le=Math.max(0,Math.min(100,Math.round((I.routed??0)/I.total*100)));fe.style.width=`${le}%`,q.appendChild(fe),se.appendChild(q)}if(I.problem_text){let q=document.createElement("div");q.className="bp-plan-problem",q.textContent=I.problem_text,se.appendChild(q)}se.addEventListener("click",()=>{this.planSelectedId=I.id,n("plan.focus",{id:I.id}),this.render()}),de.appendChild(se)}}if(this.planViewMode!=="list"){if(!this.planCanvas)this.planCanvas=new Fn({onSelect:(I)=>{if(this.planSelectedId=I,!I)this.planNoteOpen=!1;this.render()},onFocusItem:(I)=>{n("plan.focus",{id:I})},onDragEnd:()=>{if(this.planRenderDeferred)this.planRenderDeferred=!1,this.render()},onCommitFields:(I,J)=>{(this.planCommitFields??me)(I,J)},onApproveLayer:(I,J)=>{n("plan.approve",{layer:I,ids:[],approve:J})},onQuickApprove:(I,J)=>{n("plan.approve",{layer:"",ids:I,approve:J})}});let C=this.panelEl.parentElement?.classList.contains("bp-has-viewer")===!1,x=this.planExpanded||this.panelEl.clientWidth>=540||C;this.planCanvas.update({gridMode:this.planGridMode,syncZoom:this.planSyncZoom,shownLayers:R,selectedId:this.planSelectedId,board:re,bands:ue,regions:Pe,layers:oe,copperLayers:t.copper_layers},x);let F=document.createElement("div");F.className="bp-plan-canvas-scroll",F.appendChild(this.planCanvas.root),e.appendChild(F)}if(this.planViewMode!=="canvas")e.appendChild(de);if((t.draw?.bands?.length??0)>0||(t.draw?.regions?.length??0)>0){let C=document.createElement("div");C.className="bp-plan-footer",C.textContent=u("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(C)}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 E=document.createElement("div");return E.className="bp-mgmt-note bp-tone-warn",E.textContent=t.error,e.appendChild(E),e}let n=(E,k={})=>{let L=this.watchGen,M=this.project;this.fabStatus="",this.cb.hub.rpc("fab.profile",{pro:M,action:E,...k}).catch((A)=>{if(L!==this.watchGen||M!==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=u("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}`:""} · ${as(t.tier??"")}`;let o=document.createElement("button");if(o.type="button",o.className="bp-mgmt-btn",o.textContent=u("gpui.mgmt.fab.refresh","Refresh"),o.addEventListener("click",()=>n("refresh")),i.append(s,r,o),e.appendChild(i),this.fabStatus){let E=document.createElement("div");E.className="bp-mgmt-note bp-tone-bad",E.textContent=this.fabStatus,e.appendChild(E)}let a=document.createElement("div");a.className="bp-mgmt-rows",a.setAttribute("data-testid","mgmt-fab-rows");let c=t.review,p=document.createElement("div");p.className="bp-mgmt-row";let l=document.createElement("div");l.className="bp-mgmt-row-line";let h=document.createElement("span"),d=(c?.counts?.error??0)>0;if(h.className="bp-mgmt-flex1 "+(d?"bp-tone-bad":"bp-dim"),h.textContent=c?.running?"Reviewing the design…":c?.at==null?"No design review yet":`${c.counts?.error??0} must-fix · ${c.counts?.warning??0} should-fix · ${c.counts?.info??0} notes${c.scope?` (${c.scope})`:""}`,l.appendChild(h),c?.at!=null){let E=document.createElement("button");E.type="button",E.className="bp-mgmt-btn",E.textContent=u("gpui.mgmt.fab.findings","Findings"),E.addEventListener("click",()=>this.togglePanel("checks")),l.appendChild(E)}if(!c?.running){let E=document.createElement("button");E.type="button",E.className="bp-mgmt-btn",E.textContent=u("gpui.mgmt.fab.reviewbtn","Review"),E.addEventListener("click",()=>n("review")),l.appendChild(E)}if(c?.judge){let E=document.createElement("button");E.type="button",E.className="bp-mgmt-btn",E.textContent=u("gpui.mgmt.fab.judge","Datasheets"),E.addEventListener("click",()=>{if(c.judge)this.cb.onSendText(c.judge)}),l.appendChild(E)}p.appendChild(l),a.appendChild(p);let m=os(t.drc?.state??""),f=document.createElement("div");f.className="bp-mgmt-row";let b=document.createElement("div");b.className="bp-mgmt-row-line";let v=document.createElement("span");if(v.className="bp-mgmt-flex1 "+(m.button?"bp-tone-warn":"bp-dim"),v.textContent=m.text,b.appendChild(v),m.button){let E=document.createElement("button");E.type="button",E.className="bp-mgmt-btn",E.textContent=m.button,E.addEventListener("click",()=>n("drc")),b.appendChild(E)}f.appendChild(b),a.appendChild(f);for(let E of t.conflicts??[]){let k=document.createElement("div");k.className="bp-mgmt-row bp-tone-bad",k.textContent=E,a.appendChild(k)}for(let E of t.suggestions??[]){let k=document.createElement("div");k.className="bp-mgmt-row";let L=document.createElement("div");L.className="bp-mgmt-row-line";let M=document.createElement("span");M.className="bp-mgmt-flex1 bp-tone-warn",M.textContent=`${E.label||E.key}: board ${E.project??"?"} mm, fab ${E.fab??"?"} mm`;let A=document.createElement("button");A.type="button",A.className="bp-mgmt-btn",A.textContent=u("gpui.mgmt.fab.apply","Apply"),A.addEventListener("click",()=>n("apply",{key:E.key})),L.append(M,A),k.appendChild(L),a.appendChild(k)}if(t.stackup?.chosen){let E=document.createElement("div");E.className="bp-mgmt-row";let k=document.createElement("div");k.className="bp-mgmt-row-line";let L=t.stackup.by==="proposed",M=document.createElement("span");if(M.className="bp-mgmt-flex1 "+(L?"bp-tone-warn":"bp-dim"),M.textContent=`${L?"Proposed: ":""}${t.stackup.chosen}${t.stackup.outer_50_mm?` (50Ω ${t.stackup.outer_50_mm} mm)`:""}`,k.appendChild(M),L){let A=t.stackup.chosen,B=document.createElement("button");B.type="button",B.className="bp-mgmt-btn",B.textContent=u("gpui.mgmt.fab.use","Use"),B.addEventListener("click",()=>n("stackup",{id:A})),k.appendChild(B)}E.appendChild(k),a.appendChild(E)}if(Array.isArray(t.changed)&&t.changed.length>0){let E=document.createElement("div");E.className="bp-mgmt-row";let k=document.createElement("div");k.className="bp-mgmt-row-line";let L=document.createElement("span");L.className="bp-mgmt-flex1 bp-tone-warn",L.textContent=u("gpui.mgmt.fab.changed","Changed since you last looked");let M=document.createElement("button");M.type="button",M.className="bp-mgmt-btn",M.textContent=u("gpui.mgmt.fab.seen","Seen"),M.addEventListener("click",()=>n("seen")),k.append(L,M),E.appendChild(k);for(let A of t.changed.slice(0,12)){let B=document.createElement("div");B.className="bp-mgmt-faint",B.textContent=A,E.appendChild(B)}a.appendChild(E)}let w=Array.isArray(t.limits)?t.limits:[];if(w.length>0){let E=document.createElement("div");E.className="bp-mgmt-group-head";let k=document.createElement("span");k.className="bp-mgmt-flex1",k.textContent=u("gpui.mgmt.fab.limit","Limit");let L=document.createElement("span");L.className="bp-mgmt-col",L.textContent=u("gpui.mgmt.fab.free","Base price");let M=document.createElement("span");M.className="bp-mgmt-col",M.textContent=u("gpui.mgmt.fab.extra","Costs more");let A=document.createElement("span");A.className="bp-mgmt-col bp-mgmt-col-read",A.textContent=u("gpui.mgmt.fab.readcol","Read"),E.append(k,L,M,A),a.appendChild(E);for(let T of w){let H=document.createElement("div");H.className="bp-mgmt-row";let O=document.createElement("div");O.className="bp-mgmt-row-line";let P=document.createElement("span");P.className="bp-mgmt-flex1"+(T.changed?" bp-tone-warn":T.inherited?" bp-dim":""),P.textContent=`${T.changed?"• ":""}${T.label??""}`;let Y=document.createElement("span");Y.className="bp-mgmt-col",Y.textContent=T.free?.text||"—";let re=document.createElement("span");re.className="bp-mgmt-col bp-dim",re.textContent=T.extra?.text||"—";let ie=T.free&&typeof T.free==="object"?T.free:T.extra,ue=ie?.fetched??"",Pe=Boolean(ue)&&ie?.confidence!=="published",Ce=ue?Pe?`${ue}*`:ue:"—",te=ie?.source??"",oe;if(te.startsWith("https://")&&ue){let R=document.createElement("a");R.className="bp-mgmt-col bp-mgmt-col-read bp-mgmt-read-link",R.href=te,R.target="_blank",R.rel="noopener noreferrer",R.textContent=Ce,oe=R}else{let R=document.createElement("span");R.className="bp-mgmt-col bp-mgmt-col-read bp-mgmt-faint",R.textContent=Ce,oe=R}O.append(P,Y,re,oe),H.appendChild(O),a.appendChild(H)}let B=document.createElement("div");B.className="bp-mgmt-note bp-mgmt-faint",B.textContent=u("gpui.mgmt.fab.derived","* worked out from the fab's page. Dimmed: the rigid board's value. A date opens the source page."),a.appendChild(B)}return e.appendChild(a),e}makeEmpty(e){let t=document.createElement("div");return t.className="bp-mgmt-note bp-mgmt-faint",t.textContent=e,t}}var ro={trs:(e)=>e,t:(e,t)=>t},oo=new Set(["/settle"]);function ks(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((o)=>o.startsWith(n)))return 2;let r=0;for(let o=0;o0||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 Ps(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 Ss(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 Ls(e,t=ro){let{t:n,trs:i}=t,s=[],r=new Map;for(let a of e.projects)r.set(a.id,a.title||a.id);let o=e.threads.find((a)=>a.id===e.selectedThreadId)??null;for(let a of e.railItems){if(a.state==="disabled"||a.id==="commands")continue;if(!o&&a.id!=="terminal")continue;s.push({label:i(a.label),place:a.id==="terminal"?"":"viewer",kind:"action",shortcut:a.key?a.key.toUpperCase():void 0,action:{type:"rail",id:a.id}})}if(o){if(s.push({label:o.pinned?n("menu.unpin","Unpin"):n("menu.pin","Pin"),place:"",kind:"action",action:{type:"thread-act",action:o.pinned?"unpin":"pin"}}),s.push({label:o.settled?n("phone.unsettle","Unsettle"):n("menu.settle","Settle"),place:"",kind:"action",action:{type:"thread-act",action:o.settled?"unsettle":"settle"}}),s.push({label:o.archived?n("palette.unarchive","Unarchive"):n("palette.archive","Archive"),place:"",kind:"action",action:{type:"thread-act",action:o.archived?"unarchive":"archive"}}),o.project==="chats")s.push({label:n("chats.move","Move to project…"),place:"",kind:"action",action:{type:"move-project"}});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(o)for(let a of e.commands){if(!a.word)continue;let c=oo.has(a.word.toLowerCase());s.push({label:a.label?`${a.word} — ${a.label}`:a.word,place:a.desc||"command",kind:"command",action:{type:"command",word:a.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"}}),s.push({label:n("chats.new.noproject","New chat (no project)"),place:"",kind:"action",action:{type:"new-chat"}});for(let a of e.projects)s.push({label:`New thread in ${a.title||a.id}`,place:"",kind:"action",action:{type:"new-thread",projectId:a.id}});for(let a of e.threads){let{urgency:c,want:p}=xs(a);s.push({label:a.title||"Untitled thread",place:a.project==="chats"?n("chats.title","Chats"):a.project?r.get(a.project)??"":"",kind:"thread",urgency:c,want:p,dotClass:Ps(a),action:{type:"thread",id:a.id}})}for(let a of e.bots){if(!a.name||!a.thread)continue;s.push({label:a.name,place:"",kind:"bot",action:{type:"thread",id:a.thread}})}return s}function As(e,t,n,i=[],s=10,r=14){let o=t.trim(),a=o.length===0,c=e.slice();if(n?.threads&&n.threads.length>0){let d=new Map;for(let f of i)d.set(f.id,f.title||f.id);let m=new Set;for(let f of c)if(f.action.type==="thread")m.add(f.action.id);for(let f of n.threads){if(!f.id||m.has(f.id))continue;m.add(f.id);let{urgency:b,want:v}=xs(f);c.push({label:f.title||"Untitled thread",place:f.project?d.get(f.project)??"":"",kind:"thread",urgency:b,want:v,dotClass:Ps(f),action:{type:"thread",id:f.id}})}}let p=[];for(let d=0;d0)p.push({score:v,index:d,item:m})}p.sort((d,m)=>{if(a){let v=(m.item.urgency??0)-(d.item.urgency??0);if(v!==0)return v}if(m.score!==d.score)return m.score-d.score;let f=d.item.kind==="thread"?0:1,b=m.item.kind==="thread"?0:1;if(f!==b)return f-b;return d.index-m.index});let l=new Set,h=[];for(let d of p){let m=`${d.item.label}\x00${d.item.place}\x00${d.item.kind}`;if(l.has(m))continue;if(l.add(m),h.push(d.item),h.length>=s)break}if(n?.messages&&n.messages.length>0&&h.length{if(o.target===t)this.close()}),s.addEventListener("input",()=>{this.query=s.value,this.activeIdx=0,this.renderList(),this.scheduleSearch()}),s.addEventListener("keydown",(o)=>{if(o.key==="Escape")o.preventDefault(),o.stopPropagation(),this.close();else if(o.key==="ArrowDown"){if(o.preventDefault(),this.listed.length>0)this.activeIdx=(this.activeIdx+1)%this.listed.length,this.renderList(!0)}else if(o.key==="ArrowUp"){if(o.preventDefault(),this.listed.length>0)this.activeIdx=(this.activeIdx-1+this.listed.length)%this.listed.length,this.renderList(!0)}else if(o.key==="Enter")o.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=Ls(t,{t:u,trs:he}),i=this.query.trim()===this.searchHitsQuery?this.searchHits:null;if(this.listed=As(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 o=document.createElement("div");o.className="bp-palette-empty",o.textContent=u("gpui.nothing.matches","Nothing matches"),this.listEl.replaceChildren(o);return}let s=document.createDocumentFragment(),r=null;for(let o=0;o0)p.appendChild(document.createTextNode(a.label.slice(0,d)));let f=document.createElement("strong");if(f.className="bp-palette-mark",f.textContent=a.label.slice(d,m),p.appendChild(f),m{if(this.activeIdx!==o)this.activeIdx=o,this.updateActiveClass()}),c.addEventListener("click",()=>this.runAt(o)),o===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;t0?Math.floor(t.leadDays):0,i=[];for(let s of un(t.warnings)){let r=it(s).trim();if(r&&!i.includes(r))i.push(r)}return{project:it(t.project),root:it(t.root),intent:it(t.intent),parts:un(t.parts).map((s)=>Gn(s)).map((s)=>({name:it(s.name),kind:it(s.kind),path:it(s.path)})).filter((s)=>s.name||s.path),boards:un(t.boards).map(it).filter(Boolean),mech:un(t.mech).map((s)=>Gn(s)).map((s)=>({path:it(s.path),name:it(s.name),size:typeof s.size==="number"&&s.size>0?s.size:0})).filter((s)=>s.name||s.path),leadDays:n,warnings:i}}function Vn(e){let t=[];for(let n of e.split(` -`)){let i=n.trimEnd();if(!i.trim())continue;if(t.length>=60)break;let s=i.trimStart();if(s.startsWith("#"))t.push({kind:"h",text:s.replace(/^#+/,"").trim()});else if(s.startsWith("- ")||s.startsWith("* "))t.push({kind:"li",text:s.slice(2).trim()});else t.push({kind:"p",text:s})}return t}function Ms(e){return!Vn(e).some((t)=>t.kind!=="h"&&t.text.length>0)}function Ts(e){if(!Number.isFinite(e)||e<=0)return"";if(e<1024)return`${Math.floor(e)} B`;if(e<1048576)return`${(e/1024).toFixed(e<10240?1:0)} KB`;return`${(e/1048576).toFixed(1)} MB`}function Un(e){let t=e.lastIndexOf("|");return t>=0?e.slice(t+1):e}function be(e,t,n){let i=document.createElement(e);if(t)i.className=t;if(n!==void 0)i.textContent=n;return i}class Wn{root;titleEl;rootEl;newBtn;newLbl;threadsEl;bodyEl;cb;projectId="";data=null;threads=null;error="";constructor(e,t){this.cb=t,this.root=be("section","bp-project-home bp-hidden"),this.root.setAttribute("data-testid","project-home");let n=be("div","bp-home-inner"),i=be("header","bp-home-head");this.titleEl=be("h1","bp-home-title"),this.titleEl.setAttribute("data-testid","project-home-title"),this.rootEl=be("div","bp-home-root"),i.append(this.titleEl,this.rootEl);let s=be("div","bp-home-bar");this.newBtn=be("button","primary bp-home-new"),this.newBtn.type="button",this.newBtn.setAttribute("data-testid","project-home-new-thread");let r=be("span","bp-home-new-plus","+");r.setAttribute("aria-hidden","true"),this.newLbl=be("span","",u("thread.new","New thread")),this.newBtn.append(r,this.newLbl),this.newBtn.addEventListener("click",()=>{if(this.projectId)this.cb.onNewThread(this.projectId)}),s.appendChild(this.newBtn),this.threadsEl=be("div","bp-home-threads"),this.bodyEl=be("div","bp-home-body"),n.append(i,s,this.threadsEl,this.bodyEl),this.root.appendChild(n),e.appendChild(this.root)}isOpen(){return this.projectId!==""}show(e){if(this.projectId!==e.id)this.data=null,this.threads=null,this.root.scrollTop=0;this.error="",this.projectId=e.id,this.titleEl.textContent=e.title||e.id,this.root.classList.remove("bp-hidden"),this.render()}hide(){this.projectId="",this.root.classList.add("bp-hidden")}setTitle(e){if(e)this.titleEl.textContent=e}setData(e){this.data=e,this.error="",this.render()}setThreads(e){this.threads=e,this.render()}setError(e){this.error=e,this.render()}refreshLocale(){if(this.newLbl.textContent=u("thread.new","New thread"),this.isOpen())this.render()}section(e){return be("h2","bp-home-section",e)}render(){this.rootEl.textContent=this.data?.root??"",this.rootEl.classList.toggle("bp-hidden",!this.data?.root),this.renderThreads(),this.renderBody()}renderThreads(){let e=document.createDocumentFragment(),t=this.threads;if(t){if(e.appendChild(this.section(u("gpui.projects.threads","THREADS ({n})",{n:t.length}))),t.length===0)e.appendChild(be("div","bp-home-empty",u("gpui.no.threads.yet","No threads yet.")));for(let n of t){let i=be("button","bp-home-row bp-home-thread"+(n.settled?" bp-dim":""));i.type="button",i.setAttribute("data-testid",`project-home-thread-${n.id}`);let s=be("span",`bp-dot ${n.dot}`);if(n.status)s.title=n.status;let r=be("span","bp-home-row-main",n.title||"Untitled thread"),o=be("span","bp-home-row-faint",n.age);i.append(s,r,o),i.addEventListener("click",()=>this.cb.onOpenThread(n.id)),e.appendChild(i)}}this.threadsEl.replaceChildren(e)}renderBody(){let e=document.createDocumentFragment(),t=this.data;if(this.error){let s=be("div","bp-home-error");s.setAttribute("data-testid","project-home-error"),s.appendChild(be("span","",this.error));let r=be("button","bp-btn-ghost",u("tools.retry","Retry"));r.type="button";let o=this.projectId;r.addEventListener("click",()=>this.cb.onRetry(o)),s.appendChild(r),e.appendChild(s)}if(!t){if(!this.error)e.appendChild(be("div","bp-home-empty",u("web.home.loading","Loading project…")));this.bodyEl.replaceChildren(e);return}e.appendChild(this.section(u("gpui.goal.notes","GOAL & NOTES")));let n=be("div","bp-home-intent");if(n.setAttribute("data-testid","project-home-intent"),Ms(t.intent))e.appendChild(be("div","bp-home-empty",u("gpui.no.goal.yet.ask.an","No goal yet. Ask an agent to write what this project is for, or edit .backplane/intent.md.")));else{for(let s of Vn(t.intent))if(s.kind==="h")n.appendChild(be("div","bp-home-intent-h",s.text));else if(s.kind==="li"){let r=be("div","bp-home-intent-li"),o=be("span","bp-home-bullet","•");o.setAttribute("aria-hidden","true"),r.append(o,be("span","",s.text)),n.appendChild(r)}else n.appendChild(be("div","",s.text));e.appendChild(n)}let i=this.threads?.[0]?.id??"";if(t.mech.length>0)e.appendChild(this.section(u("gpui.projects.mech","MECHANICAL ({n})",{n:t.mech.length}))),t.mech.forEach((s,r)=>{let o=r===0&&t.mech.length>1,a=this.fileRow(i,"mech",`project-home-mech-${r}`);if(a.title=s.path,a.appendChild(be("span","bp-home-row-main",s.name||s.path)),o)a.appendChild(be("span","bp-home-row-accent",u("gpui.assembly","Assembly")));a.appendChild(be("span","bp-home-row-faint",Ts(s.size))),e.appendChild(a)});if(t.parts.length>0){e.appendChild(this.section(u("gpui.projects.to.order","TO ORDER ({n})",{n:t.parts.length})));let s=be("div","bp-home-order");if(s.setAttribute("data-testid","project-home-order"),t.parts.forEach((r,o)=>{let a=be("div","bp-home-row");a.setAttribute("data-testid",`project-home-part-${o}`),a.append(be("span","bp-home-row-main",r.name||r.path),be("span","bp-home-row-dim",r.kind),be("span","bp-home-row-faint",r.path)),s.appendChild(a)}),t.leadDays>0){let r=be("div","bp-home-order-note",t.leadDays===1?u("web.home.lead.one","Lead time: 1 day"):u("web.home.lead","Lead time: {n} days",{n:t.leadDays}));r.setAttribute("data-testid","project-home-lead"),s.appendChild(r)}for(let r of t.warnings){let o=be("div","bp-home-order-note warn",r);o.setAttribute("data-testid","project-home-warning"),s.appendChild(o)}e.appendChild(s)}if(t.boards.length>0)e.appendChild(this.section(u("gpui.projects.boards","BOARDS ({n})",{n:t.boards.length}))),t.boards.forEach((s,r)=>{let o=this.fileRow(i,"board",`project-home-board-${r}`);o.appendChild(be("span","bp-home-row-main",s)),e.appendChild(o)});this.bodyEl.replaceChildren(e)}fileRow(e,t,n){if(!e){let s=be("div","bp-home-row");return s.setAttribute("data-testid",n),s}let i=be("button","bp-home-row bp-home-open");return i.type="button",i.setAttribute("data-testid",n),i.addEventListener("click",()=>this.cb.onOpenViewer(e,t)),i}}function _n(e){let t=null;if(typeof e==="string"){let i=e.trim();if(!i)return null;try{let s=JSON.parse(i);if(s&&typeof s==="object"&&!Array.isArray(s))t=s}catch{return null}}else if(e&&typeof e==="object"&&!Array.isArray(e))t=e;if(!t)return null;let n=typeof t.head==="string"?t.head.trim():"";if(!n)return null;return{reason:typeof t.reason==="string"?t.reason:"",head:n,text:typeof t.text==="string"?t.text:"",button:typeof t.button==="string"&&t.button.trim()?t.button:"Open Settings → Accounts",url:typeof t.url==="string"&&t.url.trim()?t.url:"backplane://settings/accounts"}}function ao(e){return e.startsWith("No AI provider connected yet.")}function Bs(e,t){if(t==="no_provider")return!0;if(t)return!1;return ao(e)}function st(e){return typeof e==="string"?e:""}function zn(e){return typeof e==="number"&&Number.isFinite(e)?e:0}function Is(e){let t=e&&typeof e==="object"?e:{},n=[];for(let i of Array.isArray(t.notes)?t.notes:[]){if(!i||typeof i!=="object")continue;let s=i,r=st(s.id);if(!r)continue;n.push({id:r,said:zn(s.said),gesture:st(s.gesture),words:st(s.words),model:st(s.model),conf:typeof s.conf==="number"&&Number.isFinite(s.conf)?s.conf:null,unsure:st(s.unsure),state:st(s.state),error:st(s.error),thread:st(s.thread),play:st(s.play),heard:zn(s.heard)})}return{total:Math.max(zn(t.total),n.length),notes:n,busy:st(t.busy)}}function Rs(e){let t=/\/ring\/audio\/(n[0-9a-f]{16})(?:\.m4a)?\?k=([0-9a-fA-F]+)$/.exec(e);return t?`/ring/audio/${t[1]}?k=${t[2]}`:""}function js(e){if(!e.model)return{key:"web.ring.not.heard",fallback:"Not heard"};if(e.model==="ring")return{key:"web.ring.app.words",fallback:"The Pebble app's words"};if(e.conf!==null)return{key:"web.ring.heard.by.sure",fallback:"Heard by {model}, {conf}% sure",vars:{model:e.model,conf:Math.round(e.conf)}};return{key:"web.ring.heard.by",fallback:"Heard by {model}",vars:{model:e.model}}}function Hs(e,t){if(t)return{key:"web.ring.state.busy",fallback:"being heard now"};switch(e){case"sent":return{key:"web.ring.state.sent",fallback:"given to Pebble"};case"new":return{key:"web.ring.state.new",fallback:"waiting to be heard"};case"heard":return{key:"web.ring.state.heard",fallback:"waiting to go to Pebble"};case"failed":return{key:"web.ring.state.failed",fallback:"not given to Pebble"};default:return{key:"",fallback:e}}}function Ds(e,t,n){if(e<=0)return{key:"ring.no.recordings.yet",fallback:"No recordings yet."};if(n.trim())return{key:"web.ring.found",fallback:"{found} of {total} have “{q}”.",vars:{found:t,total:e,q:n.trim()}};return e===1?{key:"web.ring.count.one",fallback:"1 recording"}:{key:"web.ring.count",fallback:"{n} recordings",vars:{n:e}}}var Fs="http://www.w3.org/2000/svg",$s={terminal:["M4 17l6-6-6-6","M12 19h8"],search:["M11 19a8 8 0 1 0 0-16 8 8 0 0 0 0 16z","M21 21l-4.3-4.3"],"circuit-board":["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"],cpu:["M6 6h12v12H6z","M9 2v4","M15 2v4","M9 18v4","M15 18v4","M2 9h4","M2 15h4","M18 9h4","M18 15h4"],box:["M21 16V8l-9-5-9 5v8l9 5 9-5z","M3.3 7L12 12l8.7-5","M12 22V12"],gauge:["M12 14l4-4","M3.3 19a10 10 0 1 1 17.4 0"],"file-stack":["M16 2H6v12h10V2z","M20 6v12H10","M4 18h10v4H4z"],"layout-panel-left":["M3 3h18v18H3z","M10 3v18"],layers:["M12 2L2 7l10 5 10-5-10-5z","M2 12l10 5 10-5","M2 17l10 5 10-5"],wrench:["M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.77-3.77a6 6 0 0 1-7.94 7.94l-6.91 6.91a2.12 2.12 0 0 1-3-3l6.91-6.91a6 6 0 0 1 7.94-7.94l-3.76 3.76z"],folder:["M3 6h6l2 2h10v11H3z"],diff:["M12 5v10","M7 10h10","M7 19h10"],"circle-check":["M12 22a10 10 0 1 0 0-20 10 10 0 0 0 0 20z","M9 12l2 2 4-4"],globe:["M12 22a10 10 0 1 0 0-20 10 10 0 0 0 0 20z","M2 12h20","M12 2a15 15 0 0 1 0 20 15 15 0 0 1 0-20z"]};function lo(e){let t=document.createElementNS(Fs,"svg");t.setAttribute("viewBox","0 0 24 24"),t.setAttribute("width","18"),t.setAttribute("height","18"),t.setAttribute("fill","none"),t.setAttribute("stroke","currentColor"),t.setAttribute("stroke-width","1.75"),t.setAttribute("stroke-linecap","square"),t.setAttribute("stroke-linejoin","miter"),t.setAttribute("aria-hidden","true");let n=$s[e]??$s.folder;for(let i of n){let s=document.createElementNS(Fs,"path");s.setAttribute("d",i),t.appendChild(s)}return t}class qn{el;items=[];activeId="";onPress;pagesRo=null;constructor(e,t){this.el=e,this.onPress=t,this.render()}setItems(e){this.items=e.slice(),this.render()}setActive(e){this.activeId=e,this.render()}renderButton(e){let t=e.state==="disabled",n=!t&&(e.state==="on"||this.activeId!==""&&e.id===this.activeId),i=he(e.label),s=e.why?he(e.why):"",r=document.createElement("button");if(r.type="button",r.className="bp-rail-btn"+(n?" active":"")+(t?" disabled":""),r.disabled=t,r.setAttribute("aria-pressed",n?"true":"false"),t){if(r.title=s||i,s)r.setAttribute("data-why",s)}else r.title=e.key?`${i} (${e.key.toUpperCase()})`:i;r.setAttribute("data-rail-id",e.id),r.setAttribute("data-testid",`rail-${e.id}`),r.appendChild(lo(e.icon));let o=document.createElement("span");if(o.className="bp-rail-lbl",o.textContent=i,r.appendChild(o),!t)r.addEventListener("click",()=>this.onPress(e.id));return r}render(){let e=this.items.filter((o)=>o.group!=="tools"),t=this.items.filter((o)=>o.group==="tools"),n=document.createElement("div");n.className="bp-rail-pages";let i;for(let o of e){if(i!==void 0&&o.group!==i){let a=document.createElement("div");a.className="bp-rail-rule",n.appendChild(a)}i=o.group,n.appendChild(this.renderButton(o))}let s=()=>{let o=n.scrollLeft>2,a=n.scrollLeft+n.clientWidth0){let o=document.createElement("div");o.className="bp-rail-tools";for(let a of t)o.appendChild(this.renderButton(a));r.appendChild(o)}this.el.replaceChildren(r)}}var co=new Set(["resume","raise","retry","move","signin"]);function Kn(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 mn(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(co.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 Os(e){let t=e&&typeof e==="object"?e.open:void 0;if(typeof t!=="string")return null;let n=t.indexOf(":"),i=n<0?"":t.slice(n+1);if(!i)return null;if(t.startsWith("account:"))return{kind:"account",id:i};if(t.startsWith("thread:"))return{kind:"thread",id:i};return null}var Yn=[{id:"general",label:"General"},{id:"ai",label:"Agents and tools"},{id:"connect",label:"Connect"}],Tt=[{id:"appearance",group:"general",title:"Appearance",subtitle:"Kept in this browser only. Never sent to the hub.",icon:"sun",keywords:["theme","dark","light","auto","color","language","locale","english","espanol","japanese"]},{id:"providers",group:"ai",title:"AI providers",subtitle:"Account sign-ins live in the desktop or mobile app.",icon:"cpu",keywords:["accounts","claude","codex","antigravity","grok","openai","anthropic","signin","login","model"]},{id:"ring",group:"ai",title:"Ring",subtitle:"Voice notes from your Pebble ring. Its webhook is set up in the desktop or mobile app.",icon:"mic",keywords:["pebble","index","voice","note","notes","recording","recordings","play","hear","transcribe","search"]},{id:"devices",group:"connect",title:"Devices & browser",subtitle:"This browser session and paired devices on this hub.",icon:"link",keywords:["sign out","logout","session","cookie","revoke","paired","phone","browser","pair"]},{id:"home",group:"connect",title:"Home machine",subtitle:"Which machine hosts your always-on hub and bots.",icon:"globe",keywords:["host","boat","move","online","away","queued","linked"]}];function Gs(e){if(e==="dark"||e==="light"||e==="auto")return e;return"auto"}function Vs(e){if(e==="en"||e==="es"||e==="ja"||e==="auto")return e;return"auto"}function Wt(e,t){if(e==="dark"||e==="light")return e;return t==="light"?"light":"dark"}function Us(e){return e.trim().toLowerCase().split(/\s+/).filter(Boolean)}function Jn(e,t){if(t.length===0)return!0;let n=e.toLowerCase();return t.every((i)=>n.includes(i))}function Ws(e,t){let n=Us(t);if(n.length===0)return[];return e.filter((i)=>{let s=[i.groupLabel,i.pageTitle,i.rowTitle,i.rowDetail,...i.keywords??[]].join(" ");return Jn(s,n)})}function Xn(e,t,n){let i=Us(n);if(i.length===0)return e.map((o)=>({page:o,hits:[]}));let s=new Map(Yn.map((o)=>[o.id,o.label])),r=[];for(let o of e){let c=t.filter((l)=>l.pageId===o.id).filter((l)=>Jn([l.rowTitle,l.rowDetail,l.pageTitle,l.groupLabel,...l.keywords??[]].join(" "),i));if(Jn([s.get(o.group)??"",o.title,o.subtitle,...o.keywords].join(" "),i)||c.length>0){let l=[];for(let h of c){if(!l.includes(h.rowTitle))l.push(h.rowTitle);if(l.length>=2)break}r.push({page:o,hits:l})}}return r}function Qn(e){return e.key?u(e.key,e.fallback,e.vars):e.fallback}function po(e){let n=document.createElementNS("http://www.w3.org/2000/svg","svg");n.setAttribute("viewBox","0 0 24 24"),n.setAttribute("width","15"),n.setAttribute("height","15"),n.setAttribute("fill","none"),n.setAttribute("stroke","currentColor"),n.setAttribute("stroke-width","1.75"),n.setAttribute("stroke-linecap","square"),n.setAttribute("stroke-linejoin","miter"),n.setAttribute("aria-hidden","true");let i=(s,r)=>{let o=document.createElementNS("http://www.w3.org/2000/svg",s);for(let[a,c]of Object.entries(r))o.setAttribute(a,c);n.appendChild(o)};switch(e){case"sun":i("circle",{cx:"12",cy:"12",r:"4"}),i("path",{d:"M12 2v2m0 16v2M4.93 4.93l1.41 1.41m11.32 11.32 1.41 1.41M2 12h2m16 0h2M4.93 19.07l1.41-1.41m11.32-11.32 1.41-1.41"});break;case"cpu":i("rect",{x:"5",y:"5",width:"14",height:"14"}),i("rect",{x:"9",y:"9",width:"6",height:"6"}),i("path",{d:"M9 2v3m6-3v3M9 19v3m6-3v3M2 9h3m-3 6h3M19 9h3m-3 6h3"});break;case"link":i("path",{d:"M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"}),i("path",{d:"M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"});break;case"mic":i("rect",{x:"9",y:"2",width:"6",height:"12"}),i("path",{d:"M5 11a7 7 0 0 0 14 0M12 18v4M8 22h8"});break;case"globe":i("circle",{cx:"12",cy:"12",r:"10"}),i("path",{d:"M2 12h20M12 2a15.3 15.3 0 0 1 4 10 15.3 15.3 0 0 1-4 10 15.3 15.3 0 0 1-4-10 15.3 15.3 0 0 1 4-10z"});break}return n}function ho(){let t=document.createElementNS("http://www.w3.org/2000/svg","svg");t.setAttribute("viewBox","0 0 24 24"),t.setAttribute("width","13"),t.setAttribute("height","13"),t.setAttribute("fill","none"),t.setAttribute("stroke","currentColor"),t.setAttribute("stroke-width","1.75"),t.setAttribute("aria-hidden","true");let n=document.createElementNS("http://www.w3.org/2000/svg","circle");n.setAttribute("cx","11"),n.setAttribute("cy","11"),n.setAttribute("r","7");let i=document.createElementNS("http://www.w3.org/2000/svg","path");return i.setAttribute("d","m20 20-3.5-3.5"),t.append(n,i),t}function bn(e,t){switch(e){case"general":return u("gpui.settings.group.general",t);case"ai":return u("gpui.settings.group.agents",t);case"connect":return u("native.pair.connect",t)}}function gt(e,t){switch(e){case"appearance":return u("settings.appearance",t);case"providers":return u("web.settings.providers",t);case"ring":return u("ring.ring",t);case"devices":return t;case"home":return u("home.machine",t)}}class Zn{backdrop;titleEl;badgeEl;closeBtn;navListEl;searchInput;searchClearBtn;paneEl;cb;openState=!1;activePage="appearance";forceProviders=!1;query="";searchBrowseAll=!1;devicesLoaded=!1;devicesLoading=!1;devicesRows=[];devicesError="";loadGen=0;ringLoaded=!1;ringLoading=!1;ringList={total:0,notes:[],busy:""};ringCountEl=null;ringErrorEl=null;ringRows=new Map;ringShownQuery="";ringError="";ringQuery="";ringDraft="";ringGen=0;ringBusy=new Set;ringPolls=0;ringTimers=[];constructor(e,t){this.cb=t,this.backdrop=document.createElement("div"),this.backdrop.className="bp-modal-backdrop bp-hidden",this.backdrop.setAttribute("data-testid","settings-modal");let n=document.createElement("div");n.className="bp-modal bp-settings-modal",n.setAttribute("role","dialog"),n.setAttribute("aria-modal","true"),n.setAttribute("aria-labelledby","bp-settings-title");let i=document.createElement("div");i.className="bp-modal-head";let s=document.createElement("div");s.className="bp-settings-head-title",this.titleEl=document.createElement("h2"),this.titleEl.id="bp-settings-title",this.titleEl.textContent=u("palette.settings","Settings"),this.badgeEl=document.createElement("span"),this.badgeEl.className="bp-settings-badge",this.badgeEl.textContent="Browser",s.append(this.titleEl,this.badgeEl),this.closeBtn=document.createElement("button"),this.closeBtn.type="button",this.closeBtn.className="icon",this.closeBtn.textContent="×",this.closeBtn.setAttribute("aria-label",u("common.close","Close")),this.closeBtn.addEventListener("click",()=>this.close()),i.append(s,this.closeBtn);let r=document.createElement("div");r.className="bp-settings-body";let o=document.createElement("aside");o.className="bp-settings-nav";let a=document.createElement("div");a.className="bp-settings-search";let c=document.createElement("span");c.className="bp-settings-search-icon",c.appendChild(ho()),this.searchInput=document.createElement("input"),this.searchInput.type="text",this.searchInput.className="bp-settings-search-input",this.searchInput.placeholder="Search settings…",this.searchInput.setAttribute("aria-label","Search settings"),this.searchInput.setAttribute("data-testid","settings-search"),this.searchClearBtn=document.createElement("button"),this.searchClearBtn.type="button",this.searchClearBtn.className="bp-settings-search-clear bp-hidden",this.searchClearBtn.textContent="×",this.searchClearBtn.title="Clear search",this.searchClearBtn.setAttribute("aria-label","Clear search"),a.append(c,this.searchInput,this.searchClearBtn),this.navListEl=document.createElement("nav"),this.navListEl.className="bp-settings-nav-list",this.navListEl.setAttribute("aria-label","Settings sections"),o.append(a,this.navListEl),this.paneEl=document.createElement("div"),this.paneEl.className="bp-settings-pane",r.append(o,this.paneEl),n.append(i,r),this.backdrop.appendChild(n),this.backdrop.addEventListener("click",(p)=>{if(p.target===this.backdrop)this.close()}),this.searchInput.addEventListener("input",()=>{this.query=this.searchInput.value,this.searchBrowseAll=this.query.trim().length>0,this.syncSearchClear(),this.render()}),this.searchInput.addEventListener("keydown",(p)=>{if(p.key==="Enter"){let l=Xn(Tt,this.buildSearchItems(),this.query);if(l.length>0)p.preventDefault(),this.activePage=l[0].page.id,this.searchBrowseAll=!1,this.render()}else if(p.key==="Escape"&&this.query.trim().length>0)p.preventDefault(),p.stopPropagation(),this.clearSearch()}),this.searchClearBtn.addEventListener("click",()=>{this.clearSearch(),this.searchInput.focus()}),e.appendChild(this.backdrop)}isOpen(){return this.openState}handleEscape(){if(!this.openState)return;if(this.query.trim().length>0)this.clearSearch(),this.searchInput.focus();else this.close()}async open(e){if(this.openState=!0,e)this.activePage=e;if(this.backdrop.classList.remove("bp-hidden"),this.render(),this.loadDevices(),this.activePage==="ring")this.loadRing();window.setTimeout(()=>{if(this.openState)this.searchInput.focus()},0)}async openToAccounts(){this.forceProviders=!0,this.query="",this.searchInput.value="",this.searchBrowseAll=!1,this.syncSearchClear(),await this.open("providers")}close(){this.openState=!1,this.forceProviders=!1,this.query="",this.searchInput.value="",this.searchBrowseAll=!1,this.syncSearchClear(),this.backdrop.classList.add("bp-hidden");for(let e of this.ringTimers)window.clearTimeout(e);if(this.ringTimers=[],this.ringBusy.clear(),this.ringPolls=0,this.activePage==="ring")this.paneEl.replaceChildren()}refreshLocale(){if(this.titleEl.textContent=u("palette.settings","Settings"),this.closeBtn.setAttribute("aria-label",u("common.close","Close")),this.openState)this.render()}async refresh(){if(!this.openState)return;this.render(),await this.loadDevices()}clearSearch(){this.query="",this.searchInput.value="",this.searchBrowseAll=!1,this.syncSearchClear(),this.render()}syncSearchClear(){this.searchClearBtn.classList.toggle("bp-hidden",this.query.length===0)}async loadDevices(){let e=++this.loadGen;if(this.devicesLoading=!this.devicesLoaded,this.devicesLoading&&this.openState)this.renderPane();try{let t=await this.cb.onLoadDevices();if(e!==this.loadGen)return;this.devicesRows=t,this.devicesError="",this.devicesLoaded=!0}catch(t){if(e!==this.loadGen)return;let n=t instanceof Error&&t.message?t.message:"Not available from a browser";this.devicesError=`${n} — manage paired devices in Backplane › Settings › Devices on desktop or a paired phone.`,this.devicesRows=[],this.devicesLoaded=!0}finally{if(e===this.loadGen){if(this.devicesLoading=!1,this.openState)this.render()}}}async loadRing(){if(!this.cb.onRingList||!(this.cb.hasRing?.()??!1))return;let e=++this.ringGen;if(this.ringLoading=!this.ringLoaded,this.ringLoading)this.showRing();try{let t=await this.cb.onRingList(this.ringQuery);if(e!==this.ringGen)return;if(this.ringList=t,this.ringError="",!t.busy)this.ringBusy.clear();if(t.busy&&this.openState&&this.ringPolls<40)this.ringPolls++,this.ringLater(3000);else if(!t.busy)this.ringPolls=0}catch(t){if(e!==this.ringGen)return;this.ringError=t instanceof Error&&t.message?t.message:u("web.ring.error","Could not load recordings.")}finally{if(e===this.ringGen)this.ringLoaded=!0,this.ringLoading=!1,this.showRing()}}ringLater(e){let t=window.setTimeout(()=>{if(this.ringTimers=this.ringTimers.filter((n)=>n!==t),this.openState)this.loadRing()},e);this.ringTimers.push(t)}ringIsBusy(e){return this.ringBusy.has(e)||this.ringList.busy===e}showRing(){if(!this.openState||this.activePage!=="ring"||this.query.trim()&&this.searchBrowseAll)return;let e=this.ringList.notes.map((i)=>i.id),t=Array.from(this.ringRows.keys());if(!(this.ringCountEl?.isConnected===!0&&this.ringShownQuery===this.ringQuery&&e.length===t.length&&e.every((i,s)=>i===t[s]))){this.renderPane();return}if(this.ringCountEl)this.ringCountEl.textContent=this.ringCountLine();if(this.ringErrorEl)this.ringErrorEl.textContent=this.ringError,this.ringErrorEl.classList.toggle("bp-hidden",!this.ringError);for(let i of this.ringList.notes)this.fillRingNote(i)}ringCountLine(){return this.ringLoading?u("web.ring.loading","Loading recordings…"):Qn(Ds(this.ringList.total,this.ringList.notes.length,this.ringQuery))}fillRingNote(e){let t=this.ringRows.get(e.id);if(!t)return;let n=this.ringIsBusy(e.id);t.state.className="bp-status-pill "+(n?"accent":e.state==="sent"?"ok":e.state==="failed"?"bad":"warn"),t.state.textContent=Qn(Hs(e.state,n)),t.words.className="bp-ring-words"+(e.words?"":" bp-dim"),t.words.textContent=e.words||u("web.ring.no.words","(no words)"),t.meta.textContent=[Qn(js(e)),e.unsure,e.error].filter(Boolean).join(" · ");for(let i of t.hear)i.disabled=n}async hearRing(e,t){if(!this.cb.onRingHear||this.ringIsBusy(e))return;this.ringBusy.add(e),this.ringError="",this.showRing();try{await this.cb.onRingHear(e,t),this.ringPolls=0,this.ringLater(1500)}catch(n){this.ringBusy.delete(e),this.ringError=n instanceof Error&&n.message?n.message:u("web.ring.error","Could not load recordings."),this.showRing()}}buildSearchItems(){let e=this.cb.onGetHome?.()??null,t=this.cb.onGetNoProvider?.()??null,n=bn("general","General"),i=bn("ai","Agents and tools"),s=bn("connect","Connect"),r=gt("appearance","Appearance"),o=gt("providers","AI providers"),a=gt("devices","Devices & browser"),c=gt("home","Home machine"),p=[{pageId:"appearance",pageTitle:r,groupLabel:n,rowTitle:u("settings.theme","Theme"),rowDetail:"Auto (follow hub), Dark, or Light in this browser.",keywords:["theme","dark","light","auto","appearance","colors"]},{pageId:"appearance",pageTitle:r,groupLabel:n,rowTitle:u("settings.lang","Language"),rowDetail:"Interface language for this browser.",keywords:["locale","english","espanol","japanese","language"]},{pageId:"providers",pageTitle:o,groupLabel:i,rowTitle:t?he(t.head):"Provider connections",rowDetail:"Connect Claude, Codex, Antigravity, or other AI providers in Settings → Accounts.",keywords:["accounts","claude","codex","antigravity","grok","openai","signin"]},{pageId:"ring",pageTitle:gt("ring","Ring"),groupLabel:i,rowTitle:u("ring.recordings","Recordings"),rowDetail:"Read, search, play and hear again the voice notes from your Pebble ring.",keywords:["pebble","voice","note","recording","play","hear","transcribe"]},{pageId:"devices",pageTitle:a,groupLabel:s,rowTitle:"This browser",rowDetail:"Sign out and revoke this browser's session cookie.",keywords:["logout","sign out","session","cookie"]},{pageId:"devices",pageTitle:a,groupLabel:s,rowTitle:"Paired devices",rowDetail:this.devicesRows.map((l)=>`${l.title||l.head||""} ${l.detail||l.text||""}`).join(" ")||"Paired phones and browsers on this hub.",keywords:["phone","pair","revoke","browser"]},{pageId:"home",pageTitle:c,groupLabel:s,rowTitle:e?.name?`${e.name}`:c,rowDetail:"Which machine hosts your always-on hub and bots.",keywords:["boat","move","online","away","queued","machine"]}];for(let l of this.devicesRows){let h=l.title||l.head||"";if(h)p.push({pageId:"devices",pageTitle:a,groupLabel:s,rowTitle:h,rowDetail:l.detail||l.text||"",keywords:["paired","device"]})}return p}render(){this.renderNav(),this.renderPane()}renderNav(){let e=document.createDocumentFragment(),t=Xn(Tt,this.buildSearchItems(),this.query),n=this.cb.onGetNoProvider?.()??null,i=this.cb.onGetHome?.()??null;if(t.length===0){let r=document.createElement("div");r.className="bp-settings-nav-empty",r.setAttribute("data-testid","settings-nav-empty"),r.textContent="No matching settings",e.appendChild(r),this.navListEl.replaceChildren(e);return}let s="";for(let r of t){let o=r.page;if(o.group!==s){s=o.group;let d=Yn.find((m)=>m.id===o.group);if(d){let m=document.createElement("div");m.className="bp-settings-group",m.textContent=bn(d.id,d.label),e.appendChild(m)}}let a=document.createElement("button");a.type="button";let c=!this.searchBrowseAll&&o.id===this.activePage;a.className="bp-settings-nav-item"+(c?" active":""),a.setAttribute("data-testid",`settings-nav-${o.id}`);let p=document.createElement("div");p.className="bp-settings-nav-row";let l=document.createElement("span");l.className="bp-settings-nav-icon",l.appendChild(po(o.icon));let h=document.createElement("span");if(h.className="bp-settings-nav-label",h.textContent=gt(o.id,o.title),p.append(l,h),o.id==="providers"&&(n||this.forceProviders)){let d=document.createElement("span");d.className="bp-settings-nav-dot warn",d.title="Action needed",p.appendChild(d)}else if(o.id==="home"&&i){let d=document.createElement("span");d.className="bp-settings-nav-dot "+(i.moving?.state==="failed"?"bad":i.online?"ok":"warn"),p.appendChild(d)}if(a.appendChild(p),r.hits.length>0)for(let d of r.hits){let m=document.createElement("div");m.className="bp-settings-hit",m.textContent=d,a.appendChild(m)}a.addEventListener("click",()=>{if(this.activePage=o.id,this.searchBrowseAll=!1,this.render(),o.id==="ring")this.loadRing()}),e.appendChild(a)}this.navListEl.replaceChildren(e)}renderPane(){let e=document.createDocumentFragment(),t=this.query.trim();if(t&&this.searchBrowseAll){this.renderSearchResults(e,t),this.paneEl.replaceChildren(e);return}let n=Tt.find((o)=>o.id===this.activePage)??Tt[0],i=document.createElement("div");i.className="bp-settings-pane-head";let s=document.createElement("h3");s.textContent=gt(n.id,n.title);let r=document.createElement("div");switch(r.className="bp-settings-pane-sub",r.textContent=n.subtitle,i.append(s,r),e.appendChild(i),n.id){case"appearance":this.renderAppearancePage(e);break;case"providers":this.renderProvidersPage(e);break;case"ring":this.renderRingPage(e);break;case"devices":this.renderDevicesPage(e);break;case"home":this.renderHomePage(e);break}this.paneEl.replaceChildren(e)}renderSearchResults(e,t){let n=Ws(this.buildSearchItems(),t),i=document.createElement("div");i.className="bp-settings-pane-head";let s=document.createElement("h3");s.textContent="Search results";let r=document.createElement("div");if(r.className="bp-settings-pane-sub",r.textContent=n.length===0?`No settings match "${t}".`:`${n.length} matching ${n.length===1?"setting":"settings"} for "${t}"`,i.append(s,r),e.appendChild(i),n.length===0){let a=document.createElement("div");a.className="bp-settings-empty",a.textContent="Try searching for theme, language, providers, sign out, devices, or home.",e.appendChild(a);return}let o=Array.from(new Set(n.map((a)=>a.pageId)));for(let a of o){let c=Tt.find((m)=>m.id===a);if(!c)continue;let p=document.createElement("div");p.className="bp-settings-search-sec";let l=document.createElement("div");l.className="bp-settings-subhead",l.textContent=gt(c.id,c.title);let h=document.createElement("button");h.type="button",h.className="bp-settings-search-open",h.textContent="Open page ›",h.addEventListener("click",()=>{if(this.activePage=a,this.searchBrowseAll=!1,this.render(),a==="ring")this.loadRing()}),p.append(l,h),e.appendChild(p);let d=new Set(n.filter((m)=>m.pageId===a).map((m)=>m.rowTitle));if(a==="appearance")this.renderAppearancePage(e,d);else if(a==="providers")this.renderProvidersPage(e);else if(a==="ring"){let m=document.createElement("div");m.className="bp-settings-empty",m.textContent="Read, search, play and hear again the voice notes from your Pebble ring.",e.appendChild(m)}else if(a==="devices")this.renderDevicesPage(e,d);else if(a==="home")this.renderHomePage(e)}}renderAppearancePage(e,t){let n=this.cb.onGetThemePref?.()??"auto",i=this.cb.onGetHubTheme?.()??"dark",s=Wt(n,i),r=this.cb.onGetLocalePref?.()??"auto",o=u("settings.theme","Theme"),a=u("settings.lang","Language");if(!t||t.has(o)){let c=u("settings.theme.dark","Dark"),p=u("settings.theme.light","Light"),l=n==="auto"?`Following hub theme (${i==="light"?p:c}). Stored in this browser only.`:`Using ${s==="light"?p:c} in this browser. Select Auto to follow the hub.`;e.appendChild(this.makeSegmentedRow(o,l,[{value:"auto",label:"Auto"},{value:"dark",label:c},{value:"light",label:p}],n,"settings-theme",(h)=>{this.cb.onSetThemePref?.(h),this.render()}))}if(!t||t.has(a))e.appendChild(this.makeSegmentedRow(a,"Interface language for this browser. Automatic follows the hub or browser language.",[{value:"auto",label:u("settings.lang.auto","Automatic")},{value:"en",label:u("settings.lang.en","English")},{value:"es",label:u("settings.lang.es","Español")},{value:"ja",label:u("settings.lang.ja","日本語")}],r,"settings-locale",(c)=>{this.cb.onSetLocalePref?.(c),this.render()}))}makeSegmentedRow(e,t,n,i,s,r){let o=document.createElement("div");o.className="bp-settings-row";let a=document.createElement("div");a.className="bp-settings-row-info";let c=document.createElement("div");c.className="bp-settings-row-title",c.textContent=e;let p=document.createElement("div");p.className="bp-settings-row-detail",p.textContent=t,a.append(c,p);let l=document.createElement("div");l.className="bp-chip-group",l.setAttribute("role","group"),l.setAttribute("aria-label",e);for(let h of n){let d=document.createElement("button");d.type="button";let m=h.value===i;d.className="bp-chip"+(m?" active":""),d.textContent=h.label,d.setAttribute("aria-pressed",m?"true":"false"),d.setAttribute("data-testid",`${s}-${h.value}`),d.addEventListener("click",()=>r(h.value)),l.appendChild(d)}return o.append(a,l),o}renderProvidersPage(e){let t=this.cb.onGetNoProvider?.()??null,n=document.createElement("section");if(n.className="bp-settings-section",n.setAttribute("data-testid","settings-providers"),t||this.forceProviders){let i=document.createElement("div");i.className="bp-settings-notice warn";let s=document.createElement("div");s.className="bp-settings-row-info";let r=document.createElement("div");r.className="bp-settings-row-title",r.textContent=t?he(t.head):u("provider.notice.head","No AI provider connected");let o=document.createElement("div");o.className="bp-settings-row-detail",o.textContent=u("web.settings.providers.browser","Connect a provider in the Backplane desktop or mobile app under Settings → Accounts."),s.append(r,o);let a=document.createElement("div");a.className="bp-set-btns";let c=document.createElement("a");c.className="bp-link-btn primary",c.href=t?.url||"backplane://settings/accounts",c.setAttribute("data-testid","settings-open-accounts"),c.textContent=t?he(t.button):u("provider.notice.button","Open Settings → Accounts"),a.appendChild(c),i.append(s,a),n.appendChild(i)}else{let i=document.createElement("div");i.className="bp-settings-row";let s=document.createElement("div");s.className="bp-settings-row-info";let r=document.createElement("div");r.className="bp-settings-row-title-wrap";let o=document.createElement("span");o.className="bp-settings-row-title",o.textContent="Provider connections";let a=document.createElement("span");a.className="bp-status-pill ok",a.textContent=u("gpui.acct.connected","Connected"),r.append(o,a);let c=document.createElement("div");c.className="bp-settings-row-detail",c.textContent="Provider sign-ins, fallback order, API keys, and usage limits are managed in the Backplane desktop or mobile app.",s.append(r,c);let p=document.createElement("div");p.className="bp-set-btns";let l=document.createElement("a");l.className="bp-link-btn",l.href="backplane://settings/accounts",l.setAttribute("data-testid","settings-open-accounts"),l.textContent=u("provider.notice.button","Open Settings → Accounts"),p.appendChild(l),i.append(s,p),n.appendChild(i)}e.appendChild(n)}renderDevicesPage(e,t){let n=!t||t.has("This browser"),i=!t||t.has("Paired devices")||this.devicesRows.some((o)=>t.has(o.title||o.head||""));if(n){let o=document.createElement("div");o.className="bp-settings-subhead",o.textContent="This browser",e.appendChild(o);let a=document.createElement("div");a.className="bp-settings-row";let c=document.createElement("div");c.className="bp-settings-row-info";let p=document.createElement("div");p.className="bp-settings-row-title",p.textContent="Browser session";let l=document.createElement("div");l.className="bp-settings-row-detail",l.textContent="Sign out and revoke this browser's session cookie.",c.append(p,l);let h=document.createElement("button");h.type="button",h.className="primary stop",h.textContent=u("agy.signout","Sign out"),h.setAttribute("data-testid","logout-btn"),h.addEventListener("click",()=>{h.disabled=!0,this.cb.onLogout().catch(()=>{l.setAttribute("role","alert"),l.className="bp-settings-row-detail bp-bad",l.textContent=u("web.logout.failed","Could not confirm sign-out. Try again."),h.disabled=!1})}),a.append(c,h),e.appendChild(a)}if(!i)return;let s=document.createElement("div");if(s.className="bp-settings-subhead",s.textContent="Paired devices",e.appendChild(s),this.devicesLoading){let o=document.createElement("div");o.className="bp-settings-empty",o.textContent="Loading paired devices…",e.appendChild(o);return}if(this.devicesError){let o=document.createElement("div");o.className="bp-settings-notice bad";let a=document.createElement("div");a.className="bp-settings-row-detail",a.textContent=this.devicesError,o.appendChild(a),e.appendChild(o);return}let r=!t||t.has("Paired devices")?this.devicesRows:this.devicesRows.filter((o)=>t.has(o.title||o.head||""));if(r.length===0){let o=document.createElement("div");o.className="bp-settings-empty",o.textContent="No paired devices listed.",e.appendChild(o)}else for(let o of r){let a=document.createElement("div");a.className="bp-settings-row";let c=document.createElement("div");c.className="bp-settings-row-info";let p=document.createElement("div");p.className="bp-settings-row-title-wrap";let l=document.createElement("span");l.className="bp-settings-row-title",l.textContent=o.title||o.head||"",p.appendChild(l);let h=o.detail||o.text||"";if(h){let d=document.createElement("span"),m=h.toLowerCase();d.className="bp-status-pill "+(m.includes("this browser")?"accent":"neutral"),d.textContent=h,p.appendChild(d)}if(c.appendChild(p),a.appendChild(c),o.buttons?.length){let d=document.createElement("div");d.className="bp-set-btns";for(let m of o.buttons){let f=document.createElement("button");if(f.type="button",m.primary)f.className="primary";if(m.danger)f.className="primary stop";f.textContent=m.label||u("common.remove","Remove"),f.addEventListener("click",()=>{f.disabled=!0,this.cb.onDevicesAct(m.action,m.value).finally(()=>{this.refresh()})}),d.appendChild(f)}a.appendChild(d)}e.appendChild(a)}if(!t){let o=document.createElement("div");o.className="bp-settings-footnote",o.textContent="Pair new browsers or phones, configure Tailscale HTTPS forwarding, or revoke access in desktop or mobile Settings → Devices.",e.appendChild(o)}}renderRingPage(e){let t=document.createElement("section");if(t.className="bp-settings-section",t.setAttribute("data-testid","settings-ring"),!this.cb.onRingList||!(this.cb.hasRing?.()??!1)){let a=document.createElement("div");a.className="bp-settings-empty",a.textContent=u("web.ring.unavailable","This hub does not show ring notes to a browser yet. Update it, or open Settings › Ring in the desktop app."),t.appendChild(a),e.appendChild(t);return}let n=document.createElement("form");n.className="bp-ring-search";let i=document.createElement("input");i.type="search",i.className="bp-ring-search-input",i.placeholder=u("ring.search.what.you.said","Search what you said"),i.setAttribute("aria-label",u("ring.search.what.you.said","Search what you said")),i.setAttribute("data-testid","ring-search"),i.value=this.ringDraft,i.addEventListener("input",()=>{this.ringDraft=i.value});let s=document.createElement("button");if(s.type="submit",s.className="primary",s.textContent=u("common.search","Search"),n.append(i,s),this.ringQuery){let a=document.createElement("button");a.type="button",a.className="bp-btn-ghost",a.textContent=u("ring.show.all","Show all"),a.addEventListener("click",()=>{this.ringDraft="",this.ringQuery="",this.loadRing()}),n.appendChild(a)}n.addEventListener("submit",(a)=>{a.preventDefault(),this.ringQuery=this.ringDraft.trim(),this.loadRing()}),t.appendChild(n);let r=document.createElement("div");r.className="bp-settings-notice bad"+(this.ringError?"":" bp-hidden"),r.setAttribute("data-testid","ring-error"),r.textContent=this.ringError,t.appendChild(r),this.ringErrorEl=r;let o=document.createElement("div");o.className="bp-ring-count",o.setAttribute("data-testid","ring-count"),o.textContent=this.ringCountLine(),t.appendChild(o),this.ringCountEl=o,this.ringRows.clear(),this.ringShownQuery=this.ringQuery;for(let a of this.ringList.notes)t.appendChild(this.renderRingNote(a));e.appendChild(t)}renderRingNote(e){let t=document.createElement("div");t.className="bp-ring-note"+(e.state==="failed"?" bad":""),t.setAttribute("data-testid",`ring-note-${e.id}`);let n=document.createElement("div");n.className="bp-ring-note-head";let i=document.createElement("span");i.className="bp-settings-row-title";let s=e.said>0?new Date(e.said*1000).toLocaleString(Mi(),{dateStyle:"medium",timeStyle:"short"}):"";i.textContent=[s,e.gesture].filter(Boolean).join(" · ");let r=document.createElement("span");n.append(i,r);let o=document.createElement("div"),a=document.createElement("div");a.className="bp-settings-row-detail";let c=[],p=document.createElement("div");p.className="bp-ring-acts";let l=Rs(e.play);if(l){let h=document.createElement("audio");h.className="bp-ring-audio",h.controls=!0,h.preload="none",h.src=l,h.setAttribute("data-testid",`ring-audio-${e.id}`),p.appendChild(h);for(let[d,m]of[["local",u("ring.hear.again.local","Hear again (local)")],["openai",u("ring.hear.again.openai","Hear again (OpenAI)")]]){let f=document.createElement("button");f.type="button",f.className="bp-btn-ghost",f.textContent=m,f.setAttribute("data-testid",`ring-hear-${d}-${e.id}`),c.push(f),f.addEventListener("click",()=>{this.hearRing(e.id,d)}),p.appendChild(f)}}if(e.thread&&this.cb.onOpenThread){let h=document.createElement("button");h.type="button",h.className="bp-btn-ghost",h.textContent=u("ring.what.happened","What happened"),h.addEventListener("click",()=>{this.close(),this.cb.onOpenThread?.(e.thread)}),p.appendChild(h)}if(t.append(n,o,a),p.childElementCount>0)t.appendChild(p);return this.ringRows.set(e.id,{state:r,words:o,meta:a,hear:c}),this.fillRingNote(e),t}renderHomePage(e){let t=this.cb.onGetHome?.()??null,n=document.createElement("section");if(n.className="bp-settings-section",n.setAttribute("data-testid","settings-home"),!t){let d=document.createElement("div");d.className="bp-settings-empty",d.textContent="Single-hub mode — this hub is running locally without linked home machines.",n.appendChild(d),e.appendChild(n);return}let i=document.createElement("div");i.className="bp-settings-row";let s=document.createElement("div");s.className="bp-settings-row-info";let r=document.createElement("div");r.className="bp-settings-row-title-wrap";let o=document.createElement("span");o.className="bp-settings-row-title",o.textContent=t.name||(t.kind==="boat"?"Boat":"This machine"),r.appendChild(o);let a=document.createElement("span");a.className="bp-status-pill neutral",a.textContent=t.kind==="local"?"This machine":t.kind==="boat"?"Boat":"Linked machine",r.appendChild(a);let c=document.createElement("span"),p="Online",l="ok";if(t.moving?.state==="moving")p="Moving",l="accent";else if(t.moving?.state==="failed")p="Move failed",l="bad";else if(!t.online)p="Away",l="warn";c.className=`bp-status-pill ${l}`,c.textContent=p,r.appendChild(c);let h=document.createElement("div");if(h.className="bp-settings-row-detail",t.moving?.state==="moving")h.textContent=t.moving.step?u("home.moving.step","Moving home to {to}: {step}").replace("{to}",t.moving.to).replace("{step}",t.moving.step):u("home.moving","Moving home to {to}…").replace("{to}",t.moving.to);else if(t.moving?.state==="failed")h.textContent=t.moving.note?u("home.move.failed.note","Home move failed: {note}").replace("{note}",t.moving.note):u("home.move.failed","Home move failed");else if(!t.online)h.textContent=t.queuedCount>0?u("home.away.queued","Home ({name}) is away · {n} queued").replace("{name}",t.name||"home").replace("{n}",String(t.queuedCount)):u("home.away","Home ({name}) is away").replace("{name}",t.name||"home");else h.textContent="Your active home hub is online and serving threads and bots.";if(s.append(r,h),i.appendChild(s),t.canMoveHere&&this.cb.onMoveHomeHere){let d=document.createElement("button");d.type="button",d.className="primary",d.textContent=u("home.move.here","Make this machine the home"),d.setAttribute("data-testid","home-move-here-btn"),d.addEventListener("click",()=>{d.disabled=!0,this.cb.onMoveHomeHere?.().finally(()=>{this.refresh()})}),i.appendChild(d)}n.appendChild(i),e.appendChild(n)}}function xe(e,t,n){let i=document.createElement(e);if(t)i.className=t;if(n)i.textContent=n;return i}function _t(e,t,n=!1){let i=xe("button",n?"primary":"bp-btn-ghost",e);return i.type="button",i.addEventListener("click",t),i}function ei(e){return xe("pre","bp-context-code",e)}function uo(e){return xe("span",`bp-context-badge ${e==="Native"||e==="Enabled"?"active":e==="Untrusted"||e==="Invalid"?"warn":""}`,he(e))}function gn(e,t){let n=xe("div","bp-context-row");return n.append(xe("strong",void 0,e),uo(t)),n}class ti{fetchContext;dialog=xe("dialog","bp-context");title=xe("h2");cwd=xe("div","bp-context-path");tabs=xe("div","bp-context-tabs");body=xe("div","bp-context-body");notice=xe("p","bp-context-notice");current;thread="";requestId=0;tab=0;busy=!1;constructor(e,t){this.fetchContext=t;let n=xe("div","bp-context-head"),i=xe("div");i.append(this.title,this.cwd),this.title.id="bp-context-title",this.dialog.setAttribute("aria-labelledby",this.title.id),this.notice.setAttribute("role","status"),n.append(i,_t(u("common.refresh","Refresh"),()=>{this.load()}),_t(u("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=u("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=u("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=[u("thread.context.instructions","Instructions"),u("thread.context.system","System Prompt"),u("thread.context.skills","Skills"),u("thread.context.mcp","Project MCPs")];this.tabs.replaceChildren(...e.map((n,i)=>{let s=_t(n,()=>{this.tab=i,this.render(),this.body.scrollTop=0,this.tabs.children[i].focus()});return s.setAttribute("aria-pressed",String(i===this.tab)),s})),this.body.replaceChildren();let t=this.current;if(!t)return;switch(this.tab){case 0:this.instructions(t.instructions);break;case 1:this.prompt(t);break;case 2:this.skills(t.skills);break;case 3:this.mcps(t.mcp);break}}instructions(e){if(!e.length)this.body.append(xe("p","bp-dim",u("thread.context.none.instructions","No project instructions found.")));for(let t of e){let n=xe("details","bp-context-card"),i=xe("summary");if(i.append(gn(t.path,t.status),xe("small","bp-dim",u("thread.context.size","{bytes} B · ≈{tokens} tokens",{bytes:t.bytes,tokens:t.estimated_tokens}))),n.append(i,ei(t.preview)),t.note)n.append(xe("small","bp-dim",t.note));this.body.append(n)}}prompt(e){let t=xe("div","bp-context-row"),n=_t(u("thread.context.copy","Copy prompt"),()=>{navigator.clipboard.writeText(e.prompt).then(()=>{this.notice.textContent=u("thread.context.copied","Prompt copied.")}).catch((i)=>{this.notice.textContent=String(i)})});t.append(xe("p","bp-dim",u("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[[u("thread.context.base","Backplane"),e.sections.base],[u("thread.context.injected.label","Injected project instructions"),e.sections.instructions],[u("thread.context.index","Available skills index"),e.sections.skills]])if(s)this.body.append(xe("h3",void 0,i),ei(s))}skills(e){for(let t of["Project","User","Bundled"]){let n=e.filter((i)=>i.scope===t);if(!n.length)continue;this.body.append(xe("h3",void 0,he(t)));for(let i of n){let s=xe("article","bp-context-card");s.append(gn(i.name,i.status),xe("p",void 0,i.description),xe("small","bp-context-path",[i.source,i.provider,i.model].filter(Boolean).join(" · ")),xe("small","bp-context-path",i.path)),this.body.append(s)}}}mcps(e){if(!e.length)this.body.append(xe("p","bp-dim",u("thread.context.none.mcp","No project MCP configurations found.")));for(let t of e){let n=xe("article","bp-context-card");n.append(gn(t.path,t.state));for(let s of t.servers){let r=s.url||[s.command,...s.args].map((o)=>JSON.stringify(o)).join(" ");if(n.append(gn(s.name,s.status),ei(r)),s.cwd)n.append(xe("small","bp-context-path",s.cwd))}if(t.error)n.append(xe("p","bp-warn",t.error));let i=t.state==="Untrusted"?"trust":t.state==="Enabled"?"disable":t.state==="Disabled"?"enable":"";if(i){let s=i==="trust"?u("thread.context.trust","Trust and enable"):i==="disable"?u("thread.context.disable","Disable"):u("thread.context.enable","Enable"),r=_t(s,()=>{this.load({action:i,path:t.path,sha256:t.sha256})},i==="trust");r.disabled=this.busy;let o=xe("div","bp-context-actions");o.append(r),n.append(o)}this.body.append(n)}}}var yt="chats";function Js(e){return e.filter((t)=>t.id&&t.id!==yt&&t.id!=="scratch"&&!t.id.includes("~")).slice().sort((t,n)=>(t.title||t.id).toLowerCase().localeCompare((n.title||n.id).toLowerCase()))}function mo(e,t){if(e.settled)return!1;if(e.state==="done"||e.state==="stopped")return!1;if(!t)return!0;let n=e.working??0,i=Boolean(e.monitoring),s=Boolean(Kn(e.need))||e.word==="needs";return(n>0||i)&&e.state!=="paused"||s}function bo(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 _s="http://www.w3.org/2000/svg";function pt(e,t=14,n=""){let i=document.createElementNS(_s,"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(_s,"path");r.setAttribute("d",s),i.appendChild(r)}return i}function zs(){return pt(["M3 6h6l2 2h10v11H3z"],14,"bp-folder-icon")}function qs(e=14,t="bp-folder-icon bp-hw-icon"){return pt(["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 go(e=13){return pt(["M6 6h12v12H6z","M9 2v4","M15 2v4","M9 18v4","M15 18v4","M2 9h4","M2 15h4","M18 9h4","M18 15h4"],e)}function fo(e=15){return pt(["M4 10V4l4 3h8l4-3v6l-2 9H6z","M9 13h1","M14 13h1","M11 16h2"],e,"bp-cat-glyph")}function vo(e=11){return pt(["M4 12l5 5 11-11"],e)}function wo(e=13){return pt(["M12 3H5a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7","M18.4 2.6a2.1 2.1 0 0 1 3 3L12 15l-4 1 1-4z"],e)}function yo(e=11){return pt(["M2 9V5a2 2 0 0 1 2-2h4l2 3h10a2 2 0 0 1 2 2v10a2 2 0 0 1-2 2H2","M2 13h10","M9 16l3-3-3-3"],e)}function Eo(){return typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.platform||"")?"⌥⇧N":"Alt+Shift+N"}function Co(e=11){return pt(["M12 22a10 10 0 1 0 0-20 10 10 0 0 0 0 20z","M12 6v6l4 2"],e)}function ko(e=11){return pt(["M12 17v5","M8 4h8l-1 5 3 3v2H6v-2l3-3z"],e,"bp-pin-icon")}function Ks(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 xo(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 ni(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 ii{el;hostLabel;homeBanner;crewEl;filterInput;listEl;connEl;filterText="";allFilter="all";snoozeMenuRowId="";collapsedProjects=new Set;addShown=!1;sections=null;projects=[];selectedProjectId="";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 o=document.createElement("div");o.className="bp-side-head",this.filterInput=document.createElement("input"),this.filterInput.type="search",this.filterInput.className="bp-input bp-side-search";let a=u("sidebar.search.projects","Search projects, threads…");this.filterInput.placeholder=a,this.filterInput.setAttribute("aria-label",a),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=u("thread.new","New thread"),c.setAttribute("aria-label",u("thread.new","New thread")),c.setAttribute("data-testid","sidebar-new-thread"),c.addEventListener("click",()=>{let d=this.firstProjectId();if(d)this.cb.onNewThread(d)});let p=document.createElement("button");p.type="button",p.className="icon bp-side-add bp-side-new-chat",p.appendChild(wo(13));let l=`${u("chats.new.noproject","New chat (no project)")} (${Eo()})`;p.title=l,p.setAttribute("aria-label",u("chats.new.noproject","New chat (no project)")),p.setAttribute("data-testid","sidebar-new-chat"),p.addEventListener("click",()=>this.cb.onNewChat?.()),o.append(this.filterInput,p,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 h=document.createElement("div");h.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"),h.appendChild(this.connEl),this.el.append(n,o,this.homeBanner,this.crewEl,this.listEl,h)}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?u("home.moving.step","Moving home to {to}: {step}").replace("{to}",e.moving.to).replace("{step}",e.moving.step):u("home.moving","Moving home to {to}…").replace("{to}",e.moving.to);else if(e.moving?.state==="failed")t=e.moving.note?u("home.move.failed.note","Home move failed: {note}").replace("{note}",e.moving.note):u("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=u("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=u("home.away.since","Home ({name}) is away since {time}").replace("{name}",i).replace("{time}",s);else if(e.queuedCount>0)t=u("home.away.queued","Home ({name}) is away · {n} queued").replace("{name}",i).replace("{n}",String(e.queuedCount));else t=u("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()}setSelectedProject(e){if(this.selectedProjectId===e)return;this.selectedProjectId=e,this.render()}makeFoldChevron(e,t){let n=document.createElement("button");n.type="button",n.className="bp-proj-chev"+(e?" folded":""),n.textContent=e?"▸":"▾";let i=e?u("web.home.unfold","Show threads"):u("web.home.fold","Hide threads");return n.title=i,n.setAttribute("aria-label",i),n.setAttribute("aria-expanded",e?"false":"true"),n.setAttribute("data-testid",`project-fold-${t}`),n}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=u("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,o=i.length>0||Boolean(this.cb.onNewRoom)&&!e;if(!s&&!r&&!o){this.crewEl.classList.add("bp-hidden"),this.crewEl.replaceChildren();return}let a=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 p=document.createElement("span");if(p.className=`bp-crew-uber-avatar ${ni(t.mood)}`,t.color)p.style.color=t.color;p.appendChild(fo(14));let l=document.createElement("span");l.className="bp-crew-uber-meta";let h=document.createElement("span");if(h.className="bp-crew-uber-name",h.textContent=t.name,l.appendChild(h),t.note){let d=document.createElement("span");d.className=`bp-crew-uber-note ${ni(t.mood)}`,d.textContent=t.note,l.appendChild(d)}if(c.append(p,l),t.mood==="wait"||t.mood==="error"){let d=document.createElement("span");d.className="bp-status-pill bp-pill-bad",d.textContent="? Input",c.appendChild(d)}c.addEventListener("click",()=>this.cb.onSelectBot(t)),a.appendChild(c)}if(r){let c=document.createElement("div");c.className="bp-crew-bots",c.setAttribute("data-testid","crew-bots");let p=document.createElement("span");p.className="bp-crew-lbl",p.textContent=u("tour.title.bots","Bots").toUpperCase(),c.appendChild(p);let l=document.createElement("div");l.className="bp-crew-bot-tiles";for(let h of n){let d=document.createElement("button");if(d.type="button",d.className=`bp-crew-bot-tile ${ni(h.mood)}`+(h.thread===this.selectedThreadId?" active":""),d.title=h.note?`@${h.name} — ${h.note}`:`@${h.name}`,d.setAttribute("aria-label",`@${h.name}`),d.setAttribute("data-testid",`crew-bot-${h.id}`),h.color)d.style.setProperty("--bot-c",h.color);let m=document.createElement("span");if(m.className="bp-crew-bot-init",m.textContent=xo(h.name),d.appendChild(m),h.mood==="wait"||h.mood==="error"){let f=document.createElement("span");f.className="bp-crew-bot-wait",d.appendChild(f)}d.addEventListener("click",()=>this.cb.onSelectBot(h)),l.appendChild(d)}if(this.cb.onNewBot&&!e){let h=document.createElement("button");h.type="button",h.className="bp-crew-bot-tile bp-crew-add",h.textContent="+",h.title=u("bots.new","New bot"),h.setAttribute("aria-label",u("bots.new","New bot")),h.setAttribute("data-testid","crew-new-bot"),h.addEventListener("click",()=>this.cb.onNewBot?.()),l.appendChild(h)}c.appendChild(l),a.appendChild(c)}if(o){let c=document.createElement("div");c.className="bp-crew-rooms",c.setAttribute("data-testid","crew-rooms");for(let p of i){let l=document.createElement("button");l.type="button",l.className="bp-crew-room-chip",l.setAttribute("data-testid",`crew-room-${p.id}`);let h=document.createElement("span");h.className="bp-dim",h.textContent="#";let d=document.createElement("span");if(d.textContent=p.name,l.append(h,d),p.members!==void 0&&p.members>0){let m=document.createElement("span");m.className="bp-crew-room-cnt",m.textContent=String(p.members),l.appendChild(m)}l.title=p.members?`#${p.name} (${p.members})`:`#${p.name}`,l.addEventListener("click",()=>this.cb.onSelectRoom?.(p)),c.appendChild(l)}if(this.cb.onNewRoom&&!e){let p=document.createElement("button");p.type="button",p.className="bp-crew-room-chip bp-crew-add",p.textContent="+",p.title=u("rooms.new","New room"),p.setAttribute("aria-label",u("rooms.new","New room")),p.setAttribute("data-testid","crew-new-room"),p.addEventListener("click",()=>this.cb.onNewRoom?.()),c.appendChild(p)}a.appendChild(c)}this.crewEl.classList.remove("bp-hidden"),this.crewEl.replaceChildren(a)}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=u("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=e.kind==="swarm",s=Boolean(e.settle)&&(!i||Boolean(this.cb.onSettleSwarm)),r=Boolean(e.chat)&&Boolean(this.cb.onMoveToProject);if(!t&&!n&&!s&&!r)return null;let o=document.createElement("span");if(o.className="bp-row-acts",n&&e.wake){let a=document.createElement("button");a.type="button",a.className="bp-row-act-btn bp-wake-btn",a.textContent=u("menu.wake","Wake"),a.title=u("menu.wake","Wake snoozed thread"),a.setAttribute("data-testid",`wake-row-${e.id}`),a.addEventListener("click",(c)=>{c.stopPropagation(),this.cb.onSnoozeRow?.(e.wake)}),o.appendChild(a)}if(t&&e.snooze){let a=document.createElement("button");a.type="button",a.className="bp-row-act-btn bp-snooze-btn",a.title=u("menu.snooze","Snooze thread"),a.setAttribute("aria-label",u("menu.snooze","Snooze thread")),a.setAttribute("data-testid",`snooze-row-${e.id}`),a.appendChild(Co(11)),a.addEventListener("click",(c)=>{c.stopPropagation(),this.snoozeMenuRowId=this.snoozeMenuRowId===e.id?"":e.id,this.render()}),o.appendChild(a)}if(r){let a=document.createElement("button");a.type="button",a.className="bp-row-act-btn bp-move-btn",a.title=u("chats.move","Move to project…"),a.setAttribute("aria-label",u("chats.move","Move to project…")),a.setAttribute("data-testid",`move-row-${e.id}`),a.appendChild(yo(11)),a.addEventListener("click",(c)=>{c.stopPropagation(),this.cb.onMoveToProject?.(Qe(e.id))}),o.appendChild(a)}if(s&&e.settle){let a=document.createElement("button");a.type="button",a.className="bp-row-act-btn bp-settle-btn",a.title=u("menu.settle","Settle"),a.setAttribute("aria-label",u("menu.settle","Settle")),a.setAttribute("data-testid",`settle-row-${e.id}`),a.appendChild(vo(11)),a.addEventListener("click",(c)=>{if(c.stopPropagation(),i)this.cb.onSettleSwarm?.(Qe(e.settle));else this.cb.onThreadAct(Qe(e.settle),"settle")}),o.appendChild(a)}return o}renderSectionThreadRow(e,t,n=!1){let i=document.createElement("div");i.className="bp-thread-row"+(n?" bp-inbox-row":"")+(!this.selectedProjectId&&(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=bo(e),r=this.renderRowActions(e);if(n){let l=document.createElement("div");l.className="bp-inbox-main";let h=document.createElement("div");h.className="bp-inbox-top";let d=document.createElement("div");if(d.className="bp-thread-title",d.textContent=e.title||"Untitled thread",h.appendChild(d),r)h.appendChild(r);let m=document.createElement("div");if(m.className="bp-inbox-meta",s)m.appendChild(this.renderStatusPill(s,e.say));if(e.project&&!e.chat){let f=document.createElement("span");f.className="bp-inbox-proj",f.textContent=e.project,m.appendChild(f)}if(e.ago){let f=document.createElement("span");if(f.className="bp-thread-age",f.textContent=e.ago,e.pinned)f.title=u("tools.pinned","Pinned");m.appendChild(f)}l.append(h,m),i.appendChild(l)}else{if(t){let h=document.createElement("span");h.className="bp-tree-branch",h.setAttribute("aria-hidden","true"),i.appendChild(h)}if(s)i.appendChild(this.renderStatusPill(s,e.say));let l=document.createElement("div");if(l.className="bp-thread-title",l.textContent=e.title||"Untitled thread",i.appendChild(l),r)i.appendChild(r);if(e.ago){let h=document.createElement("span");if(h.className="bp-thread-age",h.textContent=e.ago,e.pinned)h.title=u("tools.pinned","Pinned");i.appendChild(h)}}let o=e.nav||e.id;if(!e.off&&o&&!o.startsWith("@room:"))i.addEventListener("click",()=>this.cb.onSelectThread(Qe(o)));let a=this.snoozeMenuRowId===e.id&&Array.isArray(e.snooze)&&e.snooze.length>0,c=e.kind==="swarm"?Kn(e.need):null;if(!c&&!a)return i;let p=document.createElement("div");if(p.className="bp-need-wrap",p.appendChild(i),a&&e.snooze){let l=document.createElement("div");l.className="bp-snooze-bar"+(t?" nested":""),l.setAttribute("data-testid",`snooze-bar-${e.id}`);let h=document.createElement("span");h.className="bp-dim",h.textContent="Snooze:",l.appendChild(h);for(let d of e.snooze){let m=document.createElement("button");m.type="button",m.className="bp-snooze-opt",m.textContent=d.label,m.addEventListener("click",(f)=>{f.stopPropagation(),this.snoozeMenuRowId="",this.cb.onSnoozeRow?.(d.value),this.render()}),l.appendChild(m)}p.appendChild(l)}if(c){let l=document.createElement("div");l.className="bp-need"+(t?" nested":"")+(e.off?" bp-dim":""),l.setAttribute("data-testid",`need-${e.id}`);let h=document.createElement("span");h.className="bp-need-line",h.textContent=c.line,h.title=c.line,l.appendChild(h);for(let m of c.actions){if(!mn(m,Boolean(this.cb.hasRoomView)))continue;let f=document.createElement("button");f.type="button",f.className="bp-need-btn",f.textContent=m.label,f.setAttribute("data-testid",`need-${m.act}-${e.id}`),f.disabled=Boolean(e.off)||this.needBusy.has(e.id)||!this.cb.onNeedAct,f.addEventListener("click",(b)=>{b.stopPropagation();let v=this.cb.onNeedAct;if(!v)return;this.needErr.delete(e.id),this.needBusy.add(e.id),this.render(),v(m).catch((w)=>{this.needErr.set(e.id,w instanceof Error?w.message:String(w))}).finally(()=>{this.needBusy.delete(e.id),this.render()})}),l.appendChild(f)}p.appendChild(l);let d=this.needErr.get(e.id);if(d){let m=document.createElement("div");m.className="bp-need-err"+(t?" nested":""),m.textContent=d,p.appendChild(m)}}return p}renderHubSections(e,t){let n=this.sections??[],i=new Set;for(let o of n)if(o.kind==="threads")for(let a of o.rows)i.add(a.id),i.add(Qe(a.id));else if(o.kind==="projects")for(let a of o.rows)for(let c of a.threads??[])i.add(c.id),i.add(Qe(c.id));let s=this.selectedThreadId?this.threads.find((o)=>o.id===this.selectedThreadId)??null:null,r=!1;for(let o of n)if(o.kind==="projects"&&(o.rows.length>0||(o.count??0)>0))r=!0;for(let o of n){if(o.kind==="bub")continue;if(o.kind==="threads"){let a=Boolean(o.fold&&o.toggle),c=o.rows.filter((l)=>{if(!t)return!0;return`${l.title} ${l.project??""}`.toLowerCase().includes(t)});if(!a&&c.length===0)continue;if(a&&t&&c.length===0)continue;if(a&&!t&&(o.count??c.length)===0)continue;let p=document.createElement("section");if(p.className=`bp-side-section bp-side-inbox bp-sec-${o.id}`,p.setAttribute("data-section-id",o.id),a){let l=document.createElement("button");l.type="button",l.className="bp-side-section-head bp-side-section-toggle";let h=t?c.length:o.count??c.length,d=o.open||Boolean(t)?"▾":"▸";if(l.textContent=`${d} ${o.title.toUpperCase()} (${h})`,o.hint)l.title=o.hint;l.setAttribute("data-testid",`section-toggle-${o.id}`),l.addEventListener("click",()=>{if(o.toggle)this.cb.onToggleSection?.(o.toggle)}),p.appendChild(l)}else{let l=document.createElement("div");if(l.className="bp-side-section-head"+(o.id==="needs"?" bp-head-needs":o.id==="running"?" bp-head-running":""),o.id===yt&&this.cb.onNewChat){l.classList.add("bp-side-section-row");let h=document.createElement("span");h.textContent=`${u("chats.title",o.title).toUpperCase()} ${c.length}`;let d=document.createElement("button");d.type="button",d.className="bp-side-sec-plus bp-side-sec-btn",d.textContent="+",d.title=u("chats.new.noproject","New chat (no project)"),d.setAttribute("aria-label",d.title),d.setAttribute("data-testid","section-new-chat"),d.addEventListener("click",(m)=>{m.stopPropagation(),this.cb.onNewChat?.()}),l.append(h,d)}else l.textContent=`${o.title.toUpperCase()} ${c.length}`;p.appendChild(l)}if(!a||Boolean(o.open)||Boolean(t))for(let l of c)p.appendChild(this.renderSectionThreadRow(l,!1,!0));e.appendChild(p);continue}if(o.kind==="projects"){let a=o.rows,c=a.filter((d)=>{if(!t)return!0;if((d.title||d.id).toLowerCase().includes(t))return!0;if((d.threads??[]).some((m)=>m.title.toLowerCase().includes(t)))return!0;if((d.swarms??[]).some((m)=>m.title.toLowerCase().includes(t)))return!0;return!1}),p=Boolean(o.fold&&o.toggle);if(t&&c.length===0)continue;if(!p&&o.id!=="active"&&c.length===0)continue;let l=document.createElement("section");if(l.className=`bp-side-section bp-sec-${o.id}`,l.setAttribute("data-section-id",o.id),p){let d=document.createElement("button");d.type="button",d.className="bp-side-section-head bp-side-section-toggle";let m=t?c.length:o.count??c.length,f=o.open||Boolean(t)?"▾":"▸";if(d.textContent=`${f} ${o.title.toUpperCase()} (${m})`,o.hint)d.title=o.hint;d.setAttribute("data-testid",`section-toggle-${o.id}`),d.addEventListener("click",()=>{if(o.toggle)this.cb.onToggleSection?.(o.toggle)}),l.appendChild(d)}else l.appendChild(this.projectsHead(o.title.toUpperCase()));if(!p||Boolean(o.open)||Boolean(t)){if(o.id==="all"&&!t){let d=a.some((f)=>f.hasBoard||f.hasSchematic),m=a.some((f)=>!f.hasBoard&&!f.hasSchematic);if(d&&m){let f=document.createElement("div");f.className="bp-proj-filter",f.setAttribute("data-testid","all-projects-filter");let b=[{id:"all",label:"All"},{id:"hw",label:"Boards"},{id:"sw",label:"Code"}];for(let v of b){let w=document.createElement("button");w.type="button",w.className="bp-proj-filter-btn"+(this.allFilter===v.id?" active":""),w.textContent=v.label,w.addEventListener("click",()=>{this.allFilter=v.id,this.render()}),f.appendChild(w)}if(l.appendChild(f),this.allFilter==="hw")c=c.filter((v)=>v.hasBoard||v.hasSchematic);else if(this.allFilter==="sw")c=c.filter((v)=>!v.hasBoard&&!v.hasSchematic)}}if(o.id==="active"&&!r&&!t){let d=document.createElement("div");d.className="bp-side-empty",d.textContent="No projects yet.",l.appendChild(d)}for(let d of c){let m=document.createElement("div");if(m.className="bp-proj-group"+(d.off||o.id==="quiet"?" bp-dim":""),m.setAttribute("data-project-id",d.id),d.nav||d.key)m.setAttribute("data-project-key",d.nav||d.key||"");let f=document.createElement("div");f.className="bp-proj-head";let b=document.createElement("button");b.type="button",b.className="bp-proj-toggle";let w=Boolean(d.hasBoard||d.hasSchematic)?qs(14):zs();if(d.css)w.style.color=d.css;let E=document.createElement("span");E.className="bp-proj-name",E.textContent=d.title||d.id,b.append(w,E);let k=d.fold==="project-fold"&&Boolean(d.nav),L=()=>{if(k)this.cb.onToggleProjectFold?.(d.nav)};if(!d.off&&this.cb.canOpenProject?.())b.title=u("web.home.open","Open project home");if(b.setAttribute("data-testid",`project-open-${d.id}`),this.selectedProjectId&&Qe(d.id)===this.selectedProjectId)f.classList.add("active");b.addEventListener("click",()=>{if(d.off||!this.cb.onOpenProject?.(d.id))L()});let M=this.makeFoldChevron(Boolean(d.folded),d.id);if(k)M.addEventListener("click",(P)=>{P.stopPropagation(),L()});else M.disabled=!0;f.appendChild(M);let A=document.createElement("div");if(A.className="bp-proj-meta",(d.needsCount??0)>0){let P=document.createElement("span");P.className="bp-proj-badge-need",P.textContent=String(d.needsCount),P.title=`${d.needsCount} needing you`,A.appendChild(P)}if((d.running??0)>0){let P=document.createElement("span");P.className="bp-proj-badge-run",P.textContent=String(d.running),P.title=`${d.running} running`,A.appendChild(P)}if(d.pinned&&o.id!=="pinned")A.appendChild(ko(11));let B=document.createElement("div");if(B.className="bp-proj-acts",!d.off&&this.cb.onQuickOpenViewer){if(d.hasBoard){let P=document.createElement("button");P.type="button",P.className="bp-proj-quick",P.title=u("viewer.board","Open Board"),P.setAttribute("aria-label",`Open Board (${d.title})`),P.setAttribute("data-testid",`quick-board-${d.id}`),P.appendChild(qs(13,"")),P.addEventListener("click",(Y)=>{Y.stopPropagation(),this.cb.onQuickOpenViewer?.(Qe(d.id),"board")}),B.appendChild(P)}if(d.hasSchematic){let P=document.createElement("button");P.type="button",P.className="bp-proj-quick",P.title=u("viewer.schematic","Open Schematic"),P.setAttribute("aria-label",`Open Schematic (${d.title})`),P.setAttribute("data-testid",`quick-sch-${d.id}`),P.appendChild(go(13)),P.addEventListener("click",(Y)=>{Y.stopPropagation(),this.cb.onQuickOpenViewer?.(Qe(d.id),"schematic")}),B.appendChild(P)}}let T=document.createElement("button");if(T.type="button",T.className="icon bp-proj-add",T.title=u("thread.new","New thread"),T.textContent="+",T.setAttribute("data-testid",`new-thread-${d.id}`),d.off)T.disabled=!0;T.addEventListener("click",(P)=>{P.stopPropagation(),this.cb.onNewThread(Qe(d.id))}),B.appendChild(T),f.append(b,A,B),m.appendChild(f);let H=Boolean(t)&&(d.title||d.id).toLowerCase().includes(t),O=Boolean(d.folded&&!t);for(let P of d.swarms??[]){if(!mo(P,O))continue;if(t&&!H&&!P.title.toLowerCase().includes(t))continue;m.appendChild(this.renderSectionThreadRow(P,!0))}if(!O){for(let P of d.threads??[]){if(t&&!H&&!P.title.toLowerCase().includes(t))continue;m.appendChild(this.renderSectionThreadRow(P,!0))}if(s&&s.project===Qe(d.id)&&!i.has(s.id)&&(!t||H||s.title.toLowerCase().includes(t)))m.appendChild(this.renderSectionThreadRow({id:s.id,title:s.title,status:s.status,state:s.state,ago:Ks(s.updatedAt),pinned:s.pinned,nav:s.id},!0))}l.appendChild(m)}}e.appendChild(l)}}}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 o=document.createElement("div");o.className="bp-proj-head";let a=document.createElement("button");a.type="button",a.className="bp-proj-toggle";let c=this.collapsedProjects.has(i.id)&&!e,p=zs();if(i.css)p.style.color=i.css;let l=document.createElement("span");l.className="bp-proj-name",l.textContent=i.title||i.id,a.append(p,l);let h=()=>{if(this.collapsedProjects.has(i.id))this.collapsedProjects.delete(i.id);else this.collapsedProjects.add(i.id);this.render()};if(this.cb.canOpenProject?.())a.title=u("web.home.open","Open project home");if(a.setAttribute("data-testid",`project-open-${i.id}`),this.selectedProjectId&&i.id===this.selectedProjectId)o.classList.add("active");a.addEventListener("click",()=>{if(!this.cb.onOpenProject?.(i.id))h()});let d=this.makeFoldChevron(c,i.id);d.addEventListener("click",(f)=>{f.stopPropagation(),h()}),o.appendChild(d);let m=document.createElement("button");if(m.type="button",m.className="icon bp-proj-add",m.title=u("thread.new","New thread"),m.textContent="+",m.setAttribute("data-testid",`new-thread-${i.id}`),m.addEventListener("click",(f)=>{f.stopPropagation(),this.cb.onNewThread(i.id)}),o.append(a,m),r.appendChild(o),!c)for(let f of s)r.appendChild(this.renderSectionThreadRow({id:f.id,title:f.title,status:f.status,state:f.state,ago:Ks(f.updatedAt),pinned:f.pinned,nav:f.id},!0));t.appendChild(r)}}this.listEl.replaceChildren(t)}}function Po(e){try{return new URL(e,window.location.origin).searchParams.get("s")||""}catch{return""}}function zt(e){if(!e)return;for(let t of e.getTracks())try{t.stop()}catch{}}function So(e,t){if(t===16000){let r=new Int16Array(e.length);for(let o=0;o0?c/p:0));s[r]=l<0?l*32768:l*32767}return s}class si{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){zt(n);return}if(this.stream=n,await this.stopDrain,t!==this.sessionGen||this.cb.getThreadId()!==e){if(zt(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(zt(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?Po(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(zt(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 o=new Int16Array(this.pendingPcm);this.pendingPcm=[],this.enqueuePost(i,new Uint8Array(o.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??""),o=Math.max(0,Math.min(i.length,this.mark)),a=Math.max(0,o-s),c=i.slice(0,a)+r+i.slice(o);this.mark=a+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=(o)=>{if(!this.active||t!==this.sessionGen||!this.sessionKey)return;let a=So(o.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;zt(this.stream),this.stream=null}}var Ys=[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],Xs=[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],Qs=[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],Zs=[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],Lo=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];function qt(e,t){let n=new Int32Array(16),i=0;for(let a=0;a0){if(n[c]++,c>i)i=c}}let s=new Int32Array(16),r=0;for(let a=1;a<=15;a++)s[a]=r,r+=n[a];let o=new Int32Array(r);for(let a=0;a0)o[s[c]++]=a}return{counts:n,symbols:o,maxBits:i}}var Ao=(()=>{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),qt(e,288)})(),No=(()=>{let e=new Uint8Array(32);return e.fill(5),qt(e,32)})();class ri{win=new Uint8Array(32768);winPos=0;feed(e,t=16777216){let n=0,i=0,s=0,r=(h)=>{while(s=e.length)throw Error("truncated deflate frame");i|=e[n++]<>>=h,s-=h,d},o=(h)=>{let d=0,m=0,f=0;for(let b=1;b<=h.maxBits;b++){d|=r(1);let v=h.counts[b];if(d-v{let d=c+h;if(d>t)throw Error("inflated frame exceeds limit");if(d<=a.length)return;let m=a.length;while(m{p(1),a[c++]=h,this.win[this.winPos]=h,this.winPos=this.winPos+1&32767};while(n0){if(n>=e.length&&s<3)break;let h=r(1),d=r(2);if(d===0){if(i=0,s=0,n+4>e.length)throw Error("truncated stored block");let m=e[n]|e[n+1]<<8,f=e[n+2]|e[n+3]<<8;if(n+=4,(m^65535)!==f)throw Error("invalid stored block length");if(n+m>e.length)throw Error("truncated stored payload");p(m);for(let b=0;b=e.length)break}else if(d===1||d===2){let m=Ao,f=No;if(d===2){let b=r(5)+257,v=r(5)+1,w=r(4)+4,E=new Uint8Array(19);for(let B=0;BL)throw Error("code length overflow");for(let O=0;OL)throw Error("code length overflow");A+=T}else if(B===18){let T=r(7)+11;if(A+T>L)throw Error("code length overflow");A+=T}else throw Error("invalid code length symbol")}m=qt(M,b),f=qt(M.subarray(b),v)}while(!0){let b=o(m);if(b<256)l(b);else if(b===256)break;else{let v=b-257;if(v>=Ys.length)throw Error("invalid length symbol");let w=Ys[v]+(Xs[v]?r(Xs[v]):0),E=o(f);if(E>=Qs.length)throw Error("invalid distance symbol");let k=Qs[E]+(Zs[E]?r(Zs[E]):0);p(w);let L=this.winPos-k&32767;for(let M=0;M{this.stateListeners.delete(e)}}onFrame(e){return this.frameListeners.add(e),()=>{this.frameListeners.delete(e)}}onBinary(e){return this.binaryListeners.add(e),()=>{this.binaryListeners.delete(e)}}rpc(e,t={},n=20000){return new Promise((i,s)=>{if(!this.ws||this.ws.readyState!==WebSocket.OPEN){s(Error("Not connected to hub"));return}let r=this.nextId++,o=window.setTimeout(()=>{this.pending.delete(r),s(Error(`RPC timeout: ${e}`))},n);this.pending.set(r,{resolve:i,reject:s,timer:o}),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 ri:null,this.reconnectDelay=500,this.setState("connected");else if(r.t==="reply"&&typeof r.id==="number"){let o=this.pending.get(r.id);if(o)if(this.pending.delete(r.id),window.clearTimeout(o.timer),r.ok)o.resolve(r.result??{});else{let a=r.error,c=typeof a==="string"?a:a&&typeof a==="object"&&("message"in a)?String(a.message):"Request failed",p=typeof r.errorCode==="string"?r.errorCode:void 0,l=typeof r.machine==="string"?r.machine:void 0,h=typeof r.thread==="string"?r.thread:void 0;o.reject(new Kt(c,{code:p,machine:l,thread:h}))}return}for(let o of this.frameListeners)o(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 o=r.buffer.slice(r.byteOffset,r.byteOffset+r.byteLength);for(let a of this.binaryListeners)a(o)}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 Mo=new TextDecoder;function er(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 tr(e){let t=0,n=0;function i(o){if(o<=23)return o;if(o===24){if(t>=e.length)return null;return e[t++]}if(o===25){if(t+2>e.length)return null;let a=e[t]<<8|e[t+1];return t+=2,a}if(o===26){if(t+4>e.length)return null;let a=(e[t]<<24|e[t+1]<<16|e[t+2]<<8|e[t+3])>>>0;return t+=4,a}return null}function s(o){if(n++,o>32||n>400000||t>=e.length)return null;let a=e[t++],c=a>>5,p=i(a&31);if(p===null)return null;switch(c){case 0:return p;case 1:return-1-p;case 2:{if(t+p>e.length)return null;let l=e.subarray(t,t+p);return t+=p,l}case 3:{if(t+p>e.length)return null;let l=Mo.decode(e.subarray(t,t+p));return t+=p,l}case 4:{if(p>e.length)return null;let l=Array(p);for(let h=0;h=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 ir(e){let t=0xcbf29ce484222325n,n=0x100000001b3n,i=0xffffffffffffffffn;for(let s=0;stypeof e[b]==="number"?e[b]:v,n=t("l",0),i=t("c",0),s=t("a",255)/255,r=t("m",1),o=t("w",0),a=o/2,c=r===0&&o!==0,p=e.d instanceof Uint8Array?e.d:new Uint8Array(0),l=new nr(p),h=[],d=[],m=0,f=0;while(l.more()){let b=l.nextU32(),v=h.length,w=1/0,E=1/0,k=-1/0,L=-1/0;if(r===2)m=m+l.nextI32()|0,f=f+l.nextI32()|0,h.push(m,f),w=k=m,E=L=f;else{let A=Math.min(l.nextU32(),1048576);for(let B=0;Bk)k=m;if(fL)L=f}}let M=(h.length-v)/2;if(M>0){let A=r===2||M===1?2:r===0?0:1,B=r===0?0:a;d.push({info:b,x0:w-B,y0:E-B,x1:k+B,y1:L+B,at:v,n:M,kind:A})}}return{layer:n,color:i,alpha:s,mode:r,r:a,own:c,pts:new Float32Array(h),pieces:d}}function sr(e,t,n){let i=(o)=>Array.isArray(o)&&o.length>=4?[Number(o[0])||0,Number(o[1])||0,Number(o[2])||0,Number(o[3])||0]:[0,0,0,0],s=Array.isArray(e.cs)?e.cs:[],r=[];for(let o=0;o=0&&a0){n.delete(a.h),n.set(a.h,c);while(n.size>1024){let p=n.keys().next().value;if(p!==void 0)n.delete(p);else break}}}}return{key:typeof e.key==="string"?e.key:"",fam:typeof e.fam==="string"?e.fam:"",base:typeof e.base==="string"?e.base:"",box:i(e.box),edge:i(e.edge),thick:typeof e.thick==="number"?e.thick:1600,note:typeof e.note==="string"?e.note:"",warn:typeof e.warn==="number"?e.warn!==0:!1,chunks:r}}function rr(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,o=n.naturalHeight*s,a=n.left+(n.width-r)/2,c=i?n.top:n.top+(n.height-o)/2,p=(e-a)/r,l=(t-c)/o;if(p<0||p>1||l<0||l>1)return null;return{x:Math.max(0,Math.min(1000,Math.round(p*1000))),y:Math.max(0,Math.min(1000,Math.round(l*1000)))}}var or=[["Enter","Enter"],["Tab","Tab"],["Bksp","Backspace"],["Esc","Escape"],["↑","ArrowUp"],["↓","ArrowDown"],["←","ArrowLeft"],["→","ArrowRight"]];function ar(e){let t=e.trim();if(!t)return"";if(/^[a-zA-Z][a-zA-Z0-9+.-]*:/.test(t))return t;return`https://${t}`}class ai{tail=Promise.resolve();enqueue(e){let t=this.tail.then(e,e);return this.tail=t.catch(()=>{}),t}}function lr(e,t,n){let i=!0,s=!1,r=!1,o="",a=!1,c=!1,p=-1,l=null,h=new ai,d=document.createElement("div");d.className="bp-pane bp-browser-pane",d.setAttribute("data-testid","pane-browser");let m=document.createElement("div");m.className="bp-pane-bar bp-browser-nav";function f(ee,ge,C){let x=document.createElement("button");if(x.type="button",x.className="bp-v-btn",x.textContent=ee,x.setAttribute("data-testid",ge),C)x.title=C;return x}let b=f("←","browser-back","Back"),v=f("→","browser-forward","Forward"),w=f("↻","browser-reload","Reload"),E=document.createElement("form");E.className="bp-browser-url-form";let k=document.createElement("input");k.type="text",k.className="bp-browser-input",k.placeholder="https://…",k.autocomplete="off",k.spellcheck=!1,k.setAttribute("data-testid","browser-url");let L=f("Go","browser-go","Navigate");L.type="submit",E.append(k,L);let M=f("Take over","browser-takeover");M.classList.add("is-primary"),m.append(b,v,w,E,M);let A=document.createElement("div");A.className="bp-browser-drive-bar",A.hidden=!0;let B=document.createElement("div");B.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 H=f("Send","browser-type-send");B.append(T,H);let O=document.createElement("div");O.className="bp-browser-quick-keys";for(let[ee,ge]of or){let C=f(ee,`browser-key-${ge}`);C.addEventListener("click",()=>te("press",{key:ge})),O.append(C)}A.append(B,O);let P=document.createElement("div");P.className="bp-browser-err",P.setAttribute("data-testid","browser-error"),P.hidden=!0;let Y=document.createElement("div");Y.className="bp-browser-stage",Y.setAttribute("data-testid","browser-stage");let re=document.createElement("img");re.className="bp-browser-img",re.alt="Hub browser screen",re.draggable=!1,re.hidden=!0,re.setAttribute("data-testid","browser-frame");let ie=document.createElement("div");ie.className="bp-pane-empty",ie.setAttribute("data-testid","browser-empty"),ie.textContent="Loading browser screen…",Y.append(re,ie);let ue=document.createElement("div");ue.className="bp-browser-hint",ue.textContent="You have the page: click to tap, scroll to wheel, type in the key box. Hand it back when done.",ue.hidden=!0,d.append(m,A,P,Y,ue),e.replaceChildren(d);function Pe(ee){P.textContent=ee,P.hidden=!ee}function Ce(){A.hidden=!s,ue.hidden=!s,M.textContent=s?"Hand back":"Take over",M.setAttribute("data-testid",s?"browser-handback":"browser-takeover"),M.classList.toggle("is-on",s),re.classList.toggle("is-driving",s)}function te(ee,ge={},C){h.enqueue(async()=>{if(!i)return;Pe("");try{if(await t.hub.rpc("browser",{thread:n,op:ee,...ge}),!i)return;C?.(),me()}catch(x){if(!i)return;Pe(x instanceof Error?x.message:String(x))}})}function oe(ee){te("toolbar",{command:ee},()=>{s=!0,Ce()})}b.addEventListener("click",()=>oe("back")),v.addEventListener("click",()=>oe("forward")),w.addEventListener("click",()=>oe("reload")),E.addEventListener("submit",(ee)=>{ee.preventDefault();let ge=ar(k.value);if(!ge)return;if(k.value=ge,!s)te("takeover",{},()=>{s=!0,Ce()});te("navigate",{url:ge},()=>{s=!0,Ce()})}),M.addEventListener("click",()=>{if(s)te("handback",{},()=>{s=!1,Ce()});else te("takeover",{},()=>{s=!0,Ce(),T.focus()})});function R(){let ee=T.value;if(!ee)return;T.value="",te("type",{text:ee})}H.addEventListener("click",R),T.addEventListener("keydown",(ee)=>{if(!s)return;if(ee.key==="Enter"){if(ee.preventDefault(),T.value)R();te("press",{key:"Enter"});return}if(ee.key==="Tab"||ee.key==="Escape"||ee.key==="ArrowUp"||ee.key==="ArrowDown"||ee.key==="ArrowLeft"||ee.key==="ArrowRight"||ee.key==="Backspace"&&T.value==="")ee.preventDefault(),te("press",{key:ee.key})}),re.addEventListener("click",(ee)=>{if(!s||!r)return;let ge=re.getBoundingClientRect(),C=rr(ee.clientX,ee.clientY,{left:ge.left,top:ge.top,width:ge.width,height:ge.height,naturalWidth:re.naturalWidth,naturalHeight:re.naturalHeight});if(!C)return;te("click",C)}),re.addEventListener("wheel",(ee)=>{if(!s||!r)return;ee.preventDefault();let ge=Math.round(ee.deltaX),C=Math.round(ee.deltaY);if(ge===0&&C===0)return;te("scroll",{dx:ge,dy:C})},{passive:!1});async function me(){if(!i)return;if(a){c=!0;return}a=!0;try{do{c=!1,l=new AbortController;let ee=await fetch(`/bots/${encodeURIComponent(n)}/screen.jpg`,{credentials:"same-origin",cache:"no-store",signal:l.signal});if(!i)return;if(ee.ok){let ge=await ee.blob();if(!i)return;let C=URL.createObjectURL(ge),x=o;if(o=C,re.src=C,re.hidden=!1,ie.hidden=!0,r=!0,x)URL.revokeObjectURL(x)}else if(!r)re.hidden=!0,ie.hidden=!1,ie.textContent="No browser page yet. An agent opens one when it needs the web."}while(i&&c)}catch{if(!i)return;if(!r)re.hidden=!0,ie.hidden=!1,ie.textContent="No browser page yet. An agent opens one when it needs the web."}finally{l=null,a=!1}}let de=t.hub.onFrame((ee)=>{if(!i)return;if(ee.t==="shot"&&ee.bot===n){if(typeof ee.n==="number"){if(ee.n===p)return;p=ee.n}me()}});return me(),{destroy(){if(i=!1,de(),l?.abort(),o)URL.revokeObjectURL(o),o=""}}}function U(e,t,n){let i=document.createElement(e);if(t)i.className=t;if(n!==void 0)i.textContent=n;return i}function fn(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 dr(e){let t=e.lastIndexOf(".");return t>=0?e.slice(t+1).toLowerCase():""}function Bo(e){return["png","jpg","jpeg","gif","webp","svg","bmp","ico"].includes(e)}function cr(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 Io(e){let t=dr(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 pr(e,t,n,i){let s=!0,r="",o="",a=U("div","bp-pane bp-files-pane");a.setAttribute("data-testid","pane-files");let c=U("div","bp-pane-bar"),p=U("div","bp-files-crumbs"),l=U("button","bp-v-btn","Refresh");l.type="button",l.addEventListener("click",()=>void v(r)),c.append(p,l);let h=U("div","bp-files-split"),d=U("div","bp-files-list");d.setAttribute("data-testid","files-list");let m=U("div","bp-files-preview");m.setAttribute("data-testid","files-preview"),m.append(U("div","bp-pane-empty","Select a file to preview")),h.append(d,m),a.append(c,h),e.replaceChildren(a);function f(){p.replaceChildren();let w=U("button","bp-crumb-btn","project");if(w.type="button",w.addEventListener("click",()=>void v("")),p.append(w),!r)return;let E=r.split("/").filter(Boolean),k="";for(let L of E){k=k?`${k}/${L}`:L;let M=k;p.append(U("span","bp-vh-sep","/"));let A=U("button","bp-crumb-btn",L);A.type="button",A.addEventListener("click",()=>void v(M)),p.append(A)}}async function b(w,E,k){o=w,m.replaceChildren();let L=U("div","bp-files-prev-head");L.append(U("span","bp-files-prev-name",w));let M=U("div","bp-files-prev-acts"),A=Io(E);if(A){let O=U("button","bp-v-btn is-primary",`Open in ${A}`);O.type="button",O.setAttribute("data-testid","files-open-viewer"),O.addEventListener("click",()=>i(A,w)),M.append(O)}let B=`/files/get?thread=${encodeURIComponent(n)}&path=${encodeURIComponent(w)}`,T=U("a","bp-v-btn","Download");T.href=B,T.download=E,M.append(T),L.append(M),m.append(L);let H=dr(E);if(Bo(H)){let O=U("div","bp-files-img-wrap"),P=document.createElement("img");P.className="bp-files-img",P.alt=E,P.src=B,O.append(P),m.append(O);return}if(k>524288&&!cr(H)){m.append(U("div","bp-pane-empty",`Binary file (${fn(k)}). Use Download to save.`));return}if(cr(H)||k<=65536){let O=U("div","bp-pane-empty","Loading…");m.append(O);try{let P=await fetch(B,{credentials:"same-origin"});if(!s||o!==w)return;if(!P.ok){O.textContent=`Could not load file (${P.status})`;return}if((P.headers.get("content-type")||"").startsWith("image/")){O.remove();let de=document.createElement("img");de.className="bp-files-img",de.alt=E,de.src=B,m.append(de);return}let re=262144,ie=[],ue=0,Pe=!1;if(P.body){let de=P.body.getReader();try{while(!0){let{done:ee,value:ge}=await de.read();if(ee||!ge)break;if(ue+ge.byteLength>re){let C=re-ue;if(C>0)ie.push(ge.subarray(0,C)),ue+=C;Pe=!0,await de.cancel();break}ie.push(ge),ue+=ge.byteLength}}finally{de.releaseLock()}}if(!s||o!==w)return;let Ce=new Uint8Array(ue),te=0;for(let de of ie)Ce.set(de,te),te+=de.byteLength;let oe=!1;for(let de=0;deL.dir===M.dir?L.name.localeCompare(M.name):L.dir?-1:1),d.replaceChildren(),w){let L=U("button","bp-file-row is-dir");L.type="button",L.append(U("span","bp-file-icon","↰"),U("span","bp-file-name",".."));let M=w.includes("/")?w.slice(0,w.lastIndexOf("/")):"";L.addEventListener("click",()=>void v(M)),d.append(L)}if(k.length===0){d.append(U("div","bp-pane-empty","Empty folder"));return}for(let L of k){let M=w?`${w}/${L.name}`:L.name,A=U("button","bp-file-row"+(L.dir?" is-dir":"")+(M===o?" is-sel":""));A.type="button",A.setAttribute("data-testid",`file-row-${L.name}`),A.append(U("span","bp-file-icon",L.dir?"▸":"·"),U("span","bp-file-name",L.name),U("span","bp-file-size",L.dir?"":fn(L.size))),A.addEventListener("click",()=>{if(L.dir)v(M);else d.querySelectorAll(".bp-file-row.is-sel").forEach((B)=>B.classList.remove("is-sel")),A.classList.add("is-sel"),b(M,L.name,L.size)}),d.append(A)}}catch(E){if(!s)return;d.replaceChildren(U("div","bp-pane-empty",E instanceof Error?E.message:String(E)))}}return v(""),{destroy(){s=!1}}}function hr(e,t,n){let i=!0,s=U("div","bp-pane bp-diff-pane");s.setAttribute("data-testid","pane-diff");let r=U("div","bp-pane-bar"),o=U("span","bp-diff-summary","Loading diff…"),a=U("button","bp-v-btn","Refresh");a.type="button",a.addEventListener("click",()=>void p()),r.append(o,a);let c=U("div","bp-diff-body");c.setAttribute("data-testid","diff-body"),s.append(r,c),e.replaceChildren(s);async function p(){o.textContent="Loading diff…",c.replaceChildren();try{let l=await t.hub.rpc("viewer.diff",{thread:n});if(!i)return;if(l?.nogit){o.textContent="Not a git repository",c.append(U("div","bp-pane-empty","This project is not a git repository."));return}let h=typeof l?.diff==="string"?l.diff:"";if(!h.trim()){o.textContent="Clean working tree",c.append(U("div","bp-pane-empty","No uncommitted changes."));return}let d=h.split(` -`),m=0,f=0,b=0,v=document.createDocumentFragment(),w=U("div","bp-diff-file");for(let E of d){if(E.startsWith("diff --git ")){if(w.childNodes.length>0)v.append(w);w=U("div","bp-diff-file"),m++;let k=E.match(/ b\/(.+)$/);w.append(U("div","bp-diff-file-head",k?k[1]:E));continue}if(E.startsWith("index ")||E.startsWith("--- ")||E.startsWith("+++ "))w.append(U("div","bp-diff-line is-meta",E));else if(E.startsWith("@@"))w.append(U("div","bp-diff-line is-hunk",E));else if(E.startsWith("+"))f++,w.append(U("div","bp-diff-line is-add",E));else if(E.startsWith("-"))b++,w.append(U("div","bp-diff-line is-del",E));else w.append(U("div","bp-diff-line",E))}if(w.childNodes.length>0)v.append(w);o.textContent=`${m||1} file${m===1?"":"s"} · +${f} -${b}`,c.append(v)}catch(l){if(!i)return;o.textContent="Diff unavailable",c.append(U("div","bp-pane-empty",l instanceof Error?l.message:String(l)))}}return p(),{destroy(){i=!1}}}function Ro(e,t){let n=t.rel||"",i=t.manifest||{},s=(p)=>`/files/get?thread=${encodeURIComponent(e)}&path=${encodeURIComponent(`${n}/${p}`)}`,r=(p)=>typeof p==="string"&&p!==""&&!p.startsWith("/")&&!p.split(/[\\/]/).includes(".."),o=(Array.isArray(i.drawings)?i.drawings:[]).filter((p)=>r(p?.file)),a=new Set(o.map((p)=>p.file)),c=o.map((p)=>({title:p.title||p.kind||p.file,file:p.file,url:s(p.file),drawing:!0}));for(let p of Array.isArray(i.files)?i.files:[])if(r(p)&&!a.has(p))c.push({title:p,file:p,url:s(p),drawing:!1});return c}function ur(e,t,n){let i=!0,s="checks",r=U("div","bp-pane bp-review-pane");r.setAttribute("data-testid","pane-review");let o=U("div","bp-pane-bar"),a=U("div","bp-review-tabs"),c=U("button","bp-v-btn is-on","Checks"),p=U("button","bp-v-btn","BOM"),l=U("button","bp-v-btn","Comments"),h=U("button","bp-v-btn","Release");h.setAttribute("data-testid","review-tab-release"),c.type=p.type=l.type=h.type="button",a.append(c,p,l,h);let d=U("button","bp-v-btn","Refresh");d.type="button",d.addEventListener("click",()=>void w()),o.append(a,d);let m=U("div","bp-review-body");m.setAttribute("data-testid","review-body"),r.append(o,m),e.replaceChildren(r);function f(E){s=E,c.classList.toggle("is-on",s==="checks"),p.classList.toggle("is-on",s==="bom"),l.classList.toggle("is-on",s==="comments"),h.classList.toggle("is-on",s==="release"),w()}c.addEventListener("click",()=>f("checks")),p.addEventListener("click",()=>f("bom")),l.addEventListener("click",()=>f("comments")),h.addEventListener("click",()=>f("release"));function b(E){let k=U("div","bp-review-md bp-review-release");k.setAttribute("data-testid","review-release");let L=E.manifest||{};k.append(U("h2","bp-review-h",E.tag||"Release")),k.append(U("p","bp-review-p",[L.commit?`Commit ${L.commit.slice(0,12)}`:"",L.date||""].filter(Boolean).join(" · ")));let M=Ro(n,E),A=(T,H)=>{if(H.length===0)return;k.append(U("h3","bp-review-h",T));let O=U("table","bp-review-table");for(let P of H){let Y=document.createElement("tr"),re=U("td",void 0,P.title);re.title=P.file;let ie=document.createElement("td"),ue=U("a","bp-v-btn","Download");ue.href=P.url,ue.download=P.file.split("/").pop()||P.file,ie.append(ue),Y.append(re,ie),O.append(Y)}k.append(O)};A("Drawings",M.filter((T)=>T.drawing));let B=Array.isArray(L.openFabNotes)?L.openFabNotes:[];if(B.length>0)k.append(U("div","bp-review-gate",`Open fabrication notes, not in the board (agree them with the fabricator): ${B.join(", ")}.`));if(A("Files",M.filter((T)=>!T.drawing)),E.rel){let T=U("a","bp-v-btn","Download all (.zip)");T.href=`/files/zip?thread=${encodeURIComponent(n)}&path=${encodeURIComponent(E.rel)}`,k.append(T)}return k}function v(E){let k=U("div","bp-review-md"),L=E.split(` -`),M=0;while(M{H.preventDefault();let O=B.value.trim();if(!O)return;T.disabled=!0,t.hub.rpc("review.comment",{thread:n,text:O}).then(()=>{B.value="",T.disabled=!1,w()},()=>{T.disabled=!1})}),m.append(A),M.length===0){m.append(U("div","bp-pane-empty","No review comments yet."));return}for(let H of M){let O=U("div","bp-review-comment"+(H.resolved?" is-resolved":"")),P=[H.by||"review",H.file,H.layer,H.item].filter(Boolean).join(" · ");O.append(U("div","bp-review-comment-meta",P),U("div","bp-review-comment-text",H.text)),m.append(O)}return}let E=await t.hub.rpc("review.page",{thread:n,page:s});if(!i)return;let k=E?.report||{};if(m.replaceChildren(),k.line||k.gate){let L=U("div","bp-review-gate",[k.gate,k.line].filter(Boolean).join(" · "));m.append(L)}if(k.err)m.append(U("div","bp-review-err",k.err));if(Array.isArray(k.tasks)&&k.tasks.length>0){let L=U("div","bp-review-tasks");k.tasks.forEach((M,A)=>{let B=U("label","bp-review-task"),T=document.createElement("input");T.type="checkbox",T.checked=!!(M.done??M.checked);let H=typeof M.index==="number"?M.index:A;T.addEventListener("change",()=>{t.hub.rpc("review.tick",{thread:n,index:H}).then(()=>void w(),()=>{})}),B.append(T,U("span",void 0,M.text||M.label||`Item ${A+1}`)),L.append(B)}),m.append(L)}if(s==="release"&&k.release&&k.release.manifest)m.append(b(k.release));else if(k.md&&k.md.trim())m.append(v(k.md));else if(!k.err&&(!k.tasks||k.tasks.length===0))m.append(U("div","bp-pane-empty",s==="release"?"No release yet. A release tags this design and makes its fabrication outputs and drawings in .backplane/releases.":`No ${s==="bom"?"BOM":"design checks"} report available.`))}catch(E){if(!i)return;m.replaceChildren(U("div","bp-pane-empty",E instanceof Error?E.message:String(E)))}}return w(),{destroy(){i=!1}}}function mr(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 li{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),o=Math.max(s-n,1000),a=this.canvas.getBoundingClientRect(),c=Math.max(a.width,200),p=Math.max(a.height,200);this.cx=(t+i)*0.5,this.cy=(n+s)*0.5,this.scale=Math.min(c/r,p/o)*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 o=this.ctx;o.setTransform(i,0,0,i,0,0),o.fillStyle=this.lightTheme?"#f5f4ef":"#08090b",o.fillRect(0,0,t,n);let a=this.frame;if(!a)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,p=n*0.5,l=this.scale,h=this.cx,d=this.cy,m=h-c/l,f=h+c/l,b=d-p/l,v=d+p/l,{off:w,dim:E,lift:k}=this.masks,L=[],M=[];for(let B=0;B>>T&1)===1)continue;if(T===k)M.push(B);else L.push(B)}let A=L.concat(M);o.lineCap="round",o.lineJoin="round";for(let B=0;B>>H.layer&1)===1,P=H.alpha*(O?0.25:1);if(P<=0.01)continue;this.drawChunk(o,H,P,m,b,f,v,h,d,l,c,p)}if(this.highlights.size>0){o.fillStyle=this.lightTheme?"rgba(245,244,239,0.72)":"rgba(8,9,11,0.72)",o.fillRect(0,0,t,n);let B=this.lightTheme?"rgba(27,29,33,0.77)":"rgba(217,221,228,0.77)";for(let T=0;Tr||v.y1o)continue;if(v.n<3)continue;let w=(d[v.at]-a)*p+l,E=(d[v.at+1]-c)*p+h;e.moveTo(w,E);for(let k=1;k0)e.fill()}else if(t.mode===2){let f=Math.max(0.75,t.r*p);e.fillStyle=m,e.beginPath();let b=0;for(let v=0;vr||w.y1o)continue;let E=(d[w.at]-a)*p+l,k=(d[w.at+1]-c)*p+h;e.moveTo(E+f,k),e.arc(E,k,f,0,Math.PI*2),b++}if(b>0)e.fill()}else{e.strokeStyle=m,e.lineWidth=Math.max(1,t.r*2*p),e.beginPath();let f=0;for(let b=0;br||v.y1o)continue;let w=(d[v.at]-a)*p+l,E=(d[v.at+1]-c)*p+h;if(v.n===1)e.moveTo(w,E),e.lineTo(w+0.01,E);else{e.moveTo(w,E);for(let k=1;k0)e.stroke()}}drawLitPieces(e,t,n,i,s,r,o,a,c,p,l,h,d){let m=t.pts,f=mr(t.color,t.alpha);for(let b=0;bo||v.y1a)continue;let w=(m[v.at]-c)*l+h,E=(m[v.at+1]-p)*l+d;if(v.kind===2){let k=Math.max(1.5,t.r*l);e.fillStyle=f,e.beginPath(),e.arc(w,E,k,0,Math.PI*2),e.fill(),e.strokeStyle=i,e.lineWidth=1.5,e.stroke()}else if(v.kind===0&&v.n>=3){e.fillStyle=f,e.beginPath(),e.moveTo(w,E);for(let k=1;k=0;l--){let h=n.chunks[l];if(h.layer<32&&(p>>>h.layer&1)===1)continue;for(let d=0;dm.x1+o||rm.y1+o)continue;let f=(m.x1-m.x0+1)*(m.y1-m.y0+1);if(f{if(this.canvas.setPointerCapture(e.pointerId),this.pointers.set(e.pointerId,{x:e.clientX,y:e.clientY}),this.pointers.size===1)this.dragStart={x:e.clientX,y:e.clientY,cx:this.cx,cy:this.cy,moved:!1},this.pinchStart=null;else if(this.pointers.size===2){let[t,n]=Array.from(this.pointers.values());this.pinchStart={dist:Math.hypot(n.x-t.x,n.y-t.y)||1,midX:(t.x+n.x)*0.5,midY:(t.y+n.y)*0.5,scale:this.scale,cx:this.cx,cy:this.cy},this.dragStart=null}};onPointerMove=(e)=>{if(!this.pointers.has(e.pointerId))return;if(this.pointers.set(e.pointerId,{x:e.clientX,y:e.clientY}),this.pointers.size===2&&this.pinchStart){let[t,n]=Array.from(this.pointers.values()),i=Math.hypot(n.x-t.x,n.y-t.y)||1,s=(t.x+n.x)*0.5,r=(t.y+n.y)*0.5,o=i/this.pinchStart.dist,a=Math.max(0.0000001,Math.min(2,this.pinchStart.scale*o)),c=this.canvas.getBoundingClientRect(),p=this.pinchStart.midX-c.left-c.width*0.5,l=this.pinchStart.midY-c.top-c.height*0.5,h=s-c.left-c.width*0.5,d=r-c.top-c.height*0.5;this.scale=a,this.cx=this.pinchStart.cx+p/this.pinchStart.scale-h/a,this.cy=this.pinchStart.cy+l/this.pinchStart.scale-d/a,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 br=[{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 gr(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 ci(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 o=s[1]||r.slice(4).join("\t");if(!o)return!1;let a=o.replace(/\\/g,"/"),c=i.replace(/\\/g,"/");if(c.startsWith("/")||/^[A-Za-z]:\//.test(c))return a===c;return a===c||a.endsWith(`/${c}`)}class di{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 jo=`#version 300 es +`),h=document.createElement("div");h.className="bp-code-block";let d=document.createElement("div");d.className="bp-code-head";let u=document.createElement("span");u.className="bp-code-lang",u.textContent=c||"code";let f=document.createElement("button");f.type="button",f.className="bp-btn-ghost bp-code-copy";let b=m("common.copy","Copy");f.textContent=b,f.addEventListener("click",()=>{navigator.clipboard?.writeText(l).then(()=>{f.textContent="✓",window.setTimeout(()=>{f.textContent=b},1200)}).catch(()=>{})}),d.append(u,f);let v=document.createElement("pre"),w=document.createElement("code");w.textContent=l,v.appendChild(w),h.append(d,v),t.appendChild(h);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",$t(c,r[2]),t.appendChild(c),i++;continue}if(s.startsWith("> ")){let c=document.createElement("blockquote");c.className="bp-md-quote";let p=[];while(i "))p.push(n[i].slice(2)),i++;$t(c,p.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]))o.push(n[i]),i++;let a=document.createElement("p");a.className="bp-md-p";for(let c=0;c0)a.appendChild(document.createElement("br"));$t(a,o[c])}t.appendChild(a)}return t}var Hr=new Set(["(","[",'"',"'","`"]);function Dr(e){return/[\p{L}\p{N}\-_\/+\[]/u.test(e)}function Fr(e){return/[\p{L}\p{N}\-_\/]/u.test(e)}function $r(e){return/[\p{L}\p{N}]/u.test(e)}function Ti(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(so)r=l,o=h,a=c;break}p=l+1}}if(a===null)break;if(r>s)i.push({kind:"text",text:e.slice(s,r)});i.push({kind:"model",word:a.word,label:a.label}),s=o}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 Vr(e,t){let n=document.createDocumentFragment(),i=Ti(e,t),s=m("native.thread.model","Model").toLowerCase();for(let r of i){if(r.kind==="text"){n.appendChild(document.createTextNode(r.text));continue}let o=document.createElement("span");o.className="bp-ref-chip bp-ref-model",o.title=r.word,o.setAttribute("data-ref-word",r.word);let a=document.createElement("span");a.className="bp-ref-sigil",a.textContent="&";let c=document.createElement("span");c.className="bp-ref-label",c.textContent=r.label;let p=document.createElement("span");p.className="bp-ref-kind",p.textContent=s,o.append(a,c,p),n.appendChild(o)}return n}function Ur(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,a=(s.nodeType===Node.ELEMENT_NODE?s:s.parentElement)?.closest(".bp-ref-chip[data-ref-word]")?.getAttribute("data-ref-word"),c;if(a)c=a;else{let p=i.cloneContents(),l=p.querySelectorAll(".bp-ref-chip[data-ref-word]");if(l.length===0)return;for(let d of l){let u=d.getAttribute("data-ref-word")||d.textContent||"";d.replaceWith(document.createTextNode(u))}let h=p.querySelectorAll(".bp-entry");for(let d=1;d{if(!this.loadingOlder&&this.hasMore)this.loadingOlder=!0,this.cb.onLoadOlder()}),this.scrollEl.addEventListener("scroll",()=>{if(this.pinnedToBottom=this.isNearBottom(),this.hasMore&&!this.loadingOlder&&this.scrollEl.scrollTop<48)this.loadingOlder=!0,this.cb.onLoadOlder()}),typeof ResizeObserver<"u"){let n=0;new ResizeObserver(()=>{let s=this.scrollEl.clientHeight;if(n>0&&s!==n&&this.pinnedToBottom)this.scrollToBottom();n=s}).observe(this.scrollEl)}this.listEl=document.createElement("div"),this.listEl.className="bp-timeline-list",Ur(this.scrollEl),this.scrollEl.append(this.olderBtn,this.listEl),e.append(this.bannerEl,this.scrollEl)}setLoading(e){this.thread=e,this.entries=[],this.hasMore=!1,this.loadingOlder=!1,this.review=null,this.unanswered=null,this.btwNote=null,this.liveNodes.clear(),this.planExpanded.clear(),this.planRevisingId="",this.planReviseDrafts.clear(),this.renderBanners(),this.olderBtn.classList.add("bp-hidden");let t=document.createElement("div");t.className="bp-empty-state",t.textContent=m("web.chat.loading","Loading messages…"),this.listEl.replaceChildren(t)}setError(e,t,n){this.thread=e,this.entries=[],this.hasMore=!1,this.loadingOlder=!1,this.review=null,this.unanswered=null,this.btwNote=null,this.liveNodes.clear(),this.planExpanded.clear(),this.planRevisingId="",this.planReviseDrafts.clear(),this.renderBanners(),this.olderBtn.classList.add("bp-hidden");let i=document.createElement("div");i.className="bp-empty-state";let s=document.createElement("div");s.className="bp-bad",s.textContent=t;let r=document.createElement("button");r.type="button",r.textContent=m("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=m("android.load.earlier","Load earlier"),this.renderBanners(),this.thread&&this.entries.length>0)this.renderEntries(!1);this.scrollEl.scrollTop=e}setThread(e,t,n,i,s){if((this.thread?.id??"")!==(e?.id??""))this.planExpanded.clear(),this.planRevisingId="",this.planReviseDrafts.clear();this.thread=e,this.entries=t.filter((r)=>!Sn(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)=>!Sn(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(Sn(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((o)=>o.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(Ot(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=he(this.noProvider.head),n.appendChild(i),this.noProvider.text){let o=document.createElement("span");o.className="bp-dim",o.textContent=he(this.noProvider.text),n.appendChild(o)}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=he(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||m("web.chat.review.mode","Review mode"),t.appendChild(n),this.review.button){let i=document.createElement("button");i.type="button",i.textContent=this.review.button,i.addEventListener("click",()=>this.cb.onToggleReview(!(this.review?.on??!0))),t.appendChild(i)}e.appendChild(t)}if(this.unanswered&&(this.unanswered.head||this.unanswered.text)){let t=document.createElement("div");t.className="bp-banner bp-unanswered",t.setAttribute("data-testid","unanswered-notice");let n=document.createElement("div");if(n.className="bp-unanswered-body",this.unanswered.head){let i=document.createElement("strong");i.textContent=this.unanswered.head,n.appendChild(i)}if(this.unanswered.text){let i=document.createElement("span");i.textContent=this.unanswered.text,n.appendChild(i)}if(t.appendChild(n),this.unanswered.buttons?.length){let i=document.createElement("div");i.className="bp-banner-actions";for(let s of this.unanswered.buttons){let 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(Ot(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=m("common.copy","Copy"),o=document.createElement("span");o.textContent=r,s.append(Gt(["M9 9h11v11H9z","M5 15H4a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1h10a1 1 0 0 1 1 1v1"]),o),s.addEventListener("click",()=>{navigator.clipboard?.writeText(e.text||"").then(()=>{o.textContent="✓",window.setTimeout(()=>{o.textContent=r},1000)}).catch(()=>{})});let a=document.createElement("button");a.type="button",a.className="bp-entry-act";let c=document.createElement("span");c.textContent=m("reply.action","Reply"),a.append(Gt(["M9 17l-5-5 5-5","M20 18v-2a4 4 0 0 0-4-4H4"]),c),a.addEventListener("click",()=>this.cb.onReplyEntry(e));let p=!e.live&&!e.id.startsWith("local-")&&!e.id.startsWith("live:"),l=document.createElement("span");l.className="bp-entry-time";let h=Or(e.at);if(t)l.textContent=h,i.append(s,...p?[a]:[],l);else{let d=n&&e.at?Gr(Ln(e.at)-Ln(n)):"",u=h?d?m("web.chat.finished.dur","Finished {time} · {dur}",{time:h,dur:d}):m("web.chat.finished","Finished {time}",{time:h}):"";l.textContent=e.live?m("web.chat.streaming","Streaming…"):u,i.append(l,s,...p?[a]:[])}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=m("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=m("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 o=document.createElement("article");if(o.className=`bp-entry bp-entry-${r.kind}`+(r.live?" is-live":""),o.setAttribute("data-entry-id",r.id),r.kind==="tool"&&r.tool){let l=document.createElement("div");l.className=`bp-tool-pill bp-tool-${r.tool.state||"done"}`;let h=document.createElement("span");if(h.className="bp-tool-name",h.textContent=r.tool.name,l.appendChild(h),r.tool.summary){let d=document.createElement("span");d.className="bp-tool-summary",d.textContent=r.tool.summary,l.appendChild(d)}o.appendChild(l),i.appendChild(o);continue}if(r.kind==="ask"&&r.ask){let l=r.ask;if(l.kind==="plan"){o.appendChild(this.renderPlanAsk(l)),i.appendChild(o);continue}let h=document.createElement("div");h.className="bp-ask-card",h.setAttribute("data-testid",`ask-${l.id}`);let d=document.createElement("div");if(d.className="bp-ask-q",d.textContent=l.question,h.appendChild(d),l.state==="open"){let u=document.createElement("div");if(u.className="bp-ask-opts",l.options&&l.options.length>0)for(let f of l.options){let b=document.createElement("button");b.type="button",b.textContent=f.label,b.addEventListener("click",()=>this.cb.onAnswerAsk(l.id,f.id)),u.appendChild(b)}else{let f=document.createElement("input");f.type="text",f.className="bp-input",f.placeholder=m("web.chat.answer.placeholder","Type answer…");let b=document.createElement("button");b.type="button",b.className="primary",b.textContent=m("web.chat.answer.btn","Answer"),b.addEventListener("click",()=>{if(f.value.trim())this.cb.onAnswerAsk(l.id,f.value.trim())}),u.append(f,b)}h.appendChild(u)}else{let u=document.createElement("div");u.className="bp-ask-answered",u.textContent=m("web.chat.answered","Answered: {answer}",{answer:l.answered??""}),h.appendChild(u)}o.appendChild(h),i.appendChild(o);continue}let a=Boolean(r.text&&r.text.trim().length>0),c=Boolean(r.images&&r.images.length>0),p=Boolean(r.attachments&&r.attachments.length>0);if(!a&&!c&&!p&&!r.live)continue;if(r.replyTo?.quote){let l=document.createElement("div");l.className="bp-reply-quote",l.textContent=m("gpui.b.in.reply.to","↩ In reply to: {quote}",{quote:r.replyTo.quote});let h=r.replyTo.id;l.setAttribute("role","button"),l.tabIndex=0,l.setAttribute("data-testid","entry-reply-quote");let d=()=>{if(this.cb.onGoToEntry)this.cb.onGoToEntry(h);else this.goTo(h)};l.addEventListener("click",d),l.addEventListener("keydown",(u)=>{if(u.key==="Enter"||u.key===" ")u.preventDefault(),d()}),o.appendChild(l)}if(a||r.live){let l=document.createElement("div");if(l.className="bp-entry-body",r.kind==="user")l.appendChild(Vr(r.text||"",r.refs));else l.appendChild(Ot(r.text||""));if(r.live)this.liveNodes.set(r.id,l);o.appendChild(l)}if(p&&r.attachments){let l=document.createElement("div");l.className="bp-entry-images";for(let h of r.attachments)if(h.previewUrl){let d=document.createElement("img");d.className="bp-reply-img",d.src=h.previewUrl,d.alt=h.name||"attachment",l.appendChild(d)}else if(h.path||h.name){let d=document.createElement("span");d.className="bp-tool-pill",d.textContent=h.name||h.path||"image",l.appendChild(d)}if(l.childElementCount>0)o.appendChild(l)}if(r.images&&r.images.length>0){let l=document.createElement("div");l.className="bp-entry-images";for(let h of r.images){let d=document.createElement("img");d.className="bp-reply-img",d.alt=h;let u=`${r.id}|${h}`,f=this.imageCache.get(u);if(f)d.src=f;else this.cb.onLoadImage(r.id,h).then((b)=>{if(!b)return;let v=b.url??(b.mime&&b.data?`data:${b.mime};base64,${b.data}`:"");if(!v)return;this.imageCache.set(u,v),d.src=v});l.appendChild(d)}o.appendChild(l)}o.appendChild(this.makeEntryActions(r,r.kind==="user",r.kind==="assistant"?s:void 0)),i.appendChild(o)}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=Gt(["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 o=document.createElement("span");if(o.className="bp-plan-title",o.textContent=!e.head||e.head==="Proposed plan"?m("ask.plan","Proposed plan"):he(e.head),s.append(r,o),e.state==="open"){let l=document.createElement("span");l.className="bp-plan-badge",l.textContent=m("gpui.ask.plan.ready","Ready for review"),s.appendChild(l)}let a=document.createElement("span");if(a.className="bp-mgmt-flex1",s.appendChild(a),e.question){let l=document.createElement("button");l.type="button",l.className="bp-plan-head-btn";let h=m("common.copy","Copy"),d=document.createElement("span");d.textContent=h,l.append(Gt(["M9 9h11v11H9z","M5 15H4a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1h10a1 1 0 0 1 1 1v1"]),d),l.addEventListener("click",()=>{navigator.clipboard?.writeText(e.question).then(()=>{l.classList.add("copied"),d.textContent=m("web.clone.copied","Copied"),window.setTimeout(()=>{l.classList.remove("copied"),d.textContent=h},1200)}).catch(()=>{})}),s.appendChild(l)}let c=document.createElement("button");c.type="button",c.className="bp-plan-head-btn",c.setAttribute("data-testid","plan-expand"),c.textContent=t?m("gpui.c.term.collapse","Collapse"):m("gpui.c.term.expand","Expand"),c.addEventListener("click",()=>{if(this.planExpanded.has(e.id))this.planExpanded.delete(e.id);else this.planExpanded.add(e.id);let l=this.scrollEl.scrollTop;this.renderEntries(!1),this.scrollEl.scrollTop=l}),s.appendChild(c),i.appendChild(s);let p=document.createElement("div");if(p.className="bp-plan-body"+(t?" is-expanded":""),p.setAttribute("data-testid","plan-body"),p.appendChild(Ot(e.question||"")),i.appendChild(p),e.state==="open"){let l=document.createElement("div");l.className="bp-plan-actions";let h=e.options?.find((b)=>b.id==="implement"||b.id.endsWith("|implement")),d=document.createElement("button");if(d.type="button",d.className="primary",d.setAttribute("data-testid","plan-implement"),d.textContent=h?.label&&h.label!=="Implement"?he(h.label):m("approval.implement","Implement"),d.addEventListener("click",()=>{this.planRevisingId="",this.planReviseDrafts.delete(e.id),this.cb.onAnswerAsk(e.id,h?.id??"implement")}),l.appendChild(d),e.revise!==!1){let b=document.createElement("button");b.type="button",b.className="bp-plan-revise-btn"+(n?" active":""),b.setAttribute("data-testid","plan-revise"),b.append(Gt(["M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7","M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"]),document.createTextNode(m("gpui.ask.plan.revise","Revise"))),b.addEventListener("click",()=>{let v=this.planRevisingId!==e.id;this.planRevisingId=v?e.id:"";let w=this.scrollEl.scrollTop;if(this.renderEntries(!1),this.scrollEl.scrollTop=w,v)this.listEl.querySelector(`[data-testid="ask-${CSS.escape(e.id)}"] .bp-plan-revise-input`)?.focus()}),l.appendChild(b)}let u=e.options?.find((b)=>b.id==="dismiss"||b.id.endsWith("|dismiss")),f=document.createElement("button");if(f.type="button",f.className="bp-plan-dismiss-btn",f.setAttribute("data-testid","plan-dismiss"),f.textContent=u?.label&&u.label!=="Dismiss"?he(u.label):m("approval.dismiss","Dismiss"),f.addEventListener("click",()=>{this.planRevisingId="",this.planReviseDrafts.delete(e.id),this.cb.onAnswerAsk(e.id,u?.id??"dismiss")}),l.appendChild(f),i.appendChild(l),n){let b=document.createElement("div");b.className="bp-plan-revise",b.setAttribute("data-testid","plan-revise-drawer");let v=document.createElement("textarea");v.rows=2,v.className="bp-input bp-plan-revise-input",v.placeholder=m("gpui.ask.plan.reviseph","What should change in the plan?"),v.value=this.planReviseDrafts.get(e.id)??"";let w=document.createElement("button");w.type="button",w.className="bp-plan-revise-send",w.setAttribute("data-testid","plan-revise-send"),w.textContent=m("gpui.ask.plan.sendrev","Send revision"),w.disabled=v.value.trim().length===0;let E=()=>{let M=v.value.trim();if(!M)return;this.planRevisingId="",this.planReviseDrafts.delete(e.id),this.cb.onAnswerAsk(e.id,`revise:${M}`)},k=()=>{this.closePlanRevise()};b.addEventListener("keydown",(M)=>{if(M.key==="Escape")M.preventDefault(),M.stopPropagation(),k()}),v.addEventListener("input",()=>{this.planReviseDrafts.set(e.id,v.value),w.disabled=v.value.trim().length===0}),v.addEventListener("keydown",(M)=>{if(M.key==="Enter"&&!M.shiftKey)M.preventDefault(),E()}),w.addEventListener("click",E);let L=document.createElement("button");L.type="button",L.className="bp-btn-ghost",L.textContent=m("common.cancel","Cancel"),L.addEventListener("click",k),b.append(v,w,L),i.appendChild(b)}}else{let l=document.createElement("div");l.className="bp-ask-answered",l.textContent=m("web.chat.answered","Answered: {answer}",{answer:e.answered??""}),i.appendChild(l)}return i}}var Wr={claude:"Claude Code",codex:"Codex CLI",grok:"Grok CLI",muse:"Muse Code",antigravity:"Google Antigravity",opencode:"OpenCode",pi:"Pi",omp:"Oh My Pi"};var Ii=/[\x00-\x1f\x7f]/,_r=/\s/;function Pt(e){return e.trim().replace(/^@+/,"").toLowerCase()}function ft(e,t){if(Ii.test(e)||Ii.test(t))return"";let n=Pt(e),i=t.trim();if(!n||!i||n.includes("/")||_r.test(n))return"";if(n.length+1+i.length>200)return"";return`${n}/${i}`}function Ri(e){let t=e.indexOf("/");if(t<=0)return null;let n=e.slice(0,t),i=e.slice(t+1);if(!ft(n,i))return null;return{provider:Pt(n),model:i.trim()}}function dt(e){if(!Array.isArray(e))return[];let t=[],n=new Set;for(let i of e){if(typeof i!=="string")continue;let s=Ri(i);if(!s)continue;let r=`${s.provider}/${s.model}`;if(!n.has(r)){if(n.add(r),t.push(r),t.length>=64)break}}return t}function Nn(e,t,n,i){let s=ft(t,n),r=dt(e);if(!s)return{keys:r,starred:!1};let o=r.indexOf(s),a=i!==void 0?i:o<0;if(a&&o<0){if(r.length>=64)return{keys:r,starred:!1};r.push(s)}else if(!a&&o>=0)r.splice(o,1);return{keys:r,starred:a}}function nt(e){return e&&typeof e==="object"&&!Array.isArray(e)?e:null}function xt(e){return Array.isArray(e)?e:[]}function Se(e){return typeof e==="string"?e:""}function zr(e){return Wr[e]??e}function ji(e,t,n,i){let s=new Map;for(let o of e)s.set(o.provider,o);let r=[];for(let o of dt(t)){let a=Ri(o);if(!a)continue;let c=s.get(a.provider),p=Boolean(c&&c.models.some((u)=>u.value!=="")),l=c?.models.find((u)=>u.value===a.model),h=l?l.ok&&(c?.ok??!0):c?.ok??!0,d=l?.why||c?.why||"";if(h&&p&&!l)h=!1,d="not available on this machine";r.push({key:o,provider:a.provider,model:a.model,label:l?.label||a.model,note:l?.note||"",on:a.provider===n&&a.model===i,ok:h,why:d})}return r}function Hi(e,t=[]){let n=nt(e),i=nt(n?.picker)??n??{},s=xt(i.sections).map(nt).filter((P)=>Boolean(P)),r=(P)=>s.find((Y)=>Se(Y.action)===P),o=r("provider"),a=r("model"),c=r("effort"),p=xt(o?.choices).map(nt).filter((P)=>Boolean(P)),l=xt(a?.choices).map(nt).filter((P)=>Boolean(P)),h=xt(c?.choices).map(nt).filter((P)=>Boolean(P)),d=Se(i.chip),u=Se(p.find((P)=>P.on===!0)?.value)||d.split("/")[0]?.trim()||"claude",f=Pt(u)||"claude",b=Se(l.find((P)=>P.on===!0)?.value),v=Se(h.find((P)=>P.on===!0)?.value),w=h.map((P)=>({value:Se(P.value),label:Se(P.label)||"auto",on:P.on===!0})),E=nt(i.agents),k=[],L=new Set,M=(P)=>{let Y=Pt(P);if(Y&&!L.has(Y))L.add(Y),k.push(Y)};for(let P of p)M(Se(P.value)||Se(P.label));if(E)for(let P of Object.keys(E))M(P);M(f);let A=k.map((P)=>{let Y=p.find((te)=>Pt(Se(te.value)||Se(te.label))===P),re=nt(E?.[P]),ie=re?re.ok!==!1:Y?Y.ok!==!1:!0,me=Se(re?.why)||Se(Y?.why),Pe=xt(re?.models).map(nt).filter((te)=>Boolean(te)),Ce;if(Pe.length>0)Ce=Pe.map((te)=>{let oe=Se(te.value),R=Se(te.label)||(oe===""?"default":oe),ue=Se(te.note);return{value:oe,label:R,note:ue,on:P===f&&oe===b,ok:te.ok!==!1&&ie,why:Se(te.why)||me}});else if(P===f&&l.length>0)Ce=l.map((te)=>{let oe=Se(te.value),R=Se(te.label);return{value:oe,label:oe===""?"default":oe,note:R&&R!==oe?R:"",on:te.on===!0,ok:te.ok!==!1&&ie,why:Se(te.why)||me}});else if(ie)Ce=[{value:"",label:"default",note:"",on:P===f&&b==="",ok:!0,why:""}];else Ce=[];if(P===f&&b&&!Ce.some((te)=>te.value===b)){let te=l.find((R)=>Se(R.value)===b),oe=Se(te?.label);Ce.push({value:b,label:b,note:oe&&oe!==b?oe:"",on:!0,ok:!0,why:""})}return{provider:P,label:zr(P),ok:ie,why:me,models:Ce}}),B=Array.isArray(i.favoriteKeys),T=xt(i.favorites).map(nt).filter((P)=>Boolean(P)),H=B?dt(i.favoriteKeys):T.length>0?dt(T.map((P)=>Se(P.key)||ft(Se(P.provider),Se(P.model)))):dt(t),O=T.length>0?T.map((P)=>{let Y=Pt(Se(P.provider)),re=Se(P.model).trim(),ie=ft(Y,re);if(!ie)return null;return{key:ie,provider:Y,model:re,label:Se(P.label)||re,note:Se(P.note),on:P.on===!0||Y===f&&re===b,ok:P.ok!==!1,why:Se(P.why)}}).filter((P)=>Boolean(P)):ji(A,H,f,b);return{chip:d,provider:f,model:b,effort:v,efforts:w,providers:A,favoriteKeys:H,favorites:O}}function Vt(e,t){let n=dt(t);return{...e,favoriteKeys:n,favorites:ji(e.providers,n,e.provider,e.model)}}function Di(e,t){let n=t.trim().toLowerCase().split(/\s+/).filter(Boolean),i=(a)=>{if(n.length===0)return!0;let c=a.toLowerCase();return n.every((p)=>c.includes(p))},s=new Set(e.favoriteKeys),r=e.favorites.filter((a)=>i(`${a.provider} ${a.model} ${a.label} ${a.note}`)),o=[];for(let a of e.providers){let c=a.models.filter((p)=>i(`${a.provider} ${a.label} ${p.value} ${p.label} ${p.note}`)).map((p)=>{let l=p.value?ft(a.provider,p.value):"";return{...p,provider:a.provider,starrable:p.value!=="",starred:Boolean(l&&s.has(l))}});if(c.length>0||n.length===0&&!a.ok&&a.why)o.push({provider:a.provider,label:a.label,ok:a.ok,why:a.why,models:c})}return{favorites:r,groups:o,efforts:e.efforts}}var Fi={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 St="http://www.w3.org/2000/svg",$i=4,Oi=new Set(["image/png","image/jpeg","image/webp","image/gif"]);function on(e){let t=document.createElementNS(St,"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(St,"path");i.setAttribute("d",n),t.appendChild(i)}return t}function Mn(){return on(["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 Gi(){return on(["M6 4l14 8-14 8z"])}function Vi(e){let t=document.createElementNS(St,"svg");t.setAttribute("viewBox","0 0 24 24"),t.setAttribute("width","13"),t.setAttribute("height","13"),t.setAttribute("fill",e?"currentColor":"none"),t.setAttribute("stroke","currentColor"),t.setAttribute("stroke-width","1.8"),t.setAttribute("stroke-linejoin","round"),t.setAttribute("aria-hidden","true");let n=document.createElementNS(St,"path");return n.setAttribute("d","M12 2.5l2.9 6 6.6.9-4.8 4.6 1.2 6.5L12 17.4l-5.9 3.1 1.2-6.5-4.8-4.6 6.6-.9z"),t.appendChild(n),t}function Ui(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 Wi(e){let t=Fi[e];if(!t||!t.d)return null;let n=document.createElementNS(St,"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(St,"path");return i.setAttribute("d",t.d),n.appendChild(i),n}class Tn{popupEl;attachStripEl;planBarEl;fileInput;textarea;memoryEl;memoryFill;memoryText;modelBtn;providerMarkEl;modelTextEl;ctxEl;modelPickerEl;modelSearchInput;modelPickerBodyEl;modelPickerEffortsEl;modelPickerOpen=!1;modelPickerLoading=!1;modelPickerSnap=null;modelPickerQuery="";modelPickerFocusIdx=-1;onDocMouseDown;planChipBtn;planChipIconHost;planChipLbl;attachBtn;voiceBtn;sendBtn;stopBtn;errorEl;replyEl;cb;commands=[];popupMode="none";filteredSlash=[];mentionItems=[];popupIdx=0;enabled=!1;attachments=[];planMode=null;constructor(e,t){this.cb=t;let n=document.createElement("div");n.className="bp-composer",n.setAttribute("data-testid","composer");let i=document.createElement("div");i.className="bp-composer-inner",this.popupEl=document.createElement("div"),this.popupEl.className="bp-composer-popup bp-hidden",this.popupEl.setAttribute("data-testid","slash-menu"),this.errorEl=document.createElement("div"),this.errorEl.className="bp-composer-err bp-hidden",this.replyEl=document.createElement("div"),this.replyEl.className="bp-reply-strip bp-hidden",this.replyEl.setAttribute("data-testid","composer-reply"),this.attachStripEl=document.createElement("div"),this.attachStripEl.className="bp-attach-strip bp-hidden",this.attachStripEl.setAttribute("data-testid","composer-attachments"),this.planBarEl=document.createElement("div"),this.planBarEl.className="bp-plan-bar bp-hidden",this.planBarEl.setAttribute("data-testid","composer-plan-bar"),this.fileInput=document.createElement("input"),this.fileInput.type="file",this.fileInput.accept="image/png,image/jpeg,image/webp,image/gif",this.fileInput.multiple=!0,this.fileInput.className="bp-hidden",this.fileInput.setAttribute("data-testid","composer-file-input"),this.fileInput.addEventListener("change",()=>{if(this.fileInput.files)this.addFiles(Array.from(this.fileInput.files));this.fileInput.value=""}),this.textarea=document.createElement("textarea"),this.textarea.className="bp-composer-input",this.textarea.rows=2,this.textarea.placeholder=m("composer.placeholder","Ask anything: @bot, >thread, %project, #room, $skill, /btw"),this.textarea.setAttribute("data-testid","composer-input");let s=document.createElement("div");s.className="bp-composer-bar";let r=document.createElement("button");r.type="button",r.className="bp-composer-model",r.setAttribute("data-testid","composer-model-chip"),r.setAttribute("aria-haspopup","dialog"),r.setAttribute("aria-expanded","false"),r.title=m("composer.model.tip","Choose the model and effort"),this.modelBtn=r,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");let o=document.createElement("span");o.className="bp-model-caret",o.textContent="▾",r.append(this.providerMarkEl,this.modelTextEl,this.ctxEl,o),r.addEventListener("click",()=>{this.toggleModelPicker()}),this.modelPickerEl=document.createElement("div"),this.modelPickerEl.className="bp-model-picker bp-hidden",this.modelPickerEl.setAttribute("data-testid","model-picker"),this.modelPickerEl.setAttribute("role","dialog");let a=document.createElement("div");a.className="bp-mp-search-wrap",this.modelSearchInput=document.createElement("input"),this.modelSearchInput.type="search",this.modelSearchInput.className="bp-mp-search",this.modelSearchInput.placeholder=m("gpui.search.models","Search models"),this.modelSearchInput.setAttribute("data-testid","model-picker-search"),this.modelSearchInput.addEventListener("input",()=>{this.modelPickerQuery=this.modelSearchInput.value,this.modelPickerFocusIdx=-1,this.renderModelPicker()}),this.modelSearchInput.addEventListener("keydown",(l)=>{if(l.key==="Escape"){l.preventDefault(),l.stopPropagation(),this.closeModelPicker(),this.textarea.focus();return}if(l.key==="ArrowDown"||l.key==="ArrowUp"){let h=this.modelPickerFocusableButtons();if(h.length===0)return;l.preventDefault();let d=l.key==="ArrowDown"?1:-1;this.modelPickerFocusIdx=this.modelPickerFocusIdx<0?d>0?0:h.length-1:(this.modelPickerFocusIdx+d+h.length)%h.length,this.updateModelPickerKbdFocus(h);return}if(l.key==="Enter"){let h=this.modelPickerFocusableButtons(),d=this.modelPickerFocusIdx>=0&&this.modelPickerFocusIdxthis.cb.onCyclePlanMode?.()),this.memoryEl=document.createElement("div"),this.memoryEl.className="bp-composer-memory bp-hidden",this.memoryEl.setAttribute("data-testid","composer-memory");let c=document.createElement("div");c.className="bp-memory-meter",this.memoryFill=document.createElement("div"),this.memoryFill.className="bp-memory-fill",c.appendChild(this.memoryFill),this.memoryText=document.createElement("span"),this.memoryEl.append(c,this.memoryText);let p=document.createElement("div");p.className="bp-composer-btns",this.attachBtn=document.createElement("button"),this.attachBtn.type="button",this.attachBtn.className="icon bp-composer-tool",this.attachBtn.title=m("web.composer.attach","Attach image"),this.attachBtn.setAttribute("aria-label",m("web.composer.attach","Attach image")),this.attachBtn.setAttribute("data-testid","composer-attach"),this.attachBtn.appendChild(on(["M21.44 11.05l-9.19 9.19a6 6 0 0 1-8.49-8.49l9.19-9.19a4 4 0 0 1 5.66 5.66l-9.2 9.19a2 2 0 0 1-2.83-2.83l8.49-8.48"])),this.attachBtn.addEventListener("click",()=>this.fileInput.click()),this.voiceBtn=document.createElement("button"),this.voiceBtn.type="button",this.voiceBtn.className="icon bp-composer-tool",this.voiceBtn.title=m("web.composer.voice","Voice dictation"),this.voiceBtn.setAttribute("aria-label",m("web.composer.voice","Voice dictation")),this.voiceBtn.setAttribute("data-testid","composer-voice"),this.voiceBtn.appendChild(on(["M12 1a3 3 0 0 0-3 3v8a3 3 0 0 0 6 0V4a3 3 0 0 0-3-3z","M19 10v2a7 7 0 0 1-14 0v-2","M12 19v4","M8 23h8"])),this.voiceBtn.addEventListener("click",()=>this.cb.onToggleVoice?.()),this.stopBtn=document.createElement("button"),this.stopBtn.type="button",this.stopBtn.className="primary stop bp-hidden",this.stopBtn.textContent=m("composer.stop","Stop"),this.stopBtn.setAttribute("data-testid","composer-stop"),this.stopBtn.addEventListener("click",()=>this.cb.onInterrupt()),this.sendBtn=document.createElement("button"),this.sendBtn.type="button",this.sendBtn.className="primary bp-send-btn",this.sendBtn.textContent=m("composer.send","Send"),this.sendBtn.setAttribute("data-testid","composer-send"),this.sendBtn.addEventListener("click",()=>this.submit()),p.append(this.attachBtn,this.voiceBtn,this.stopBtn,this.sendBtn),s.append(r,this.planChipBtn,this.memoryEl,p),i.append(this.modelPickerEl,this.popupEl,this.errorEl,this.replyEl,this.attachStripEl,this.planBarEl,this.fileInput,this.textarea,s),n.appendChild(i),e.appendChild(n),this.onDocMouseDown=(l)=>{if(!this.modelPickerEl.isConnected){document.removeEventListener("mousedown",this.onDocMouseDown);return}if(!this.modelPickerOpen)return;let h=l.target;if(h&&(this.modelPickerEl.contains(h)||this.modelBtn.contains(h)))return;this.closeModelPicker()},document.addEventListener("mousedown",this.onDocMouseDown),this.textarea.addEventListener("paste",(l)=>{let h=l.clipboardData?.items;if(!h)return;let d=[];for(let u=0;u0)l.preventDefault(),this.addFiles(d)}),this.textarea.addEventListener("input",()=>{this.autoGrow(),this.clearError(),this.updatePopups()}),this.textarea.addEventListener("keydown",(l)=>{if(this.popupMode!=="none"){let h=this.popupMode==="slash"?this.filteredSlash.length:this.mentionItems.length;if(l.key==="ArrowDown"){l.preventDefault(),this.popupIdx=(this.popupIdx+1)%Math.max(1,h),this.renderPopup();return}if(l.key==="ArrowUp"){l.preventDefault(),this.popupIdx=(this.popupIdx-1+Math.max(1,h))%Math.max(1,h),this.renderPopup();return}if(l.key==="Tab"||l.key==="Enter"&&!l.shiftKey&&this.shouldCompleteOnEnter()){l.preventDefault(),this.applyPopupChoice(this.popupIdx);return}if(l.key==="Escape"){l.preventDefault(),this.closePopup();return}}if(l.key==="Tab"&&l.shiftKey&&this.planMode!==null){l.preventDefault(),this.cb.onCyclePlanMode?.();return}if(l.key==="Enter"&&!l.shiftKey)l.preventDefault(),this.submit()})}setCommands(e){this.commands=e.map((t)=>({...t,word:t.word.replace(/^\//,"")}))}setModelChip(e,t,n){let i=Ui(t),s=i.mark?Wi(i.mark):null;if(s)this.providerMarkEl.replaceChildren(s);else this.providerMarkEl.textContent=i.glyph;if(this.providerMarkEl.style.color=i.color,this.providerMarkEl.title=i.title,this.modelTextEl.textContent=e||"default",typeof n==="number"&&Number.isFinite(n)&&n>=0)this.ctxEl.textContent=`ctx ${Math.round(n)}%`,this.ctxEl.classList.remove("bp-hidden");else this.ctxEl.textContent="",this.ctxEl.classList.add("bp-hidden")}setFeatures(e,t){this.attachBtn.classList.toggle("bp-hidden",!e),this.voiceBtn.classList.toggle("bp-hidden",!t)}setVoiceRecording(e){this.voiceBtn.classList.toggle("recording",e),this.voiceBtn.setAttribute("aria-pressed",e?"true":"false")}setVoiceLevel(e){this.voiceBtn.setAttribute("data-level",String(e))}getDraft(){return this.textarea.value}getCaret(){return this.textarea.selectionStart??this.textarea.value.length}setMemory(e){if(this.memoryEl.classList.toggle("bp-hidden",!e),!e)return;let t=e.total??0,n=t>0?Math.min(1,(e.done??0)/t):1;this.memoryFill.style.width=`${Math.round(n*100)}%`,this.memoryFill.dataset.state=e.state??"",this.memoryText.textContent=e.line??"",this.memoryEl.title=[e.status,e.lines,e.viewLine].filter(Boolean).join(` +`)}setPlanMode(e){if(this.planMode=e,this.textarea.classList.remove("is-plan","is-plan-exec"),this.sendBtn.classList.remove("is-plan","is-plan-exec"),this.planChipBtn.classList.remove("is-plan","is-exec"),this.planBarEl.classList.remove("is-exec"),!e){this.planChipBtn.classList.add("bp-hidden"),this.planChipBtn.setAttribute("aria-pressed","false"),this.planBarEl.classList.add("bp-hidden"),this.planBarEl.replaceChildren(),this.sendBtn.textContent=m("composer.send","Send");return}let t=e.phase,n=t!=="off",i=t==="armed"||t==="planning"||t==="pending",s=t==="executing";this.planChipBtn.classList.remove("bp-hidden"),this.planChipBtn.classList.toggle("is-plan",i),this.planChipBtn.classList.toggle("is-exec",s),this.planChipBtn.setAttribute("aria-pressed",n?"true":"false");let r=`${m("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?Gi():Mn()),this.planChipLbl.textContent=s?m("gpui.planmode.chip.building","Building"):t==="pending"?m("gpui.mgmt.fab.reviewbtn","Review"):i&&e.once?m("gpui.planmode.chip.once","Plan · 1t"):m("gpui.mgmt.plan.tab","Plan"),this.textarea.classList.toggle("is-plan",i),this.textarea.classList.toggle("is-plan-exec",s),this.sendBtn.classList.toggle("is-plan",i),this.sendBtn.classList.toggle("is-plan-exec",s),this.sendBtn.textContent=i?m("gpui.mgmt.plan.tab","Plan"):m("composer.send","Send"),!n){this.planBarEl.classList.add("bp-hidden"),this.planBarEl.replaceChildren();return}this.planBarEl.classList.remove("bp-hidden"),this.planBarEl.classList.toggle("is-exec",s);let o=document.createElement("span");o.className="bp-plan-bar-ic",o.appendChild(s?Gi():Mn());let a=document.createElement("span");a.className="bp-plan-bar-text",a.textContent=t==="armed"&&e.once?m("gpui.planmode.bar.once","Plan mode (1 turn) — explores and proposes a plan before editing"):t==="armed"?m("gpui.planmode.bar.always","Plan mode — explores and proposes a plan before editing"):t==="planning"?m("gpui.planmode.bar.planning","Planning — drafting a plan before edits"):t==="pending"?m("gpui.planmode.bar.pending","Proposed plan awaits review below"):m("gpui.planmode.bar.executing","Building the approved plan");let c=[o,a];if(t==="armed"||t==="planning"){let p=document.createElement("div");p.className="bp-plan-scopes";let l=(h,d,u,f)=>{let b=document.createElement("button");return b.type="button",b.className="bp-plan-scope-btn"+(d?" active":""),b.textContent=h,b.disabled=!this.enabled,b.setAttribute("data-testid",f),b.addEventListener("click",()=>this.cb.onSetPlanMode?.(u)),b};p.append(l(m("gpui.planmode.scope.once","1 turn"),e.once,"once","plan-scope-once"),l(m("gpui.planmode.scope.always","Always"),!e.once,"always","plan-scope-always"),l(m("gpui.bots.recall.off","Off"),!1,"off","plan-scope-off")),c.push(p)}this.planBarEl.replaceChildren(...c)}setState(e,t){if(this.enabled=e,this.textarea.disabled=!e,this.sendBtn.disabled=!e,this.attachBtn.disabled=!e,this.voiceBtn.disabled=!e,this.modelBtn.disabled=!e,!e)this.closeModelPicker();this.planChipBtn.disabled=!e,this.planBarEl.querySelectorAll(".bp-plan-scope-btn").forEach((n)=>{n.disabled=!e}),this.stopBtn.classList.toggle("bp-hidden",!t)}destroy(){document.removeEventListener("mousedown",this.onDocMouseDown)}isModelPickerOpen(){return this.modelPickerOpen}closeModelPicker(){if(!this.modelPickerOpen)return;this.modelPickerOpen=!1,this.modelPickerFocusIdx=-1,this.modelPickerEl.classList.add("bp-hidden"),this.modelBtn.classList.remove("is-open"),this.modelBtn.setAttribute("aria-expanded","false")}modelPickerFocusableButtons(){return Array.from(this.modelPickerBodyEl.querySelectorAll(".bp-mp-row-main:not(:disabled)"))}updateModelPickerKbdFocus(e){e.forEach((t,n)=>{let i=n===this.modelPickerFocusIdx;if(t.classList.toggle("is-kbd",i),i)t.scrollIntoView({block:"nearest"})})}updateFavoriteModels(e){if(!this.modelPickerSnap)return;if(this.modelPickerSnap=Vt(this.modelPickerSnap,e),this.modelPickerOpen)this.renderModelPicker()}async toggleModelPicker(){if(!this.enabled)return;if(this.modelPickerOpen){this.closeModelPicker();return}this.closePopup(),this.modelPickerOpen=!0,this.modelPickerQuery="",this.modelPickerFocusIdx=-1,this.modelSearchInput.value="",this.modelPickerEl.classList.remove("bp-hidden"),this.modelBtn.classList.add("is-open"),this.modelBtn.setAttribute("aria-expanded","true"),this.modelPickerLoading=!0,this.renderModelPicker(),this.modelSearchInput.focus(),await this.reloadModelPicker()}async reloadModelPicker(){if(!this.cb.onLoadModelPicker){this.modelPickerLoading=!1,this.renderModelPicker();return}try{let e=await this.cb.onLoadModelPicker();if(!this.modelPickerOpen)return;this.modelPickerSnap=Hi(e,this.cb.getFavoriteModels?.()??[])}catch{}finally{if(this.modelPickerLoading=!1,this.modelPickerOpen)this.renderModelPicker()}}async toggleFavoriteInPicker(e,t){if(!this.modelPickerSnap)return;let n=this.modelPickerSnap,i=ft(e,t);if(!i)return;let s=n.favoriteKeys.includes(i),r=Nn(n.favoriteKeys,e,t);if(r.keys.length===n.favoriteKeys.length&&r.starred===s)return;if(this.modelPickerSnap=Vt(n,r.keys),this.renderModelPicker(),!this.cb.onToggleFavorite)return;try{let o=await this.cb.onToggleFavorite(e,t,r.starred);if(Array.isArray(o)&&this.modelPickerSnap){if(this.modelPickerSnap=Vt(this.modelPickerSnap,dt(o)),this.modelPickerOpen)this.renderModelPicker()}}catch(o){if(this.modelPickerSnap){let a=this.cb.getFavoriteModels?.(),c=Array.isArray(a)?dt(a):Nn(this.modelPickerSnap.favoriteKeys,e,t,!r.starred).keys;if(this.modelPickerSnap=Vt(this.modelPickerSnap,c),this.modelPickerOpen)this.renderModelPicker()}this.showError(o instanceof Error&&o.message?o.message:"Could not update favorite model")}}renderProviderGlyph(e){let t=Ui(e),n=document.createElement("span");n.className="bp-mp-mark",n.style.color=t.color,n.title=t.title;let i=t.mark?Wi(t.mark):null;if(i)n.appendChild(i);else n.textContent=t.glyph;return n}makeStarButton(e,t,n,i="model-star"){let s=document.createElement("button");s.type="button",s.className="bp-mp-star"+(n?" is-starred":"");let r=n?m("gpui.picker.favorite.remove","Remove from favorites"):m("gpui.picker.favorite.add","Add to favorites");return s.title=r,s.setAttribute("aria-label",r),s.setAttribute("aria-pressed",n?"true":"false"),s.setAttribute("data-testid",`${i}-${e}-${t}`),s.appendChild(Vi(n)),s.addEventListener("click",(o)=>{o.preventDefault(),o.stopPropagation(),this.toggleFavoriteInPicker(e,t)}),s}renderModelPicker(){if(!this.modelPickerOpen)return;if(this.modelPickerFocusIdx=-1,!this.modelPickerSnap){let i=document.createElement("div");i.className="bp-mp-empty",i.textContent=this.modelPickerLoading?"…":m("gpui.no.models","No models"),this.modelPickerBodyEl.replaceChildren(i),this.modelPickerEffortsEl.classList.add("bp-hidden"),this.modelPickerEffortsEl.replaceChildren();return}let e=Di(this.modelPickerSnap,this.modelPickerQuery),t=document.createDocumentFragment();if(e.favorites.length>0){let i=document.createElement("div");i.className="bp-mp-section bp-mp-favorites",i.setAttribute("data-testid","model-picker-favorites");let s=document.createElement("div");s.className="bp-mp-head";let r=document.createElement("span");r.className="bp-mp-head-star",r.appendChild(Vi(!0));let o=document.createElement("span");o.textContent=m("gpui.picker.favorites","Favorites"),s.append(r,o),i.appendChild(s);for(let a of e.favorites){let c=document.createElement("div");c.className="bp-mp-row"+(a.on?" is-active":"")+(!a.ok?" is-disabled":""),c.setAttribute("data-testid",`model-fav-row-${a.provider}-${a.model}`);let p=document.createElement("button");if(p.type="button",p.className="bp-mp-row-main",p.disabled=!a.ok,!a.ok&&a.why)p.title=a.why;let l=document.createElement("span");l.className="bp-mp-check",l.textContent=a.on?"✓":"";let h=document.createElement("span");h.className="bp-mp-name",h.textContent=a.label;let d=document.createElement("span");d.className="bp-mp-note",d.textContent=!a.ok&&a.why?he(a.why):a.note&&a.note!==a.label?he(a.note):a.provider,p.append(l,this.renderProviderGlyph(a.provider),h,d),p.addEventListener("click",()=>{if(!a.ok)return;this.closeModelPicker(),this.textarea.focus(),this.cb.onSelectModel?.(a.provider,a.model)}),c.append(p,this.makeStarButton(a.provider,a.model,!0,"model-fav-star")),i.appendChild(c)}t.appendChild(i)}let n=document.createElement("div");if(n.className="bp-mp-groups",n.setAttribute("data-testid","model-picker-groups"),e.groups.length===0){let i=document.createElement("div");i.className="bp-mp-empty",i.textContent=this.modelPickerQuery.trim()?m("gpui.nothing.matches","Nothing matches"):m("gpui.no.models","No models"),n.appendChild(i)}else for(let i of e.groups){let s=document.createElement("div");s.className="bp-mp-group";let r=document.createElement("div");r.className="bp-mp-group-head";let o=document.createElement("span");if(o.className="bp-mp-group-title",o.textContent=i.label,r.append(this.renderProviderGlyph(i.provider),o),!i.ok&&i.why){let a=document.createElement("span");a.className="bp-mp-group-why",a.textContent=he(i.why),r.appendChild(a)}s.appendChild(r);for(let a of i.models){let c=document.createElement("div");c.className="bp-mp-row"+(a.on?" is-active":"")+(!a.ok?" is-disabled":""),c.setAttribute("data-testid",`model-row-${i.provider}-${a.value||"default"}`);let p=document.createElement("button");if(p.type="button",p.className="bp-mp-row-main",p.disabled=!a.ok,!a.ok&&a.why)p.title=a.why;let l=document.createElement("span");l.className="bp-mp-check",l.textContent=a.on?"✓":"";let h=document.createElement("span");h.className="bp-mp-name",h.textContent=a.label;let d=document.createElement("span");if(d.className="bp-mp-note",d.textContent=a.note&&a.note!==a.label?he(a.note):"",p.append(l,h,d),p.addEventListener("click",()=>{if(!a.ok)return;this.closeModelPicker(),this.textarea.focus(),this.cb.onSelectModel?.(i.provider,a.value)}),c.appendChild(p),a.starrable)c.appendChild(this.makeStarButton(i.provider,a.value,a.starred));s.appendChild(c)}n.appendChild(s)}if(t.appendChild(n),this.modelPickerBodyEl.replaceChildren(t),e.efforts.length>0){let i=document.createDocumentFragment(),s=document.createElement("span");s.className="bp-mp-efforts-lbl",s.textContent=m("model.col.effort","Effort"),i.appendChild(s);for(let r of e.efforts){let o=document.createElement("button");o.type="button",o.className="bp-mp-effort"+(r.on?" active":""),o.textContent=r.label,o.addEventListener("click",()=>{Promise.resolve(this.cb.onSelectEffort?.(r.value)).then(()=>{if(this.modelPickerOpen)this.reloadModelPicker()})}),i.appendChild(o)}this.modelPickerEffortsEl.replaceChildren(i),this.modelPickerEffortsEl.classList.remove("bp-hidden")}else this.modelPickerEffortsEl.classList.add("bp-hidden"),this.modelPickerEffortsEl.replaceChildren()}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=m("gpui.b.replying.to","↩ Replying to: {line}",{line:e.line}),i.append(s,r),t)i.addEventListener("click",t);let o=document.createElement("button");o.type="button",o.className="icon bp-reply-strip-drop",o.textContent="×";let a=m("reply.cancel","Cancel reply");if(o.title=a,o.setAttribute("aria-label",a),o.setAttribute("data-testid","composer-reply-drop"),n)o.addEventListener("click",n);this.replyEl.replaceChildren(i,o),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=he(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(){if(this.textarea.placeholder=m("composer.placeholder","Ask anything: @bot, >thread, %project, #room, $skill, /btw"),this.attachBtn.title=m("web.composer.attach","Attach image"),this.attachBtn.setAttribute("aria-label",m("web.composer.attach","Attach image")),this.voiceBtn.title=m("web.composer.voice","Voice dictation"),this.voiceBtn.setAttribute("aria-label",m("web.composer.voice","Voice dictation")),this.modelBtn.title=m("composer.model.tip","Choose the model and effort"),this.modelSearchInput.placeholder=m("gpui.search.models","Search models"),this.sendBtn.textContent=m("composer.send","Send"),this.stopBtn.textContent=m("composer.stop","Stop"),this.setPlanMode(this.planMode),this.modelPickerOpen)this.renderModelPicker()}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",(o)=>{o.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",(o)=>{o.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(!Oi.has(t.type)){this.showError(m("web.composer.unsupported","Unsupported image type: {type}",{type:t.type||t.name}));continue}if(this.attachments.length>=$i){this.showError(m("web.composer.maximages","At most {max} images per message.",{max:$i}));break}let n=await new Promise((s,r)=>{let o=new FileReader;o.onload=()=>s(String(o.result||"")),o.onerror=()=>r(Error("read failed")),o.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=m("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 _i(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 qr=new Set(["bom","checks","life","plan","fab"]);function an(e){if(!e||!Array.isArray(e.panels))return[];return e.panels.filter((t)=>t&&typeof t.id==="string"&&qr.has(t.id))}function Xi(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 ln(e,t=22){let n=e.join(", ");if(n.length<=t)return n;let i="";for(let s=0;s0?` +${a}`.length:0)>t)return i?`${i} +${e.length-s}`:`${e[0]} +${e.length-1}`;i=o}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 At(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 Kr=new Set(["0201","0402","0603","0805","1206","1210","1812","2010","2512"]),Jr=new Set(["QFN","DFN","SOT","SOIC","SOP","SSOP","TSSOP","MSOP","QFP","LQFP","TQFP","BGA","WLCSP","SOD","TO","SON","LGA"]);function Qi(e){if(!e)return"";let t=e.indexOf(":"),i=(t>=0?e.slice(t+1):e).split("_");for(let o of i)if(Kr.has(o))return o;let s=i[0]??"",r=s.replace(/[^a-zA-Z].*$/,"").toUpperCase();if(Jr.has(r)){let o=s.split("-");if(o.length>=2&&/^\d+$/.test(o[1]))return`${o[0]}-${o[1]}`;return o[0]}return i.slice(0,2).join("_")}function Zi(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 es(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 ts(e,t){if(!t)return e;return e.filter((n)=>n.source===t)}function In(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 cn(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 ns(e){return e.state==="routed"||e.state==="verified"}function is(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 ss(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 rs(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 o of e.layers??[])for(let a of o.items??[])if(a.state==="routed"||a.state==="verified")t+=1;else if(a.state==="routing")r+=1;else if(a.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 os(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 as(e){return e==="extra"?"costs-more limits":"base-price limits"}function Rn(e,t){return e.watchGen===t.watchGen&&e.editGen===t.editGen&&e.project!==""&&e.project===t.project&&e.editId!==""&&e.editId===t.editId}function ls(e){return{project:e.project,refs:e.refs.slice(),field:e.field,value:e.was}}function jn(e,t){return e.watchGen===t.watchGen&&e.project!==""&&e.project===t.project&&e.threadId!==""&&e.threadId===t.threadId&&e.threadGen===t.threadGen}var zi=["#f59e0b","#38bdf8","#c084fc","#2dd4bf","#ef4444","#a3e635","#f97316","#ec4899"],qi=["#14b8a6","#f59e0b","#c084fc","#22c55e","#38bdf8","#ef4444","#e879f9","#84cc16"];function cs(e){let t=2166136261;for(let n=0;n>>0;return t}function Ut(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 zi[cs(i)%zi.length]}function Nt(e,t=""){let n=t.trim().toLowerCase();if(n&&n!=="#8a8a8a")return t;return qi[cs(e)%qi.length]}function ds(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])),o=Math.max(20,t-i*2),a=Math.max(20,n-i*2),c=Math.max(0.05,Math.min(200,Math.min(o/s,a/r)));return{cx:(e[0]+e[2])*0.5,cy:(e[1]+e[3])*0.5,scale:c,fitted:c,touched:!1}}function Ke(e,t,n,i,s){return[i*0.5+(t-e.cx)*e.scale,s*0.5+(n-e.cy)*e.scale]}function dn(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 ps(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 hs(e,t,n,i,s,r){let o=Math.max(0.02,e.fitted*0.35),a=Math.max(40,e.fitted*24),c=Math.max(o,Math.min(a,e.scale*t)),[p,l]=dn(e,n,i,s,r);return{...e,cx:p-(n-s*0.5)/c,cy:l-(i-r*0.5)/c,scale:c,touched:!0}}function ms(e,t,n,i){let s=e.map((o)=>[o[0],o[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 Hn(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 Yr(e,t,n,i,s,r){let o=s-n,a=r-i,c=o*o+a*a;if(c<0.000001)return(e-n)*(e-n)+(t-i)*(t-i);let p=Math.max(0,Math.min(1,((e-n)*o+(t-i)*a)/c)),l=n+p*o,h=i+p*a;return(e-l)*(e-l)+(t-h)*(t-h)}function Ki(e,t,n){if(n.length<3)return!1;let i=!1;for(let s=0,r=n.length-1;st!==p>t&&e<(c-o)*(t-a)/(p-a+0.000000000001)+o)i=!i}return i}function Dn(e,t){return Math.max(5,Math.min(32,e*t))}function pn(e,t,n,i,s,r,o,a,c){if(i){for(let d of e){if(d.layer!==n||d.id!==i||d.locked)continue;let u=d.path??[];for(let f=0;f=3)for(let f=0;f=0;d--){let u=t[d];if(u.layer!==n)continue;let f=u.outline??[];if(!Ki(l,h,f))continue;if(!(u.holes??[]).some((v)=>Ki(l,h,v)))return{kind:"region",id:u.id}}return null}function Mt(e){let t=null,n=null,i=[];for(let r of e){if(!r.layer)continue;i.push(r.layer);let o=r.items??[],a=o.filter((p)=>p.kind==="corridor").length,c=o.filter((p)=>p.kind==="plane").length;if((a>0||r.role==="signal")&&(!t||a>t.count))t={count:a,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 Ji(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 o=1;o=s&&a>0.000000001){let c=(s-r)/a;return[e[o-1][0]+(e[o][0]-e[o-1][0])*c,e[o-1][1]+(e[o][1]-e[o-1][1])*c]}r+=a}return e[e.length-1]}function vt(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 us(e,t,n){if(e==="split"&&n.length>0)return t.filter((i)=>n.includes(i.layer));return t}function Bn(e,t){return!(e[2]<=t[0]||e[0]>=t[2]||e[3]<=t[1]||e[1]>=t[3])}function Yi(e,t,n){if(n.length<3)return!1;let i=!1;for(let s=0,r=n.length-1;st!==p>t&&e<(c-o)*(t-a)/(p-a+0.000000000001)+o)i=!i}return i}function bs(e,t){if(e.length<3)return null;let n=1/0,i=1/0,s=-1/0,r=-1/0,o=0,a=0;for(let p of e)n=Math.min(n,p[0]),i=Math.min(i,p[1]),s=Math.max(s,p[0]),r=Math.max(r,p[1]),o+=p[0],a+=p[1];let c=[[(n+s)*0.5,(i+r)*0.5],[o/e.length,a/e.length]];for(let p of[0.5,0.25,0.75,0.125,0.875])for(let l of[0.5,0.25,0.75,0.125,0.875])c.push([n+(s-n)*l,i+(r-i)*p]);for(let p of c)if(Yi(p[0],p[1],e)&&!t.some((l)=>Yi(p[0],p[1],l)))return p;return null}function gs(e,t,n,i,s,r){let o=[];for(let l of e){let h=l.nets??0,d=l.path??[];if(h<=0||d.length<2)continue;let u=0;for(let f=1;f{let d=l.sel||l.hov?1:0,u=h.sel||h.hov?1:0;if(u!==d)return u-d;if(h.nets!==l.nets)return h.nets-l.nets;return l.b.id.localeCompare(h.b.id)});let a=[],c=[],p=(l,h,d,u,f)=>[l-d*0.5-f,h-u*0.5-f,l+d*0.5+f,h+u*0.5+f];for(let l of o){let h=l.b.name||"",d=String(l.nets),u=h?`${h} · ${l.nets}`:d,f=(l.sel||l.hov||l.pxLen>=95)&&h?[u,d]:[d],b=null,v=(E,k)=>Math.max(k*0.5+3,Math.min(Math.max(k*0.5+3,n-k*0.5-3),E)),w=(E,k)=>Math.max(k*0.5+3,Math.min(Math.max(k*0.5+3,i-k*0.5-3),E));e:for(let E of f){let k=Math.max(16,E.length*5.9+10),L=15;for(let M of[0.5,0.35,0.65,0.22,0.78]){let A=Ji(l.pts,M);if(!A)continue;let[B,T]=Ke(t,A[0],A[1],n,i),H=v(B,k),O=w(T,15),P=p(H,O,k,15,2);if(!a.some((Y)=>Bn(P,Y))){b={id:l.b.id,text:E,cx:H,cy:O,pw:k,ph:15,col:l.col,sel:l.sel};break e}}}if(!b){let E=Ji(l.pts,0.5);if(E){let[k,L]=Ke(t,E[0],E[1],n,i),M=Math.max(16,d.length*6.5+8),A=15,B=v(k,M);for(let T of[-18,18]){let H=w(L+T,15);if(!a.some((O)=>Bn(p(B,H,M,15,2),O))){b={id:l.b.id,text:d,cx:B,cy:H,pw:M,ph:15,col:l.col,sel:l.sel};break}}}}if(b)a.push(p(b.cx,b.cy,b.pw,b.ph,2)),c.push(b)}return c}function fs(e,t,n,i,s,r=[]){let o=new Set(s),a=[];for(let l of e){if(!l.r||!l.b||l.b.length!==4)continue;let[h,d]=Ke(t,l.b[0],l.b[1],n,i),[u,f]=Ke(t,l.b[2],l.b[3],n,i),b=Math.abs(u-h),v=Math.abs(f-d);if(b<13||v<9)continue;let w=(h+u)*0.5,E=(d+f)*0.5;if(w<8||w>n-8||E<8||E>i-8)continue;a.push({text:l.r,cx:w,cy:E,bw:l.r.length*5.8+4,bh:11,score:b*v+(o.has(l.r)?1e4:0)})}a.sort((l,h)=>h.score-l.score);let c=[...r],p=[];for(let l of a){let h=[l.cx-l.bw*0.5,l.cy-l.bh*0.5,l.cx+l.bw*0.5,l.cy+l.bh*0.5];if(!c.some((u)=>Bn(h,u)))c.push(h),p.push({text:l.text,cx:l.cx,cy:l.cy})}return p}function vs(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 hn(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 o=n.get(r.layer);if(o)i.push(o);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 ws(e,t,n,i,s,r,o,a){return e===t&&n===i&&s===r&&(a===void 0||o>=a)}var ys="#111917",Xr="#16201d",Qr="rgba(212, 224, 219, 0.92)",Zr="rgba(61, 80, 73, 0.72)",eo="rgba(82, 107, 97, 0.85)";var Es="#f59e0b",to="#eef5f2",Cs="#ef4444";function wt(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 no(e,t,n){let i=0.14,s=0.45,r=0.85,o=!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,o=!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:o}}function io(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 so(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 Fn{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=hn(e.layers,e.copperLayers);if(t.length===0)return[];if(e.gridMode==="all")return t;if(e.gridMode==="single"){let s=e.shownLayers.find((o)=>t.some((a)=>a.layer===o))??Mt(t)[0]??t[0]?.layer,r=t.find((o)=>o.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):Mt(t),i=[];for(let s of n){let r=t.find((o)=>o.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 ds(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((E)=>E.kind==="plane");s.className="bp-plan-card-bar "+(r?"pwr":"sig");let o=document.createElement("span");o.className="bp-plan-card-title";let a=document.createElement("span");a.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=m("gpui.mgmt.plan.layer","Approve layer"),c.addEventListener("click",(E)=>{E.stopPropagation(),this.cb.onApproveLayer(e.layer,!0)});let p=document.createElement("button");p.type="button",p.className="bp-mgmt-btn bp-plan-mini-btn",p.textContent="✗",p.title=m("gpui.mgmt.plan.rejectlayer","Reject layer"),p.addEventListener("click",(E)=>{E.stopPropagation(),this.cb.onApproveLayer(e.layer,!1)}),i.append(s,o,a,c,p);let l=document.createElement("div");l.className="bp-plan-card-sub",n.append(i,l);let h=document.createElement("div");h.className="bp-plan-card-canvas-wrap";let d=document.createElement("canvas");d.className="bp-plan-card-canvas",d.setAttribute("data-testid",`mgmt-plan-canvas-${e.layer}`);let u=document.createElement("div");u.className="bp-plan-hover-hud bp-hidden",h.append(d,u);let f=document.createElement("div");f.className="bp-plan-legend bp-hidden",t.append(n,h,f);let b=d.getContext("2d"),v=new ResizeObserver(()=>this.scheduleDraw());v.observe(h),this.attachPointerListeners(d,e.layer);let w={layer:e.layer,el:t,canvas:d,ctx:b,legendEl:f,okBtn:c,noBtn:p,statusEl:a,titleEl:o,subtitleEl:l,hoverHudEl:u,ro:v};return this.syncCardHeaderAndLegend(w,e),w}syncCardHeaderAndLegend(e,t){e.titleEl.textContent=vt(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=so(t);e.statusEl.className=`bp-plan-card-status tone-${s.tone==="warn"?"dim":s.tone}`,e.statusEl.textContent=i.length>0?m(s.key,s.label):"",e.statusEl.classList.toggle("bp-hidden",i.length===0);let r=i.some((a)=>a.state==="proposed"||a.state==="edited");if(e.okBtn)e.okBtn.classList.toggle("bp-hidden",!r);if(e.noBtn)e.noBtn.classList.toggle("bp-hidden",!r);let o=(this.state?.regions??[]).filter((a)=>a.layer===t.layer);if(o.length===0)e.legendEl.classList.add("bp-hidden"),e.legendEl.replaceChildren();else{e.legendEl.classList.remove("bp-hidden");let a=document.createDocumentFragment();for(let c of o){let p=document.createElement("button");p.type="button";let l=this.state?.selectedId===c.id;p.className="bp-plan-legend-chip"+(l?" active":"");let h=document.createElement("span");h.className="bp-plan-legend-sw",h.style.background=Ut(c.net||c.id,c.color||"");let d=document.createElement("span");d.textContent=c.net||c.id,p.append(h,d),p.addEventListener("click",()=>{this.cb.onSelect(c.id),this.cb.onFocusItem(c.id)}),a.appendChild(p)}e.legendEl.replaceChildren(a)}}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(),o=i.clientX-r.left,a=i.clientY-r.top,c=Math.max(1,r.width),p=Math.max(1,r.height),l=this.getCam(t,c,p),h=pn(s.bands,s.regions,t,s.selectedId,l,c,p,o,a);if(i.button===2){if(h?.kind==="vertex"){let d=this.getItemPts(h.id,h.isPlane),u=Hn(d,h.idx,h.isPlane);if(u)this.selectedVertex=null,this.cb.onCommitFields(h.id,{[h.isPlane?"outline":"path"]:u})}return}if(i.button!==0)return;if(e.setPointerCapture(i.pointerId),this.downPos={x:i.clientX,y:i.clientY},h?.kind==="vertex"){let d=this.getItemPts(h.id,h.isPlane),u=d.map((f)=>[f[0],f[1]]);this.selectedVertex={id:h.id,idx:h.idx},this.drag={layer:t,kind:"vertex",id:h.id,isPlane:h.isPlane,idx:h.idx,pts:d.map((f)=>[f[0],f[1]]),origPts:u,moved:!1},this.scheduleDraw()}else if(h?.kind==="midpoint"){let d=this.getItemPts(h.id,h.isPlane),u=d.map((v)=>[v[0],v[1]]),f=ms(d,h.segIdx,h.pos,h.isPlane),b=h.isPlane&&h.segIdx+1>=d.length?f.length-1:Math.min(h.segIdx+1,f.length-1);this.selectedVertex={id:h.id,idx:b},this.patchLocalItem(h.id,h.isPlane,f),this.drag={layer:t,kind:"vertex",id:h.id,isPlane:h.isPlane,idx:b,pts:f,origPts:u,moved:!0},this.scheduleDraw()}else this.selectedVertex=null,this.drag={layer:t,kind:"pan",lastX:o,lastY:a}}),e.addEventListener("pointermove",(i)=>{let s=this.state;if(!s)return;let r=e.getBoundingClientRect(),o=i.clientX-r.left,a=i.clientY-r.top,c=Math.max(1,r.width),p=Math.max(1,r.height);if(this.drag&&this.drag.layer===t){if(this.drag.kind==="pan"){let L=this.getCam(t,c,p);this.setCam(t,ps(L,o-this.drag.lastX,a-this.drag.lastY)),this.drag.lastX=o,this.drag.lastY=a,this.scheduleDraw();return}if(this.downPos&&Math.hypot(i.clientX-this.downPos.x,i.clientY-this.downPos.y)<1.5&&!this.drag.moved)return;let b=this.getCam(t,c,p),[v,w]=dn(b,o,a,c,p),E=[Math.round(v*1000)/1000,Math.round(w*1000)/1000];this.drag.moved=!0,this.drag.pts[this.drag.idx]=E;let k=this.drag.pts.map((L)=>[L[0],L[1]]);this.patchLocalItem(this.drag.id,this.drag.isPlane,k),this.scheduleDraw();return}let l=this.getCam(t,c,p),h=pn(s.bands,s.regions,t,s.selectedId,l,c,p,o,a),d=this.hover?.hit?"id"in this.hover.hit?this.hover.hit.id:"":"",u=this.hover?.hit.kind??"",f=h?h.id:"";if(this.hover=h?{layer:t,hit:h}:null,e.style.cursor=h?"pointer":"crosshair",d!==f||(h?.kind??"")!==u)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,o=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&&o&&Math.hypot(i.clientX-o.x,i.clientY-o.y)<4.5){let a=e.getBoundingClientRect(),c=i.clientX-a.left,p=i.clientY-a.top,l=Math.max(1,a.width),h=Math.max(1,a.height),d=this.getCam(t,l,h),u=pn(s.bands,s.regions,t,s.selectedId,d,l,h,c,p);if(u&&(u.kind==="band"||u.kind==="region")){this.cb.onSelect(u.id),this.cb.onFocusItem(u.id);return}if(!u&&s.selectedId){this.cb.onSelect("");return}}this.cb.onDragEnd?.()}),e.addEventListener("wheel",(i)=>{i.preventDefault();let s=e.getBoundingClientRect(),r=i.clientX-s.left,o=i.clientY-s.top,a=Math.max(1,s.width),c=Math.max(1,s.height),p=this.getCam(t,a,c),l=Math.max(0.65,Math.min(1.55,1-i.deltaY*0.002));this.setCam(t,hs(p,l,r,o,a,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((a)=>a.id===i),r=n.regions.find((a)=>a.id===i),o="";if(s)o=`${s.name||i} · ${s.nets??0}n · ${(s.width??1.5).toFixed(2)}mm`;else if(r)o=r.reference?`${r.net||i} · ${r.reference}`:r.net||i;if(!o)t.hoverHudEl.classList.add("bp-hidden");else t.hoverHudEl.classList.remove("bp-hidden"),t.hoverHudEl.textContent=o}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((o)=>o.id===t.selectedId),i=t.regions.find((o)=>o.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 o=e.shiftKey?-0.25:0.25,a=Math.round(Math.max(0.15,Math.min(25,(n.width??1.5)+o))*100)/100;this.cb.onCommitFields(t.selectedId,{width:a})}else if((e.key==="Delete"||e.key==="Backspace")&&!s&&this.selectedVertex?.id===t.selectedId){e.preventDefault();let o=Boolean(i),a=this.getItemPts(t.selectedId,o),c=Hn(a,this.selectedVertex.idx,o);if(c)this.selectedVertex=null,this.cb.onCommitFields(t.selectedId,{[o?"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 o=Math.max(1,window.devicePixelRatio||1),a=Math.round(s*o),c=Math.round(r*o);if(n.canvas.width!==a||n.canvas.height!==c)n.canvas.width=a,n.canvas.height=c;n.ctx.setTransform(o,0,0,o,0,0),this.drawLayer(n.ctx,n.layer,s,r,e)}}drawLayer(e,t,n,i,s){let r=this.getCam(t,n,i),o=(b,v)=>Ke(r,b,v,n,i);e.fillStyle=ys,e.fillRect(0,0,n,i);let a=(s.board.outline??[]).filter((b)=>b.length>=3);if(e.fillStyle=Xr,a.length>0){e.beginPath();for(let b of a){for(let v=0;vb.layer===t),p=this.hover?.layer===t?this.hover.hit:null;for(let b of c){let v=b.outline??[];if(v.length<3)continue;let w=s.selectedId===b.id,E=p?.id===b.id,k=io(b.state||"proposed",w,E),L=Ut(b.net||b.id,b.color||"");e.beginPath();for(let A=0;AT)T=P;if(Y>H)H=Y}if(Math.abs(T-A)>=38&&Math.abs(H-B)>=18){let O=bs(v,b.holes??[]);if(O){let[P,Y]=o(O[0],O[1]);e.fillStyle=wt(L,w?0.91:0.67),e.font="bold 10px ui-monospace, 'SFMono-Regular', Menlo, monospace",e.textAlign="center",e.textBaseline="middle",e.fillText(M,P,Y)}}}}if(e.strokeStyle=Qr,e.lineWidth=1.25,e.lineCap="round",e.lineJoin="round",a.length>0){e.beginPath();for(let b of a){for(let v=0;vb.layer===t),d=gs(h,r,n,i,s.selectedId,p?.id??""),u=d.map((b)=>[b.cx-b.pw*0.5-1,b.cy-b.ph*0.5-1,b.cx+b.pw*0.5+1,b.cy+b.ph*0.5+1]),f=[];for(let b of h){for(let v of b.from??[])f.push(v);for(let v of b.to??[])f.push(v)}e.fillStyle="rgba(143, 163, 155, 0.72)",e.font="9.5px ui-monospace, 'SFMono-Regular', Menlo, monospace",e.textAlign="center",e.textBaseline="middle";for(let b of fs(l,r,n,i,f,u))e.fillText(b.text,b.cx,b.cy);for(let b of h){let v=b.guides??[];if(v.length===0)continue;let w=s.selectedId===b.id||p?.id===b.id,E=Nt(b.name||b.id,b.color||"");e.strokeStyle=wt(E,w?0.38:0.17),e.lineWidth=w?1:0.7,e.beginPath();for(let k of v){let[L,M]=o(k[0],k[1]),[A,B]=o(k[2],k[3]);e.moveTo(L,M),e.lineTo(A,B)}e.stroke()}for(let b of h){let v=b.path??[];if(v.length<2)continue;let w=s.selectedId===b.id,E=p?.id===b.id,k=no(b.state||"proposed",w,E),L=Nt(b.name||b.id,b.color||""),M=Dn(b.width??1.5,r.scale),A=()=>{e.beginPath();for(let B=0;B{let E=w?v.length:Math.max(0,v.length-1);for(let k=0;kn.id===e))return;if(this.openPanel!==e)this.togglePanel(e)}getTabs(){return an(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=an(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 o of t){let a=document.createElement("button");a.type="button";let c=this.openPanel===o.id;a.className="bp-mgmt-tab"+(c?" active":""),a.setAttribute("data-testid",`mgmt-tab-${o.id}`),a.setAttribute("aria-pressed",c?"true":"false");let p=document.createElement("span");p.textContent=he(o.label),a.appendChild(p);let l=this.getPanelData(o.id),h=Xi(l);if(h){let d=document.createElement("span");d.className=`bp-mgmt-badge bp-tone-${h.tone}`,d.textContent=h.text,a.appendChild(d)}a.addEventListener("click",()=>this.togglePanel(o.id)),i.appendChild(a)}if(n.appendChild(i),this.openPanel){let o=document.createElement("button");o.type="button",o.className="icon bp-mgmt-close",o.textContent="×",o.title=m("gpui.mgmt.close","Close the panel"),o.setAttribute("aria-label",m("gpui.mgmt.close","Close the panel")),o.setAttribute("data-testid","mgmt-close"),o.addEventListener("click",()=>this.closePanel()),n.appendChild(o)}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 o=document.createElement("div");o.className="bp-mgmt-note bp-tone-bad",o.textContent=this.errorMsg,r.appendChild(o)}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"),o=t.source==="kicad";if(r.className="bp-mgmt-pill"+(o?" accent":""),r.textContent=o?"live":"saved",i.append(s,r),(t.priced??0)>0&&(t.checking??0)===0&&typeof t.cost==="number"){let p=document.createElement("span");p.className="bp-dim",p.textContent=(t.priced??0)<(t.lookups??0)?`≥ ${At(t.cost)}/board`:`${At(t.cost)}/board`,i.appendChild(p)}if(t.paused){let p=document.createElement("span");p.className="bp-mgmt-faint",p.textContent="Stock check paused",i.appendChild(p)}if(e.appendChild(i),t.stock_note){let p=document.createElement("div");p.className="bp-mgmt-note bp-mgmt-faint",p.textContent=he(t.stock_note),e.appendChild(p)}let a=this.bomEditingId?n.find((p)=>p.id===this.bomEditingId)??null:null;if(a)e.appendChild(this.renderBomEditor(a));else{let p=document.createElement("div");p.className="bp-mgmt-filter-row";let l=document.createElement("input");l.type="text",l.className="bp-mgmt-filter",l.placeholder="Filter BOM (ref, value, footprint, MPN, dnp)…",l.value=this.bomFilter,l.setAttribute("data-testid","mgmt-bom-filter"),l.addEventListener("input",()=>{this.bomFilter=l.value,this.renderBomRows(c,n)}),p.appendChild(l),e.appendChild(p)}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=es(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 o=Array.isArray(r.refs)?r.refs:[],a=document.createElement("div");a.className="bp-mgmt-row"+(this.bomSelectedId===r.id?" active":"")+(r.dnp?" faint":""),a.setAttribute("data-testid",`mgmt-bom-row-${r.id}`);let c=document.createElement("div");c.className="bp-mgmt-row-line";let p=document.createElement("span");if(p.className="bp-mgmt-strong bp-mgmt-flex1",p.textContent=ln(o,24),c.appendChild(p),r.dnp){let b=document.createElement("span");b.className="bp-mgmt-pill",b.textContent=m("gpui.mgmt.bom.dnp","DNP"),c.appendChild(b)}else{let b=Zi(r.stock);if(b){let v=document.createElement("span");v.className=`bp-tone-${b.tone}`,v.textContent=b.text,c.appendChild(v)}}let l=document.createElement("button");l.type="button",l.className="bp-mgmt-btn",l.textContent="Edit",l.addEventListener("click",(b)=>{b.stopPropagation(),this.bomEditGen++,this.bomEditingId=r.id,this.bomEditDraft=r.mpn??"",this.bomEditStatus="",this.bomLastUndo=null,this.render()}),c.appendChild(l);let h=document.createElement("div");h.className="bp-mgmt-row-sub";let d=[`${r.qty??o.length}×`,r.value??"",Qi(r.footprint??"")].filter(Boolean).join(" · "),u=document.createElement("span");u.className="bp-dim",u.textContent=d;let f=document.createElement("span");if(f.className="bp-mgmt-flex1",r.mpn)f.textContent=r.mpn;else if(i&&!r.dnp)f.className+=" bp-tone-warn",f.textContent=m("gpui.mgmt.bom.nompn","no MPN");if(h.append(u,f),!r.dnp&&typeof r.stock?.price==="number"){let b=document.createElement("span");b.className="bp-dim",b.textContent=At(r.stock.price),h.appendChild(b)}if(!r.dnp&&r.stock?.class){let b=document.createElement("span");b.className="bp-mgmt-faint",b.textContent=he(r.stock.class),h.appendChild(b)}a.append(c,h),a.addEventListener("click",()=>{this.bomSelectedId=r.id,this.renderBomRows(e,t)}),s.appendChild(a)}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=ln(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 o=document.createElement("input");o.type="text",o.className="bp-mgmt-filter",o.placeholder="MPN",o.value=this.bomEditDraft,o.addEventListener("input",()=>{this.bomEditDraft=o.value});let a=()=>({watchGen:this.watchGen,editGen:this.bomEditGen,project:this.project,editId:this.bomEditingId}),c=async(d,u=!1)=>{let f=a();this.bomEditStatus="Writing…",this.render();try{let b=await this.cb.hub.rpc("mgmt.bom.edit",d);if(!Rn(f,a()))return;this.bomLastUndo=!u&&(b.changed??0)>0?{project:d.project,editId:f.editId,refs:d.refs.slice(),field:d.field,was:typeof b.was==="string"?b.was:d.field==="mpn"?e.mpn??"":e.dnp?"yes":"no"}:null,this.bomEditStatus=u?"Restored":(b.changed??0)===0?"No change":b.via==="kicad"?"Updated in KiCad":"Saved to schematic"}catch(b){if(!Rn(f,a()))return;this.bomEditStatus=b instanceof Error?b.message:"Could not save edit"}this.render()},p=document.createElement("div");p.className="bp-mgmt-btn-row";let l=document.createElement("button");l.type="button",l.className="primary bp-mgmt-btn",l.textContent="Save MPN",l.addEventListener("click",()=>{c({project:this.project,refs:n.slice(),field:"mpn",value:this.bomEditDraft.trim()})});let h=document.createElement("button");if(h.type="button",h.className="bp-mgmt-btn",h.textContent=e.dnp?"Clear DNP":"Mark DNP",h.addEventListener("click",()=>{c({project:this.project,refs:n.slice(),field:"dnp",value:e.dnp?"no":"yes"})}),p.append(l,h),this.bomLastUndo&&this.bomLastUndo.project===this.project&&this.bomLastUndo.editId===this.bomEditingId){let d=this.bomLastUndo,u=document.createElement("button");u.type="button",u.className="bp-mgmt-btn",u.textContent="Undo",u.addEventListener("click",()=>{c(ls(d),!0)}),p.appendChild(u)}if(t.append(i,o,p),this.bomEditStatus){let d=document.createElement("div");d.className="bp-mgmt-faint",d.textContent=this.bomEditStatus,t.appendChild(d)}return t}renderChecks(){let e=document.createElement("div");e.className="bp-mgmt-body";let t=this.getPanelData("checks");if(!t)return e.appendChild(this.makeEmpty("Reading checks…")),e;let n=Array.isArray(t.groups)?t.groups:[],i=Array.from(new Set(n.map((d)=>d.source).filter(Boolean))),s=(d)=>t.sources?.[d]?.label||d.toUpperCase(),r=(d)=>t.sources?.[d]?.judged===!0,o=document.createElement("div");o.className="bp-mgmt-head bp-mgmt-scroll-x";let a=document.createElement("button");a.type="button",a.className="bp-mgmt-btn"+(this.checksSource===""?" active":""),a.textContent=m("gpui.mgmt.checks.all","All"),a.addEventListener("click",()=>{this.checksSource="",this.render()}),o.appendChild(a);for(let d of i){let u=document.createElement("button");u.type="button",u.className="bp-mgmt-btn"+(this.checksSource===d?" active":""),u.textContent=s(d)+(r(d)?" · judged":""),u.addEventListener("click",()=>{this.checksSource=this.checksSource===d?"":d,this.render()}),o.appendChild(u)}let c=document.createElement("span");c.className="bp-mgmt-flex1";let p=document.createElement("button");if(p.type="button",p.className="bp-mgmt-btn",p.textContent=m("gpui.mgmt.checks.run","Run"),p.addEventListener("click",()=>{let d=this.watchGen,u=this.project;this.checksStatus="Running checks…",this.render(),this.cb.hub.rpc("kicad.checks.run",{project:u}).then(()=>{if(d!==this.watchGen||u!==this.project)return;this.checksStatus="",this.render()}).catch((f)=>{if(d!==this.watchGen||u!==this.project)return;this.checksStatus=f instanceof Error?f.message:"Could not run checks",this.render()})}),o.append(c,p),e.appendChild(o),this.checksStatus){let d=document.createElement("div");d.className="bp-mgmt-note bp-dim",d.textContent=this.checksStatus,e.appendChild(d)}let l=document.createElement("div");l.className="bp-mgmt-rows",l.setAttribute("data-testid","mgmt-checks-rows");let h=ts(n,this.checksSource);if(h.length===0)l.appendChild(this.makeEmpty("No check findings."));else for(let d of h){let u=d.severity==="error"?"bad":d.severity==="warning"?"warn":"faint",f=document.createElement("div");f.className="bp-mgmt-group-head";let b=document.createElement("span");b.className=`bp-mgmt-dot bp-tone-bg-${u}`;let v=document.createElement("span");v.className="bp-mgmt-flex1",v.textContent=`${s(d.source)} · ${d.rule}`;let w=document.createElement("span");w.className=`bp-tone-${u}`,w.textContent=String(d.n),f.append(b,v,w),l.appendChild(f);for(let E of d.rows??[]){let k=document.createElement("div");k.className="bp-mgmt-row"+(this.checksSelectedId===E.id?" active":"");let L=document.createElement("div");if(L.textContent=he(E.title??""),k.appendChild(L),E.names||this.checksSelectedId===E.id){let M=document.createElement("div");M.className="bp-mgmt-row-sub";let A=document.createElement("span");if(A.className="bp-dim bp-mgmt-flex1",A.textContent=E.names??"",M.appendChild(A),this.checksSelectedId===E.id){let B=document.createElement("button");B.type="button",B.className="bp-mgmt-btn accent",B.textContent=m("gpui.mgmt.checks.fix","Fix with agent"),B.addEventListener("click",(T)=>{T.stopPropagation();let H={watchGen:this.watchGen,project:this.project,threadId:this.cb.getThreadId(),threadGen:this.cb.getThreadGen()};this.cb.hub.rpc("kicad.checks.fix",{project:H.project,id:E.id}).then((O)=>{let P={watchGen:this.watchGen,project:this.project,threadId:this.cb.getThreadId(),threadGen:this.cb.getThreadGen()};if(!jn(H,P))return;if(O.text)this.cb.onSendText(O.text),this.checksStatus="Sent to agent",this.render()}).catch((O)=>{let P={watchGen:this.watchGen,project:this.project,threadId:this.cb.getThreadId(),threadGen:this.cb.getThreadGen()};if(!jn(H,P))return;this.checksStatus=O instanceof Error?O.message:"Could not send finding",this.render()})}),M.appendChild(B)}k.appendChild(M)}k.addEventListener("click",()=>{this.checksSelectedId=E.id,this.cb.hub.rpc("kicad.checks.focus",{project:this.project,id:E.id}).catch(()=>{}),this.render()}),l.appendChild(k)}}return e.appendChild(l),e}renderLife(){let e=document.createElement("div");e.className="bp-mgmt-body";let t=this.getPanelData("life");if(!t)return e.appendChild(this.makeEmpty("Reading lifecycle…")),e;let n=document.createElement("div");n.className="bp-mgmt-head";let i=t.counts??{};for(let c of["active","nrnd","eol"]){let p=i[c]??0,l=In(c),h=document.createElement("span");h.className=p>0?`bp-tone-${l.tone}`:"bp-mgmt-faint",h.textContent=`${l.label} ${p}`,n.appendChild(h)}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 p=document.createElement("span");p.className="bp-mgmt-faint",p.textContent=`since ${cn(t.since)} (${t.samples??0})`,n.append(c,p)}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??[],o=t.bom?.instock??[],a=t.bom?.lines??0;if(r.length===0)s.appendChild(this.makeEmpty(a===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],p=o[o.length-1],l=document.createElement("div");l.className="bp-mgmt-note bp-dim",l.textContent=`Parts/board: ${At(c[1])} · ${Math.round(p?.[1]??0)}/${a} lines in stock (${cn(c[0])})`,s.appendChild(l)}for(let c of t.parts??[]){let p=this.lifeSelectedKey===c.key,l=In(c.lifecycle??"unknown"),h=document.createElement("div");h.className="bp-mgmt-row"+(p?" active":"");let d=document.createElement("div");d.className="bp-mgmt-row-line";let u=document.createElement("span");u.className="bp-mgmt-strong",u.textContent=ln(c.refs??[],14);let f=document.createElement("span");f.className="bp-mgmt-flex1 bp-dim",f.textContent=c.mpn||c.key;let b=document.createElement("span");if(b.className=`bp-tone-${l.tone}`,b.textContent=l.label,d.append(u,f,b),typeof c.stock==="number"){let v=document.createElement("span");v.className="bp-dim",v.textContent=Lt(c.stock),d.appendChild(v)}if(h.appendChild(d),p){let v=document.createElement("div");if(v.className="bp-mgmt-row-sub bp-mgmt-faint",this.lifePartLoading)v.textContent=m("gpui.mgmt.life.reading","Reading its history…");else if(this.lifePartSamples&&this.lifePartSamples.length>0){let w=this.lifePartSamples[this.lifePartSamples.length-1];v.textContent=`${this.lifePartSamples.length} samples · latest ${w.at?cn(w.at):""}`+(typeof w.stock==="number"?` · stock ${Lt(w.stock)}`:"")+(typeof w.price==="number"?` · ${At(w.price)}`:"")}else v.textContent=m("gpui.mgmt.life.nopart","No reading of this part yet.");h.appendChild(v)}h.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((v)=>{if(this.lifeSelectedKey!==c.key)return;this.lifePartLoading=!1,this.lifePartSamples=Array.isArray(v.samples)?v.samples:[],this.render()}).catch(()=>{if(this.lifeSelectedKey!==c.key)return;this.lifePartLoading=!1,this.lifePartSamples=[],this.render()})}),s.appendChild(h)}return e.appendChild(s),e}renderPlan(){let e=document.createElement("div");e.className="bp-mgmt-body";let t=this.getPanelData("plan");if(!t)return e.appendChild(this.makeEmpty(m("gpui.mgmt.plan.reading","Reading the routing plan…"))),e;let n=(C,x)=>{let F=this.watchGen,I=this.project;this.planStatus="",this.cb.hub.rpc(C,{pro:I,...x}).catch((J)=>{if(F!==this.watchGen||I!==this.project)return;this.planOptimistic.clear(),this.planStatus=J instanceof Error?J.message:m("gpui.mgmt.plan.refused","KiCad refused"),this.render()})};if(t.revision!==this.planOptimisticRev)this.planOptimisticRev=t.revision,this.planOptimistic.clear();let i=`${this.project}:${t.revision??0}`;if(t.board_trimmed&&this.planHydrateAskedKey!==i&&this.project){this.planHydrateAskedKey=i;let C=this.watchGen,x=++this.planHydrateGen,F=this.project,I=t.revision??0;this.cb.hub.rpc("plan.get",{pro:F,board:!0}).then((J)=>{let se=vs(J);if(!se)return;let Ee=typeof se.revision==="number"?se.revision:I;if(!ws(C,this.watchGen,x,this.planHydrateGen,F,this.project,Ee,this.planHydratedRev))return;this.planHydratedRev=Ee,this.planHydratedKey=`${F}:${Ee}`,this.planHydratedBoard=se.board??null,this.planHydratedDraw=se.draw??null,this.render()}).catch(()=>{})}let s=t.on===!0,r=document.createElement("div");r.className="bp-plan-header";let o=document.createElement("div");o.className="bp-plan-toggle";let a=document.createElement("span");a.className="bp-mgmt-strong",a.textContent=m("gpui.mgmt.plan.before","Plan before routing"),a.title=s?m("gpui.mgmt.plan.onwords","Before routing a board with 4 or more copper layers or more than 60 nets, the agent proposes corridors and plane regions here. It routes only what you approve."):m("gpui.mgmt.plan.offwords","Agents route as you ask. Turn it on to have them propose a routing plan first and route only what you approve here."),o.appendChild(a);let c=t.awaiting??0,p=t.blocked??0,l=t.done??0,h=t.total??0,d=t.revision??0,u=t.empty?[]:rs(t),f=u.reduce((C,x)=>C+x.count,0);if(!t.empty){let C=ss(t),x=document.createElement("span");if(x.className=`bp-plan-status-badge tone-${C.tone}`,x.textContent=m(C.key,C.label),o.appendChild(x),d>0){let I=document.createElement("span");I.className="bp-dim",I.textContent=`v${d}`,o.appendChild(I)}let F=document.createElement("span");if(F.className="bp-plan-header-counts bp-mgmt-flex1 "+(c>0?"bp-tone-warn":p>0?"bp-tone-bad":"bp-dim"),F.textContent=h>0?`${l}/${h} ${m("gpui.mgmt.plan.done","done")}`:c>0?m("web.plan.awaiting","{n} awaiting approval",{n:c}):m("gpui.mgmt.plan.nothing","Nothing awaits your approval"),o.appendChild(F),!t.live){let I=document.createElement("span");I.className="bp-mgmt-pill",I.textContent=m("gpui.mgmt.plan.saved","saved plan"),o.appendChild(I)}}else{let C=document.createElement("span");C.className="bp-mgmt-flex1",o.appendChild(C)}let b=document.createElement("button");b.type="button",b.className="bp-mgmt-btn bp-plan-chip-btn"+(s?" active":""),b.setAttribute("data-testid","mgmt-plan-on"),b.setAttribute("aria-pressed",s?"true":"false"),b.textContent=m("gpui.bots.recall.on","On"),b.addEventListener("click",()=>n("plan.enable",{on:!0}));let v=document.createElement("button");if(v.type="button",v.className="bp-mgmt-btn bp-plan-chip-btn"+(!s?" active":""),v.setAttribute("data-testid","mgmt-plan-off"),v.setAttribute("aria-pressed",!s?"true":"false"),v.textContent=m("gpui.bots.recall.off","Off"),v.addEventListener("click",()=>n("plan.enable",{on:!1})),o.append(b,v),r.appendChild(o),f>0){let C=document.createElement("div");C.className="bp-plan-segbar";for(let x of u){if(x.count<=0)continue;let F=document.createElement("div");F.className=`bp-plan-seg bp-tone-bg-${x.tone}`,F.style.flexGrow=String(x.count),C.appendChild(F)}r.appendChild(C)}e.appendChild(r);for(let C of t.elsewhere??[]){let x=document.createElement("div");x.className="bp-plan-elsewhere";let F=document.createElement("span");F.className="bp-tone-warn bp-mgmt-flex1",F.textContent=m("gpui.mgmt.plan.elsewhere","A routing plan for {board} awaits your approval",{board:C.name||C.rel||""}),x.appendChild(F),e.appendChild(x)}if(t.empty){let C=document.createElement("div");C.className="bp-mgmt-note";let x=document.createElement("div");x.className="bp-dim",x.textContent=m("gpui.mgmt.plan.noboard","No routing plan for this board.");let F=document.createElement("div");return F.className="bp-mgmt-faint",F.textContent=m("gpui.mgmt.plan.emptysub","Layers, corridors, and planes appear here once a plan is proposed."),C.append(x,F),e.appendChild(C),e}let w=t.stackup_summary??"",E=Array.isArray(t.impedances)?t.impedances:[],k=Boolean(w)||E.length>0,L=document.createElement("div");if(L.className="bp-mgmt-head",c>0){let C=document.createElement("button");C.type="button",C.className="primary bp-mgmt-btn",C.setAttribute("data-testid","mgmt-plan-approve-all"),C.textContent=m("gpui.mgmt.plan.all","Approve all"),C.addEventListener("click",()=>n("plan.approve",{layer:"",ids:[],approve:!0})),L.appendChild(C)}if(t.routing){let C=document.createElement("button");C.type="button",C.className="bp-mgmt-btn",C.setAttribute("data-testid","mgmt-plan-stop"),C.textContent=m("gpui.mgmt.plan.stop","Stop routing"),C.addEventListener("click",()=>n("plan.stop",{})),L.appendChild(C)}if(t.live&&l>0){let C=document.createElement("button");C.type="button",C.className="bp-mgmt-btn",C.setAttribute("data-testid","mgmt-plan-verify"),C.textContent=m("gpui.mgmt.plan.verify","Verify"),C.addEventListener("click",()=>n("plan.verify",{})),L.appendChild(C)}let M=document.createElement("span");if(M.className="bp-mgmt-flex1",L.appendChild(M),k){let C=document.createElement("button");C.type="button",C.className="bp-mgmt-btn bp-plan-chip-btn"+(this.planStackupOpen?" active":""),C.setAttribute("data-testid","mgmt-plan-stackup-toggle"),C.setAttribute("aria-expanded",this.planStackupOpen?"true":"false"),C.textContent=`${m("gpui.mgmt.plan.stackup.short","Stackup")} ${this.planStackupOpen?"▾":"▸"}`,C.addEventListener("click",()=>{this.planStackupOpen=!this.planStackupOpen,this.render()}),L.appendChild(C)}let A=document.createElement("button");A.type="button",A.className="bp-mgmt-btn",A.setAttribute("data-testid","mgmt-plan-hide"),A.textContent=this.planHideDone?m("gpui.mgmt.plan.show","Show done"):m("gpui.mgmt.plan.hide","Hide done"),A.addEventListener("click",()=>{this.planHideDone=!this.planHideDone,this.render()}),L.appendChild(A),e.appendChild(L);let B=Array.isArray(t.asks)?t.asks:[];if(B.length>0){let C=B.map((se)=>se.what||"").filter(Boolean).join(", "),x=B[0]?.note||"",F=document.createElement("div");F.className="bp-plan-elsewhere";let I=document.createElement("div");I.className="bp-plan-ask-col";let J=document.createElement("div");if(J.className="bp-tone-warn",J.textContent=C?m("gpui.mgmt.plan.requested","Approval requested: {what}",{what:C}):m("gpui.mgmt.plan.reqplain","Approval requested"),I.appendChild(J),x){let se=document.createElement("div");se.className="bp-dim",se.textContent=x,I.appendChild(se)}F.appendChild(I),e.appendChild(F)}if(this.planStatus){let C=document.createElement("div");C.className="bp-mgmt-note bp-plan-err bp-tone-bad";let x=document.createElement("span");x.className="bp-mgmt-flex1",x.textContent=this.planStatus==="KiCad refused"?m("gpui.mgmt.plan.refused","KiCad refused"):he(this.planStatus);let F=document.createElement("button");F.type="button",F.className="icon",F.textContent="×",F.title=m("common.close","Close"),F.addEventListener("click",()=>{this.planStatus="",this.render()}),C.append(x,F),e.appendChild(C)}if(t.keys_note){let C=document.createElement("div");C.className="bp-mgmt-note bp-dim";let x="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.";C.textContent=t.keys_note===x?m("gpui.mgmt.plan.keysnote",x):he(t.keys_note),e.appendChild(C)}if(k&&this.planStackupOpen){let C=document.createElement("div");if(C.className="bp-plan-stackup-body",C.setAttribute("data-testid","mgmt-plan-stackup-body"),w){let x=document.createElement("div");x.className="bp-dim",x.textContent=w,C.appendChild(x)}for(let x of E){let F=document.createElement("div");F.className="bp-mgmt-faint",F.textContent=`· ${x}`,C.appendChild(F)}e.appendChild(C)}let T=(C,x,F,I)=>{let J=document.createElement("button");return J.type="button",J.className="bp-mgmt-btn bp-plan-chip-btn"+(x?" active":""),J.setAttribute("data-testid",F),J.setAttribute("aria-pressed",x?"true":"false"),J.textContent=C,J.addEventListener("click",I),J},H=document.createElement("div");if(H.className="bp-plan-viewbar",H.append(T(m("gpui.mgmt.plan.view.canvas","Canvas"),this.planViewMode==="canvas","mgmt-plan-view-canvas",()=>{this.planViewMode="canvas",this.render()}),T(m("gpui.mgmt.plan.view.split","Split"),this.planViewMode==="split","mgmt-plan-view-split",()=>{this.planViewMode="split",this.render()}),T(m("gpui.mgmt.plan.view.list","List"),this.planViewMode==="list","mgmt-plan-view-list",()=>{this.planViewMode="list",this.render()})),this.planViewMode!=="list"){let C=document.createElement("span");C.className="bp-plan-sep";let x=document.createElement("span");x.className="bp-plan-sep";let F=document.createElement("button");F.type="button",F.className="bp-mgmt-btn bp-plan-mini-btn",F.setAttribute("data-testid","mgmt-plan-fit"),F.textContent=m("gpui.mgmt.plan.fit","Fit"),F.addEventListener("click",()=>this.planCanvas?.fitAll()),H.append(C,T(m("gpui.mgmt.plan.grid.pair","Side by side"),this.planGridMode==="pair","mgmt-plan-grid-pair",()=>{this.planGridMode="pair",this.render()}),T(m("gpui.mgmt.plan.grid.all","All layers"),this.planGridMode==="all","mgmt-plan-grid-all",()=>{this.planGridMode="all",this.render()}),T(m("gpui.mgmt.plan.grid.single","Single"),this.planGridMode==="single","mgmt-plan-grid-single",()=>{this.planGridMode="single",this.render()}),x,T(m("gpui.mgmt.plan.sync","Link zoom"),this.planSyncZoom,"mgmt-plan-sync",()=>{this.planSyncZoom=!this.planSyncZoom,this.render()}),F)}let O=document.createElement("span");O.className="bp-mgmt-flex1";let P=document.createElement("button");P.type="button",P.className="bp-mgmt-btn bp-plan-mini-btn",P.setAttribute("data-testid","mgmt-plan-expand"),P.textContent=this.planExpanded?m("gpui.mgmt.plan.compact","Compact"):m("gpui.mgmt.plan.expand","Expand"),P.addEventListener("click",()=>{this.planExpanded=!this.planExpanded,this.render()}),H.append(O,P),e.appendChild(H);let Y=Boolean(this.planHydratedBoard)&&this.planHydratedKey.startsWith(`${this.project}:`)&&(this.planHydratedKey===i||this.planHydratedRev!==void 0&&this.planHydratedRev>=(t.revision??0)),re=Y&&this.planHydratedBoard?this.planHydratedBoard:t.board??{bbox:[0,0,100,70],outline:[],parts:[]},ie=Y&&this.planHydratedDraw?this.planHydratedDraw:t.draw??{bands:[],regions:[]},me=(ie.bands??[]).map((C)=>{let x=this.planOptimistic.get(C.id);if(!x)return{...C};return{...C,...x,edited:!0,state:C.state==="proposed"?"edited":C.state}}),Pe=(ie.regions??[]).map((C)=>{let x=this.planOptimistic.get(C.id);if(!x)return{...C};return{...C,...x,edited:!0,state:C.state==="proposed"?"edited":C.state}}),Ce=[],te=(t.layers??[]).map((C)=>{let x=[];for(let F of C.items??[]){let I=this.planOptimistic.get(F.id);if(!I){x.push(F);continue}let J={...F,width:typeof I.width==="number"?I.width:F.width,locked:typeof I.locked==="boolean"?I.locked:F.locked,edited:!0,state:F.state==="proposed"?"edited":F.state};if(typeof I.layer==="string"&&I.layer!==C.layer)Ce.push({target:I.layer,item:J});else x.push(J)}return{...C,items:x}});for(let C of Ce){let x=te.find((F)=>F.layer===C.target);if(x)x.items=[...x.items??[],C.item]}let oe=hn(te,t.copper_layers),R=this.planGridMode==="all"?oe.map((C)=>C.layer):this.planGridMode==="single"?[this.planShownLayers.find((C)=>oe.some((x)=>x.layer===C))??Mt(oe)[0]??oe[0]?.layer??""].filter(Boolean):this.planShownLayers.length>0&&this.planShownLayers.every((C)=>oe.some((x)=>x.layer===C))?this.planShownLayers.slice(0,2):Mt(oe);if(this.planViewMode!=="list"&&this.planGridMode!=="all"&&oe.length>1){let C=document.createElement("div");C.className="bp-plan-layerbar";for(let x of oe){let F=R.includes(x.layer),I=(x.items??[]).length,J=vt(x.layer,t.copper_layers,oe)||x.title||x.layer,se=I>0?`${J} · ${I}`:J,Ee=T(se,F,`mgmt-plan-layerpill-${x.layer}`,()=>{if(this.planGridMode==="single")this.planShownLayers=[x.layer];else if(this.planGridMode==="pair"){if(!R.includes(x.layer))this.planShownLayers=R.length>=2?[R[0],x.layer]:[...R,x.layer]}else this.planGridMode="single",this.planShownLayers=[x.layer];this.render()});if(I===0&&!F)Ee.classList.add("empty-layer");C.appendChild(Ee)}e.appendChild(C)}let ue=(C,x)=>{let F=this.planOptimistic.get(C)??{};if(this.planOptimistic.set(C,{...F,...x}),typeof x.layer==="string"){if(this.planGridMode==="single")this.planShownLayers=[x.layer];else if(this.planGridMode==="pair"&&!R.includes(x.layer))this.planShownLayers=R.length>=2?[R[0],x.layer]:[...R,x.layer]}let I=typeof t.revision==="number"?t.revision:void 0;this.render(),n("plan.update",{ops:[{op:"set",id:C,fields:x}],...I!==void 0?{base:I}:{}})};if(this.planCommitFields=ue,this.planSelectedId){let C="",x=null;for(let F of te){let I=(F.items??[]).find((J)=>J.id===this.planSelectedId);if(I){C=F.layer,x=I;break}}if(x){let F=vt(C,t.copper_layers,oe),I=document.createElement("div");I.className="bp-plan-inspector",I.setAttribute("data-testid","mgmt-plan-inspector");let J=document.createElement("div");J.className="bp-plan-ins-row";let se=document.createElement("span");se.className="bp-plan-ins-sw",se.style.background=x.kind==="corridor"?Nt(x.name||x.id,x.color||""):Ut(x.name||x.id,x.color||"");let Ee=document.createElement("span");Ee.className="bp-mgmt-strong",Ee.textContent=x.name||x.id;let D=document.createElement("span");if(D.className="bp-dim",D.textContent=F,J.append(se,Ee,D),x.edited||x.state==="edited"){let K=document.createElement("span");K.className="bp-plan-ins-pill warn",K.textContent=m("gpui.mgmt.plan.edited","Edited"),J.appendChild(K)}if(x.locked){let K=document.createElement("span");K.className="bp-plan-ins-pill",K.textContent=m("gpui.mgmt.plan.locked","Locked"),J.appendChild(K)}let ne=document.createElement("span");ne.className="bp-mgmt-flex1",J.appendChild(ne);let Te=document.createElement("button");if(Te.type="button",Te.className="bp-mgmt-btn bp-plan-mini-btn",Te.setAttribute("data-testid","mgmt-plan-lock"),Te.textContent=x.locked?m("gpui.mgmt.plan.unlock","Unlock"):m("gpui.mgmt.plan.lock","Lock"),Te.addEventListener("click",()=>ue(x.id,{locked:!x.locked})),J.appendChild(Te),x.state==="proposed"||x.state==="edited"){let K=document.createElement("button");K.type="button",K.className="primary bp-mgmt-btn bp-plan-mini-btn",K.textContent=m("android.hub.machines.approve","Approve"),K.addEventListener("click",()=>n("plan.approve",{layer:"",ids:[x.id],approve:!0}));let fe=document.createElement("button");fe.type="button",fe.className="bp-mgmt-btn bp-plan-mini-btn",fe.textContent=m("gpui.mgmt.plan.reject","Reject"),fe.addEventListener("click",()=>n("plan.approve",{layer:"",ids:[x.id],approve:!1})),J.append(K,fe)}let Le=document.createElement("button");Le.type="button",Le.className="bp-mgmt-btn bp-plan-mini-btn",Le.setAttribute("data-testid","mgmt-plan-note-toggle"),Le.textContent=m("gpui.mgmt.plan.addnote","Add note"),Le.addEventListener("click",()=>{this.planNoteOpen=!this.planNoteOpen,this.render()});let Be=document.createElement("button");if(Be.type="button",Be.className="icon",Be.textContent="×",Be.addEventListener("click",()=>{this.planSelectedId="",this.planNoteOpen=!1,this.planMoveLayerOpen=!1,this.render()}),J.append(Le,Be),I.appendChild(J),!x.locked){let K=document.createElement("div");if(K.className="bp-plan-ins-row",x.kind==="corridor"){let le=typeof x.width==="number"?x.width:1.5,He=document.createElement("span");He.className="bp-dim",He.textContent=m("gpui.mgmt.plan.width","Width");let $e=document.createElement("button");$e.type="button",$e.className="bp-mgmt-btn bp-plan-mini-btn",$e.setAttribute("data-testid","mgmt-plan-w-down"),$e.textContent="-",$e.addEventListener("click",()=>{let ze=Math.round(Math.max(0.15,le-0.25)*100)/100;ue(x.id,{width:ze})});let Oe=document.createElement("span");Oe.className="bp-plan-ins-val",Oe.textContent=`${le.toFixed(2)}mm`;let Ne=document.createElement("button");Ne.type="button",Ne.className="bp-mgmt-btn bp-plan-mini-btn",Ne.setAttribute("data-testid","mgmt-plan-w-up"),Ne.textContent="+",Ne.addEventListener("click",()=>{let ze=Math.round(Math.min(25,le+0.25)*100)/100;ue(x.id,{width:ze})});let We=document.createElement("span");We.className="bp-plan-sep",K.append(He,$e,Oe,Ne,We)}let fe=(t.copper_layers??[]).length>0?(t.copper_layers??[]).map((le)=>le.layer):te.map((le)=>le.layer);if(fe.length>0){let le=document.createElement("span");le.className="bp-dim",le.textContent=m("gpui.mgmt.plan.layer.short","Layer"),K.appendChild(le),K.appendChild(T(`${F} ${this.planMoveLayerOpen?"▴":"▾"}`,this.planMoveLayerOpen,"mgmt-plan-move-toggle",()=>{this.planMoveLayerOpen=!this.planMoveLayerOpen,this.render()}))}if(I.appendChild(K),this.planMoveLayerOpen&&fe.length>0){let le=document.createElement("div");le.className="bp-plan-ins-row";for(let He of fe){let $e=vt(He,t.copper_layers,oe);le.appendChild(T($e,He===C,`mgmt-plan-move-${He}`,()=>{if(this.planMoveLayerOpen=!1,He!==C)ue(x.id,{layer:He});else this.render()}))}I.appendChild(le)}}if(this.planNoteOpen){let K=document.createElement("form");K.className="bp-plan-note-form";let fe=document.createElement("input");fe.type="text",fe.className="bp-plan-note-input",fe.setAttribute("data-testid","mgmt-plan-note-input"),fe.placeholder=m("gpui.mgmt.plan.note.placeholder","Steering note for router…");let le=document.createElement("button");le.type="submit",le.className="primary bp-mgmt-btn bp-plan-mini-btn",le.setAttribute("data-testid","mgmt-plan-note-submit"),le.textContent=m("gpui.mgmt.plan.addnote","Add note"),K.append(fe,le),K.addEventListener("submit",(He)=>{He.preventDefault();let $e=fe.value.trim();if(!$e)return;fe.value="",this.planNoteOpen=!1;let Oe=typeof t.revision==="number"?t.revision:void 0;this.render(),n("plan.update",{ops:[{op:"note",target:x.id,text:$e}],...Oe!==void 0?{base:Oe}:{}})}),I.appendChild(K)}if(this.planViewMode!=="list"&&!x.locked){let K=document.createElement("div");K.className="bp-plan-hint",K.textContent=m("gpui.mgmt.plan.hint","Drag waypoints to steer · Click + on edge to insert · Right-click vertex to remove"),I.appendChild(K)}e.appendChild(I)}}let de=document.createElement("div");de.className="bp-mgmt-rows"+(this.planViewMode==="split"?" bp-plan-split-list":""),de.setAttribute("data-testid","mgmt-plan-rows");let ee=m("gpui.mgmt.plan.done","done"),ge=us(this.planViewMode,te,R);if(this.planViewMode==="split"&&ge.length===0){let C=document.createElement("div");C.className="bp-dim",C.style.padding="6px 8px",C.style.fontSize="11px",C.textContent=m("gpui.mgmt.plan.noitems","No corridors or planes on this layer"),de.appendChild(C)}for(let C of ge){let x=C.items??[],F=vt(C.layer,t.copper_layers,oe)||C.layer;if(this.planViewMode==="split"){if(ge.length>1){let I=document.createElement("div");I.className="bp-plan-split-divider";let J=C.role==="power"||C.role==="plane",se=document.createElement("span");se.className="bp-plan-card-bar "+(J?"pwr":"sig");let Ee=document.createElement("span");Ee.className="bp-mgmt-strong",Ee.textContent=F;let D=document.createElement("span");D.className="bp-dim",D.textContent=`${C.done??0}/${x.length} ${ee}`,I.append(se,Ee,D),de.appendChild(I)}}else{let I=document.createElement("div");I.className="bp-mgmt-group-head bp-plan-layer-head";let J=document.createElement("div");J.className="bp-mgmt-row-line";let se=document.createElement("span");se.className="bp-mgmt-strong",se.textContent=F;let Ee=document.createElement("span");if(Ee.className="bp-dim bp-mgmt-flex1",Ee.textContent=`${C.role?`${C.role} · `:""}${C.done??0}/${x.length} ${ee}`,J.append(se,Ee),C.status!=="approved"&&x.length>0){let D=document.createElement("button");D.type="button",D.className="bp-mgmt-btn",D.textContent=m("gpui.mgmt.plan.layer","Approve layer"),D.addEventListener("click",()=>n("plan.approve",{layer:C.layer,ids:[],approve:!0}));let ne=document.createElement("button");ne.type="button",ne.className="bp-mgmt-btn",ne.textContent=m("gpui.mgmt.plan.reject","Reject"),ne.addEventListener("click",()=>n("plan.approve",{layer:C.layer,ids:[],approve:!1})),J.append(D,ne)}if(I.appendChild(J),C.stackup){let D=document.createElement("div");D.className="bp-plan-layer-stackup",D.textContent=C.stackup,I.appendChild(D)}de.appendChild(I)}for(let I of x){if(this.planHideDone&&ns(I))continue;let J=this.planSelectedId===I.id,se=document.createElement("div");se.className="bp-mgmt-row bp-plan-row"+(J?" active":""),se.setAttribute("data-testid",`mgmt-plan-row-${I.id}`);let Ee=document.createElement("div");Ee.className="bp-mgmt-row-line";let D=document.createElement("span");D.className=`bp-plan-swatch bp-plan-st-${I.state||"proposed"}`,D.style.setProperty("--swatch-color",I.color||"#8a8a8a");let ne=document.createElement("span");ne.className="bp-mgmt-flex1"+(I.state==="blocked"||I.state==="failed"?" bp-tone-bad":I.state==="edited"?" bp-tone-warn":I.state==="rejected"||I.state==="routed"||I.state==="verified"?" bp-dim":""),ne.textContent=`${I.name||I.id}${I.locked?" \uD83D\uDD12":""}`;let Te=[];if(I.kind==="plane"){if(I.reference)Te.push(m("gpui.mgmt.plan.reference","over {layer}",{layer:I.reference}))}else{let K=I.nets??0;Te.push(K===1?m("web.plan.net.one","1 net"):m("web.plan.nets","{n} nets",{n:K}))}if(typeof I.width==="number"&&Number.isFinite(I.width))Te.push(`${I.width.toFixed(2)}mm`);if(I.impedance)Te.push(I.impedance);let Le=Te.join(" · "),Be=document.createElement("span");if(Be.className="bp-plan-mark "+(I.state==="blocked"||I.state==="failed"?"bp-tone-bad":I.state==="verified"||I.state==="routed"?"bp-tone-ok":I.state==="approved"?"bp-tone-accent":"bp-dim"),Be.textContent=is(I),Ee.append(D,ne,Be),I.state==="proposed"||I.state==="edited"){let K=document.createElement("button");K.type="button",K.className="bp-mgmt-btn",K.textContent="✓",K.title=m("gpui.mgmt.plan.layer","Approve layer"),K.addEventListener("click",(le)=>{le.stopPropagation(),n("plan.approve",{layer:"",ids:[I.id],approve:!0})});let fe=document.createElement("button");fe.type="button",fe.className="bp-mgmt-btn",fe.textContent="✗",fe.title=m("gpui.mgmt.plan.reject","Reject"),fe.addEventListener("click",(le)=>{le.stopPropagation(),n("plan.approve",{layer:"",ids:[I.id],approve:!1})}),Ee.append(K,fe)}if(se.appendChild(Ee),Le){let K=document.createElement("div");K.className="bp-mgmt-row-sub bp-plan-detail bp-dim",K.textContent=Le,se.appendChild(K)}if(I.state==="routing"&&typeof I.total==="number"&&I.total>0){let K=document.createElement("div");K.className="bp-plan-microbar";let fe=document.createElement("div");fe.className="bp-plan-microbar-fill";let le=Math.max(0,Math.min(100,Math.round((I.routed??0)/I.total*100)));fe.style.width=`${le}%`,K.appendChild(fe),se.appendChild(K)}if(I.problem_text){let K=document.createElement("div");K.className="bp-plan-problem",K.textContent=I.problem_text,se.appendChild(K)}se.addEventListener("click",()=>{this.planSelectedId=I.id,n("plan.focus",{id:I.id}),this.render()}),de.appendChild(se)}}if(this.planViewMode!=="list"){if(!this.planCanvas)this.planCanvas=new Fn({onSelect:(I)=>{if(this.planSelectedId=I,!I)this.planNoteOpen=!1;this.render()},onFocusItem:(I)=>{n("plan.focus",{id:I})},onDragEnd:()=>{if(this.planRenderDeferred)this.planRenderDeferred=!1,this.render()},onCommitFields:(I,J)=>{(this.planCommitFields??ue)(I,J)},onApproveLayer:(I,J)=>{n("plan.approve",{layer:I,ids:[],approve:J})},onQuickApprove:(I,J)=>{n("plan.approve",{layer:"",ids:I,approve:J})}});let C=this.panelEl.parentElement?.classList.contains("bp-has-viewer")===!1,x=this.planExpanded||this.panelEl.clientWidth>=540||C;this.planCanvas.update({gridMode:this.planGridMode,syncZoom:this.planSyncZoom,shownLayers:R,selectedId:this.planSelectedId,board:re,bands:me,regions:Pe,layers:oe,copperLayers:t.copper_layers},x);let F=document.createElement("div");F.className="bp-plan-canvas-scroll",F.appendChild(this.planCanvas.root),e.appendChild(F)}if(this.planViewMode!=="canvas")e.appendChild(de);if((t.draw?.bands?.length??0)>0||(t.draw?.regions?.length??0)>0){let C=document.createElement("div");C.className="bp-plan-footer",C.textContent=m("gpui.mgmt.plan.drawn","The plan's corridors and planes are drawn on the board while this panel is open. Close it to hide them."),e.appendChild(C)}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 E=document.createElement("div");return E.className="bp-mgmt-note bp-tone-warn",E.textContent=t.error,e.appendChild(E),e}let n=(E,k={})=>{let L=this.watchGen,M=this.project;this.fabStatus="",this.cb.hub.rpc("fab.profile",{pro:M,action:E,...k}).catch((A)=>{if(L!==this.watchGen||M!==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=m("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}`:""} · ${as(t.tier??"")}`;let o=document.createElement("button");if(o.type="button",o.className="bp-mgmt-btn",o.textContent=m("gpui.mgmt.fab.refresh","Refresh"),o.addEventListener("click",()=>n("refresh")),i.append(s,r,o),e.appendChild(i),this.fabStatus){let E=document.createElement("div");E.className="bp-mgmt-note bp-tone-bad",E.textContent=this.fabStatus,e.appendChild(E)}let a=document.createElement("div");a.className="bp-mgmt-rows",a.setAttribute("data-testid","mgmt-fab-rows");let c=t.review,p=document.createElement("div");p.className="bp-mgmt-row";let l=document.createElement("div");l.className="bp-mgmt-row-line";let h=document.createElement("span"),d=(c?.counts?.error??0)>0;if(h.className="bp-mgmt-flex1 "+(d?"bp-tone-bad":"bp-dim"),h.textContent=c?.running?"Reviewing the design…":c?.at==null?"No design review yet":`${c.counts?.error??0} must-fix · ${c.counts?.warning??0} should-fix · ${c.counts?.info??0} notes${c.scope?` (${c.scope})`:""}`,l.appendChild(h),c?.at!=null){let E=document.createElement("button");E.type="button",E.className="bp-mgmt-btn",E.textContent=m("gpui.mgmt.fab.findings","Findings"),E.addEventListener("click",()=>this.togglePanel("checks")),l.appendChild(E)}if(!c?.running){let E=document.createElement("button");E.type="button",E.className="bp-mgmt-btn",E.textContent=m("gpui.mgmt.fab.reviewbtn","Review"),E.addEventListener("click",()=>n("review")),l.appendChild(E)}if(c?.judge){let E=document.createElement("button");E.type="button",E.className="bp-mgmt-btn",E.textContent=m("gpui.mgmt.fab.judge","Datasheets"),E.addEventListener("click",()=>{if(c.judge)this.cb.onSendText(c.judge)}),l.appendChild(E)}p.appendChild(l),a.appendChild(p);let u=os(t.drc?.state??""),f=document.createElement("div");f.className="bp-mgmt-row";let b=document.createElement("div");b.className="bp-mgmt-row-line";let v=document.createElement("span");if(v.className="bp-mgmt-flex1 "+(u.button?"bp-tone-warn":"bp-dim"),v.textContent=u.text,b.appendChild(v),u.button){let E=document.createElement("button");E.type="button",E.className="bp-mgmt-btn",E.textContent=u.button,E.addEventListener("click",()=>n("drc")),b.appendChild(E)}f.appendChild(b),a.appendChild(f);for(let E of t.conflicts??[]){let k=document.createElement("div");k.className="bp-mgmt-row bp-tone-bad",k.textContent=E,a.appendChild(k)}for(let E of t.suggestions??[]){let k=document.createElement("div");k.className="bp-mgmt-row";let L=document.createElement("div");L.className="bp-mgmt-row-line";let M=document.createElement("span");M.className="bp-mgmt-flex1 bp-tone-warn",M.textContent=`${E.label||E.key}: board ${E.project??"?"} mm, fab ${E.fab??"?"} mm`;let A=document.createElement("button");A.type="button",A.className="bp-mgmt-btn",A.textContent=m("gpui.mgmt.fab.apply","Apply"),A.addEventListener("click",()=>n("apply",{key:E.key})),L.append(M,A),k.appendChild(L),a.appendChild(k)}if(t.stackup?.chosen){let E=document.createElement("div");E.className="bp-mgmt-row";let k=document.createElement("div");k.className="bp-mgmt-row-line";let L=t.stackup.by==="proposed",M=document.createElement("span");if(M.className="bp-mgmt-flex1 "+(L?"bp-tone-warn":"bp-dim"),M.textContent=`${L?"Proposed: ":""}${t.stackup.chosen}${t.stackup.outer_50_mm?` (50Ω ${t.stackup.outer_50_mm} mm)`:""}`,k.appendChild(M),L){let A=t.stackup.chosen,B=document.createElement("button");B.type="button",B.className="bp-mgmt-btn",B.textContent=m("gpui.mgmt.fab.use","Use"),B.addEventListener("click",()=>n("stackup",{id:A})),k.appendChild(B)}E.appendChild(k),a.appendChild(E)}if(Array.isArray(t.changed)&&t.changed.length>0){let E=document.createElement("div");E.className="bp-mgmt-row";let k=document.createElement("div");k.className="bp-mgmt-row-line";let L=document.createElement("span");L.className="bp-mgmt-flex1 bp-tone-warn",L.textContent=m("gpui.mgmt.fab.changed","Changed since you last looked");let M=document.createElement("button");M.type="button",M.className="bp-mgmt-btn",M.textContent=m("gpui.mgmt.fab.seen","Seen"),M.addEventListener("click",()=>n("seen")),k.append(L,M),E.appendChild(k);for(let A of t.changed.slice(0,12)){let B=document.createElement("div");B.className="bp-mgmt-faint",B.textContent=A,E.appendChild(B)}a.appendChild(E)}let w=Array.isArray(t.limits)?t.limits:[];if(w.length>0){let E=document.createElement("div");E.className="bp-mgmt-group-head";let k=document.createElement("span");k.className="bp-mgmt-flex1",k.textContent=m("gpui.mgmt.fab.limit","Limit");let L=document.createElement("span");L.className="bp-mgmt-col",L.textContent=m("gpui.mgmt.fab.free","Base price");let M=document.createElement("span");M.className="bp-mgmt-col",M.textContent=m("gpui.mgmt.fab.extra","Costs more");let A=document.createElement("span");A.className="bp-mgmt-col bp-mgmt-col-read",A.textContent=m("gpui.mgmt.fab.readcol","Read"),E.append(k,L,M,A),a.appendChild(E);for(let T of w){let H=document.createElement("div");H.className="bp-mgmt-row";let O=document.createElement("div");O.className="bp-mgmt-row-line";let P=document.createElement("span");P.className="bp-mgmt-flex1"+(T.changed?" bp-tone-warn":T.inherited?" bp-dim":""),P.textContent=`${T.changed?"• ":""}${T.label??""}`;let Y=document.createElement("span");Y.className="bp-mgmt-col",Y.textContent=T.free?.text||"—";let re=document.createElement("span");re.className="bp-mgmt-col bp-dim",re.textContent=T.extra?.text||"—";let ie=T.free&&typeof T.free==="object"?T.free:T.extra,me=ie?.fetched??"",Pe=Boolean(me)&&ie?.confidence!=="published",Ce=me?Pe?`${me}*`:me:"—",te=ie?.source??"",oe;if(te.startsWith("https://")&&me){let R=document.createElement("a");R.className="bp-mgmt-col bp-mgmt-col-read bp-mgmt-read-link",R.href=te,R.target="_blank",R.rel="noopener noreferrer",R.textContent=Ce,oe=R}else{let R=document.createElement("span");R.className="bp-mgmt-col bp-mgmt-col-read bp-mgmt-faint",R.textContent=Ce,oe=R}O.append(P,Y,re,oe),H.appendChild(O),a.appendChild(H)}let B=document.createElement("div");B.className="bp-mgmt-note bp-mgmt-faint",B.textContent=m("gpui.mgmt.fab.derived","* worked out from the fab's page. Dimmed: the rigid board's value. A date opens the source page."),a.appendChild(B)}return e.appendChild(a),e}makeEmpty(e){let t=document.createElement("div");return t.className="bp-mgmt-note bp-mgmt-faint",t.textContent=e,t}}var ro={trs:(e)=>e,t:(e,t)=>t},oo=new Set(["/settle"]);function ks(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((o)=>o.startsWith(n)))return 2;let r=0;for(let o=0;o0||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 Ps(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 Ss(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 Ls(e,t=ro){let{t:n,trs:i}=t,s=[],r=new Map;for(let a of e.projects)r.set(a.id,a.title||a.id);let o=e.threads.find((a)=>a.id===e.selectedThreadId)??null;for(let a of e.railItems){if(a.state==="disabled"||a.id==="commands")continue;if(!o&&a.id!=="terminal")continue;s.push({label:i(a.label),place:a.id==="terminal"?"":"viewer",kind:"action",shortcut:a.key?a.key.toUpperCase():void 0,action:{type:"rail",id:a.id}})}if(o){if(s.push({label:o.pinned?n("menu.unpin","Unpin"):n("menu.pin","Pin"),place:"",kind:"action",action:{type:"thread-act",action:o.pinned?"unpin":"pin"}}),s.push({label:o.settled?n("phone.unsettle","Unsettle"):n("menu.settle","Settle"),place:"",kind:"action",action:{type:"thread-act",action:o.settled?"unsettle":"settle"}}),s.push({label:o.archived?n("palette.unarchive","Unarchive"):n("palette.archive","Archive"),place:"",kind:"action",action:{type:"thread-act",action:o.archived?"unarchive":"archive"}}),o.project==="chats")s.push({label:n("chats.move","Move to project…"),place:"",kind:"action",action:{type:"move-project"}});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(o)for(let a of e.commands){if(!a.word)continue;let c=oo.has(a.word.toLowerCase());s.push({label:a.label?`${a.word} — ${a.label}`:a.word,place:a.desc||"command",kind:"command",action:{type:"command",word:a.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"}}),s.push({label:n("chats.new.noproject","New chat (no project)"),place:"",kind:"action",action:{type:"new-chat"}});for(let a of e.projects)s.push({label:`New thread in ${a.title||a.id}`,place:"",kind:"action",action:{type:"new-thread",projectId:a.id}});for(let a of e.threads){let{urgency:c,want:p}=xs(a);s.push({label:a.title||"Untitled thread",place:a.project==="chats"?n("chats.title","Chats"):a.project?r.get(a.project)??"":"",kind:"thread",urgency:c,want:p,dotClass:Ps(a),action:{type:"thread",id:a.id}})}for(let a of e.bots){if(!a.name||!a.thread)continue;s.push({label:a.name,place:"",kind:"bot",action:{type:"thread",id:a.thread}})}return s}function As(e,t,n,i=[],s=10,r=14){let o=t.trim(),a=o.length===0,c=e.slice();if(n?.threads&&n.threads.length>0){let d=new Map;for(let f of i)d.set(f.id,f.title||f.id);let u=new Set;for(let f of c)if(f.action.type==="thread")u.add(f.action.id);for(let f of n.threads){if(!f.id||u.has(f.id))continue;u.add(f.id);let{urgency:b,want:v}=xs(f);c.push({label:f.title||"Untitled thread",place:f.project?d.get(f.project)??"":"",kind:"thread",urgency:b,want:v,dotClass:Ps(f),action:{type:"thread",id:f.id}})}}let p=[];for(let d=0;d0)p.push({score:v,index:d,item:u})}p.sort((d,u)=>{if(a){let v=(u.item.urgency??0)-(d.item.urgency??0);if(v!==0)return v}if(u.score!==d.score)return u.score-d.score;let f=d.item.kind==="thread"?0:1,b=u.item.kind==="thread"?0:1;if(f!==b)return f-b;return d.index-u.index});let l=new Set,h=[];for(let d of p){let u=`${d.item.label}\x00${d.item.place}\x00${d.item.kind}`;if(l.has(u))continue;if(l.add(u),h.push(d.item),h.length>=s)break}if(n?.messages&&n.messages.length>0&&h.length{if(o.target===t)this.close()}),s.addEventListener("input",()=>{this.query=s.value,this.activeIdx=0,this.renderList(),this.scheduleSearch()}),s.addEventListener("keydown",(o)=>{if(o.key==="Escape")o.preventDefault(),o.stopPropagation(),this.close();else if(o.key==="ArrowDown"){if(o.preventDefault(),this.listed.length>0)this.activeIdx=(this.activeIdx+1)%this.listed.length,this.renderList(!0)}else if(o.key==="ArrowUp"){if(o.preventDefault(),this.listed.length>0)this.activeIdx=(this.activeIdx-1+this.listed.length)%this.listed.length,this.renderList(!0)}else if(o.key==="Enter")o.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=Ls(t,{t:m,trs:he}),i=this.query.trim()===this.searchHitsQuery?this.searchHits:null;if(this.listed=As(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 o=document.createElement("div");o.className="bp-palette-empty",o.textContent=m("gpui.nothing.matches","Nothing matches"),this.listEl.replaceChildren(o);return}let s=document.createDocumentFragment(),r=null;for(let o=0;o0)p.appendChild(document.createTextNode(a.label.slice(0,d)));let f=document.createElement("strong");if(f.className="bp-palette-mark",f.textContent=a.label.slice(d,u),p.appendChild(f),u{if(this.activeIdx!==o)this.activeIdx=o,this.updateActiveClass()}),c.addEventListener("click",()=>this.runAt(o)),o===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;t0?Math.floor(t.leadDays):0,i=[];for(let s of mn(t.warnings)){let r=it(s).trim();if(r&&!i.includes(r))i.push(r)}return{project:it(t.project),root:it(t.root),intent:it(t.intent),parts:mn(t.parts).map((s)=>Gn(s)).map((s)=>({name:it(s.name),kind:it(s.kind),path:it(s.path)})).filter((s)=>s.name||s.path),boards:mn(t.boards).map(it).filter(Boolean),mech:mn(t.mech).map((s)=>Gn(s)).map((s)=>({path:it(s.path),name:it(s.name),size:typeof s.size==="number"&&s.size>0?s.size:0})).filter((s)=>s.name||s.path),leadDays:n,warnings:i}}function Vn(e){let t=[];for(let n of e.split(` +`)){let i=n.trimEnd();if(!i.trim())continue;if(t.length>=60)break;let s=i.trimStart();if(s.startsWith("#"))t.push({kind:"h",text:s.replace(/^#+/,"").trim()});else if(s.startsWith("- ")||s.startsWith("* "))t.push({kind:"li",text:s.slice(2).trim()});else t.push({kind:"p",text:s})}return t}function Ms(e){return!Vn(e).some((t)=>t.kind!=="h"&&t.text.length>0)}function Ts(e){if(!Number.isFinite(e)||e<=0)return"";if(e<1024)return`${Math.floor(e)} B`;if(e<1048576)return`${(e/1024).toFixed(e<10240?1:0)} KB`;return`${(e/1048576).toFixed(1)} MB`}function Un(e){let t=e.lastIndexOf("|");return t>=0?e.slice(t+1):e}function be(e,t,n){let i=document.createElement(e);if(t)i.className=t;if(n!==void 0)i.textContent=n;return i}class Wn{root;titleEl;rootEl;newBtn;newLbl;threadsEl;bodyEl;cb;projectId="";data=null;threads=null;error="";constructor(e,t){this.cb=t,this.root=be("section","bp-project-home bp-hidden"),this.root.setAttribute("data-testid","project-home");let n=be("div","bp-home-inner"),i=be("header","bp-home-head");this.titleEl=be("h1","bp-home-title"),this.titleEl.setAttribute("data-testid","project-home-title"),this.rootEl=be("div","bp-home-root"),i.append(this.titleEl,this.rootEl);let s=be("div","bp-home-bar");this.newBtn=be("button","primary bp-home-new"),this.newBtn.type="button",this.newBtn.setAttribute("data-testid","project-home-new-thread");let r=be("span","bp-home-new-plus","+");r.setAttribute("aria-hidden","true"),this.newLbl=be("span","",m("thread.new","New thread")),this.newBtn.append(r,this.newLbl),this.newBtn.addEventListener("click",()=>{if(this.projectId)this.cb.onNewThread(this.projectId)}),s.appendChild(this.newBtn),this.threadsEl=be("div","bp-home-threads"),this.bodyEl=be("div","bp-home-body"),n.append(i,s,this.threadsEl,this.bodyEl),this.root.appendChild(n),e.appendChild(this.root)}isOpen(){return this.projectId!==""}show(e){if(this.projectId!==e.id)this.data=null,this.threads=null,this.root.scrollTop=0;this.error="",this.projectId=e.id,this.titleEl.textContent=e.title||e.id,this.root.classList.remove("bp-hidden"),this.render()}hide(){this.projectId="",this.root.classList.add("bp-hidden")}setTitle(e){if(e)this.titleEl.textContent=e}setData(e){this.data=e,this.error="",this.render()}setThreads(e){this.threads=e,this.render()}setError(e){this.error=e,this.render()}refreshLocale(){if(this.newLbl.textContent=m("thread.new","New thread"),this.isOpen())this.render()}section(e){return be("h2","bp-home-section",e)}render(){this.rootEl.textContent=this.data?.root??"",this.rootEl.classList.toggle("bp-hidden",!this.data?.root),this.renderThreads(),this.renderBody()}renderThreads(){let e=document.createDocumentFragment(),t=this.threads;if(t){if(e.appendChild(this.section(m("gpui.projects.threads","THREADS ({n})",{n:t.length}))),t.length===0)e.appendChild(be("div","bp-home-empty",m("gpui.no.threads.yet","No threads yet.")));for(let n of t){let i=be("button","bp-home-row bp-home-thread"+(n.settled?" bp-dim":""));i.type="button",i.setAttribute("data-testid",`project-home-thread-${n.id}`);let s=be("span",`bp-dot ${n.dot}`);if(n.status)s.title=n.status;let r=be("span","bp-home-row-main",n.title||"Untitled thread"),o=be("span","bp-home-row-faint",n.age);i.append(s,r,o),i.addEventListener("click",()=>this.cb.onOpenThread(n.id)),e.appendChild(i)}}this.threadsEl.replaceChildren(e)}renderBody(){let e=document.createDocumentFragment(),t=this.data;if(this.error){let s=be("div","bp-home-error");s.setAttribute("data-testid","project-home-error"),s.appendChild(be("span","",this.error));let r=be("button","bp-btn-ghost",m("tools.retry","Retry"));r.type="button";let o=this.projectId;r.addEventListener("click",()=>this.cb.onRetry(o)),s.appendChild(r),e.appendChild(s)}if(!t){if(!this.error)e.appendChild(be("div","bp-home-empty",m("web.home.loading","Loading project…")));this.bodyEl.replaceChildren(e);return}e.appendChild(this.section(m("gpui.goal.notes","GOAL & NOTES")));let n=be("div","bp-home-intent");if(n.setAttribute("data-testid","project-home-intent"),Ms(t.intent))e.appendChild(be("div","bp-home-empty",m("gpui.no.goal.yet.ask.an","No goal yet. Ask an agent to write what this project is for, or edit .backplane/intent.md.")));else{for(let s of Vn(t.intent))if(s.kind==="h")n.appendChild(be("div","bp-home-intent-h",s.text));else if(s.kind==="li"){let r=be("div","bp-home-intent-li"),o=be("span","bp-home-bullet","•");o.setAttribute("aria-hidden","true"),r.append(o,be("span","",s.text)),n.appendChild(r)}else n.appendChild(be("div","",s.text));e.appendChild(n)}let i=this.threads?.[0]?.id??"";if(t.mech.length>0)e.appendChild(this.section(m("gpui.projects.mech","MECHANICAL ({n})",{n:t.mech.length}))),t.mech.forEach((s,r)=>{let o=r===0&&t.mech.length>1,a=this.fileRow(i,"mech",`project-home-mech-${r}`);if(a.title=s.path,a.appendChild(be("span","bp-home-row-main",s.name||s.path)),o)a.appendChild(be("span","bp-home-row-accent",m("gpui.assembly","Assembly")));a.appendChild(be("span","bp-home-row-faint",Ts(s.size))),e.appendChild(a)});if(t.parts.length>0){e.appendChild(this.section(m("gpui.projects.to.order","TO ORDER ({n})",{n:t.parts.length})));let s=be("div","bp-home-order");if(s.setAttribute("data-testid","project-home-order"),t.parts.forEach((r,o)=>{let a=be("div","bp-home-row");a.setAttribute("data-testid",`project-home-part-${o}`),a.append(be("span","bp-home-row-main",r.name||r.path),be("span","bp-home-row-dim",r.kind),be("span","bp-home-row-faint",r.path)),s.appendChild(a)}),t.leadDays>0){let r=be("div","bp-home-order-note",t.leadDays===1?m("web.home.lead.one","Lead time: 1 day"):m("web.home.lead","Lead time: {n} days",{n:t.leadDays}));r.setAttribute("data-testid","project-home-lead"),s.appendChild(r)}for(let r of t.warnings){let o=be("div","bp-home-order-note warn",r);o.setAttribute("data-testid","project-home-warning"),s.appendChild(o)}e.appendChild(s)}if(t.boards.length>0)e.appendChild(this.section(m("gpui.projects.boards","BOARDS ({n})",{n:t.boards.length}))),t.boards.forEach((s,r)=>{let o=this.fileRow(i,"board",`project-home-board-${r}`);o.appendChild(be("span","bp-home-row-main",s)),e.appendChild(o)});this.bodyEl.replaceChildren(e)}fileRow(e,t,n){if(!e){let s=be("div","bp-home-row");return s.setAttribute("data-testid",n),s}let i=be("button","bp-home-row bp-home-open");return i.type="button",i.setAttribute("data-testid",n),i.addEventListener("click",()=>this.cb.onOpenViewer(e,t)),i}}function _n(e){let t=null;if(typeof e==="string"){let i=e.trim();if(!i)return null;try{let s=JSON.parse(i);if(s&&typeof s==="object"&&!Array.isArray(s))t=s}catch{return null}}else if(e&&typeof e==="object"&&!Array.isArray(e))t=e;if(!t)return null;let n=typeof t.head==="string"?t.head.trim():"";if(!n)return null;return{reason:typeof t.reason==="string"?t.reason:"",head:n,text:typeof t.text==="string"?t.text:"",button:typeof t.button==="string"&&t.button.trim()?t.button:"Open Settings → Accounts",url:typeof t.url==="string"&&t.url.trim()?t.url:"backplane://settings/accounts"}}function ao(e){return e.startsWith("No AI provider connected yet.")}function Bs(e,t){if(t==="no_provider")return!0;if(t)return!1;return ao(e)}function st(e){return typeof e==="string"?e:""}function zn(e){return typeof e==="number"&&Number.isFinite(e)?e:0}function Is(e){let t=e&&typeof e==="object"?e:{},n=[];for(let i of Array.isArray(t.notes)?t.notes:[]){if(!i||typeof i!=="object")continue;let s=i,r=st(s.id);if(!r)continue;n.push({id:r,said:zn(s.said),gesture:st(s.gesture),words:st(s.words),model:st(s.model),conf:typeof s.conf==="number"&&Number.isFinite(s.conf)?s.conf:null,unsure:st(s.unsure),state:st(s.state),error:st(s.error),thread:st(s.thread),play:st(s.play),heard:zn(s.heard)})}return{total:Math.max(zn(t.total),n.length),notes:n,busy:st(t.busy)}}function Rs(e){let t=/\/ring\/audio\/(n[0-9a-f]{16})(?:\.m4a)?\?k=([0-9a-fA-F]+)$/.exec(e);return t?`/ring/audio/${t[1]}?k=${t[2]}`:""}function js(e){if(!e.model)return{key:"web.ring.not.heard",fallback:"Not heard"};if(e.model==="ring")return{key:"web.ring.app.words",fallback:"The Pebble app's words"};if(e.conf!==null)return{key:"web.ring.heard.by.sure",fallback:"Heard by {model}, {conf}% sure",vars:{model:e.model,conf:Math.round(e.conf)}};return{key:"web.ring.heard.by",fallback:"Heard by {model}",vars:{model:e.model}}}function Hs(e,t){if(t)return{key:"web.ring.state.busy",fallback:"being heard now"};switch(e){case"sent":return{key:"web.ring.state.sent",fallback:"given to Pebble"};case"new":return{key:"web.ring.state.new",fallback:"waiting to be heard"};case"heard":return{key:"web.ring.state.heard",fallback:"waiting to go to Pebble"};case"failed":return{key:"web.ring.state.failed",fallback:"not given to Pebble"};default:return{key:"",fallback:e}}}function Ds(e,t,n){if(e<=0)return{key:"ring.no.recordings.yet",fallback:"No recordings yet."};if(n.trim())return{key:"web.ring.found",fallback:"{found} of {total} have “{q}”.",vars:{found:t,total:e,q:n.trim()}};return e===1?{key:"web.ring.count.one",fallback:"1 recording"}:{key:"web.ring.count",fallback:"{n} recordings",vars:{n:e}}}var Fs="http://www.w3.org/2000/svg",$s={terminal:["M4 17l6-6-6-6","M12 19h8"],search:["M11 19a8 8 0 1 0 0-16 8 8 0 0 0 0 16z","M21 21l-4.3-4.3"],"circuit-board":["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"],cpu:["M6 6h12v12H6z","M9 2v4","M15 2v4","M9 18v4","M15 18v4","M2 9h4","M2 15h4","M18 9h4","M18 15h4"],box:["M21 16V8l-9-5-9 5v8l9 5 9-5z","M3.3 7L12 12l8.7-5","M12 22V12"],gauge:["M12 14l4-4","M3.3 19a10 10 0 1 1 17.4 0"],"file-stack":["M16 2H6v12h10V2z","M20 6v12H10","M4 18h10v4H4z"],"layout-panel-left":["M3 3h18v18H3z","M10 3v18"],layers:["M12 2L2 7l10 5 10-5-10-5z","M2 12l10 5 10-5","M2 17l10 5 10-5"],wrench:["M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.77-3.77a6 6 0 0 1-7.94 7.94l-6.91 6.91a2.12 2.12 0 0 1-3-3l6.91-6.91a6 6 0 0 1 7.94-7.94l-3.76 3.76z"],folder:["M3 6h6l2 2h10v11H3z"],diff:["M12 5v10","M7 10h10","M7 19h10"],"circle-check":["M12 22a10 10 0 1 0 0-20 10 10 0 0 0 0 20z","M9 12l2 2 4-4"],globe:["M12 22a10 10 0 1 0 0-20 10 10 0 0 0 0 20z","M2 12h20","M12 2a15 15 0 0 1 0 20 15 15 0 0 1 0-20z"]};function lo(e){let t=document.createElementNS(Fs,"svg");t.setAttribute("viewBox","0 0 24 24"),t.setAttribute("width","18"),t.setAttribute("height","18"),t.setAttribute("fill","none"),t.setAttribute("stroke","currentColor"),t.setAttribute("stroke-width","1.75"),t.setAttribute("stroke-linecap","square"),t.setAttribute("stroke-linejoin","miter"),t.setAttribute("aria-hidden","true");let n=$s[e]??$s.folder;for(let i of n){let s=document.createElementNS(Fs,"path");s.setAttribute("d",i),t.appendChild(s)}return t}class qn{el;items=[];activeId="";onPress;pagesRo=null;constructor(e,t){this.el=e,this.onPress=t,this.render()}setItems(e){this.items=e.slice(),this.render()}setActive(e){this.activeId=e,this.render()}renderButton(e){let t=e.state==="disabled",n=!t&&(e.state==="on"||this.activeId!==""&&e.id===this.activeId),i=he(e.label),s=e.why?he(e.why):"",r=document.createElement("button");if(r.type="button",r.className="bp-rail-btn"+(n?" active":"")+(t?" disabled":""),r.disabled=t,r.setAttribute("aria-pressed",n?"true":"false"),t){if(r.title=s||i,s)r.setAttribute("data-why",s)}else r.title=e.key?`${i} (${e.key.toUpperCase()})`:i;r.setAttribute("data-rail-id",e.id),r.setAttribute("data-testid",`rail-${e.id}`),r.appendChild(lo(e.icon));let o=document.createElement("span");if(o.className="bp-rail-lbl",o.textContent=i,r.appendChild(o),!t)r.addEventListener("click",()=>this.onPress(e.id));return r}render(){let e=this.items.filter((o)=>o.group!=="tools"),t=this.items.filter((o)=>o.group==="tools"),n=document.createElement("div");n.className="bp-rail-pages";let i;for(let o of e){if(i!==void 0&&o.group!==i){let a=document.createElement("div");a.className="bp-rail-rule",n.appendChild(a)}i=o.group,n.appendChild(this.renderButton(o))}let s=()=>{let o=n.scrollLeft>2,a=n.scrollLeft+n.clientWidth0){let o=document.createElement("div");o.className="bp-rail-tools";for(let a of t)o.appendChild(this.renderButton(a));r.appendChild(o)}this.el.replaceChildren(r)}}var co=new Set(["resume","raise","retry","move","signin"]);function Kn(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 un(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(co.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 Os(e){let t=e&&typeof e==="object"?e.open:void 0;if(typeof t!=="string")return null;let n=t.indexOf(":"),i=n<0?"":t.slice(n+1);if(!i)return null;if(t.startsWith("account:"))return{kind:"account",id:i};if(t.startsWith("thread:"))return{kind:"thread",id:i};return null}var Yn=[{id:"general",label:"General"},{id:"ai",label:"Agents and tools"},{id:"connect",label:"Connect"}],Tt=[{id:"appearance",group:"general",title:"Appearance",subtitle:"Kept in this browser only. Never sent to the hub.",icon:"sun",keywords:["theme","dark","light","auto","color","language","locale","english","espanol","japanese"]},{id:"providers",group:"ai",title:"AI providers",subtitle:"Account sign-ins live in the desktop or mobile app.",icon:"cpu",keywords:["accounts","claude","codex","antigravity","grok","openai","anthropic","signin","login","model"]},{id:"ring",group:"ai",title:"Ring",subtitle:"Voice notes from your Pebble ring. Its webhook is set up in the desktop or mobile app.",icon:"mic",keywords:["pebble","index","voice","note","notes","recording","recordings","play","hear","transcribe","search"]},{id:"devices",group:"connect",title:"Devices & browser",subtitle:"This browser session and paired devices on this hub.",icon:"link",keywords:["sign out","logout","session","cookie","revoke","paired","phone","browser","pair"]},{id:"home",group:"connect",title:"Home machine",subtitle:"Which machine hosts your always-on hub and bots.",icon:"globe",keywords:["host","boat","move","online","away","queued","linked"]}];function Gs(e){if(e==="dark"||e==="light"||e==="auto")return e;return"auto"}function Vs(e){if(e==="en"||e==="es"||e==="ja"||e==="auto")return e;return"auto"}function Wt(e,t){if(e==="dark"||e==="light")return e;return t==="light"?"light":"dark"}function Us(e){return e.trim().toLowerCase().split(/\s+/).filter(Boolean)}function Jn(e,t){if(t.length===0)return!0;let n=e.toLowerCase();return t.every((i)=>n.includes(i))}function Ws(e,t){let n=Us(t);if(n.length===0)return[];return e.filter((i)=>{let s=[i.groupLabel,i.pageTitle,i.rowTitle,i.rowDetail,...i.keywords??[]].join(" ");return Jn(s,n)})}function Xn(e,t,n){let i=Us(n);if(i.length===0)return e.map((o)=>({page:o,hits:[]}));let s=new Map(Yn.map((o)=>[o.id,o.label])),r=[];for(let o of e){let c=t.filter((l)=>l.pageId===o.id).filter((l)=>Jn([l.rowTitle,l.rowDetail,l.pageTitle,l.groupLabel,...l.keywords??[]].join(" "),i));if(Jn([s.get(o.group)??"",o.title,o.subtitle,...o.keywords].join(" "),i)||c.length>0){let l=[];for(let h of c){if(!l.includes(h.rowTitle))l.push(h.rowTitle);if(l.length>=2)break}r.push({page:o,hits:l})}}return r}function Qn(e){return e.key?m(e.key,e.fallback,e.vars):e.fallback}function po(e){let n=document.createElementNS("http://www.w3.org/2000/svg","svg");n.setAttribute("viewBox","0 0 24 24"),n.setAttribute("width","15"),n.setAttribute("height","15"),n.setAttribute("fill","none"),n.setAttribute("stroke","currentColor"),n.setAttribute("stroke-width","1.75"),n.setAttribute("stroke-linecap","square"),n.setAttribute("stroke-linejoin","miter"),n.setAttribute("aria-hidden","true");let i=(s,r)=>{let o=document.createElementNS("http://www.w3.org/2000/svg",s);for(let[a,c]of Object.entries(r))o.setAttribute(a,c);n.appendChild(o)};switch(e){case"sun":i("circle",{cx:"12",cy:"12",r:"4"}),i("path",{d:"M12 2v2m0 16v2M4.93 4.93l1.41 1.41m11.32 11.32 1.41 1.41M2 12h2m16 0h2M4.93 19.07l1.41-1.41m11.32-11.32 1.41-1.41"});break;case"cpu":i("rect",{x:"5",y:"5",width:"14",height:"14"}),i("rect",{x:"9",y:"9",width:"6",height:"6"}),i("path",{d:"M9 2v3m6-3v3M9 19v3m6-3v3M2 9h3m-3 6h3M19 9h3m-3 6h3"});break;case"link":i("path",{d:"M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"}),i("path",{d:"M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"});break;case"mic":i("rect",{x:"9",y:"2",width:"6",height:"12"}),i("path",{d:"M5 11a7 7 0 0 0 14 0M12 18v4M8 22h8"});break;case"globe":i("circle",{cx:"12",cy:"12",r:"10"}),i("path",{d:"M2 12h20M12 2a15.3 15.3 0 0 1 4 10 15.3 15.3 0 0 1-4 10 15.3 15.3 0 0 1-4-10 15.3 15.3 0 0 1 4-10z"});break}return n}function ho(){let t=document.createElementNS("http://www.w3.org/2000/svg","svg");t.setAttribute("viewBox","0 0 24 24"),t.setAttribute("width","13"),t.setAttribute("height","13"),t.setAttribute("fill","none"),t.setAttribute("stroke","currentColor"),t.setAttribute("stroke-width","1.75"),t.setAttribute("aria-hidden","true");let n=document.createElementNS("http://www.w3.org/2000/svg","circle");n.setAttribute("cx","11"),n.setAttribute("cy","11"),n.setAttribute("r","7");let i=document.createElementNS("http://www.w3.org/2000/svg","path");return i.setAttribute("d","m20 20-3.5-3.5"),t.append(n,i),t}function bn(e,t){switch(e){case"general":return m("gpui.settings.group.general",t);case"ai":return m("gpui.settings.group.agents",t);case"connect":return m("native.pair.connect",t)}}function gt(e,t){switch(e){case"appearance":return m("settings.appearance",t);case"providers":return m("web.settings.providers",t);case"ring":return m("ring.ring",t);case"devices":return t;case"home":return m("home.machine",t)}}class Zn{backdrop;titleEl;badgeEl;closeBtn;navListEl;searchInput;searchClearBtn;paneEl;cb;openState=!1;activePage="appearance";forceProviders=!1;query="";searchBrowseAll=!1;devicesLoaded=!1;devicesLoading=!1;devicesRows=[];devicesError="";loadGen=0;ringLoaded=!1;ringLoading=!1;ringList={total:0,notes:[],busy:""};ringCountEl=null;ringErrorEl=null;ringRows=new Map;ringShownQuery="";ringError="";ringQuery="";ringDraft="";ringGen=0;ringBusy=new Set;ringPolls=0;ringTimers=[];constructor(e,t){this.cb=t,this.backdrop=document.createElement("div"),this.backdrop.className="bp-modal-backdrop bp-hidden",this.backdrop.setAttribute("data-testid","settings-modal");let n=document.createElement("div");n.className="bp-modal bp-settings-modal",n.setAttribute("role","dialog"),n.setAttribute("aria-modal","true"),n.setAttribute("aria-labelledby","bp-settings-title");let i=document.createElement("div");i.className="bp-modal-head";let s=document.createElement("div");s.className="bp-settings-head-title",this.titleEl=document.createElement("h2"),this.titleEl.id="bp-settings-title",this.titleEl.textContent=m("palette.settings","Settings"),this.badgeEl=document.createElement("span"),this.badgeEl.className="bp-settings-badge",this.badgeEl.textContent="Browser",s.append(this.titleEl,this.badgeEl),this.closeBtn=document.createElement("button"),this.closeBtn.type="button",this.closeBtn.className="icon",this.closeBtn.textContent="×",this.closeBtn.setAttribute("aria-label",m("common.close","Close")),this.closeBtn.addEventListener("click",()=>this.close()),i.append(s,this.closeBtn);let r=document.createElement("div");r.className="bp-settings-body";let o=document.createElement("aside");o.className="bp-settings-nav";let a=document.createElement("div");a.className="bp-settings-search";let c=document.createElement("span");c.className="bp-settings-search-icon",c.appendChild(ho()),this.searchInput=document.createElement("input"),this.searchInput.type="text",this.searchInput.className="bp-settings-search-input",this.searchInput.placeholder="Search settings…",this.searchInput.setAttribute("aria-label","Search settings"),this.searchInput.setAttribute("data-testid","settings-search"),this.searchClearBtn=document.createElement("button"),this.searchClearBtn.type="button",this.searchClearBtn.className="bp-settings-search-clear bp-hidden",this.searchClearBtn.textContent="×",this.searchClearBtn.title="Clear search",this.searchClearBtn.setAttribute("aria-label","Clear search"),a.append(c,this.searchInput,this.searchClearBtn),this.navListEl=document.createElement("nav"),this.navListEl.className="bp-settings-nav-list",this.navListEl.setAttribute("aria-label","Settings sections"),o.append(a,this.navListEl),this.paneEl=document.createElement("div"),this.paneEl.className="bp-settings-pane",r.append(o,this.paneEl),n.append(i,r),this.backdrop.appendChild(n),this.backdrop.addEventListener("click",(p)=>{if(p.target===this.backdrop)this.close()}),this.searchInput.addEventListener("input",()=>{this.query=this.searchInput.value,this.searchBrowseAll=this.query.trim().length>0,this.syncSearchClear(),this.render()}),this.searchInput.addEventListener("keydown",(p)=>{if(p.key==="Enter"){let l=Xn(Tt,this.buildSearchItems(),this.query);if(l.length>0)p.preventDefault(),this.activePage=l[0].page.id,this.searchBrowseAll=!1,this.render()}else if(p.key==="Escape"&&this.query.trim().length>0)p.preventDefault(),p.stopPropagation(),this.clearSearch()}),this.searchClearBtn.addEventListener("click",()=>{this.clearSearch(),this.searchInput.focus()}),e.appendChild(this.backdrop)}isOpen(){return this.openState}handleEscape(){if(!this.openState)return;if(this.query.trim().length>0)this.clearSearch(),this.searchInput.focus();else this.close()}async open(e){if(this.openState=!0,e)this.activePage=e;if(this.backdrop.classList.remove("bp-hidden"),this.render(),this.loadDevices(),this.activePage==="ring")this.loadRing();window.setTimeout(()=>{if(this.openState)this.searchInput.focus()},0)}async openToAccounts(){this.forceProviders=!0,this.query="",this.searchInput.value="",this.searchBrowseAll=!1,this.syncSearchClear(),await this.open("providers")}close(){this.openState=!1,this.forceProviders=!1,this.query="",this.searchInput.value="",this.searchBrowseAll=!1,this.syncSearchClear(),this.backdrop.classList.add("bp-hidden");for(let e of this.ringTimers)window.clearTimeout(e);if(this.ringTimers=[],this.ringBusy.clear(),this.ringPolls=0,this.activePage==="ring")this.paneEl.replaceChildren()}refreshLocale(){if(this.titleEl.textContent=m("palette.settings","Settings"),this.closeBtn.setAttribute("aria-label",m("common.close","Close")),this.openState)this.render()}async refresh(){if(!this.openState)return;this.render(),await this.loadDevices()}clearSearch(){this.query="",this.searchInput.value="",this.searchBrowseAll=!1,this.syncSearchClear(),this.render()}syncSearchClear(){this.searchClearBtn.classList.toggle("bp-hidden",this.query.length===0)}async loadDevices(){let e=++this.loadGen;if(this.devicesLoading=!this.devicesLoaded,this.devicesLoading&&this.openState)this.renderPane();try{let t=await this.cb.onLoadDevices();if(e!==this.loadGen)return;this.devicesRows=t,this.devicesError="",this.devicesLoaded=!0}catch(t){if(e!==this.loadGen)return;let n=t instanceof Error&&t.message?t.message:"Not available from a browser";this.devicesError=`${n} — manage paired devices in Backplane › Settings › Devices on desktop or a paired phone.`,this.devicesRows=[],this.devicesLoaded=!0}finally{if(e===this.loadGen){if(this.devicesLoading=!1,this.openState)this.render()}}}async loadRing(){if(!this.cb.onRingList||!(this.cb.hasRing?.()??!1))return;let e=++this.ringGen;if(this.ringLoading=!this.ringLoaded,this.ringLoading)this.showRing();try{let t=await this.cb.onRingList(this.ringQuery);if(e!==this.ringGen)return;if(this.ringList=t,this.ringError="",!t.busy)this.ringBusy.clear();if(t.busy&&this.openState&&this.ringPolls<40)this.ringPolls++,this.ringLater(3000);else if(!t.busy)this.ringPolls=0}catch(t){if(e!==this.ringGen)return;this.ringError=t instanceof Error&&t.message?t.message:m("web.ring.error","Could not load recordings.")}finally{if(e===this.ringGen)this.ringLoaded=!0,this.ringLoading=!1,this.showRing()}}ringLater(e){let t=window.setTimeout(()=>{if(this.ringTimers=this.ringTimers.filter((n)=>n!==t),this.openState)this.loadRing()},e);this.ringTimers.push(t)}ringIsBusy(e){return this.ringBusy.has(e)||this.ringList.busy===e}showRing(){if(!this.openState||this.activePage!=="ring"||this.query.trim()&&this.searchBrowseAll)return;let e=this.ringList.notes.map((i)=>i.id),t=Array.from(this.ringRows.keys());if(!(this.ringCountEl?.isConnected===!0&&this.ringShownQuery===this.ringQuery&&e.length===t.length&&e.every((i,s)=>i===t[s]))){this.renderPane();return}if(this.ringCountEl)this.ringCountEl.textContent=this.ringCountLine();if(this.ringErrorEl)this.ringErrorEl.textContent=this.ringError,this.ringErrorEl.classList.toggle("bp-hidden",!this.ringError);for(let i of this.ringList.notes)this.fillRingNote(i)}ringCountLine(){return this.ringLoading?m("web.ring.loading","Loading recordings…"):Qn(Ds(this.ringList.total,this.ringList.notes.length,this.ringQuery))}fillRingNote(e){let t=this.ringRows.get(e.id);if(!t)return;let n=this.ringIsBusy(e.id);t.state.className="bp-status-pill "+(n?"accent":e.state==="sent"?"ok":e.state==="failed"?"bad":"warn"),t.state.textContent=Qn(Hs(e.state,n)),t.words.className="bp-ring-words"+(e.words?"":" bp-dim"),t.words.textContent=e.words||m("web.ring.no.words","(no words)"),t.meta.textContent=[Qn(js(e)),e.unsure,e.error].filter(Boolean).join(" · ");for(let i of t.hear)i.disabled=n}async hearRing(e,t){if(!this.cb.onRingHear||this.ringIsBusy(e))return;this.ringBusy.add(e),this.ringError="",this.showRing();try{await this.cb.onRingHear(e,t),this.ringPolls=0,this.ringLater(1500)}catch(n){this.ringBusy.delete(e),this.ringError=n instanceof Error&&n.message?n.message:m("web.ring.error","Could not load recordings."),this.showRing()}}buildSearchItems(){let e=this.cb.onGetHome?.()??null,t=this.cb.onGetNoProvider?.()??null,n=bn("general","General"),i=bn("ai","Agents and tools"),s=bn("connect","Connect"),r=gt("appearance","Appearance"),o=gt("providers","AI providers"),a=gt("devices","Devices & browser"),c=gt("home","Home machine"),p=[{pageId:"appearance",pageTitle:r,groupLabel:n,rowTitle:m("settings.theme","Theme"),rowDetail:"Auto (follow hub), Dark, or Light in this browser.",keywords:["theme","dark","light","auto","appearance","colors"]},{pageId:"appearance",pageTitle:r,groupLabel:n,rowTitle:m("settings.lang","Language"),rowDetail:"Interface language for this browser.",keywords:["locale","english","espanol","japanese","language"]},{pageId:"providers",pageTitle:o,groupLabel:i,rowTitle:t?he(t.head):"Provider connections",rowDetail:"Connect Claude, Codex, Antigravity, or other AI providers in Settings → Accounts.",keywords:["accounts","claude","codex","antigravity","grok","openai","signin"]},{pageId:"ring",pageTitle:gt("ring","Ring"),groupLabel:i,rowTitle:m("ring.recordings","Recordings"),rowDetail:"Read, search, play and hear again the voice notes from your Pebble ring.",keywords:["pebble","voice","note","recording","play","hear","transcribe"]},{pageId:"devices",pageTitle:a,groupLabel:s,rowTitle:"This browser",rowDetail:"Sign out and revoke this browser's session cookie.",keywords:["logout","sign out","session","cookie"]},{pageId:"devices",pageTitle:a,groupLabel:s,rowTitle:"Paired devices",rowDetail:this.devicesRows.map((l)=>`${l.title||l.head||""} ${l.detail||l.text||""}`).join(" ")||"Paired phones and browsers on this hub.",keywords:["phone","pair","revoke","browser"]},{pageId:"home",pageTitle:c,groupLabel:s,rowTitle:e?.name?`${e.name}`:c,rowDetail:"Which machine hosts your always-on hub and bots.",keywords:["boat","move","online","away","queued","machine"]}];for(let l of this.devicesRows){let h=l.title||l.head||"";if(h)p.push({pageId:"devices",pageTitle:a,groupLabel:s,rowTitle:h,rowDetail:l.detail||l.text||"",keywords:["paired","device"]})}return p}render(){this.renderNav(),this.renderPane()}renderNav(){let e=document.createDocumentFragment(),t=Xn(Tt,this.buildSearchItems(),this.query),n=this.cb.onGetNoProvider?.()??null,i=this.cb.onGetHome?.()??null;if(t.length===0){let r=document.createElement("div");r.className="bp-settings-nav-empty",r.setAttribute("data-testid","settings-nav-empty"),r.textContent="No matching settings",e.appendChild(r),this.navListEl.replaceChildren(e);return}let s="";for(let r of t){let o=r.page;if(o.group!==s){s=o.group;let d=Yn.find((u)=>u.id===o.group);if(d){let u=document.createElement("div");u.className="bp-settings-group",u.textContent=bn(d.id,d.label),e.appendChild(u)}}let a=document.createElement("button");a.type="button";let c=!this.searchBrowseAll&&o.id===this.activePage;a.className="bp-settings-nav-item"+(c?" active":""),a.setAttribute("data-testid",`settings-nav-${o.id}`);let p=document.createElement("div");p.className="bp-settings-nav-row";let l=document.createElement("span");l.className="bp-settings-nav-icon",l.appendChild(po(o.icon));let h=document.createElement("span");if(h.className="bp-settings-nav-label",h.textContent=gt(o.id,o.title),p.append(l,h),o.id==="providers"&&(n||this.forceProviders)){let d=document.createElement("span");d.className="bp-settings-nav-dot warn",d.title="Action needed",p.appendChild(d)}else if(o.id==="home"&&i){let d=document.createElement("span");d.className="bp-settings-nav-dot "+(i.moving?.state==="failed"?"bad":i.online?"ok":"warn"),p.appendChild(d)}if(a.appendChild(p),r.hits.length>0)for(let d of r.hits){let u=document.createElement("div");u.className="bp-settings-hit",u.textContent=d,a.appendChild(u)}a.addEventListener("click",()=>{if(this.activePage=o.id,this.searchBrowseAll=!1,this.render(),o.id==="ring")this.loadRing()}),e.appendChild(a)}this.navListEl.replaceChildren(e)}renderPane(){let e=document.createDocumentFragment(),t=this.query.trim();if(t&&this.searchBrowseAll){this.renderSearchResults(e,t),this.paneEl.replaceChildren(e);return}let n=Tt.find((o)=>o.id===this.activePage)??Tt[0],i=document.createElement("div");i.className="bp-settings-pane-head";let s=document.createElement("h3");s.textContent=gt(n.id,n.title);let r=document.createElement("div");switch(r.className="bp-settings-pane-sub",r.textContent=n.subtitle,i.append(s,r),e.appendChild(i),n.id){case"appearance":this.renderAppearancePage(e);break;case"providers":this.renderProvidersPage(e);break;case"ring":this.renderRingPage(e);break;case"devices":this.renderDevicesPage(e);break;case"home":this.renderHomePage(e);break}this.paneEl.replaceChildren(e)}renderSearchResults(e,t){let n=Ws(this.buildSearchItems(),t),i=document.createElement("div");i.className="bp-settings-pane-head";let s=document.createElement("h3");s.textContent="Search results";let r=document.createElement("div");if(r.className="bp-settings-pane-sub",r.textContent=n.length===0?`No settings match "${t}".`:`${n.length} matching ${n.length===1?"setting":"settings"} for "${t}"`,i.append(s,r),e.appendChild(i),n.length===0){let a=document.createElement("div");a.className="bp-settings-empty",a.textContent="Try searching for theme, language, providers, sign out, devices, or home.",e.appendChild(a);return}let o=Array.from(new Set(n.map((a)=>a.pageId)));for(let a of o){let c=Tt.find((u)=>u.id===a);if(!c)continue;let p=document.createElement("div");p.className="bp-settings-search-sec";let l=document.createElement("div");l.className="bp-settings-subhead",l.textContent=gt(c.id,c.title);let h=document.createElement("button");h.type="button",h.className="bp-settings-search-open",h.textContent="Open page ›",h.addEventListener("click",()=>{if(this.activePage=a,this.searchBrowseAll=!1,this.render(),a==="ring")this.loadRing()}),p.append(l,h),e.appendChild(p);let d=new Set(n.filter((u)=>u.pageId===a).map((u)=>u.rowTitle));if(a==="appearance")this.renderAppearancePage(e,d);else if(a==="providers")this.renderProvidersPage(e);else if(a==="ring"){let u=document.createElement("div");u.className="bp-settings-empty",u.textContent="Read, search, play and hear again the voice notes from your Pebble ring.",e.appendChild(u)}else if(a==="devices")this.renderDevicesPage(e,d);else if(a==="home")this.renderHomePage(e)}}renderAppearancePage(e,t){let n=this.cb.onGetThemePref?.()??"auto",i=this.cb.onGetHubTheme?.()??"dark",s=Wt(n,i),r=this.cb.onGetLocalePref?.()??"auto",o=m("settings.theme","Theme"),a=m("settings.lang","Language");if(!t||t.has(o)){let c=m("settings.theme.dark","Dark"),p=m("settings.theme.light","Light"),l=n==="auto"?`Following hub theme (${i==="light"?p:c}). Stored in this browser only.`:`Using ${s==="light"?p:c} in this browser. Select Auto to follow the hub.`;e.appendChild(this.makeSegmentedRow(o,l,[{value:"auto",label:"Auto"},{value:"dark",label:c},{value:"light",label:p}],n,"settings-theme",(h)=>{this.cb.onSetThemePref?.(h),this.render()}))}if(!t||t.has(a))e.appendChild(this.makeSegmentedRow(a,"Interface language for this browser. Automatic follows the hub or browser language.",[{value:"auto",label:m("settings.lang.auto","Automatic")},{value:"en",label:m("settings.lang.en","English")},{value:"es",label:m("settings.lang.es","Español")},{value:"ja",label:m("settings.lang.ja","日本語")}],r,"settings-locale",(c)=>{this.cb.onSetLocalePref?.(c),this.render()}))}makeSegmentedRow(e,t,n,i,s,r){let o=document.createElement("div");o.className="bp-settings-row";let a=document.createElement("div");a.className="bp-settings-row-info";let c=document.createElement("div");c.className="bp-settings-row-title",c.textContent=e;let p=document.createElement("div");p.className="bp-settings-row-detail",p.textContent=t,a.append(c,p);let l=document.createElement("div");l.className="bp-chip-group",l.setAttribute("role","group"),l.setAttribute("aria-label",e);for(let h of n){let d=document.createElement("button");d.type="button";let u=h.value===i;d.className="bp-chip"+(u?" active":""),d.textContent=h.label,d.setAttribute("aria-pressed",u?"true":"false"),d.setAttribute("data-testid",`${s}-${h.value}`),d.addEventListener("click",()=>r(h.value)),l.appendChild(d)}return o.append(a,l),o}renderProvidersPage(e){let t=this.cb.onGetNoProvider?.()??null,n=document.createElement("section");if(n.className="bp-settings-section",n.setAttribute("data-testid","settings-providers"),t||this.forceProviders){let i=document.createElement("div");i.className="bp-settings-notice warn";let s=document.createElement("div");s.className="bp-settings-row-info";let r=document.createElement("div");r.className="bp-settings-row-title",r.textContent=t?he(t.head):m("provider.notice.head","No AI provider connected");let o=document.createElement("div");o.className="bp-settings-row-detail",o.textContent=m("web.settings.providers.browser","Connect a provider in the Backplane desktop or mobile app under Settings → Accounts."),s.append(r,o);let a=document.createElement("div");a.className="bp-set-btns";let c=document.createElement("a");c.className="bp-link-btn primary",c.href=t?.url||"backplane://settings/accounts",c.setAttribute("data-testid","settings-open-accounts"),c.textContent=t?he(t.button):m("provider.notice.button","Open Settings → Accounts"),a.appendChild(c),i.append(s,a),n.appendChild(i)}else{let i=document.createElement("div");i.className="bp-settings-row";let s=document.createElement("div");s.className="bp-settings-row-info";let r=document.createElement("div");r.className="bp-settings-row-title-wrap";let o=document.createElement("span");o.className="bp-settings-row-title",o.textContent="Provider connections";let a=document.createElement("span");a.className="bp-status-pill ok",a.textContent=m("gpui.acct.connected","Connected"),r.append(o,a);let c=document.createElement("div");c.className="bp-settings-row-detail",c.textContent="Provider sign-ins, fallback order, API keys, and usage limits are managed in the Backplane desktop or mobile app.",s.append(r,c);let p=document.createElement("div");p.className="bp-set-btns";let l=document.createElement("a");l.className="bp-link-btn",l.href="backplane://settings/accounts",l.setAttribute("data-testid","settings-open-accounts"),l.textContent=m("provider.notice.button","Open Settings → Accounts"),p.appendChild(l),i.append(s,p),n.appendChild(i)}e.appendChild(n)}renderDevicesPage(e,t){let n=!t||t.has("This browser"),i=!t||t.has("Paired devices")||this.devicesRows.some((o)=>t.has(o.title||o.head||""));if(n){let o=document.createElement("div");o.className="bp-settings-subhead",o.textContent="This browser",e.appendChild(o);let a=document.createElement("div");a.className="bp-settings-row";let c=document.createElement("div");c.className="bp-settings-row-info";let p=document.createElement("div");p.className="bp-settings-row-title",p.textContent="Browser session";let l=document.createElement("div");l.className="bp-settings-row-detail",l.textContent="Sign out and revoke this browser's session cookie.",c.append(p,l);let h=document.createElement("button");h.type="button",h.className="primary stop",h.textContent=m("agy.signout","Sign out"),h.setAttribute("data-testid","logout-btn"),h.addEventListener("click",()=>{h.disabled=!0,this.cb.onLogout().catch(()=>{l.setAttribute("role","alert"),l.className="bp-settings-row-detail bp-bad",l.textContent=m("web.logout.failed","Could not confirm sign-out. Try again."),h.disabled=!1})}),a.append(c,h),e.appendChild(a)}if(!i)return;let s=document.createElement("div");if(s.className="bp-settings-subhead",s.textContent="Paired devices",e.appendChild(s),this.devicesLoading){let o=document.createElement("div");o.className="bp-settings-empty",o.textContent="Loading paired devices…",e.appendChild(o);return}if(this.devicesError){let o=document.createElement("div");o.className="bp-settings-notice bad";let a=document.createElement("div");a.className="bp-settings-row-detail",a.textContent=this.devicesError,o.appendChild(a),e.appendChild(o);return}let r=!t||t.has("Paired devices")?this.devicesRows:this.devicesRows.filter((o)=>t.has(o.title||o.head||""));if(r.length===0){let o=document.createElement("div");o.className="bp-settings-empty",o.textContent="No paired devices listed.",e.appendChild(o)}else for(let o of r){let a=document.createElement("div");a.className="bp-settings-row";let c=document.createElement("div");c.className="bp-settings-row-info";let p=document.createElement("div");p.className="bp-settings-row-title-wrap";let l=document.createElement("span");l.className="bp-settings-row-title",l.textContent=o.title||o.head||"",p.appendChild(l);let h=o.detail||o.text||"";if(h){let d=document.createElement("span"),u=h.toLowerCase();d.className="bp-status-pill "+(u.includes("this browser")?"accent":"neutral"),d.textContent=h,p.appendChild(d)}if(c.appendChild(p),a.appendChild(c),o.buttons?.length){let d=document.createElement("div");d.className="bp-set-btns";for(let u of o.buttons){let f=document.createElement("button");if(f.type="button",u.primary)f.className="primary";if(u.danger)f.className="primary stop";f.textContent=u.label||m("common.remove","Remove"),f.addEventListener("click",()=>{f.disabled=!0,this.cb.onDevicesAct(u.action,u.value).finally(()=>{this.refresh()})}),d.appendChild(f)}a.appendChild(d)}e.appendChild(a)}if(!t){let o=document.createElement("div");o.className="bp-settings-footnote",o.textContent="Pair new browsers or phones, configure Tailscale HTTPS forwarding, or revoke access in desktop or mobile Settings → Devices.",e.appendChild(o)}}renderRingPage(e){let t=document.createElement("section");if(t.className="bp-settings-section",t.setAttribute("data-testid","settings-ring"),!this.cb.onRingList||!(this.cb.hasRing?.()??!1)){let a=document.createElement("div");a.className="bp-settings-empty",a.textContent=m("web.ring.unavailable","This hub does not show ring notes to a browser yet. Update it, or open Settings › Ring in the desktop app."),t.appendChild(a),e.appendChild(t);return}let n=document.createElement("form");n.className="bp-ring-search";let i=document.createElement("input");i.type="search",i.className="bp-ring-search-input",i.placeholder=m("ring.search.what.you.said","Search what you said"),i.setAttribute("aria-label",m("ring.search.what.you.said","Search what you said")),i.setAttribute("data-testid","ring-search"),i.value=this.ringDraft,i.addEventListener("input",()=>{this.ringDraft=i.value});let s=document.createElement("button");if(s.type="submit",s.className="primary",s.textContent=m("common.search","Search"),n.append(i,s),this.ringQuery){let a=document.createElement("button");a.type="button",a.className="bp-btn-ghost",a.textContent=m("ring.show.all","Show all"),a.addEventListener("click",()=>{this.ringDraft="",this.ringQuery="",this.loadRing()}),n.appendChild(a)}n.addEventListener("submit",(a)=>{a.preventDefault(),this.ringQuery=this.ringDraft.trim(),this.loadRing()}),t.appendChild(n);let r=document.createElement("div");r.className="bp-settings-notice bad"+(this.ringError?"":" bp-hidden"),r.setAttribute("data-testid","ring-error"),r.textContent=this.ringError,t.appendChild(r),this.ringErrorEl=r;let o=document.createElement("div");o.className="bp-ring-count",o.setAttribute("data-testid","ring-count"),o.textContent=this.ringCountLine(),t.appendChild(o),this.ringCountEl=o,this.ringRows.clear(),this.ringShownQuery=this.ringQuery;for(let a of this.ringList.notes)t.appendChild(this.renderRingNote(a));e.appendChild(t)}renderRingNote(e){let t=document.createElement("div");t.className="bp-ring-note"+(e.state==="failed"?" bad":""),t.setAttribute("data-testid",`ring-note-${e.id}`);let n=document.createElement("div");n.className="bp-ring-note-head";let i=document.createElement("span");i.className="bp-settings-row-title";let s=e.said>0?new Date(e.said*1000).toLocaleString(Mi(),{dateStyle:"medium",timeStyle:"short"}):"";i.textContent=[s,e.gesture].filter(Boolean).join(" · ");let r=document.createElement("span");n.append(i,r);let o=document.createElement("div"),a=document.createElement("div");a.className="bp-settings-row-detail";let c=[],p=document.createElement("div");p.className="bp-ring-acts";let l=Rs(e.play);if(l){let h=document.createElement("audio");h.className="bp-ring-audio",h.controls=!0,h.preload="none",h.src=l,h.setAttribute("data-testid",`ring-audio-${e.id}`),p.appendChild(h);for(let[d,u]of[["local",m("ring.hear.again.local","Hear again (local)")],["openai",m("ring.hear.again.openai","Hear again (OpenAI)")]]){let f=document.createElement("button");f.type="button",f.className="bp-btn-ghost",f.textContent=u,f.setAttribute("data-testid",`ring-hear-${d}-${e.id}`),c.push(f),f.addEventListener("click",()=>{this.hearRing(e.id,d)}),p.appendChild(f)}}if(e.thread&&this.cb.onOpenThread){let h=document.createElement("button");h.type="button",h.className="bp-btn-ghost",h.textContent=m("ring.what.happened","What happened"),h.addEventListener("click",()=>{this.close(),this.cb.onOpenThread?.(e.thread)}),p.appendChild(h)}if(t.append(n,o,a),p.childElementCount>0)t.appendChild(p);return this.ringRows.set(e.id,{state:r,words:o,meta:a,hear:c}),this.fillRingNote(e),t}renderHomePage(e){let t=this.cb.onGetHome?.()??null,n=document.createElement("section");if(n.className="bp-settings-section",n.setAttribute("data-testid","settings-home"),!t){let d=document.createElement("div");d.className="bp-settings-empty",d.textContent="Single-hub mode — this hub is running locally without linked home machines.",n.appendChild(d),e.appendChild(n);return}let i=document.createElement("div");i.className="bp-settings-row";let s=document.createElement("div");s.className="bp-settings-row-info";let r=document.createElement("div");r.className="bp-settings-row-title-wrap";let o=document.createElement("span");o.className="bp-settings-row-title",o.textContent=t.name||(t.kind==="boat"?"Boat":"This machine"),r.appendChild(o);let a=document.createElement("span");a.className="bp-status-pill neutral",a.textContent=t.kind==="local"?"This machine":t.kind==="boat"?"Boat":"Linked machine",r.appendChild(a);let c=document.createElement("span"),p="Online",l="ok";if(t.moving?.state==="moving")p="Moving",l="accent";else if(t.moving?.state==="failed")p="Move failed",l="bad";else if(!t.online)p="Away",l="warn";c.className=`bp-status-pill ${l}`,c.textContent=p,r.appendChild(c);let h=document.createElement("div");if(h.className="bp-settings-row-detail",t.moving?.state==="moving")h.textContent=t.moving.step?m("home.moving.step","Moving home to {to}: {step}").replace("{to}",t.moving.to).replace("{step}",t.moving.step):m("home.moving","Moving home to {to}…").replace("{to}",t.moving.to);else if(t.moving?.state==="failed")h.textContent=t.moving.note?m("home.move.failed.note","Home move failed: {note}").replace("{note}",t.moving.note):m("home.move.failed","Home move failed");else if(!t.online)h.textContent=t.queuedCount>0?m("home.away.queued","Home ({name}) is away · {n} queued").replace("{name}",t.name||"home").replace("{n}",String(t.queuedCount)):m("home.away","Home ({name}) is away").replace("{name}",t.name||"home");else h.textContent="Your active home hub is online and serving threads and bots.";if(s.append(r,h),i.appendChild(s),t.canMoveHere&&this.cb.onMoveHomeHere){let d=document.createElement("button");d.type="button",d.className="primary",d.textContent=m("home.move.here","Make this machine the home"),d.setAttribute("data-testid","home-move-here-btn"),d.addEventListener("click",()=>{d.disabled=!0,this.cb.onMoveHomeHere?.().finally(()=>{this.refresh()})}),i.appendChild(d)}n.appendChild(i),e.appendChild(n)}}function xe(e,t,n){let i=document.createElement(e);if(t)i.className=t;if(n)i.textContent=n;return i}function _t(e,t,n=!1){let i=xe("button",n?"primary":"bp-btn-ghost",e);return i.type="button",i.addEventListener("click",t),i}function ei(e){return xe("pre","bp-context-code",e)}function mo(e){return xe("span",`bp-context-badge ${e==="Native"||e==="Enabled"?"active":e==="Untrusted"||e==="Invalid"?"warn":""}`,he(e))}function gn(e,t){let n=xe("div","bp-context-row");return n.append(xe("strong",void 0,e),mo(t)),n}class ti{fetchContext;dialog=xe("dialog","bp-context");title=xe("h2");cwd=xe("div","bp-context-path");tabs=xe("div","bp-context-tabs");body=xe("div","bp-context-body");notice=xe("p","bp-context-notice");current;thread="";requestId=0;tab=0;busy=!1;constructor(e,t){this.fetchContext=t;let n=xe("div","bp-context-head"),i=xe("div");i.append(this.title,this.cwd),this.title.id="bp-context-title",this.dialog.setAttribute("aria-labelledby",this.title.id),this.notice.setAttribute("role","status"),n.append(i,_t(m("common.refresh","Refresh"),()=>{this.load()}),_t(m("common.close","Close"),()=>this.dialog.close())),this.dialog.append(n,this.tabs,this.notice,this.body),this.dialog.addEventListener("close",()=>{this.requestId++}),e.append(this.dialog)}open(e){if(this.thread=e,this.tab=0,this.current=void 0,this.busy=!1,this.title.textContent=m("thread.context.title","Context & Prompt"),this.cwd.textContent="",!this.dialog.open)this.dialog.showModal();this.render(),this.load()}async load(e){if(this.busy)return;let t=++this.requestId;this.busy=!0,this.notice.textContent=m("thread.context.reading","Reading thread context…"),this.render();try{let n=await this.fetchContext(this.thread,e);if(t!==this.requestId)return;this.current=n,this.cwd.textContent=n.cwd,this.notice.textContent=""}catch(n){if(t===this.requestId)this.notice.textContent=String(n)}finally{if(t===this.requestId)this.busy=!1,this.render()}}render(){let e=[m("thread.context.instructions","Instructions"),m("thread.context.system","System Prompt"),m("thread.context.skills","Skills"),m("thread.context.mcp","Project MCPs")];this.tabs.replaceChildren(...e.map((n,i)=>{let s=_t(n,()=>{this.tab=i,this.render(),this.body.scrollTop=0,this.tabs.children[i].focus()});return s.setAttribute("aria-pressed",String(i===this.tab)),s})),this.body.replaceChildren();let t=this.current;if(!t)return;switch(this.tab){case 0:this.instructions(t.instructions);break;case 1:this.prompt(t);break;case 2:this.skills(t.skills);break;case 3:this.mcps(t.mcp);break}}instructions(e){if(!e.length)this.body.append(xe("p","bp-dim",m("thread.context.none.instructions","No project instructions found.")));for(let t of e){let n=xe("details","bp-context-card"),i=xe("summary");if(i.append(gn(t.path,t.status),xe("small","bp-dim",m("thread.context.size","{bytes} B · ≈{tokens} tokens",{bytes:t.bytes,tokens:t.estimated_tokens}))),n.append(i,ei(t.preview)),t.note)n.append(xe("small","bp-dim",t.note));this.body.append(n)}}prompt(e){let t=xe("div","bp-context-row"),n=_t(m("thread.context.copy","Copy prompt"),()=>{navigator.clipboard.writeText(e.prompt).then(()=>{this.notice.textContent=m("thread.context.copied","Prompt copied.")}).catch((i)=>{this.notice.textContent=String(i)})});t.append(xe("p","bp-dim",m("thread.context.native.note","Backplane’s launch prompt. Native files are loaded by the provider.")),n),this.body.append(t);for(let[i,s]of[[m("thread.context.base","Backplane"),e.sections.base],[m("thread.context.injected.label","Injected project instructions"),e.sections.instructions],[m("thread.context.index","Available skills index"),e.sections.skills]])if(s)this.body.append(xe("h3",void 0,i),ei(s))}skills(e){for(let t of["Project","User","Bundled"]){let n=e.filter((i)=>i.scope===t);if(!n.length)continue;this.body.append(xe("h3",void 0,he(t)));for(let i of n){let s=xe("article","bp-context-card");s.append(gn(i.name,i.status),xe("p",void 0,i.description),xe("small","bp-context-path",[i.source,i.provider,i.model].filter(Boolean).join(" · ")),xe("small","bp-context-path",i.path)),this.body.append(s)}}}mcps(e){if(!e.length)this.body.append(xe("p","bp-dim",m("thread.context.none.mcp","No project MCP configurations found.")));for(let t of e){let n=xe("article","bp-context-card");n.append(gn(t.path,t.state));for(let s of t.servers){let r=s.url||[s.command,...s.args].map((o)=>JSON.stringify(o)).join(" ");if(n.append(gn(s.name,s.status),ei(r)),s.cwd)n.append(xe("small","bp-context-path",s.cwd))}if(t.error)n.append(xe("p","bp-warn",t.error));let i=t.state==="Untrusted"?"trust":t.state==="Enabled"?"disable":t.state==="Disabled"?"enable":"";if(i){let s=i==="trust"?m("thread.context.trust","Trust and enable"):i==="disable"?m("thread.context.disable","Disable"):m("thread.context.enable","Enable"),r=_t(s,()=>{this.load({action:i,path:t.path,sha256:t.sha256})},i==="trust");r.disabled=this.busy;let o=xe("div","bp-context-actions");o.append(r),n.append(o)}this.body.append(n)}}}var yt="chats";function Js(e){return e.filter((t)=>t.id&&t.id!==yt&&t.id!=="scratch"&&!t.id.includes("~")).slice().sort((t,n)=>(t.title||t.id).toLowerCase().localeCompare((n.title||n.id).toLowerCase()))}function uo(e){if(!e)return null;if(e.moving?.state==="moving")return{text:e.moving.step?m("home.moving.step","Moving home to {to}: {step}").replace("{to}",e.moving.to).replace("{step}",e.moving.step):m("home.moving","Moving home to {to}…").replace("{to}",e.moving.to),isError:!1,dismissible:!1};if(e.moving?.state==="failed")return{text:e.moving.note?m("home.move.failed.note","Home move failed: {note}").replace("{note}",e.moving.note):m("home.move.failed","Home move failed"),isError:!0,dismissible:!0};if(!e.online){let t=e.name||"home",n="";if(e.awaySince&&e.awaySince>0){let s=new Date(e.awaySince);n=`${String(s.getHours()).padStart(2,"0")}:${String(s.getMinutes()).padStart(2,"0")}`}let i="";if(n&&e.queuedCount>0)i=m("home.away.since.queued","Home ({name}) is away since {time} · {n} queued").replace("{name}",t).replace("{time}",n).replace("{n}",String(e.queuedCount));else if(n)i=m("home.away.since","Home ({name}) is away since {time}").replace("{name}",t).replace("{time}",n);else if(e.queuedCount>0)i=m("home.away.queued","Home ({name}) is away · {n} queued").replace("{name}",t).replace("{n}",String(e.queuedCount));else i=m("home.away","Home ({name}) is away").replace("{name}",t);return{text:i,isError:!1,dismissible:!1}}return null}function bo(e,t){if(e.settled)return!1;if(e.state==="done"||e.state==="stopped")return!1;if(!t)return!0;let n=e.working??0,i=Boolean(e.monitoring),s=Boolean(Kn(e.need))||e.word==="needs";return(n>0||i)&&e.state!=="paused"||s}function go(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 _s="http://www.w3.org/2000/svg";function pt(e,t=14,n=""){let i=document.createElementNS(_s,"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(_s,"path");r.setAttribute("d",s),i.appendChild(r)}return i}function zs(){return pt(["M3 6h6l2 2h10v11H3z"],14,"bp-folder-icon")}function qs(e=14,t="bp-folder-icon bp-hw-icon"){return pt(["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 fo(e=13){return pt(["M6 6h12v12H6z","M9 2v4","M15 2v4","M9 18v4","M15 18v4","M2 9h4","M2 15h4","M18 9h4","M18 15h4"],e)}function vo(e=15){return pt(["M4 10V4l4 3h8l4-3v6l-2 9H6z","M9 13h1","M14 13h1","M11 16h2"],e,"bp-cat-glyph")}function wo(e=11){return pt(["M4 12l5 5 11-11"],e)}function yo(e=13){return pt(["M12 3H5a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7","M18.4 2.6a2.1 2.1 0 0 1 3 3L12 15l-4 1 1-4z"],e)}function Eo(e=11){return pt(["M2 9V5a2 2 0 0 1 2-2h4l2 3h10a2 2 0 0 1 2 2v10a2 2 0 0 1-2 2H2","M2 13h10","M9 16l3-3-3-3"],e)}function Co(){return typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.platform||"")?"⌥⇧N":"Alt+Shift+N"}function ko(e=11){return pt(["M12 22a10 10 0 1 0 0-20 10 10 0 0 0 0 20z","M12 6v6l4 2"],e)}function xo(e=11){return pt(["M12 17v5","M8 4h8l-1 5 3 3v2H6v-2l3-3z"],e,"bp-pin-icon")}function Ks(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 Po(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 ni(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 ii{el;hostLabel;homeBanner;crewEl;filterInput;listEl;connEl;filterText="";allFilter="all";snoozeMenuRowId="";collapsedProjects=new Set;addShown=!1;sections=null;projects=[];selectedProjectId="";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 o=document.createElement("div");o.className="bp-side-head",this.filterInput=document.createElement("input"),this.filterInput.type="search",this.filterInput.className="bp-input bp-side-search";let a=m("sidebar.search.projects","Search projects, threads…");this.filterInput.placeholder=a,this.filterInput.setAttribute("aria-label",a),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=m("thread.new","New thread"),c.setAttribute("aria-label",m("thread.new","New thread")),c.setAttribute("data-testid","sidebar-new-thread"),c.addEventListener("click",()=>{let d=this.firstProjectId();if(d)this.cb.onNewThread(d)});let p=document.createElement("button");p.type="button",p.className="icon bp-side-add bp-side-new-chat",p.appendChild(yo(13));let l=`${m("chats.new.noproject","New chat (no project)")} (${Co()})`;p.title=l,p.setAttribute("aria-label",m("chats.new.noproject","New chat (no project)")),p.setAttribute("data-testid","sidebar-new-chat"),p.addEventListener("click",()=>this.cb.onNewChat?.()),o.append(this.filterInput,p,c),this.homeBanner=document.createElement("div"),this.homeBanner.className="bp-side-home bp-hidden",this.homeBanner.setAttribute("data-testid","home-away-banner"),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 h=document.createElement("div");h.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"),h.appendChild(this.connEl),this.el.append(n,o,this.homeBanner,this.crewEl,this.listEl,h)}setHome(e){let t=uo(e);if(!t){this.homeBanner.className="bp-side-home bp-hidden",this.homeBanner.replaceChildren();return}this.homeBanner.className=t.isError?"bp-side-home bp-bad":"bp-side-home bp-dim";let n=document.createElement("span");if(n.className="bp-side-home-text",n.textContent=t.text,!t.dismissible){this.homeBanner.replaceChildren(n);return}let i=document.createElement("button");i.type="button",i.className="icon bp-side-home-dismiss",i.textContent="×",i.setAttribute("data-testid","home-move-dismiss");let s=m("approval.dismiss","Dismiss");i.title=s,i.setAttribute("aria-label",s),i.addEventListener("click",()=>this.cb.onDismissHomeMove?.()),this.homeBanner.replaceChildren(n,i)}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()}setSelectedProject(e){if(this.selectedProjectId===e)return;this.selectedProjectId=e,this.render()}makeFoldChevron(e,t){let n=document.createElement("button");n.type="button",n.className="bp-proj-chev"+(e?" folded":""),n.textContent=e?"▸":"▾";let i=e?m("web.home.unfold","Show threads"):m("web.home.fold","Hide threads");return n.title=i,n.setAttribute("aria-label",i),n.setAttribute("aria-expanded",e?"false":"true"),n.setAttribute("data-testid",`project-fold-${t}`),n}focusFilter(){this.filterInput.focus()}firstProjectId(){if(this.sections){for(let e of this.sections)if(e.kind==="projects"&&e.rows.length>0){let t=e.rows[0];if(t.id&&!t.off)return t.id}}return this.projects[0]?.id??""}refreshLocale(){let e=m("sidebar.search.projects","Search projects, threads…");this.filterInput.placeholder=e,this.filterInput.setAttribute("aria-label",e),this.render()}renderCrewBand(e){let t=this.bots.find((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,o=i.length>0||Boolean(this.cb.onNewRoom)&&!e;if(!s&&!r&&!o){this.crewEl.classList.add("bp-hidden"),this.crewEl.replaceChildren();return}let a=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 p=document.createElement("span");if(p.className=`bp-crew-uber-avatar ${ni(t.mood)}`,t.color)p.style.color=t.color;p.appendChild(vo(14));let l=document.createElement("span");l.className="bp-crew-uber-meta";let h=document.createElement("span");if(h.className="bp-crew-uber-name",h.textContent=t.name,l.appendChild(h),t.note){let d=document.createElement("span");d.className=`bp-crew-uber-note ${ni(t.mood)}`,d.textContent=t.note,l.appendChild(d)}if(c.append(p,l),t.mood==="wait"||t.mood==="error"){let d=document.createElement("span");d.className="bp-status-pill bp-pill-bad",d.textContent="? Input",c.appendChild(d)}c.addEventListener("click",()=>this.cb.onSelectBot(t)),a.appendChild(c)}if(r){let c=document.createElement("div");c.className="bp-crew-bots",c.setAttribute("data-testid","crew-bots");let p=document.createElement("span");p.className="bp-crew-lbl",p.textContent=m("tour.title.bots","Bots").toUpperCase(),c.appendChild(p);let l=document.createElement("div");l.className="bp-crew-bot-tiles";for(let h of n){let d=document.createElement("button");if(d.type="button",d.className=`bp-crew-bot-tile ${ni(h.mood)}`+(h.thread===this.selectedThreadId?" active":""),d.title=h.note?`@${h.name} — ${h.note}`:`@${h.name}`,d.setAttribute("aria-label",`@${h.name}`),d.setAttribute("data-testid",`crew-bot-${h.id}`),h.color)d.style.setProperty("--bot-c",h.color);let u=document.createElement("span");if(u.className="bp-crew-bot-init",u.textContent=Po(h.name),d.appendChild(u),h.mood==="wait"||h.mood==="error"){let f=document.createElement("span");f.className="bp-crew-bot-wait",d.appendChild(f)}d.addEventListener("click",()=>this.cb.onSelectBot(h)),l.appendChild(d)}if(this.cb.onNewBot&&!e){let h=document.createElement("button");h.type="button",h.className="bp-crew-bot-tile bp-crew-add",h.textContent="+",h.title=m("bots.new","New bot"),h.setAttribute("aria-label",m("bots.new","New bot")),h.setAttribute("data-testid","crew-new-bot"),h.addEventListener("click",()=>this.cb.onNewBot?.()),l.appendChild(h)}c.appendChild(l),a.appendChild(c)}if(o){let c=document.createElement("div");c.className="bp-crew-rooms",c.setAttribute("data-testid","crew-rooms");for(let p of i){let l=document.createElement("button");l.type="button",l.className="bp-crew-room-chip",l.setAttribute("data-testid",`crew-room-${p.id}`);let h=document.createElement("span");h.className="bp-dim",h.textContent="#";let d=document.createElement("span");if(d.textContent=p.name,l.append(h,d),p.members!==void 0&&p.members>0){let u=document.createElement("span");u.className="bp-crew-room-cnt",u.textContent=String(p.members),l.appendChild(u)}l.title=p.members?`#${p.name} (${p.members})`:`#${p.name}`,l.addEventListener("click",()=>this.cb.onSelectRoom?.(p)),c.appendChild(l)}if(this.cb.onNewRoom&&!e){let p=document.createElement("button");p.type="button",p.className="bp-crew-room-chip bp-crew-add",p.textContent="+",p.title=m("rooms.new","New room"),p.setAttribute("aria-label",m("rooms.new","New room")),p.setAttribute("data-testid","crew-new-room"),p.addEventListener("click",()=>this.cb.onNewRoom?.()),c.appendChild(p)}a.appendChild(c)}this.crewEl.classList.remove("bp-hidden"),this.crewEl.replaceChildren(a)}projectsHead(e){let t=document.createElement("div");if(t.className="bp-side-section-head",!this.cb.onAddProject||this.addShown)return t.textContent=e,t;this.addShown=!0,t.classList.add("bp-side-section-row");let n=document.createElement("span");n.textContent=e;let i=document.createElement("button");i.type="button",i.className="bp-side-sec-plus bp-side-sec-btn",i.textContent="+";let s=m("sidebar.add.project","Add project");return i.title=s,i.setAttribute("aria-label",s),i.setAttribute("data-testid","sidebar-add-project"),i.addEventListener("click",(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=e.kind==="swarm",s=Boolean(e.settle)&&(!i||Boolean(this.cb.onSettleSwarm)),r=Boolean(e.chat)&&Boolean(this.cb.onMoveToProject);if(!t&&!n&&!s&&!r)return null;let o=document.createElement("span");if(o.className="bp-row-acts",n&&e.wake){let a=document.createElement("button");a.type="button",a.className="bp-row-act-btn bp-wake-btn",a.textContent=m("menu.wake","Wake"),a.title=m("menu.wake","Wake snoozed thread"),a.setAttribute("data-testid",`wake-row-${e.id}`),a.addEventListener("click",(c)=>{c.stopPropagation(),this.cb.onSnoozeRow?.(e.wake)}),o.appendChild(a)}if(t&&e.snooze){let a=document.createElement("button");a.type="button",a.className="bp-row-act-btn bp-snooze-btn",a.title=m("menu.snooze","Snooze thread"),a.setAttribute("aria-label",m("menu.snooze","Snooze thread")),a.setAttribute("data-testid",`snooze-row-${e.id}`),a.appendChild(ko(11)),a.addEventListener("click",(c)=>{c.stopPropagation(),this.snoozeMenuRowId=this.snoozeMenuRowId===e.id?"":e.id,this.render()}),o.appendChild(a)}if(r){let a=document.createElement("button");a.type="button",a.className="bp-row-act-btn bp-move-btn",a.title=m("chats.move","Move to project…"),a.setAttribute("aria-label",m("chats.move","Move to project…")),a.setAttribute("data-testid",`move-row-${e.id}`),a.appendChild(Eo(11)),a.addEventListener("click",(c)=>{c.stopPropagation(),this.cb.onMoveToProject?.(Qe(e.id))}),o.appendChild(a)}if(s&&e.settle){let a=document.createElement("button");a.type="button",a.className="bp-row-act-btn bp-settle-btn",a.title=m("menu.settle","Settle"),a.setAttribute("aria-label",m("menu.settle","Settle")),a.setAttribute("data-testid",`settle-row-${e.id}`),a.appendChild(wo(11)),a.addEventListener("click",(c)=>{if(c.stopPropagation(),i)this.cb.onSettleSwarm?.(Qe(e.settle));else this.cb.onThreadAct(Qe(e.settle),"settle")}),o.appendChild(a)}return o}renderSectionThreadRow(e,t,n=!1){let i=document.createElement("div");i.className="bp-thread-row"+(n?" bp-inbox-row":"")+(!this.selectedProjectId&&(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=go(e),r=this.renderRowActions(e);if(n){let l=document.createElement("div");l.className="bp-inbox-main";let h=document.createElement("div");h.className="bp-inbox-top";let d=document.createElement("div");if(d.className="bp-thread-title",d.textContent=e.title||"Untitled thread",h.appendChild(d),r)h.appendChild(r);let u=document.createElement("div");if(u.className="bp-inbox-meta",s)u.appendChild(this.renderStatusPill(s,e.say));if(e.project&&!e.chat){let f=document.createElement("span");f.className="bp-inbox-proj",f.textContent=e.project,u.appendChild(f)}if(e.ago){let f=document.createElement("span");if(f.className="bp-thread-age",f.textContent=e.ago,e.pinned)f.title=m("tools.pinned","Pinned");u.appendChild(f)}l.append(h,u),i.appendChild(l)}else{if(t){let h=document.createElement("span");h.className="bp-tree-branch",h.setAttribute("aria-hidden","true"),i.appendChild(h)}if(s)i.appendChild(this.renderStatusPill(s,e.say));let l=document.createElement("div");if(l.className="bp-thread-title",l.textContent=e.title||"Untitled thread",i.appendChild(l),r)i.appendChild(r);if(e.ago){let h=document.createElement("span");if(h.className="bp-thread-age",h.textContent=e.ago,e.pinned)h.title=m("tools.pinned","Pinned");i.appendChild(h)}}let o=e.nav||e.id;if(!e.off&&o&&!o.startsWith("@room:"))i.addEventListener("click",()=>this.cb.onSelectThread(Qe(o)));let a=this.snoozeMenuRowId===e.id&&Array.isArray(e.snooze)&&e.snooze.length>0,c=e.kind==="swarm"?Kn(e.need):null;if(!c&&!a)return i;let p=document.createElement("div");if(p.className="bp-need-wrap",p.appendChild(i),a&&e.snooze){let l=document.createElement("div");l.className="bp-snooze-bar"+(t?" nested":""),l.setAttribute("data-testid",`snooze-bar-${e.id}`);let h=document.createElement("span");h.className="bp-dim",h.textContent="Snooze:",l.appendChild(h);for(let d of e.snooze){let u=document.createElement("button");u.type="button",u.className="bp-snooze-opt",u.textContent=d.label,u.addEventListener("click",(f)=>{f.stopPropagation(),this.snoozeMenuRowId="",this.cb.onSnoozeRow?.(d.value),this.render()}),l.appendChild(u)}p.appendChild(l)}if(c){let l=document.createElement("div");l.className="bp-need"+(t?" nested":"")+(e.off?" bp-dim":""),l.setAttribute("data-testid",`need-${e.id}`);let h=document.createElement("span");h.className="bp-need-line",h.textContent=c.line,h.title=c.line,l.appendChild(h);for(let u of c.actions){if(!un(u,Boolean(this.cb.hasRoomView)))continue;let f=document.createElement("button");f.type="button",f.className="bp-need-btn",f.textContent=u.label,f.setAttribute("data-testid",`need-${u.act}-${e.id}`),f.disabled=Boolean(e.off)||this.needBusy.has(e.id)||!this.cb.onNeedAct,f.addEventListener("click",(b)=>{b.stopPropagation();let v=this.cb.onNeedAct;if(!v)return;this.needErr.delete(e.id),this.needBusy.add(e.id),this.render(),v(u).catch((w)=>{this.needErr.set(e.id,w instanceof Error?w.message:String(w))}).finally(()=>{this.needBusy.delete(e.id),this.render()})}),l.appendChild(f)}p.appendChild(l);let d=this.needErr.get(e.id);if(d){let u=document.createElement("div");u.className="bp-need-err"+(t?" nested":""),u.textContent=d,p.appendChild(u)}}return p}renderHubSections(e,t){let n=this.sections??[],i=new Set;for(let o of n)if(o.kind==="threads")for(let a of o.rows)i.add(a.id),i.add(Qe(a.id));else if(o.kind==="projects")for(let a of o.rows)for(let c of a.threads??[])i.add(c.id),i.add(Qe(c.id));let s=this.selectedThreadId?this.threads.find((o)=>o.id===this.selectedThreadId)??null:null,r=!1;for(let o of n)if(o.kind==="projects"&&(o.rows.length>0||(o.count??0)>0))r=!0;for(let o of n){if(o.kind==="bub")continue;if(o.kind==="threads"){let a=Boolean(o.fold&&o.toggle),c=o.rows.filter((l)=>{if(!t)return!0;return`${l.title} ${l.project??""}`.toLowerCase().includes(t)});if(!a&&c.length===0)continue;if(a&&t&&c.length===0)continue;if(a&&!t&&(o.count??c.length)===0)continue;let p=document.createElement("section");if(p.className=`bp-side-section bp-side-inbox bp-sec-${o.id}`,p.setAttribute("data-section-id",o.id),a){let l=document.createElement("button");l.type="button",l.className="bp-side-section-head bp-side-section-toggle";let h=t?c.length:o.count??c.length,d=o.open||Boolean(t)?"▾":"▸";if(l.textContent=`${d} ${o.title.toUpperCase()} (${h})`,o.hint)l.title=o.hint;l.setAttribute("data-testid",`section-toggle-${o.id}`),l.addEventListener("click",()=>{if(o.toggle)this.cb.onToggleSection?.(o.toggle)}),p.appendChild(l)}else{let l=document.createElement("div");if(l.className="bp-side-section-head"+(o.id==="needs"?" bp-head-needs":o.id==="running"?" bp-head-running":""),o.id===yt&&this.cb.onNewChat){l.classList.add("bp-side-section-row");let h=document.createElement("span");h.textContent=`${m("chats.title",o.title).toUpperCase()} ${c.length}`;let d=document.createElement("button");d.type="button",d.className="bp-side-sec-plus bp-side-sec-btn",d.textContent="+",d.title=m("chats.new.noproject","New chat (no project)"),d.setAttribute("aria-label",d.title),d.setAttribute("data-testid","section-new-chat"),d.addEventListener("click",(u)=>{u.stopPropagation(),this.cb.onNewChat?.()}),l.append(h,d)}else l.textContent=`${o.title.toUpperCase()} ${c.length}`;p.appendChild(l)}if(!a||Boolean(o.open)||Boolean(t))for(let l of c)p.appendChild(this.renderSectionThreadRow(l,!1,!0));e.appendChild(p);continue}if(o.kind==="projects"){let a=o.rows,c=a.filter((d)=>{if(!t)return!0;if((d.title||d.id).toLowerCase().includes(t))return!0;if((d.threads??[]).some((u)=>u.title.toLowerCase().includes(t)))return!0;if((d.swarms??[]).some((u)=>u.title.toLowerCase().includes(t)))return!0;return!1}),p=Boolean(o.fold&&o.toggle);if(t&&c.length===0)continue;if(!p&&o.id!=="active"&&c.length===0)continue;let l=document.createElement("section");if(l.className=`bp-side-section bp-sec-${o.id}`,l.setAttribute("data-section-id",o.id),p){let d=document.createElement("button");d.type="button",d.className="bp-side-section-head bp-side-section-toggle";let u=t?c.length:o.count??c.length,f=o.open||Boolean(t)?"▾":"▸";if(d.textContent=`${f} ${o.title.toUpperCase()} (${u})`,o.hint)d.title=o.hint;d.setAttribute("data-testid",`section-toggle-${o.id}`),d.addEventListener("click",()=>{if(o.toggle)this.cb.onToggleSection?.(o.toggle)}),l.appendChild(d)}else l.appendChild(this.projectsHead(o.title.toUpperCase()));if(!p||Boolean(o.open)||Boolean(t)){if(o.id==="all"&&!t){let d=a.some((f)=>f.hasBoard||f.hasSchematic),u=a.some((f)=>!f.hasBoard&&!f.hasSchematic);if(d&&u){let f=document.createElement("div");f.className="bp-proj-filter",f.setAttribute("data-testid","all-projects-filter");let b=[{id:"all",label:"All"},{id:"hw",label:"Boards"},{id:"sw",label:"Code"}];for(let v of b){let w=document.createElement("button");w.type="button",w.className="bp-proj-filter-btn"+(this.allFilter===v.id?" active":""),w.textContent=v.label,w.addEventListener("click",()=>{this.allFilter=v.id,this.render()}),f.appendChild(w)}if(l.appendChild(f),this.allFilter==="hw")c=c.filter((v)=>v.hasBoard||v.hasSchematic);else if(this.allFilter==="sw")c=c.filter((v)=>!v.hasBoard&&!v.hasSchematic)}}if(o.id==="active"&&!r&&!t){let d=document.createElement("div");d.className="bp-side-empty",d.textContent="No projects yet.",l.appendChild(d)}for(let d of c){let u=document.createElement("div");if(u.className="bp-proj-group"+(d.off||o.id==="quiet"?" bp-dim":""),u.setAttribute("data-project-id",d.id),d.nav||d.key)u.setAttribute("data-project-key",d.nav||d.key||"");let f=document.createElement("div");f.className="bp-proj-head";let b=document.createElement("button");b.type="button",b.className="bp-proj-toggle";let w=Boolean(d.hasBoard||d.hasSchematic)?qs(14):zs();if(d.css)w.style.color=d.css;let E=document.createElement("span");E.className="bp-proj-name",E.textContent=d.title||d.id,b.append(w,E);let k=d.fold==="project-fold"&&Boolean(d.nav),L=()=>{if(k)this.cb.onToggleProjectFold?.(d.nav)};if(!d.off&&this.cb.canOpenProject?.())b.title=m("web.home.open","Open project home");if(b.setAttribute("data-testid",`project-open-${d.id}`),this.selectedProjectId&&Qe(d.id)===this.selectedProjectId)f.classList.add("active");b.addEventListener("click",()=>{if(d.off||!this.cb.onOpenProject?.(d.id))L()});let M=this.makeFoldChevron(Boolean(d.folded),d.id);if(k)M.addEventListener("click",(P)=>{P.stopPropagation(),L()});else M.disabled=!0;f.appendChild(M);let A=document.createElement("div");if(A.className="bp-proj-meta",(d.needsCount??0)>0){let P=document.createElement("span");P.className="bp-proj-badge-need",P.textContent=String(d.needsCount),P.title=`${d.needsCount} needing you`,A.appendChild(P)}if((d.running??0)>0){let P=document.createElement("span");P.className="bp-proj-badge-run",P.textContent=String(d.running),P.title=`${d.running} running`,A.appendChild(P)}if(d.pinned&&o.id!=="pinned")A.appendChild(xo(11));let B=document.createElement("div");if(B.className="bp-proj-acts",!d.off&&this.cb.onQuickOpenViewer){if(d.hasBoard){let P=document.createElement("button");P.type="button",P.className="bp-proj-quick",P.title=m("viewer.board","Open Board"),P.setAttribute("aria-label",`Open Board (${d.title})`),P.setAttribute("data-testid",`quick-board-${d.id}`),P.appendChild(qs(13,"")),P.addEventListener("click",(Y)=>{Y.stopPropagation(),this.cb.onQuickOpenViewer?.(Qe(d.id),"board")}),B.appendChild(P)}if(d.hasSchematic){let P=document.createElement("button");P.type="button",P.className="bp-proj-quick",P.title=m("viewer.schematic","Open Schematic"),P.setAttribute("aria-label",`Open Schematic (${d.title})`),P.setAttribute("data-testid",`quick-sch-${d.id}`),P.appendChild(fo(13)),P.addEventListener("click",(Y)=>{Y.stopPropagation(),this.cb.onQuickOpenViewer?.(Qe(d.id),"schematic")}),B.appendChild(P)}}let T=document.createElement("button");if(T.type="button",T.className="icon bp-proj-add",T.title=m("thread.new","New thread"),T.textContent="+",T.setAttribute("data-testid",`new-thread-${d.id}`),d.off)T.disabled=!0;T.addEventListener("click",(P)=>{P.stopPropagation(),this.cb.onNewThread(Qe(d.id))}),B.appendChild(T),f.append(b,A,B),u.appendChild(f);let H=Boolean(t)&&(d.title||d.id).toLowerCase().includes(t),O=Boolean(d.folded&&!t);for(let P of d.swarms??[]){if(!bo(P,O))continue;if(t&&!H&&!P.title.toLowerCase().includes(t))continue;u.appendChild(this.renderSectionThreadRow(P,!0))}if(!O){for(let P of d.threads??[]){if(t&&!H&&!P.title.toLowerCase().includes(t))continue;u.appendChild(this.renderSectionThreadRow(P,!0))}if(s&&s.project===Qe(d.id)&&!i.has(s.id)&&(!t||H||s.title.toLowerCase().includes(t)))u.appendChild(this.renderSectionThreadRow({id:s.id,title:s.title,status:s.status,state:s.state,ago:Ks(s.updatedAt),pinned:s.pinned,nav:s.id},!0))}l.appendChild(u)}}e.appendChild(l)}}}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 o=document.createElement("div");o.className="bp-proj-head";let a=document.createElement("button");a.type="button",a.className="bp-proj-toggle";let c=this.collapsedProjects.has(i.id)&&!e,p=zs();if(i.css)p.style.color=i.css;let l=document.createElement("span");l.className="bp-proj-name",l.textContent=i.title||i.id,a.append(p,l);let h=()=>{if(this.collapsedProjects.has(i.id))this.collapsedProjects.delete(i.id);else this.collapsedProjects.add(i.id);this.render()};if(this.cb.canOpenProject?.())a.title=m("web.home.open","Open project home");if(a.setAttribute("data-testid",`project-open-${i.id}`),this.selectedProjectId&&i.id===this.selectedProjectId)o.classList.add("active");a.addEventListener("click",()=>{if(!this.cb.onOpenProject?.(i.id))h()});let d=this.makeFoldChevron(c,i.id);d.addEventListener("click",(f)=>{f.stopPropagation(),h()}),o.appendChild(d);let u=document.createElement("button");if(u.type="button",u.className="icon bp-proj-add",u.title=m("thread.new","New thread"),u.textContent="+",u.setAttribute("data-testid",`new-thread-${i.id}`),u.addEventListener("click",(f)=>{f.stopPropagation(),this.cb.onNewThread(i.id)}),o.append(a,u),r.appendChild(o),!c)for(let f of s)r.appendChild(this.renderSectionThreadRow({id:f.id,title:f.title,status:f.status,state:f.state,ago:Ks(f.updatedAt),pinned:f.pinned,nav:f.id},!0));t.appendChild(r)}}this.listEl.replaceChildren(t)}}function So(e){try{return new URL(e,window.location.origin).searchParams.get("s")||""}catch{return""}}function zt(e){if(!e)return;for(let t of e.getTracks())try{t.stop()}catch{}}function Lo(e,t){if(t===16000){let r=new Int16Array(e.length);for(let o=0;o0?c/p:0));s[r]=l<0?l*32768:l*32767}return s}class si{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){zt(n);return}if(this.stream=n,await this.stopDrain,t!==this.sessionGen||this.cb.getThreadId()!==e){if(zt(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(zt(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?So(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(zt(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 o=new Int16Array(this.pendingPcm);this.pendingPcm=[],this.enqueuePost(i,new Uint8Array(o.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??""),o=Math.max(0,Math.min(i.length,this.mark)),a=Math.max(0,o-s),c=i.slice(0,a)+r+i.slice(o);this.mark=a+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=(o)=>{if(!this.active||t!==this.sessionGen||!this.sessionKey)return;let a=Lo(o.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;zt(this.stream),this.stream=null}}var Ys=[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],Xs=[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],Qs=[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],Zs=[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],Ao=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];function qt(e,t){let n=new Int32Array(16),i=0;for(let a=0;a0){if(n[c]++,c>i)i=c}}let s=new Int32Array(16),r=0;for(let a=1;a<=15;a++)s[a]=r,r+=n[a];let o=new Int32Array(r);for(let a=0;a0)o[s[c]++]=a}return{counts:n,symbols:o,maxBits:i}}var No=(()=>{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),qt(e,288)})(),Mo=(()=>{let e=new Uint8Array(32);return e.fill(5),qt(e,32)})();class ri{win=new Uint8Array(32768);winPos=0;feed(e,t=16777216){let n=0,i=0,s=0,r=(h)=>{while(s=e.length)throw Error("truncated deflate frame");i|=e[n++]<>>=h,s-=h,d},o=(h)=>{let d=0,u=0,f=0;for(let b=1;b<=h.maxBits;b++){d|=r(1);let v=h.counts[b];if(d-v{let d=c+h;if(d>t)throw Error("inflated frame exceeds limit");if(d<=a.length)return;let u=a.length;while(u{p(1),a[c++]=h,this.win[this.winPos]=h,this.winPos=this.winPos+1&32767};while(n0){if(n>=e.length&&s<3)break;let h=r(1),d=r(2);if(d===0){if(i=0,s=0,n+4>e.length)throw Error("truncated stored block");let u=e[n]|e[n+1]<<8,f=e[n+2]|e[n+3]<<8;if(n+=4,(u^65535)!==f)throw Error("invalid stored block length");if(n+u>e.length)throw Error("truncated stored payload");p(u);for(let b=0;b=e.length)break}else if(d===1||d===2){let u=No,f=Mo;if(d===2){let b=r(5)+257,v=r(5)+1,w=r(4)+4,E=new Uint8Array(19);for(let B=0;BL)throw Error("code length overflow");for(let O=0;OL)throw Error("code length overflow");A+=T}else if(B===18){let T=r(7)+11;if(A+T>L)throw Error("code length overflow");A+=T}else throw Error("invalid code length symbol")}u=qt(M,b),f=qt(M.subarray(b),v)}while(!0){let b=o(u);if(b<256)l(b);else if(b===256)break;else{let v=b-257;if(v>=Ys.length)throw Error("invalid length symbol");let w=Ys[v]+(Xs[v]?r(Xs[v]):0),E=o(f);if(E>=Qs.length)throw Error("invalid distance symbol");let k=Qs[E]+(Zs[E]?r(Zs[E]):0);p(w);let L=this.winPos-k&32767;for(let M=0;M{this.stateListeners.delete(e)}}onFrame(e){return this.frameListeners.add(e),()=>{this.frameListeners.delete(e)}}onBinary(e){return this.binaryListeners.add(e),()=>{this.binaryListeners.delete(e)}}rpc(e,t={},n=20000){return new Promise((i,s)=>{if(!this.ws||this.ws.readyState!==WebSocket.OPEN){s(Error("Not connected to hub"));return}let r=this.nextId++,o=window.setTimeout(()=>{this.pending.delete(r),s(Error(`RPC timeout: ${e}`))},n);this.pending.set(r,{resolve:i,reject:s,timer:o}),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 ri:null,this.reconnectDelay=500,this.setState("connected");else if(r.t==="reply"&&typeof r.id==="number"){let o=this.pending.get(r.id);if(o)if(this.pending.delete(r.id),window.clearTimeout(o.timer),r.ok)o.resolve(r.result??{});else{let a=r.error,c=typeof a==="string"?a:a&&typeof a==="object"&&("message"in a)?String(a.message):"Request failed",p=typeof r.errorCode==="string"?r.errorCode:void 0,l=typeof r.machine==="string"?r.machine:void 0,h=typeof r.thread==="string"?r.thread:void 0;o.reject(new Kt(c,{code:p,machine:l,thread:h}))}return}for(let o of this.frameListeners)o(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 o=r.buffer.slice(r.byteOffset,r.byteOffset+r.byteLength);for(let a of this.binaryListeners)a(o)}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 To=new TextDecoder;function er(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 tr(e){let t=0,n=0;function i(o){if(o<=23)return o;if(o===24){if(t>=e.length)return null;return e[t++]}if(o===25){if(t+2>e.length)return null;let a=e[t]<<8|e[t+1];return t+=2,a}if(o===26){if(t+4>e.length)return null;let a=(e[t]<<24|e[t+1]<<16|e[t+2]<<8|e[t+3])>>>0;return t+=4,a}return null}function s(o){if(n++,o>32||n>400000||t>=e.length)return null;let a=e[t++],c=a>>5,p=i(a&31);if(p===null)return null;switch(c){case 0:return p;case 1:return-1-p;case 2:{if(t+p>e.length)return null;let l=e.subarray(t,t+p);return t+=p,l}case 3:{if(t+p>e.length)return null;let l=To.decode(e.subarray(t,t+p));return t+=p,l}case 4:{if(p>e.length)return null;let l=Array(p);for(let h=0;h=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 ir(e){let t=0xcbf29ce484222325n,n=0x100000001b3n,i=0xffffffffffffffffn;for(let s=0;stypeof e[b]==="number"?e[b]:v,n=t("l",0),i=t("c",0),s=t("a",255)/255,r=t("m",1),o=t("w",0),a=o/2,c=r===0&&o!==0,p=e.d instanceof Uint8Array?e.d:new Uint8Array(0),l=new nr(p),h=[],d=[],u=0,f=0;while(l.more()){let b=l.nextU32(),v=h.length,w=1/0,E=1/0,k=-1/0,L=-1/0;if(r===2)u=u+l.nextI32()|0,f=f+l.nextI32()|0,h.push(u,f),w=k=u,E=L=f;else{let A=Math.min(l.nextU32(),1048576);for(let B=0;Bk)k=u;if(fL)L=f}}let M=(h.length-v)/2;if(M>0){let A=r===2||M===1?2:r===0?0:1,B=r===0?0:a;d.push({info:b,x0:w-B,y0:E-B,x1:k+B,y1:L+B,at:v,n:M,kind:A})}}return{layer:n,color:i,alpha:s,mode:r,r:a,own:c,pts:new Float32Array(h),pieces:d}}function sr(e,t,n){let i=(o)=>Array.isArray(o)&&o.length>=4?[Number(o[0])||0,Number(o[1])||0,Number(o[2])||0,Number(o[3])||0]:[0,0,0,0],s=Array.isArray(e.cs)?e.cs:[],r=[];for(let o=0;o=0&&a0){n.delete(a.h),n.set(a.h,c);while(n.size>1024){let p=n.keys().next().value;if(p!==void 0)n.delete(p);else break}}}}return{key:typeof e.key==="string"?e.key:"",fam:typeof e.fam==="string"?e.fam:"",base:typeof e.base==="string"?e.base:"",box:i(e.box),edge:i(e.edge),thick:typeof e.thick==="number"?e.thick:1600,note:typeof e.note==="string"?e.note:"",warn:typeof e.warn==="number"?e.warn!==0:!1,chunks:r}}function rr(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,o=n.naturalHeight*s,a=n.left+(n.width-r)/2,c=i?n.top:n.top+(n.height-o)/2,p=(e-a)/r,l=(t-c)/o;if(p<0||p>1||l<0||l>1)return null;return{x:Math.max(0,Math.min(1000,Math.round(p*1000))),y:Math.max(0,Math.min(1000,Math.round(l*1000)))}}var or=[["Enter","Enter"],["Tab","Tab"],["Bksp","Backspace"],["Esc","Escape"],["↑","ArrowUp"],["↓","ArrowDown"],["←","ArrowLeft"],["→","ArrowRight"]];function ar(e){let t=e.trim();if(!t)return"";if(/^[a-zA-Z][a-zA-Z0-9+.-]*:/.test(t))return t;return`https://${t}`}class ai{tail=Promise.resolve();enqueue(e){let t=this.tail.then(e,e);return this.tail=t.catch(()=>{}),t}}function lr(e,t,n){let i=!0,s=!1,r=!1,o="",a=!1,c=!1,p=-1,l=null,h=new ai,d=document.createElement("div");d.className="bp-pane bp-browser-pane",d.setAttribute("data-testid","pane-browser");let u=document.createElement("div");u.className="bp-pane-bar bp-browser-nav";function f(ee,ge,C){let x=document.createElement("button");if(x.type="button",x.className="bp-v-btn",x.textContent=ee,x.setAttribute("data-testid",ge),C)x.title=C;return x}let b=f("←","browser-back","Back"),v=f("→","browser-forward","Forward"),w=f("↻","browser-reload","Reload"),E=document.createElement("form");E.className="bp-browser-url-form";let k=document.createElement("input");k.type="text",k.className="bp-browser-input",k.placeholder="https://…",k.autocomplete="off",k.spellcheck=!1,k.setAttribute("data-testid","browser-url");let L=f("Go","browser-go","Navigate");L.type="submit",E.append(k,L);let M=f("Take over","browser-takeover");M.classList.add("is-primary"),u.append(b,v,w,E,M);let A=document.createElement("div");A.className="bp-browser-drive-bar",A.hidden=!0;let B=document.createElement("div");B.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 H=f("Send","browser-type-send");B.append(T,H);let O=document.createElement("div");O.className="bp-browser-quick-keys";for(let[ee,ge]of or){let C=f(ee,`browser-key-${ge}`);C.addEventListener("click",()=>te("press",{key:ge})),O.append(C)}A.append(B,O);let P=document.createElement("div");P.className="bp-browser-err",P.setAttribute("data-testid","browser-error"),P.hidden=!0;let Y=document.createElement("div");Y.className="bp-browser-stage",Y.setAttribute("data-testid","browser-stage");let re=document.createElement("img");re.className="bp-browser-img",re.alt="Hub browser screen",re.draggable=!1,re.hidden=!0,re.setAttribute("data-testid","browser-frame");let ie=document.createElement("div");ie.className="bp-pane-empty",ie.setAttribute("data-testid","browser-empty"),ie.textContent="Loading browser screen…",Y.append(re,ie);let me=document.createElement("div");me.className="bp-browser-hint",me.textContent="You have the page: click to tap, scroll to wheel, type in the key box. Hand it back when done.",me.hidden=!0,d.append(u,A,P,Y,me),e.replaceChildren(d);function Pe(ee){P.textContent=ee,P.hidden=!ee}function Ce(){A.hidden=!s,me.hidden=!s,M.textContent=s?"Hand back":"Take over",M.setAttribute("data-testid",s?"browser-handback":"browser-takeover"),M.classList.toggle("is-on",s),re.classList.toggle("is-driving",s)}function te(ee,ge={},C){h.enqueue(async()=>{if(!i)return;Pe("");try{if(await t.hub.rpc("browser",{thread:n,op:ee,...ge}),!i)return;C?.(),ue()}catch(x){if(!i)return;Pe(x instanceof Error?x.message:String(x))}})}function oe(ee){te("toolbar",{command:ee},()=>{s=!0,Ce()})}b.addEventListener("click",()=>oe("back")),v.addEventListener("click",()=>oe("forward")),w.addEventListener("click",()=>oe("reload")),E.addEventListener("submit",(ee)=>{ee.preventDefault();let ge=ar(k.value);if(!ge)return;if(k.value=ge,!s)te("takeover",{},()=>{s=!0,Ce()});te("navigate",{url:ge},()=>{s=!0,Ce()})}),M.addEventListener("click",()=>{if(s)te("handback",{},()=>{s=!1,Ce()});else te("takeover",{},()=>{s=!0,Ce(),T.focus()})});function R(){let ee=T.value;if(!ee)return;T.value="",te("type",{text:ee})}H.addEventListener("click",R),T.addEventListener("keydown",(ee)=>{if(!s)return;if(ee.key==="Enter"){if(ee.preventDefault(),T.value)R();te("press",{key:"Enter"});return}if(ee.key==="Tab"||ee.key==="Escape"||ee.key==="ArrowUp"||ee.key==="ArrowDown"||ee.key==="ArrowLeft"||ee.key==="ArrowRight"||ee.key==="Backspace"&&T.value==="")ee.preventDefault(),te("press",{key:ee.key})}),re.addEventListener("click",(ee)=>{if(!s||!r)return;let ge=re.getBoundingClientRect(),C=rr(ee.clientX,ee.clientY,{left:ge.left,top:ge.top,width:ge.width,height:ge.height,naturalWidth:re.naturalWidth,naturalHeight:re.naturalHeight});if(!C)return;te("click",C)}),re.addEventListener("wheel",(ee)=>{if(!s||!r)return;ee.preventDefault();let ge=Math.round(ee.deltaX),C=Math.round(ee.deltaY);if(ge===0&&C===0)return;te("scroll",{dx:ge,dy:C})},{passive:!1});async function ue(){if(!i)return;if(a){c=!0;return}a=!0;try{do{c=!1,l=new AbortController;let ee=await fetch(`/bots/${encodeURIComponent(n)}/screen.jpg`,{credentials:"same-origin",cache:"no-store",signal:l.signal});if(!i)return;if(ee.ok){let ge=await ee.blob();if(!i)return;let C=URL.createObjectURL(ge),x=o;if(o=C,re.src=C,re.hidden=!1,ie.hidden=!0,r=!0,x)URL.revokeObjectURL(x)}else if(!r)re.hidden=!0,ie.hidden=!1,ie.textContent="No browser page yet. An agent opens one when it needs the web."}while(i&&c)}catch{if(!i)return;if(!r)re.hidden=!0,ie.hidden=!1,ie.textContent="No browser page yet. An agent opens one when it needs the web."}finally{l=null,a=!1}}let de=t.hub.onFrame((ee)=>{if(!i)return;if(ee.t==="shot"&&ee.bot===n){if(typeof ee.n==="number"){if(ee.n===p)return;p=ee.n}ue()}});return ue(),{destroy(){if(i=!1,de(),l?.abort(),o)URL.revokeObjectURL(o),o=""}}}function U(e,t,n){let i=document.createElement(e);if(t)i.className=t;if(n!==void 0)i.textContent=n;return i}function fn(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 dr(e){let t=e.lastIndexOf(".");return t>=0?e.slice(t+1).toLowerCase():""}function Io(e){return["png","jpg","jpeg","gif","webp","svg","bmp","ico"].includes(e)}function cr(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 Ro(e){let t=dr(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 pr(e,t,n,i){let s=!0,r="",o="",a=U("div","bp-pane bp-files-pane");a.setAttribute("data-testid","pane-files");let c=U("div","bp-pane-bar"),p=U("div","bp-files-crumbs"),l=U("button","bp-v-btn","Refresh");l.type="button",l.addEventListener("click",()=>void v(r)),c.append(p,l);let h=U("div","bp-files-split"),d=U("div","bp-files-list");d.setAttribute("data-testid","files-list");let u=U("div","bp-files-preview");u.setAttribute("data-testid","files-preview"),u.append(U("div","bp-pane-empty","Select a file to preview")),h.append(d,u),a.append(c,h),e.replaceChildren(a);function f(){p.replaceChildren();let w=U("button","bp-crumb-btn","project");if(w.type="button",w.addEventListener("click",()=>void v("")),p.append(w),!r)return;let E=r.split("/").filter(Boolean),k="";for(let L of E){k=k?`${k}/${L}`:L;let M=k;p.append(U("span","bp-vh-sep","/"));let A=U("button","bp-crumb-btn",L);A.type="button",A.addEventListener("click",()=>void v(M)),p.append(A)}}async function b(w,E,k){o=w,u.replaceChildren();let L=U("div","bp-files-prev-head");L.append(U("span","bp-files-prev-name",w));let M=U("div","bp-files-prev-acts"),A=Ro(E);if(A){let O=U("button","bp-v-btn is-primary",`Open in ${A}`);O.type="button",O.setAttribute("data-testid","files-open-viewer"),O.addEventListener("click",()=>i(A,w)),M.append(O)}let B=`/files/get?thread=${encodeURIComponent(n)}&path=${encodeURIComponent(w)}`,T=U("a","bp-v-btn","Download");T.href=B,T.download=E,M.append(T),L.append(M),u.append(L);let H=dr(E);if(Io(H)){let O=U("div","bp-files-img-wrap"),P=document.createElement("img");P.className="bp-files-img",P.alt=E,P.src=B,O.append(P),u.append(O);return}if(k>524288&&!cr(H)){u.append(U("div","bp-pane-empty",`Binary file (${fn(k)}). Use Download to save.`));return}if(cr(H)||k<=65536){let O=U("div","bp-pane-empty","Loading…");u.append(O);try{let P=await fetch(B,{credentials:"same-origin"});if(!s||o!==w)return;if(!P.ok){O.textContent=`Could not load file (${P.status})`;return}if((P.headers.get("content-type")||"").startsWith("image/")){O.remove();let de=document.createElement("img");de.className="bp-files-img",de.alt=E,de.src=B,u.append(de);return}let re=262144,ie=[],me=0,Pe=!1;if(P.body){let de=P.body.getReader();try{while(!0){let{done:ee,value:ge}=await de.read();if(ee||!ge)break;if(me+ge.byteLength>re){let C=re-me;if(C>0)ie.push(ge.subarray(0,C)),me+=C;Pe=!0,await de.cancel();break}ie.push(ge),me+=ge.byteLength}}finally{de.releaseLock()}}if(!s||o!==w)return;let Ce=new Uint8Array(me),te=0;for(let de of ie)Ce.set(de,te),te+=de.byteLength;let oe=!1;for(let de=0;deL.dir===M.dir?L.name.localeCompare(M.name):L.dir?-1:1),d.replaceChildren(),w){let L=U("button","bp-file-row is-dir");L.type="button",L.append(U("span","bp-file-icon","↰"),U("span","bp-file-name",".."));let M=w.includes("/")?w.slice(0,w.lastIndexOf("/")):"";L.addEventListener("click",()=>void v(M)),d.append(L)}if(k.length===0){d.append(U("div","bp-pane-empty","Empty folder"));return}for(let L of k){let M=w?`${w}/${L.name}`:L.name,A=U("button","bp-file-row"+(L.dir?" is-dir":"")+(M===o?" is-sel":""));A.type="button",A.setAttribute("data-testid",`file-row-${L.name}`),A.append(U("span","bp-file-icon",L.dir?"▸":"·"),U("span","bp-file-name",L.name),U("span","bp-file-size",L.dir?"":fn(L.size))),A.addEventListener("click",()=>{if(L.dir)v(M);else d.querySelectorAll(".bp-file-row.is-sel").forEach((B)=>B.classList.remove("is-sel")),A.classList.add("is-sel"),b(M,L.name,L.size)}),d.append(A)}}catch(E){if(!s)return;d.replaceChildren(U("div","bp-pane-empty",E instanceof Error?E.message:String(E)))}}return v(""),{destroy(){s=!1}}}function hr(e,t,n){let i=!0,s=U("div","bp-pane bp-diff-pane");s.setAttribute("data-testid","pane-diff");let r=U("div","bp-pane-bar"),o=U("span","bp-diff-summary","Loading diff…"),a=U("button","bp-v-btn","Refresh");a.type="button",a.addEventListener("click",()=>void p()),r.append(o,a);let c=U("div","bp-diff-body");c.setAttribute("data-testid","diff-body"),s.append(r,c),e.replaceChildren(s);async function p(){o.textContent="Loading diff…",c.replaceChildren();try{let l=await t.hub.rpc("viewer.diff",{thread:n});if(!i)return;if(l?.nogit){o.textContent="Not a git repository",c.append(U("div","bp-pane-empty","This project is not a git repository."));return}let h=typeof l?.diff==="string"?l.diff:"";if(!h.trim()){o.textContent="Clean working tree",c.append(U("div","bp-pane-empty","No uncommitted changes."));return}let d=h.split(` +`),u=0,f=0,b=0,v=document.createDocumentFragment(),w=U("div","bp-diff-file");for(let E of d){if(E.startsWith("diff --git ")){if(w.childNodes.length>0)v.append(w);w=U("div","bp-diff-file"),u++;let k=E.match(/ b\/(.+)$/);w.append(U("div","bp-diff-file-head",k?k[1]:E));continue}if(E.startsWith("index ")||E.startsWith("--- ")||E.startsWith("+++ "))w.append(U("div","bp-diff-line is-meta",E));else if(E.startsWith("@@"))w.append(U("div","bp-diff-line is-hunk",E));else if(E.startsWith("+"))f++,w.append(U("div","bp-diff-line is-add",E));else if(E.startsWith("-"))b++,w.append(U("div","bp-diff-line is-del",E));else w.append(U("div","bp-diff-line",E))}if(w.childNodes.length>0)v.append(w);o.textContent=`${u||1} file${u===1?"":"s"} · +${f} -${b}`,c.append(v)}catch(l){if(!i)return;o.textContent="Diff unavailable",c.append(U("div","bp-pane-empty",l instanceof Error?l.message:String(l)))}}return p(),{destroy(){i=!1}}}function jo(e,t){let n=t.rel||"",i=t.manifest||{},s=(p)=>`/files/get?thread=${encodeURIComponent(e)}&path=${encodeURIComponent(`${n}/${p}`)}`,r=(p)=>typeof p==="string"&&p!==""&&!p.startsWith("/")&&!p.split(/[\\/]/).includes(".."),o=(Array.isArray(i.drawings)?i.drawings:[]).filter((p)=>r(p?.file)),a=new Set(o.map((p)=>p.file)),c=o.map((p)=>({title:p.title||p.kind||p.file,file:p.file,url:s(p.file),drawing:!0}));for(let p of Array.isArray(i.files)?i.files:[])if(r(p)&&!a.has(p))c.push({title:p,file:p,url:s(p),drawing:!1});return c}function mr(e,t,n){let i=!0,s="checks",r=U("div","bp-pane bp-review-pane");r.setAttribute("data-testid","pane-review");let o=U("div","bp-pane-bar"),a=U("div","bp-review-tabs"),c=U("button","bp-v-btn is-on","Checks"),p=U("button","bp-v-btn","BOM"),l=U("button","bp-v-btn","Comments"),h=U("button","bp-v-btn","Release");h.setAttribute("data-testid","review-tab-release"),c.type=p.type=l.type=h.type="button",a.append(c,p,l,h);let d=U("button","bp-v-btn","Refresh");d.type="button",d.addEventListener("click",()=>void w()),o.append(a,d);let u=U("div","bp-review-body");u.setAttribute("data-testid","review-body"),r.append(o,u),e.replaceChildren(r);function f(E){s=E,c.classList.toggle("is-on",s==="checks"),p.classList.toggle("is-on",s==="bom"),l.classList.toggle("is-on",s==="comments"),h.classList.toggle("is-on",s==="release"),w()}c.addEventListener("click",()=>f("checks")),p.addEventListener("click",()=>f("bom")),l.addEventListener("click",()=>f("comments")),h.addEventListener("click",()=>f("release"));function b(E){let k=U("div","bp-review-md bp-review-release");k.setAttribute("data-testid","review-release");let L=E.manifest||{};k.append(U("h2","bp-review-h",E.tag||"Release")),k.append(U("p","bp-review-p",[L.commit?`Commit ${L.commit.slice(0,12)}`:"",L.date||""].filter(Boolean).join(" · ")));let M=jo(n,E),A=(T,H)=>{if(H.length===0)return;k.append(U("h3","bp-review-h",T));let O=U("table","bp-review-table");for(let P of H){let Y=document.createElement("tr"),re=U("td",void 0,P.title);re.title=P.file;let ie=document.createElement("td"),me=U("a","bp-v-btn","Download");me.href=P.url,me.download=P.file.split("/").pop()||P.file,ie.append(me),Y.append(re,ie),O.append(Y)}k.append(O)};A("Drawings",M.filter((T)=>T.drawing));let B=Array.isArray(L.openFabNotes)?L.openFabNotes:[];if(B.length>0)k.append(U("div","bp-review-gate",`Open fabrication notes, not in the board (agree them with the fabricator): ${B.join(", ")}.`));if(A("Files",M.filter((T)=>!T.drawing)),E.rel){let T=U("a","bp-v-btn","Download all (.zip)");T.href=`/files/zip?thread=${encodeURIComponent(n)}&path=${encodeURIComponent(E.rel)}`,k.append(T)}return k}function v(E){let k=U("div","bp-review-md"),L=E.split(` +`),M=0;while(M{H.preventDefault();let O=B.value.trim();if(!O)return;T.disabled=!0,t.hub.rpc("review.comment",{thread:n,text:O}).then(()=>{B.value="",T.disabled=!1,w()},()=>{T.disabled=!1})}),u.append(A),M.length===0){u.append(U("div","bp-pane-empty","No review comments yet."));return}for(let H of M){let O=U("div","bp-review-comment"+(H.resolved?" is-resolved":"")),P=[H.by||"review",H.file,H.layer,H.item].filter(Boolean).join(" · ");O.append(U("div","bp-review-comment-meta",P),U("div","bp-review-comment-text",H.text)),u.append(O)}return}let E=await t.hub.rpc("review.page",{thread:n,page:s});if(!i)return;let k=E?.report||{};if(u.replaceChildren(),k.line||k.gate){let L=U("div","bp-review-gate",[k.gate,k.line].filter(Boolean).join(" · "));u.append(L)}if(k.err)u.append(U("div","bp-review-err",k.err));if(Array.isArray(k.tasks)&&k.tasks.length>0){let L=U("div","bp-review-tasks");k.tasks.forEach((M,A)=>{let B=U("label","bp-review-task"),T=document.createElement("input");T.type="checkbox",T.checked=!!(M.done??M.checked);let H=typeof M.index==="number"?M.index:A;T.addEventListener("change",()=>{t.hub.rpc("review.tick",{thread:n,index:H}).then(()=>void w(),()=>{})}),B.append(T,U("span",void 0,M.text||M.label||`Item ${A+1}`)),L.append(B)}),u.append(L)}if(s==="release"&&k.release&&k.release.manifest)u.append(b(k.release));else if(k.md&&k.md.trim())u.append(v(k.md));else if(!k.err&&(!k.tasks||k.tasks.length===0))u.append(U("div","bp-pane-empty",s==="release"?"No release yet. A release tags this design and makes its fabrication outputs and drawings in .backplane/releases.":`No ${s==="bom"?"BOM":"design checks"} report available.`))}catch(E){if(!i)return;u.replaceChildren(U("div","bp-pane-empty",E instanceof Error?E.message:String(E)))}}return w(),{destroy(){i=!1}}}function ur(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 li{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),o=Math.max(s-n,1000),a=this.canvas.getBoundingClientRect(),c=Math.max(a.width,200),p=Math.max(a.height,200);this.cx=(t+i)*0.5,this.cy=(n+s)*0.5,this.scale=Math.min(c/r,p/o)*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 o=this.ctx;o.setTransform(i,0,0,i,0,0),o.fillStyle=this.lightTheme?"#f5f4ef":"#08090b",o.fillRect(0,0,t,n);let a=this.frame;if(!a)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,p=n*0.5,l=this.scale,h=this.cx,d=this.cy,u=h-c/l,f=h+c/l,b=d-p/l,v=d+p/l,{off:w,dim:E,lift:k}=this.masks,L=[],M=[];for(let B=0;B>>T&1)===1)continue;if(T===k)M.push(B);else L.push(B)}let A=L.concat(M);o.lineCap="round",o.lineJoin="round";for(let B=0;B>>H.layer&1)===1,P=H.alpha*(O?0.25:1);if(P<=0.01)continue;this.drawChunk(o,H,P,u,b,f,v,h,d,l,c,p)}if(this.highlights.size>0){o.fillStyle=this.lightTheme?"rgba(245,244,239,0.72)":"rgba(8,9,11,0.72)",o.fillRect(0,0,t,n);let B=this.lightTheme?"rgba(27,29,33,0.77)":"rgba(217,221,228,0.77)";for(let T=0;Tr||v.y1o)continue;if(v.n<3)continue;let w=(d[v.at]-a)*p+l,E=(d[v.at+1]-c)*p+h;e.moveTo(w,E);for(let k=1;k0)e.fill()}else if(t.mode===2){let f=Math.max(0.75,t.r*p);e.fillStyle=u,e.beginPath();let b=0;for(let v=0;vr||w.y1o)continue;let E=(d[w.at]-a)*p+l,k=(d[w.at+1]-c)*p+h;e.moveTo(E+f,k),e.arc(E,k,f,0,Math.PI*2),b++}if(b>0)e.fill()}else{e.strokeStyle=u,e.lineWidth=Math.max(1,t.r*2*p),e.beginPath();let f=0;for(let b=0;br||v.y1o)continue;let w=(d[v.at]-a)*p+l,E=(d[v.at+1]-c)*p+h;if(v.n===1)e.moveTo(w,E),e.lineTo(w+0.01,E);else{e.moveTo(w,E);for(let k=1;k0)e.stroke()}}drawLitPieces(e,t,n,i,s,r,o,a,c,p,l,h,d){let u=t.pts,f=ur(t.color,t.alpha);for(let b=0;bo||v.y1a)continue;let w=(u[v.at]-c)*l+h,E=(u[v.at+1]-p)*l+d;if(v.kind===2){let k=Math.max(1.5,t.r*l);e.fillStyle=f,e.beginPath(),e.arc(w,E,k,0,Math.PI*2),e.fill(),e.strokeStyle=i,e.lineWidth=1.5,e.stroke()}else if(v.kind===0&&v.n>=3){e.fillStyle=f,e.beginPath(),e.moveTo(w,E);for(let k=1;k=0;l--){let h=n.chunks[l];if(h.layer<32&&(p>>>h.layer&1)===1)continue;for(let d=0;du.x1+o||ru.y1+o)continue;let f=(u.x1-u.x0+1)*(u.y1-u.y0+1);if(f{if(this.canvas.setPointerCapture(e.pointerId),this.pointers.set(e.pointerId,{x:e.clientX,y:e.clientY}),this.pointers.size===1)this.dragStart={x:e.clientX,y:e.clientY,cx:this.cx,cy:this.cy,moved:!1},this.pinchStart=null;else if(this.pointers.size===2){let[t,n]=Array.from(this.pointers.values());this.pinchStart={dist:Math.hypot(n.x-t.x,n.y-t.y)||1,midX:(t.x+n.x)*0.5,midY:(t.y+n.y)*0.5,scale:this.scale,cx:this.cx,cy:this.cy},this.dragStart=null}};onPointerMove=(e)=>{if(!this.pointers.has(e.pointerId))return;if(this.pointers.set(e.pointerId,{x:e.clientX,y:e.clientY}),this.pointers.size===2&&this.pinchStart){let[t,n]=Array.from(this.pointers.values()),i=Math.hypot(n.x-t.x,n.y-t.y)||1,s=(t.x+n.x)*0.5,r=(t.y+n.y)*0.5,o=i/this.pinchStart.dist,a=Math.max(0.0000001,Math.min(2,this.pinchStart.scale*o)),c=this.canvas.getBoundingClientRect(),p=this.pinchStart.midX-c.left-c.width*0.5,l=this.pinchStart.midY-c.top-c.height*0.5,h=s-c.left-c.width*0.5,d=r-c.top-c.height*0.5;this.scale=a,this.cx=this.pinchStart.cx+p/this.pinchStart.scale-h/a,this.cy=this.pinchStart.cy+l/this.pinchStart.scale-d/a,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 br=[{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 gr(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 ci(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 o=s[1]||r.slice(4).join("\t");if(!o)return!1;let a=o.replace(/\\/g,"/"),c=i.replace(/\\/g,"/");if(c.startsWith("/")||/^[A-Za-z]:\//.test(c))return a===c;return a===c||a.endsWith(`/${c}`)}class di{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 Ho=`#version 300 es precision highp float; out vec2 vUv; void main() { @@ -20,7 +20,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); } -`,Ho=`#version 300 es +`,Do=`#version 300 es precision highp float; in vec2 vUv; uniform vec3 uBgTop; @@ -37,7 +37,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); } -`,Do=`#version 300 es +`,Fo=`#version 300 es precision highp float; layout(location = 0) in vec3 aPos; layout(location = 1) in vec3 aNrm; @@ -55,7 +55,7 @@ void main() { vCol = aCol; gl_Position = uMvp * vec4(aPos, 1.0); } -`,Fo=`#version 300 es +`,$o=`#version 300 es precision highp float; in vec3 vPos; in vec3 vNrm; @@ -151,8 +151,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 $o=[Ze(77),Ze(83),Ze(94)],Oo=[Ze(53),Ze(58),Ze(67)],Go=[Ze(245),Ze(246),Ze(248)],Vo=[Ze(225),Ze(228),Ze(233)];function fr(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 vr(e,t,n){let i=fr(e,e.VERTEX_SHADER,t),s=fr(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 o=e.getProgramInfoLog(r)||"program link error";throw e.deleteProgram(r),Error(o)}return r}function Uo(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 Wo(e,t,n,i){let s=1/Math.tan(e*0.5),r=1/(n-i),o=new Float32Array(16);return o[0]=s/t,o[5]=s,o[10]=(i+n)*r,o[11]=-1,o[14]=2*i*n*r,o}function wr(e){let t=Math.hypot(e[0],e[1],e[2])||1;return[e[0]/t,e[1]/t,e[2]/t]}function yr(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 pi(e,t){return e[0]*t[0]+e[1]*t[1]+e[2]*t[2]}class hi{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=vr(n,jo,Ho),this.bgVao=n.createVertexArray(),this.uBgTop=n.getUniformLocation(this.bgProg,"uBgTop"),this.uBgBot=n.getUniformLocation(this.bgProg,"uBgBot"),this.prog=vr(n,Do,Fo),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=ir(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 o++;let a=r>0?new Float32Array(r*9):null,c=r>0?new Float32Array(r*9):null,p=r>0?new Float32Array(r*12):null,l=o>0?new Float32Array(o*9):null,h=o>0?new Float32Array(o*9):null,d=o>0?new Float32Array(o*12):null,m=0,f=0;for(let w=0;w>>24&255,L=1-k/255,M=(E>>>16&255)/255,A=(E>>>8&255)/255,B=(E&255)/255,T=w*9;if(k===0&&a&&c&&p){let H=m*9;for(let P=0;P<9;P++)a[H+P]=e[T+P],c[H+P]=t[T+P];let O=m*12;for(let P=0;P<3;P++)p[O+P*4]=M,p[O+P*4+1]=A,p[O+P*4+2]=B,p[O+P*4+3]=1;m++}else if(l&&h&&d){let H=f*9;for(let P=0;P<9;P++)l[H+P]=e[T+P],h[H+P]=t[T+P];let O=f*12;for(let P=0;P<3;P++)d[O+P*4]=M,d[O+P*4+1]=A,d[O+P*4+2]=B,d[O+P*4+3]=L;f++}}let b=a&&c&&p?this.createSubBatch(a,c,p,r*3):null,v=l&&h&&d?this.createSubBatch(l,h,d,o*3):null;if(!b&&!v)return null;return{opaque:b,translucent:v,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}=gr(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),o=Math.round(i*r),a=Math.round(s*r);if(this.canvas.width!==o||this.canvas.height!==a)this.canvas.width=o,this.canvas.height=a;if(t.viewport(0,0,o,a),!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 H=this.lightTheme?Go:$o,O=this.lightTheme?Vo:Oo;t.uniform3f(this.uBgTop,H[0],H[1],H[2]),t.uniform3f(this.uBgBot,O[0],O[1],O[2]),t.bindVertexArray(this.bgVao),t.drawArrays(t.TRIANGLE_STRIP,0,4),t.bindVertexArray(null)}let c=Math.cos(this.pitch),p=Math.sin(this.pitch),l=Math.cos(this.yaw),h=Math.sin(this.yaw),d=[this.target[0]+this.dist*c*h,this.target[1]-this.dist*c*l,this.target[2]+this.dist*p],m=wr([this.target[0]-d[0],this.target[1]-d[1],this.target[2]-d[2]]),f=Math.abs(m[2])>0.99?[0,1,0]:[0,0,1],b=wr(yr(m,f)),v=yr(b,m),w=new Float32Array([b[0],v[0],-m[0],0,b[1],v[1],-m[1],0,b[2],v[2],-m[2],0,-pi(b,d),-pi(v,d),pi(m,d),1]),E=Math.max(0.05,this.dist*0.01),k=Math.max(this.dist*10,this.radius*20),L=Wo(35*Math.PI/180,o/a,E,k),M=Uo(L,w);t.useProgram(this.prog),t.uniformMatrix4fv(this.uMvp,!1,M),t.uniform3f(this.uEye,d[0],d[1],d[2]),t.uniform3f(this.uRight,b[0],b[1],b[2]),t.uniform3f(this.uUp,v[0],v[1],v[2]),t.uniform3f(this.uFwd,m[0],m[1],m[2]);let A=!1,B=[],T=[];for(let H of this.partBatches){let O=e-H.fadeStartMs,P=H.fadeStartMs===0?1:Math.min(1,Math.max(0,O/300));if(P<1){if(A=!0,P>0)T.push({batch:H,fade:P})}else B.push(H)}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 H of B)this.drawSubBatch(H.opaque);if(t.depthMask(!1),t.enable(t.BLEND),t.uniform1f(this.uFade,1),this.boardBatch)this.drawSubBatch(this.boardBatch.translucent);for(let H of B)this.drawSubBatch(H.translucent);for(let{batch:H,fade:O}of T)t.uniform1f(this.uFade,O),this.drawSubBatch(H.opaque),this.drawSubBatch(H.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()),o=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/o)));this.pinchDist=o,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),o=Math.sin(this.yaw);this.target[0]-=n*r*s,this.target[1]-=n*o*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 Er=64,_o=16777216;function zo(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 Jt(e){if(!e)return"";let t=e.replace(/\\/g,"/").replace(/\/+$/,""),n=t.lastIndexOf("/");return n>=0?t.slice(n+1):t}function Cr(e){switch(e){case"board":return u("viewer.board","Board");case"schematic":return u("viewer.schematic","Schematic");case"3d":return u("viewer.solid","3D");case"gerbers":return u("gpui.gerbers","Gerbers");case"mech":return u("viewer.mech","Mech");case"files":return u("viewer.files","Files");case"diff":return u("viewer.diff","Diff");case"review":return u("viewer.review","Review");case"browser":return u("bots.tab.browser","Browser");case"terminal":return u("viewer.terminal","Terminal");default:return e?e.charAt(0).toUpperCase()+e.slice(1):""}}function ui(e){return e==="board"||e==="schematic"||e==="gerbers"}function qo(e){return e==="files"||e==="diff"||e==="review"||e==="browser"||e==="terminal"}function mi(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 o=document.createElement("span");o.className="bp-vh-file",o.hidden=!0,i.append(s,r,o);let a=document.createElement("div");a.className="bp-vh-actions",n.append(i,a);let c=document.createElement("div");c.className="bp-solid-bar",c.setAttribute("data-testid","solid-presets-bar"),c.hidden=!0;let p=document.createElement("div");p.className="bp-v-banner",p.hidden=!0;let l=document.createElement("div");l.className="bp-v-stage-wrap";let h=document.createElement("div");h.className="bp-v-stage";let d=document.createElement("div");d.className="bp-v-overlay",d.hidden=!0;let m=document.createElement("div");m.className="bp-v-layers",m.hidden=!0;let f=document.createElement("div");f.className="bp-v-info",f.hidden=!0,l.append(h,d,m,f);let b=document.createElement("div");b.className="bp-history-bar",b.setAttribute("data-testid","viewer-history-bar"),b.hidden=!0,e.replaceChildren(n,c,p,l,b);let v="",w="",E=0,k=!1,L=new Set,M=[],A=0,B=new Map,T=new Map,H={},O=[],P="",Y="",re=!1,ie=!1,ue=0,Pe=!1,Ce=0,te="",oe=0,R=null,me=null,de=null,ee=null,ge=null,C=new di,x=0,F=!1,I="",J="",se="",ye="";document.addEventListener("click",(V)=>{if(!F)return;if(V.target instanceof Node&&b.contains(V.target))return;F=!1,Le()}),document.addEventListener("keydown",(V)=>{if(F&&V.key==="Escape")F=!1,Le()});function D(){if(x)window.clearInterval(x),x=0;C.playing=!1}function ne(){let V=w==="3d"||w==="mech";if(c.hidden=!V,!V)return;if(c.childElementCount>0)return;for(let _ of br){let G=document.createElement("button");G.type="button",G.className="bp-v-btn",G.textContent=_.label,G.setAttribute("data-testid",`solid-view-${_.id}`),G.addEventListener("click",()=>{de?.setView(_.id)}),c.append(G)}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(!de)return;de.snapPng().then((_)=>{if(!_)return;let G=URL.createObjectURL(_),z=document.createElement("a");z.href=G;let ae=($e()||w||"view").replace(/[^a-zA-Z0-9._-]/g,"_");z.download=`${ae}-snap.png`,z.click(),setTimeout(()=>URL.revokeObjectURL(G),1000)})}),c.append(W)}async function Te(){if(!v||w!=="board"&&w!=="schematic")return;Le();let V=C.compareRequest();if(!V){I="",J="",se="",ye="",await ht(!1);return}let W=`${w}|${V.commit}|${V.bits}|${Y}`;if(W===ye&&L.size>0){He(C.highlightEdits?`Comparing against ${C.activeRef()?.label||V.commit.slice(0,7)} (edits highlighted)`:`Comparing against ${C.activeRef()?.label||V.commit.slice(0,7)}`,!1);return}let _=++E;L.clear(),B.clear(),ve(),k=!0,I="",J=V.commit,se="",ye=W;try{let G=Y||(w==="schematic"?H.sch:H.pcb)||"";if(!G){let ke=await t.hub.rpc("viewer.files",{thread:v});if(_!==E)return;H=ke||{},Oe(),G=(w==="schematic"?H.sch:H.pcb)||""}if(!G)throw Error(`Unable to resolve ${w} file path for compare`);let z=await t.hub.rpc("viewer.compare",{thread:v,kind:w,commit:V.commit,bits:V.bits,...Y?{path:Y}:{}});if(_!==E)return;let ae=typeof z?.root==="string"?z.root:"",K=w==="schematic"?"1":"0";I=ae?`${K}|${ae}|diff -`:`${K}|`,J=V.commit,se=G.startsWith("/")||/^[A-Za-z]:[\\/]/.test(G)||!ae?G:`${ae.replace(/\/+$/,"")}/${G.replace(/^\/+/,"")}`,k=!1;let we=M;ve();for(let ke of we)if(ke.kind==="bin")tt(ke.buf);else et(ke.key,ke.none,ke.retryable,ke.big);He(C.highlightEdits?`Comparing against ${C.activeRef()?.label||V.commit.slice(0,7)} (edits highlighted)`:`Viewing snapshot: ${C.activeRef()?.label||V.commit.slice(0,7)}`,!1)}catch(G){if(_!==E)return;k=!1,I="",J="",se="",ye="",ve(),He(G instanceof Error?G.message:String(G),!0)}}function Le(){let V=w==="board"||w==="schematic";if(b.hidden=!V,!V)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=C.refs.length===0||C.index>=C.refs.length-1,_.setAttribute("data-testid","history-prev"),_.addEventListener("click",()=>{if(D(),C.step(1))Te()});let G=document.createElement("button");G.type="button",G.className="bp-v-btn"+(C.playing?" is-on":""),G.textContent=C.playing?"⏸":"▶",G.title=C.playing?"Pause history":"Play history",G.disabled=C.refs.length===0,G.setAttribute("data-testid","history-play"),G.addEventListener("click",()=>{if(C.playing){D(),Le();return}if(C.refs.length===0)return;if(C.playing=!0,C.isLive())C.index=C.refs.length-1,Te();else Le();x=window.setInterval(()=>{if(!C.playing||w!=="board"&&w!=="schematic"){D(),Le();return}if(C.step(-1))Te();else D(),Le()},1400)});let z=document.createElement("button");z.type="button",z.className="bp-v-btn",z.textContent=">",z.title="Newer snapshot",z.disabled=C.isLive(),z.setAttribute("data-testid","history-next"),z.addEventListener("click",()=>{if(D(),C.step(-1))Te()});let ae=document.createElement("button");ae.type="button",ae.className="bp-v-btn"+(C.isLive()?" is-on":""),ae.textContent="Live",ae.setAttribute("data-testid","history-live"),ae.addEventListener("click",()=>{if(D(),C.goLive())He("",!1),Te()});let K=document.createElement("span");K.className="bp-history-label",K.setAttribute("data-testid","history-label");let we=C.activeRef();K.textContent=we?we.label||we.commit.slice(0,7):C.refs.length>0?`Live (${C.refs.length} saved)`:"Live",W.append(_,G,z,ae,K);let ke=document.createElement("div");ke.className="bp-history-group";let Ae=document.createElement("button");Ae.type="button",Ae.className="bp-v-btn"+(C.highlightEdits?" is-on":""),Ae.textContent="Highlight edits",Ae.disabled=C.refs.length===0,Ae.setAttribute("data-testid","history-highlight"),Ae.addEventListener("click",()=>{D(),C.toggleHighlight(),Te()});let Ge=document.createElement("div");Ge.className="bp-history-menu-wrap";let je=document.createElement("button");if(je.type="button",je.className="bp-v-btn"+(F||!C.isLive()?" is-on":""),je.disabled=C.refs.length===0,je.setAttribute("data-testid","history-compare"),je.setAttribute("aria-haspopup","menu"),je.setAttribute("aria-expanded",String(F)),je.textContent=we?`Compare: ${we.label||we.commit.slice(0,7)} ▾`:"Compare ▾",je.addEventListener("click",(De)=>{De.stopPropagation(),F=!F,Le()}),Ge.append(je),F&&C.refs.length>0){let De=document.createElement("div");De.className="bp-history-menu",De.setAttribute("role","menu"),De.setAttribute("data-testid","history-compare-menu");let Ie=(Ve,ut,tn)=>{let at=document.createElement("button");at.type="button",at.className="bp-history-menu-item"+(tn?" is-active":""),at.setAttribute("role","menuitem"),at.setAttribute("data-commit",ut),at.textContent=Ve,at.addEventListener("click",()=>{if(F=!1,D(),C.selectCommit(ut)){if(C.isLive())He("",!1);Te()}else Le()}),De.append(at)};Ie("Live (working tree)","",C.isLive());for(let Ve of C.refs)Ie(Ve.label||Ve.commit.slice(0,7),Ve.commit,we?.commit===Ve.commit);Ge.append(De)}ke.append(Ae,Ge),b.replaceChildren(W,ke)}async function Be(V){if(!V)return;try{let W=await t.hub.rpc("viewer.refs",{thread:V});if(V!==v)return;C.setRefs(Array.isArray(W?.refs)?W.refs:[]),Le()}catch{if(V!==v)return;C.setRefs([]),Le()}}function q(){return document.documentElement.classList.contains("light")}let fe=new MutationObserver(()=>{let V=q();me?.setTheme(V),de?.setTheme(V),ge?.setTheme(V)});fe.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]});function le(V,W="",_=!1,G=""){if(V==="none"){d.hidden=!0,d.replaceChildren();return}d.hidden=!1,d.className=`bp-v-overlay is-${V}`;let z=document.createElement("div");z.className="bp-v-state-card";let ae=document.createElement("div");if(ae.className="bp-v-state-msg",ae.textContent=W,z.append(ae),_){let K=document.createElement("button");K.type="button",K.className="bp-v-btn is-primary",K.textContent=u("tools.retry","Retry"),K.addEventListener("click",()=>void ht(!0)),z.append(K)}if(G){let K=document.createElement("div");K.className="bp-v-state-msg",K.textContent=u("gpui.c.solid.big.next","Loading it may take a while and a lot of memory.");let we=document.createElement("button");we.type="button",we.className="bp-v-btn is-primary",we.textContent=u("gpui.c.solid.load.big","Load it anyway"),we.addEventListener("click",()=>{le("loading",u("gpui.c.solid.loading.big","Loading it anyway…")),t.hub.rpc("kicad.big",{key:G}).catch(()=>le("error",W,!1,G))}),z.append(K,we)}d.replaceChildren(z)}function He(V,W){p.textContent=V,p.hidden=!V,p.classList.toggle("is-warn",W)}function $e(){if(Y)return Jt(Y);if(w==="board"||w==="3d")return Jt(H.pcb);if(w==="schematic")return Jt(H.sch);if(w==="mech")return Jt(P);return""}function Oe(){s.textContent=Cr(w);let V=$e();if(r.hidden=!V,o.hidden=!V,o.textContent=V,a.replaceChildren(),w==="mech"&&O.length>1){let _=document.createElement("select");_.className="bp-v-select",_.setAttribute("aria-label",u("viewer.mech","Mech"));for(let G of O){let z=document.createElement("option");z.value=G,z.textContent=Jt(G),z.selected=G===P,_.append(z)}_.addEventListener("change",()=>{P=_.value,Oe(),ht(!1)}),a.append(_)}if(ui(w)){let _=document.createElement("button");_.type="button",_.className="bp-v-btn"+(Pe?" is-on":""),_.textContent=R?.layerHead||"Layers",_.setAttribute("data-testid","viewer-layers-btn"),_.addEventListener("click",()=>{if(Pe=!Pe,m.hidden=!Pe,_.classList.toggle("is-on",Pe),Pe)We("","")}),a.append(_)}if(w==="board"||w==="schematic"||w==="3d"||w==="mech"||w==="gerbers"){let _=document.createElement("button");_.type="button",_.className="bp-v-btn",_.textContent="Fit",_.setAttribute("data-testid","viewer-fit-btn"),_.addEventListener("click",()=>{me?.fit(),de?.fit()}),a.append(_)}if((w==="board"||w==="schematic")&&t.hub.hasFeature("follow")){let _=document.createElement("button");_.type="button",_.className="bp-v-btn"+(re&&!ie?" is-on":""),_.textContent=re?ie?u("gpui.follow.paused","Follow (paused)"):"Follow agent":"Follow agent",_.setAttribute("data-testid","viewer-follow-btn"),_.addEventListener("click",()=>void Qt()),a.append(_)}let W=document.createElement("button");W.type="button",W.className="bp-v-btn bp-v-close",W.textContent="✕",W.title=u("common.close","Close"),W.setAttribute("aria-label",u("common.close","Close")),W.setAttribute("data-testid","viewer-close-btn"),W.addEventListener("click",()=>t.closeViewer()),a.append(W)}function Ne(){if(!R){m.replaceChildren();return}let V=document.createDocumentFragment(),W=document.createElement("div");W.className="bp-v-layers-head";let _=document.createElement("span");if(_.textContent=R.layerHead||"Layers",W.append(_),R.layerReset){let K=document.createElement("button");K.type="button",K.className="bp-v-btn",K.textContent="Reset",K.addEventListener("click",()=>void We("reset","")),W.append(K)}if(V.append(W),R.layerModes){let K=document.createElement("div");K.className="bp-v-layers-modes",["All","Dim","Only"].forEach((we,ke)=>{let Ae=document.createElement("button");Ae.type="button",Ae.className="bp-v-btn"+(R?.layerMode===ke?" is-on":""),Ae.textContent=we,Ae.addEventListener("click",()=>void We("mode",String(ke))),K.append(Ae)}),V.append(K)}let G=me?.presentColors()??new Map,z=(R.layerList||[]).concat(R.layerMarks||[]),ae=document.createElement("div");ae.className="bp-v-layers-list";for(let K of z){let we=G.get(K.layer);if(we===void 0)continue;let ke=document.createElement("div");ke.className="bp-v-layer-row"+(K.active?" is-focus":"");let Ae=document.createElement("input");Ae.type="checkbox",Ae.checked=K.on!==!1,Ae.addEventListener("change",()=>void We("toggle",String(K.layer)));let Ge=document.createElement("span");Ge.className="bp-v-layer-swatch";let je=we>>>16&255,De=we>>>8&255,Ie=we&255;Ge.style.background=K.on!==!1?`rgb(${je},${De},${Ie})`:`rgba(${je},${De},${Ie},0.2)`;let Ve=document.createElement("button");Ve.type="button",Ve.className="bp-v-layer-name",Ve.textContent=K.name,Ve.addEventListener("click",()=>void We("pick",String(K.layer))),ke.append(Ae,Ge,Ve),ae.append(ke)}V.append(ae),m.replaceChildren(V)}async function We(V,W){if(!ui(w))return;let _=E;try{let G=await t.hub.rpc("viewer.layers",{kind:w,present:oe,off:Ce,focus:te,...V?{action:V,value:W}:{}});if(_!==E||!G)return;Ce=Number(G.own)||0,te=typeof G.focus==="string"?G.focus:"",R=G;let z={off:Number(G.off)||0,dim:Number(G.dim)||0,lift:typeof G.lift==="number"?G.lift:255};if(me?.setLayers(z),Oe(),Pe)Ne()}catch{}}async function ze(){if(!re||ie||!v||!t.hub.hasFeature("follow"))return;ie=!0,Oe();try{await t.hub.rpc("viewer.follow",{thread:v,action:"pause"})}catch{}}async function Qt(){if(!v||!t.hub.hasFeature("follow"))return;let V=!re?"on":ie?"resume":"off";try{let W=await t.hub.rpc("viewer.follow",{thread:v,action:V});if(re=!!W.on,ie=!!W.paused,Oe(),W.on&&!W.paused&&W.focus&&Array.isArray(W.focus.box)&&W.focus.box.length===4&&(W.seq||0)>ue)ue=W.seq||ue,me?.zoomToBoxMm([W.focus.box[0],W.focus.box[1],W.focus.box[2],W.focus.box[3]])}catch{}}function rt(){f.hidden=!0,f.replaceChildren(),me?.setHighlights([])}function Zt(V){let W=V.split(";").filter(Boolean),_=W.shift()||V,G=[],z="",ae="";for(let Ge of W){if(Ge.startsWith("g="))continue;let je=Ge.indexOf("=");if(je>0){let De=Ge.slice(0,je),Ie=Ge.slice(je+1);if((De==="ref"||De==="symbol")&&!z)z=Ie;if(De==="net"&&!ae)ae=Ie;G.push([De,Ie])}else G.push([Ge,""])}let K=document.createElement("div");K.className="bp-v-info-head";let we=document.createElement("span");we.className="bp-v-info-title",we.textContent=_;let ke=document.createElement("button");ke.type="button",ke.className="bp-v-info-x",ke.textContent="×",ke.setAttribute("aria-label","Clear selection"),ke.addEventListener("click",rt),K.append(we,ke);let Ae=document.createElement("div");Ae.className="bp-v-info-rows";for(let[Ge,je]of G){let De=document.createElement("span");De.className="bp-v-info-chip",De.textContent=je?`${Ge}: ${je}`:Ge,Ae.append(De)}return f.replaceChildren(K,...G.length>0?[Ae]:[]),f.hidden=!1,{ref:z||void 0,net:ae||void 0}}async function It(V){if(!V){rt();return}let W=Array.from(L)[0]||"";if(!W)return;let _=E;try{let G=await t.hub.rpc("viewer.info",{key:W,at:V.at,idx:V.idx});if(_!==E)return;let z=typeof G.info==="string"?G.info:"";if(!z){rt();return}let{ref:ae,net:K}=Zt(z),we=[];if(ae)we.push(["ref",ae]);if(K)we.push(["net",K]);let ke=[[V.at,V.idx]];for(let[Ae,Ge]of we){let je=await t.hub.rpc("viewer.probe",{key:W,name:Ae,value:Ge});if(_!==E)return;if(Array.isArray(je.matches))for(let De of je.matches)ke.push(De)}me?.setHighlights(ke)}catch{rt()}}function Ee(){ee?.destroy(),ee=null,ge?.destroy(),ge=null,me?.destroy(),me=null,de?.destroy(),de=null,h.replaceChildren(),Pe=!1,m.hidden=!0,f.hidden=!0,f.replaceChildren(),He("",!1),le("none")}function ve(){M=[],A=0}async function ht(V){if(!v||!w)return;let W=++E;if(L.clear(),k=!1,ve(),Ee(),Oe(),ne(),Le(),(w==="board"||w==="schematic")&&v)Be(v);if(qo(w)){if(t.hub.rpc("viewer.watch",{thread:v,kind:""}).catch(()=>{}),w==="files")ee=pr(h,t,v,(z,ae)=>{if(w=z,Y=ae,z==="mech")P=ae;ht(!1)});else if(w==="diff")ee=hr(h,t,v);else if(w==="review")ee=ur(h,t,v);else if(w==="browser")ee=lr(h,t,v);else if(w==="terminal")le("loading","Loading terminal…"),import("/assets/terminal.js").then((ae)=>{if(W!==E)return;if(le("none"),ae?.mountTerminalPane)ge=ae.mountTerminalPane(h,t,v,q());else le("error","Terminal chunk missing",!0)},(ae)=>{if(W!==E)return;le("error",ae instanceof Error?ae.message:String(ae),!0)});return}if(le("loading","Loading…"),!H.root)try{let z=await t.hub.rpc("viewer.files",{thread:v});if(W!==E)return;H=z||{},Oe()}catch{}if(w==="gerbers"&&H.hasGerbers===!1){le("empty","No Gerbers in this project",!1);return}let _=q();if(w==="3d"||w==="mech")de=new hi(h,{onStatus:(z,ae)=>{if(ae)le("none"),He(z,!1);else if(z)le("loading",z);else le("none"),He("",!1)},onUserMove:()=>void ze()}),de.setTheme(_);else if(w==="board"||w==="schematic"||w==="gerbers")me=new li(h,{onPick:(z)=>void It(z),onUserMove:()=>void ze()}),me.setTheme(_);else{le("empty",`${Cr(w)} is not available in this viewer`,!1);return}let G={thread:v};if(V)G.force=!0;if(w==="mech"){if(O.length===0)try{let z=await t.hub.rpc("mech.list",{thread:v});if(W!==E)return;if(O=Array.isArray(z.parts)?z.parts:[],!P)P=z.primary||O[0]||"";Oe()}catch(z){if(W!==E)return;le("error",z instanceof Error?z.message:String(z),!0);return}if(!P){le("empty",u("gpui.rail.no.mech","No mechanical parts in this project"),!1);return}G.kind="3d",G.path=P}else{if(G.kind=w,Y&&(w==="board"||w==="schematic"))G.path=Y;if(w==="3d"&&!V&&de){let z=de.keptToken();if(z)G.kept=z}if((w==="board"||w==="schematic"||w==="gerbers")&&!V&&t.hub.hasFeature("keptChunks"))G.keptChunks=Array.from(T.keys())}k=!0,I="",J="",se="",ye="";try{let z=await t.hub.rpc("viewer.watch",G);if(W!==E)return;L=new Set(Array.isArray(z.keys)?z.keys:[]),k=!1;let ae=M;ve();for(let K of ae)if(K.kind==="bin")tt(K.buf);else et(K.key,K.none,K.retryable,K.big)}catch(z){if(W!==E)return;k=!1,L.clear(),ve();let ae=z instanceof Error?z.message:String(z),K=/no gerbers|not in this project|another machine/i.test(ae);le(K?"empty":"error",ae,!K)}}function et(V,W,_,G=!1){if(k){if(M.length{if(V.t==="plot"&&typeof V.none==="string"&&typeof V.key==="string")et(V.key,V.none,V.retryable===!0)}),ot=rn(()=>{if(w)Oe()}),en=(V)=>{if(V.key==="Escape"&&w&&!f.hidden)rt()};return window.addEventListener("keydown",en),{open(V,W){if(W!==v){if(v=W,H={},O=[],P="",B.clear(),re=!1,ie=!1,ue=0,Ce=0,te="",oe=0,R=null,t.hub.hasFeature("follow"))t.hub.rpc("viewer.follow",{thread:W}).then((_)=>{if(W!==v)return;if(re=!!_.on,ie=!!_.paused,ue=Number(_.seq)||0,w)Oe()}).catch(()=>{})}if(V!==w)D(),C.goLive(),Ce=0,te="",oe=0,R=null;w=V,Y="",ht(!1)},reconcileHas(V){if(w&&!zo(w,V))t.closeViewer()},close(){if(E++,k=!1,D(),F=!1,I="",J="",se="",ye="",C.goLive(),c.hidden=!0,b.hidden=!0,ve(),v)t.hub.rpc("viewer.watch",{thread:v,kind:""}).catch(()=>{});w="",L.clear(),Ee()}}}var kr="http://www.w3.org/2000/svg";function Yt(e){let t=document.createElementNS(kr,"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(kr,"path");i.setAttribute("d",n),t.appendChild(i)}return t}function xr(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 Ko(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 Pr(e,t){if(!e)return!0;if(t==="board"||t==="3d")return e.board!==!1;if(t==="schematic")return e.schematic!==!1;if(t==="mech")return e.mech!==!1;if(t==="gerbers")return e.gerbers!==!1;return!0}var Xt="dark",vn=(()=>{try{return Gs(localStorage.getItem("bp.theme.pref"))}catch{return"auto"}})(),bi=null,Bt=(()=>{try{return Vs(localStorage.getItem("bp.locale"))}catch{return"auto"}})();function Nr(){let e=Wt(vn,Xt);document.documentElement.classList.toggle("light",e==="light");try{localStorage.setItem("bp.theme",e)}catch{}}function Sr(e){if(!e)return;Xt=e==="light"?"light":"dark",Nr()}function Lr(){if(Bt!=="auto")kt(Bt);else if(bi)kt(bi);else if(typeof navigator<"u"&&navigator.language){if(!kt(navigator.language))kt("en")}}function Jo(){return`web-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`}function Ar(){let e=document.getElementById("root");if(!e)return;try{if(localStorage.getItem("bp.theme")==="light")Xt="light";if(Wt(vn,Xt)==="light")document.documentElement.classList.add("light");if(Bt!=="auto")kt(Bt)}catch{}let t=document.createElement("header");t.className="bp-topbar",t.setAttribute("data-testid","topbar");let n=document.createElement("button");n.type="button",n.className="icon bp-side-toggle",n.textContent="☰",n.title="Toggle sidebar",n.setAttribute("aria-label","Toggle sidebar");let i=document.createElement("div");i.className="bp-brand";let s=document.createElement("img");s.src="/assets/favicon.svg",s.alt="Backplane",s.className="bp-logo";let r=document.createElement("span");r.className="bp-brand-name bp-hide-phone",r.textContent="Backplane";let o=document.createElement("span");o.className="bp-crumb-sep bp-hide-phone",o.textContent="/";let a=document.createElement("span");a.className="bp-crumb-proj bp-hide-phone";let c=document.createElement("span");c.className="bp-crumb-sep bp-hide-phone",c.textContent="/";let p=document.createElement("span");p.className="bp-crumb-thread",p.setAttribute("data-testid","thread-title");let l=document.createElement("span");l.className="bp-plan-top-badge bp-hidden",l.setAttribute("data-testid","plan-top-badge"),i.append(s,r,o,a,c,p,l);let h=document.createElement("div");h.className="bp-top-state bp-hide-phone bp-hidden";let d=document.createElement("span");d.className="bp-top-state-lbl",d.textContent="STATE";let m=document.createElement("span");m.className="bp-dot bp-dot-idle";let f=document.createElement("span");f.className="bp-top-state-word",h.append(d,m,f);let b=document.createElement("div");b.className="bp-top-acts bp-hide-phone bp-hidden";let v=document.createElement("button");v.type="button",v.className="bp-btn-ghost bp-top-act";let w=document.createElement("span");w.textContent=u("menu.pin","Pin"),v.append(Yt(["M12 17v5","M9 3h6l1 7 3 3H5l3-3 1-7z"]),w);let E=document.createElement("button");E.type="button",E.className="bp-btn-ghost bp-top-act";let k=document.createElement("span");k.textContent=u("menu.settle","Settle"),E.append(Yt(["M12 22a10 10 0 1 0 0-20 10 10 0 0 0 0 20z","M9 12l2 2 4-4"]),k);let L=document.createElement("div");L.className="bp-menu-wrap";let M=document.createElement("button");M.type="button",M.className="bp-btn-ghost bp-top-act",M.textContent="▾",M.title="Thread menu",M.setAttribute("aria-label","Thread menu"),M.setAttribute("data-testid","thread-menu-btn");let A=document.createElement("div");A.className="bp-popover bp-hidden",A.setAttribute("data-testid","thread-menu"),L.append(M,A),b.append(v,E,L);let B=document.createElement("div");B.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 H=document.createElement("span");H.textContent=u("gpui.improvements","Improvements"),T.append(Yt(["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"]),H);let O=document.createElement("button");O.type="button",O.className="bp-cmd-box bp-hide-tablet",O.textContent="> Jump or run a command";let P=document.createElement("button");P.type="button",P.className="icon bp-top-icon",P.title="Search",P.setAttribute("aria-label","Search"),P.appendChild(Yt(["M11 19a8 8 0 1 0 0-16 8 8 0 0 0 0 16z","M21 21l-4.3-4.3"]));let Y=document.createElement("button");Y.type="button",Y.className="icon bp-top-icon",Y.title=u("palette.settings","Settings"),Y.setAttribute("aria-label",u("palette.settings","Settings")),Y.setAttribute("data-testid","settings-btn"),Y.appendChild(Yt(["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"])),B.append(T,O,P,Y),t.append(n,i,h,b,B);let re=document.createElement("div");re.className="bp-body";let ie=document.createElement("aside");ie.className="bp-sidebar",ie.setAttribute("data-testid","sidebar");let ue=document.createElement("main");ue.className="bp-center";let Pe=document.createElement("div");Pe.className="bp-right-area bp-hidden",Pe.setAttribute("data-testid","right-area");let Ce=document.createElement("div");Ce.className="bp-right-top";let te=document.createElement("section");te.className="bp-viewer-pane bp-hidden",te.setAttribute("data-testid","viewer-pane"),Ce.appendChild(te),Pe.appendChild(Ce);let oe=document.createElement("nav");oe.className="bp-rail",oe.setAttribute("aria-label","Viewer rail"),oe.setAttribute("data-testid","viewer-rail"),re.append(ie,ue,Pe,oe),e.append(t,re);let R=new oi,me=null,de=new Set,ee=0,ge=null,C=[],x=[],F=[],I=[],J=[],se=[],ye=[],D="",ne=0,Te=0,Le=null,Be=null,q="",fe=null,le=20,He={},$e=new Map;function Oe(g,y){$e.delete(g),$e.set(g,y);while($e.size>le){let S=$e.keys().next().value;if(S!==void 0)$e.delete(S);else break}}let Ne="",We=0,ze=new Wn(ue,{onNewThread:(g)=>{mt(g)},onOpenThread:(g)=>{qe(g)},onOpenViewer:(g,y)=>{qe(g).then(()=>{if(D===g)ut(y)})},onRetry:(g)=>{It(g)}});function Qt(){if(!Ne)return;Ne="",We++,ue.classList.remove("bp-home-open"),ze.hide(),Ee.setSelectedProject(""),Ie()}function rt(g){return C.find((y)=>y.id===g)??C.find((y)=>Un(y.id)===g)}async function Zt(g,y){try{let S=await R.rpc("threads.list",{project:g,limit:50,archived:!1});if(y!==We||Ne!==g)return;let N=(S.threads??[]).filter((j)=>!j.swarm).map((j)=>({id:j.id,title:j.title,dot:xr(j),status:j.status||j.state||"",age:Ko(j.updatedAt),settled:j.settled}));ze.setThreads(N)}catch{if(y===We&&Ne===g)ze.setThreads([])}}function It(g){if(!g||!R.hasFeature("projecthome"))return!1;tt.cancel(),pe.closeModelPicker(),Ne=g;let y=++We,S=rt(g);return ue.classList.add("bp-home-open"),ie.classList.remove("bp-sidebar-open"),ze.show({id:g,title:S?.title??g}),Ee.setSelectedProject(g),Ie(),Zt(g,y),R.rpc("project.home",{project:g}).then((N)=>{if(y===We&&Ne===g)ze.setData(Ns(N))}).catch((N)=>{if(y!==We||Ne!==g)return;ze.setError(N instanceof Error&&N.message?N.message:u("web.home.error","Could not load this project."))}),!0}let Ee=new ii(ie,{onSelectThread:(g)=>{if(g===D&&Le!==null){Qt(),ie.classList.remove("bp-sidebar-open");return}qe(g)},onNewThread:(g)=>{mt(g)},onOpenProject:(g)=>It(Un(g)),canOpenProject:()=>R.hasFeature("projecthome"),onSelectBot:(g)=>{qe(g.thread)},onQuickOpenViewer:(g,y)=>{let S=x.find((j)=>j.project===g&&!j.archived&&!j.swarm);(async()=>{if(S)await qe(S.id);else await mt(g);if(D)q=y,G.setActive(y),fe?.open(y,D)})()},onThreadAct:(g,y)=>{bt(g,y)},onSnoozeRow:(g)=>{R.rpc("sidebar.act",{action:"row-snooze",value:g}).then(()=>Xe()).catch(()=>{})},onToggleSection:(g)=>{if(de.has(g))de.delete(g);else de.add(g);Xe()},onToggleProjectFold:(g)=>{R.rpc("sidebar.act",{action:"project-fold",value:g}).then(()=>Xe()).catch(()=>{})},onCollapseSidebar:()=>{ie.classList.remove("bp-sidebar-open"),ie.classList.add("bp-sidebar-collapsed")},onNeedAct:async(g)=>{let y=mn(g,!1);if(!y)return;if(y.kind==="thread"){qe(y.id);return}if(y.kind!=="call")return;let S=Os(await R.rpc(y.method,y.params));if(S?.kind==="thread")qe(S.id);Xe()},hasRoomView:!1,onAddProject:()=>_.open({mode:"folder"}),onSettleSwarm:(g)=>{R.rpc("sidebar.act",{action:"swarm-settle",value:g}).then(()=>Xe()).catch(()=>{})},onNewChat:()=>{mt(yt)},onMoveToProject:(g)=>De(g)}),ve=new An(ue,{onLoadOlder:()=>{wi()},onGoToEntry:(g)=>{vi(g)},onOpenAccounts:()=>{ke()},onAnswerAsk:(g,y)=>{R.rpc("ask.answer",{ask:g,answer:y}).catch((S)=>{pe.showError(S instanceof Error?S.message:"Could not send answer")})},onToggleReview:(g)=>{if(!D)return;let y=ne;R.rpc("thread.review",{thread:D,on:g}).then((S)=>{if(y===ne)ve.setReview(S.review??null)}).catch(()=>{})},onUnansweredAction:(g,y)=>{if(!D)return;if(g==="again"||g==="thread-again")R.rpc("thread.again",{thread:D,value:y}).catch(()=>{});else R.rpc("thread.act",{thread:D,action:g,value:y}).catch(()=>{})},onReplyEntry:(g)=>{if(!R.hasFeature("reply")){let y=(g.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 Oo=[Ze(77),Ze(83),Ze(94)],Go=[Ze(53),Ze(58),Ze(67)],Vo=[Ze(245),Ze(246),Ze(248)],Uo=[Ze(225),Ze(228),Ze(233)];function fr(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 vr(e,t,n){let i=fr(e,e.VERTEX_SHADER,t),s=fr(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 o=e.getProgramInfoLog(r)||"program link error";throw e.deleteProgram(r),Error(o)}return r}function Wo(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 _o(e,t,n,i){let s=1/Math.tan(e*0.5),r=1/(n-i),o=new Float32Array(16);return o[0]=s/t,o[5]=s,o[10]=(i+n)*r,o[11]=-1,o[14]=2*i*n*r,o}function wr(e){let t=Math.hypot(e[0],e[1],e[2])||1;return[e[0]/t,e[1]/t,e[2]/t]}function yr(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 pi(e,t){return e[0]*t[0]+e[1]*t[1]+e[2]*t[2]}class hi{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=vr(n,Ho,Do),this.bgVao=n.createVertexArray(),this.uBgTop=n.getUniformLocation(this.bgProg,"uBgTop"),this.uBgBot=n.getUniformLocation(this.bgProg,"uBgBot"),this.prog=vr(n,Fo,$o),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=ir(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 o++;let a=r>0?new Float32Array(r*9):null,c=r>0?new Float32Array(r*9):null,p=r>0?new Float32Array(r*12):null,l=o>0?new Float32Array(o*9):null,h=o>0?new Float32Array(o*9):null,d=o>0?new Float32Array(o*12):null,u=0,f=0;for(let w=0;w>>24&255,L=1-k/255,M=(E>>>16&255)/255,A=(E>>>8&255)/255,B=(E&255)/255,T=w*9;if(k===0&&a&&c&&p){let H=u*9;for(let P=0;P<9;P++)a[H+P]=e[T+P],c[H+P]=t[T+P];let O=u*12;for(let P=0;P<3;P++)p[O+P*4]=M,p[O+P*4+1]=A,p[O+P*4+2]=B,p[O+P*4+3]=1;u++}else if(l&&h&&d){let H=f*9;for(let P=0;P<9;P++)l[H+P]=e[T+P],h[H+P]=t[T+P];let O=f*12;for(let P=0;P<3;P++)d[O+P*4]=M,d[O+P*4+1]=A,d[O+P*4+2]=B,d[O+P*4+3]=L;f++}}let b=a&&c&&p?this.createSubBatch(a,c,p,r*3):null,v=l&&h&&d?this.createSubBatch(l,h,d,o*3):null;if(!b&&!v)return null;return{opaque:b,translucent:v,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}=gr(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),o=Math.round(i*r),a=Math.round(s*r);if(this.canvas.width!==o||this.canvas.height!==a)this.canvas.width=o,this.canvas.height=a;if(t.viewport(0,0,o,a),!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 H=this.lightTheme?Vo:Oo,O=this.lightTheme?Uo:Go;t.uniform3f(this.uBgTop,H[0],H[1],H[2]),t.uniform3f(this.uBgBot,O[0],O[1],O[2]),t.bindVertexArray(this.bgVao),t.drawArrays(t.TRIANGLE_STRIP,0,4),t.bindVertexArray(null)}let c=Math.cos(this.pitch),p=Math.sin(this.pitch),l=Math.cos(this.yaw),h=Math.sin(this.yaw),d=[this.target[0]+this.dist*c*h,this.target[1]-this.dist*c*l,this.target[2]+this.dist*p],u=wr([this.target[0]-d[0],this.target[1]-d[1],this.target[2]-d[2]]),f=Math.abs(u[2])>0.99?[0,1,0]:[0,0,1],b=wr(yr(u,f)),v=yr(b,u),w=new Float32Array([b[0],v[0],-u[0],0,b[1],v[1],-u[1],0,b[2],v[2],-u[2],0,-pi(b,d),-pi(v,d),pi(u,d),1]),E=Math.max(0.05,this.dist*0.01),k=Math.max(this.dist*10,this.radius*20),L=_o(35*Math.PI/180,o/a,E,k),M=Wo(L,w);t.useProgram(this.prog),t.uniformMatrix4fv(this.uMvp,!1,M),t.uniform3f(this.uEye,d[0],d[1],d[2]),t.uniform3f(this.uRight,b[0],b[1],b[2]),t.uniform3f(this.uUp,v[0],v[1],v[2]),t.uniform3f(this.uFwd,u[0],u[1],u[2]);let A=!1,B=[],T=[];for(let H of this.partBatches){let O=e-H.fadeStartMs,P=H.fadeStartMs===0?1:Math.min(1,Math.max(0,O/300));if(P<1){if(A=!0,P>0)T.push({batch:H,fade:P})}else B.push(H)}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 H of B)this.drawSubBatch(H.opaque);if(t.depthMask(!1),t.enable(t.BLEND),t.uniform1f(this.uFade,1),this.boardBatch)this.drawSubBatch(this.boardBatch.translucent);for(let H of B)this.drawSubBatch(H.translucent);for(let{batch:H,fade:O}of T)t.uniform1f(this.uFade,O),this.drawSubBatch(H.opaque),this.drawSubBatch(H.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()),o=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/o)));this.pinchDist=o,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),o=Math.sin(this.yaw);this.target[0]-=n*r*s,this.target[1]-=n*o*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 Er=64,zo=16777216;function qo(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 Jt(e){if(!e)return"";let t=e.replace(/\\/g,"/").replace(/\/+$/,""),n=t.lastIndexOf("/");return n>=0?t.slice(n+1):t}function Cr(e){switch(e){case"board":return m("viewer.board","Board");case"schematic":return m("viewer.schematic","Schematic");case"3d":return m("viewer.solid","3D");case"gerbers":return m("gpui.gerbers","Gerbers");case"mech":return m("viewer.mech","Mech");case"files":return m("viewer.files","Files");case"diff":return m("viewer.diff","Diff");case"review":return m("viewer.review","Review");case"browser":return m("bots.tab.browser","Browser");case"terminal":return m("viewer.terminal","Terminal");default:return e?e.charAt(0).toUpperCase()+e.slice(1):""}}function mi(e){return e==="board"||e==="schematic"||e==="gerbers"}function Ko(e){return e==="files"||e==="diff"||e==="review"||e==="browser"||e==="terminal"}function ui(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 o=document.createElement("span");o.className="bp-vh-file",o.hidden=!0,i.append(s,r,o);let a=document.createElement("div");a.className="bp-vh-actions",n.append(i,a);let c=document.createElement("div");c.className="bp-solid-bar",c.setAttribute("data-testid","solid-presets-bar"),c.hidden=!0;let p=document.createElement("div");p.className="bp-v-banner",p.hidden=!0;let l=document.createElement("div");l.className="bp-v-stage-wrap";let h=document.createElement("div");h.className="bp-v-stage";let d=document.createElement("div");d.className="bp-v-overlay",d.hidden=!0;let u=document.createElement("div");u.className="bp-v-layers",u.hidden=!0;let f=document.createElement("div");f.className="bp-v-info",f.hidden=!0,l.append(h,d,u,f);let b=document.createElement("div");b.className="bp-history-bar",b.setAttribute("data-testid","viewer-history-bar"),b.hidden=!0,e.replaceChildren(n,c,p,l,b);let v="",w="",E=0,k=!1,L=new Set,M=[],A=0,B=new Map,T=new Map,H={},O=[],P="",Y="",re=!1,ie=!1,me=0,Pe=!1,Ce=0,te="",oe=0,R=null,ue=null,de=null,ee=null,ge=null,C=new di,x=0,F=!1,I="",J="",se="",Ee="";document.addEventListener("click",(V)=>{if(!F)return;if(V.target instanceof Node&&b.contains(V.target))return;F=!1,Le()}),document.addEventListener("keydown",(V)=>{if(F&&V.key==="Escape")F=!1,Le()});function D(){if(x)window.clearInterval(x),x=0;C.playing=!1}function ne(){let V=w==="3d"||w==="mech";if(c.hidden=!V,!V)return;if(c.childElementCount>0)return;for(let _ of br){let G=document.createElement("button");G.type="button",G.className="bp-v-btn",G.textContent=_.label,G.setAttribute("data-testid",`solid-view-${_.id}`),G.addEventListener("click",()=>{de?.setView(_.id)}),c.append(G)}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(!de)return;de.snapPng().then((_)=>{if(!_)return;let G=URL.createObjectURL(_),z=document.createElement("a");z.href=G;let ae=($e()||w||"view").replace(/[^a-zA-Z0-9._-]/g,"_");z.download=`${ae}-snap.png`,z.click(),setTimeout(()=>URL.revokeObjectURL(G),1000)})}),c.append(W)}async function Te(){if(!v||w!=="board"&&w!=="schematic")return;Le();let V=C.compareRequest();if(!V){I="",J="",se="",Ee="",await ht(!1);return}let W=`${w}|${V.commit}|${V.bits}|${Y}`;if(W===Ee&&L.size>0){He(C.highlightEdits?`Comparing against ${C.activeRef()?.label||V.commit.slice(0,7)} (edits highlighted)`:`Comparing against ${C.activeRef()?.label||V.commit.slice(0,7)}`,!1);return}let _=++E;L.clear(),B.clear(),we(),k=!0,I="",J=V.commit,se="",Ee=W;try{let G=Y||(w==="schematic"?H.sch:H.pcb)||"";if(!G){let ke=await t.hub.rpc("viewer.files",{thread:v});if(_!==E)return;H=ke||{},Oe(),G=(w==="schematic"?H.sch:H.pcb)||""}if(!G)throw Error(`Unable to resolve ${w} file path for compare`);let z=await t.hub.rpc("viewer.compare",{thread:v,kind:w,commit:V.commit,bits:V.bits,...Y?{path:Y}:{}});if(_!==E)return;let ae=typeof z?.root==="string"?z.root:"",q=w==="schematic"?"1":"0";I=ae?`${q}|${ae}|diff +`:`${q}|`,J=V.commit,se=G.startsWith("/")||/^[A-Za-z]:[\\/]/.test(G)||!ae?G:`${ae.replace(/\/+$/,"")}/${G.replace(/^\/+/,"")}`,k=!1;let ye=M;we();for(let ke of ye)if(ke.kind==="bin")tt(ke.buf);else et(ke.key,ke.none,ke.retryable,ke.big);He(C.highlightEdits?`Comparing against ${C.activeRef()?.label||V.commit.slice(0,7)} (edits highlighted)`:`Viewing snapshot: ${C.activeRef()?.label||V.commit.slice(0,7)}`,!1)}catch(G){if(_!==E)return;k=!1,I="",J="",se="",Ee="",we(),He(G instanceof Error?G.message:String(G),!0)}}function Le(){let V=w==="board"||w==="schematic";if(b.hidden=!V,!V)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=C.refs.length===0||C.index>=C.refs.length-1,_.setAttribute("data-testid","history-prev"),_.addEventListener("click",()=>{if(D(),C.step(1))Te()});let G=document.createElement("button");G.type="button",G.className="bp-v-btn"+(C.playing?" is-on":""),G.textContent=C.playing?"⏸":"▶",G.title=C.playing?"Pause history":"Play history",G.disabled=C.refs.length===0,G.setAttribute("data-testid","history-play"),G.addEventListener("click",()=>{if(C.playing){D(),Le();return}if(C.refs.length===0)return;if(C.playing=!0,C.isLive())C.index=C.refs.length-1,Te();else Le();x=window.setInterval(()=>{if(!C.playing||w!=="board"&&w!=="schematic"){D(),Le();return}if(C.step(-1))Te();else D(),Le()},1400)});let z=document.createElement("button");z.type="button",z.className="bp-v-btn",z.textContent=">",z.title="Newer snapshot",z.disabled=C.isLive(),z.setAttribute("data-testid","history-next"),z.addEventListener("click",()=>{if(D(),C.step(-1))Te()});let ae=document.createElement("button");ae.type="button",ae.className="bp-v-btn"+(C.isLive()?" is-on":""),ae.textContent="Live",ae.setAttribute("data-testid","history-live"),ae.addEventListener("click",()=>{if(D(),C.goLive())He("",!1),Te()});let q=document.createElement("span");q.className="bp-history-label",q.setAttribute("data-testid","history-label");let ye=C.activeRef();q.textContent=ye?ye.label||ye.commit.slice(0,7):C.refs.length>0?`Live (${C.refs.length} saved)`:"Live",W.append(_,G,z,ae,q);let ke=document.createElement("div");ke.className="bp-history-group";let Ae=document.createElement("button");Ae.type="button",Ae.className="bp-v-btn"+(C.highlightEdits?" is-on":""),Ae.textContent="Highlight edits",Ae.disabled=C.refs.length===0,Ae.setAttribute("data-testid","history-highlight"),Ae.addEventListener("click",()=>{D(),C.toggleHighlight(),Te()});let Ge=document.createElement("div");Ge.className="bp-history-menu-wrap";let je=document.createElement("button");if(je.type="button",je.className="bp-v-btn"+(F||!C.isLive()?" is-on":""),je.disabled=C.refs.length===0,je.setAttribute("data-testid","history-compare"),je.setAttribute("aria-haspopup","menu"),je.setAttribute("aria-expanded",String(F)),je.textContent=ye?`Compare: ${ye.label||ye.commit.slice(0,7)} ▾`:"Compare ▾",je.addEventListener("click",(De)=>{De.stopPropagation(),F=!F,Le()}),Ge.append(je),F&&C.refs.length>0){let De=document.createElement("div");De.className="bp-history-menu",De.setAttribute("role","menu"),De.setAttribute("data-testid","history-compare-menu");let Ie=(Ve,mt,tn)=>{let at=document.createElement("button");at.type="button",at.className="bp-history-menu-item"+(tn?" is-active":""),at.setAttribute("role","menuitem"),at.setAttribute("data-commit",mt),at.textContent=Ve,at.addEventListener("click",()=>{if(F=!1,D(),C.selectCommit(mt)){if(C.isLive())He("",!1);Te()}else Le()}),De.append(at)};Ie("Live (working tree)","",C.isLive());for(let Ve of C.refs)Ie(Ve.label||Ve.commit.slice(0,7),Ve.commit,ye?.commit===Ve.commit);Ge.append(De)}ke.append(Ae,Ge),b.replaceChildren(W,ke)}async function Be(V){if(!V)return;try{let W=await t.hub.rpc("viewer.refs",{thread:V});if(V!==v)return;C.setRefs(Array.isArray(W?.refs)?W.refs:[]),Le()}catch{if(V!==v)return;C.setRefs([]),Le()}}function K(){return document.documentElement.classList.contains("light")}let fe=new MutationObserver(()=>{let V=K();ue?.setTheme(V),de?.setTheme(V),ge?.setTheme(V)});fe.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]});function le(V,W="",_=!1,G=""){if(V==="none"){d.hidden=!0,d.replaceChildren();return}d.hidden=!1,d.className=`bp-v-overlay is-${V}`;let z=document.createElement("div");z.className="bp-v-state-card";let ae=document.createElement("div");if(ae.className="bp-v-state-msg",ae.textContent=W,z.append(ae),_){let q=document.createElement("button");q.type="button",q.className="bp-v-btn is-primary",q.textContent=m("tools.retry","Retry"),q.addEventListener("click",()=>void ht(!0)),z.append(q)}if(G){let q=document.createElement("div");q.className="bp-v-state-msg",q.textContent=m("gpui.c.solid.big.next","Loading it may take a while and a lot of memory.");let ye=document.createElement("button");ye.type="button",ye.className="bp-v-btn is-primary",ye.textContent=m("gpui.c.solid.load.big","Load it anyway"),ye.addEventListener("click",()=>{le("loading",m("gpui.c.solid.loading.big","Loading it anyway…")),t.hub.rpc("kicad.big",{key:G}).catch(()=>le("error",W,!1,G))}),z.append(q,ye)}d.replaceChildren(z)}function He(V,W){p.textContent=V,p.hidden=!V,p.classList.toggle("is-warn",W)}function $e(){if(Y)return Jt(Y);if(w==="board"||w==="3d")return Jt(H.pcb);if(w==="schematic")return Jt(H.sch);if(w==="mech")return Jt(P);return""}function Oe(){s.textContent=Cr(w);let V=$e();if(r.hidden=!V,o.hidden=!V,o.textContent=V,a.replaceChildren(),w==="mech"&&O.length>1){let _=document.createElement("select");_.className="bp-v-select",_.setAttribute("aria-label",m("viewer.mech","Mech"));for(let G of O){let z=document.createElement("option");z.value=G,z.textContent=Jt(G),z.selected=G===P,_.append(z)}_.addEventListener("change",()=>{P=_.value,Oe(),ht(!1)}),a.append(_)}if(mi(w)){let _=document.createElement("button");_.type="button",_.className="bp-v-btn"+(Pe?" is-on":""),_.textContent=R?.layerHead||"Layers",_.setAttribute("data-testid","viewer-layers-btn"),_.addEventListener("click",()=>{if(Pe=!Pe,u.hidden=!Pe,_.classList.toggle("is-on",Pe),Pe)We("","")}),a.append(_)}if(w==="board"||w==="schematic"||w==="3d"||w==="mech"||w==="gerbers"){let _=document.createElement("button");_.type="button",_.className="bp-v-btn",_.textContent="Fit",_.setAttribute("data-testid","viewer-fit-btn"),_.addEventListener("click",()=>{ue?.fit(),de?.fit()}),a.append(_)}if((w==="board"||w==="schematic")&&t.hub.hasFeature("follow")){let _=document.createElement("button");_.type="button",_.className="bp-v-btn"+(re&&!ie?" is-on":""),_.textContent=re?ie?m("gpui.follow.paused","Follow (paused)"):"Follow agent":"Follow agent",_.setAttribute("data-testid","viewer-follow-btn"),_.addEventListener("click",()=>void Qt()),a.append(_)}let W=document.createElement("button");W.type="button",W.className="bp-v-btn bp-v-close",W.textContent="✕",W.title=m("common.close","Close"),W.setAttribute("aria-label",m("common.close","Close")),W.setAttribute("data-testid","viewer-close-btn"),W.addEventListener("click",()=>t.closeViewer()),a.append(W)}function Ne(){if(!R){u.replaceChildren();return}let V=document.createDocumentFragment(),W=document.createElement("div");W.className="bp-v-layers-head";let _=document.createElement("span");if(_.textContent=R.layerHead||"Layers",W.append(_),R.layerReset){let q=document.createElement("button");q.type="button",q.className="bp-v-btn",q.textContent="Reset",q.addEventListener("click",()=>void We("reset","")),W.append(q)}if(V.append(W),R.layerModes){let q=document.createElement("div");q.className="bp-v-layers-modes",["All","Dim","Only"].forEach((ye,ke)=>{let Ae=document.createElement("button");Ae.type="button",Ae.className="bp-v-btn"+(R?.layerMode===ke?" is-on":""),Ae.textContent=ye,Ae.addEventListener("click",()=>void We("mode",String(ke))),q.append(Ae)}),V.append(q)}let G=ue?.presentColors()??new Map,z=(R.layerList||[]).concat(R.layerMarks||[]),ae=document.createElement("div");ae.className="bp-v-layers-list";for(let q of z){let ye=G.get(q.layer);if(ye===void 0)continue;let ke=document.createElement("div");ke.className="bp-v-layer-row"+(q.active?" is-focus":"");let Ae=document.createElement("input");Ae.type="checkbox",Ae.checked=q.on!==!1,Ae.addEventListener("change",()=>void We("toggle",String(q.layer)));let Ge=document.createElement("span");Ge.className="bp-v-layer-swatch";let je=ye>>>16&255,De=ye>>>8&255,Ie=ye&255;Ge.style.background=q.on!==!1?`rgb(${je},${De},${Ie})`:`rgba(${je},${De},${Ie},0.2)`;let Ve=document.createElement("button");Ve.type="button",Ve.className="bp-v-layer-name",Ve.textContent=q.name,Ve.addEventListener("click",()=>void We("pick",String(q.layer))),ke.append(Ae,Ge,Ve),ae.append(ke)}V.append(ae),u.replaceChildren(V)}async function We(V,W){if(!mi(w))return;let _=E;try{let G=await t.hub.rpc("viewer.layers",{kind:w,present:oe,off:Ce,focus:te,...V?{action:V,value:W}:{}});if(_!==E||!G)return;Ce=Number(G.own)||0,te=typeof G.focus==="string"?G.focus:"",R=G;let z={off:Number(G.off)||0,dim:Number(G.dim)||0,lift:typeof G.lift==="number"?G.lift:255};if(ue?.setLayers(z),Oe(),Pe)Ne()}catch{}}async function ze(){if(!re||ie||!v||!t.hub.hasFeature("follow"))return;ie=!0,Oe();try{await t.hub.rpc("viewer.follow",{thread:v,action:"pause"})}catch{}}async function Qt(){if(!v||!t.hub.hasFeature("follow"))return;let V=!re?"on":ie?"resume":"off";try{let W=await t.hub.rpc("viewer.follow",{thread:v,action:V});if(re=!!W.on,ie=!!W.paused,Oe(),W.on&&!W.paused&&W.focus&&Array.isArray(W.focus.box)&&W.focus.box.length===4&&(W.seq||0)>me)me=W.seq||me,ue?.zoomToBoxMm([W.focus.box[0],W.focus.box[1],W.focus.box[2],W.focus.box[3]])}catch{}}function rt(){f.hidden=!0,f.replaceChildren(),ue?.setHighlights([])}function Zt(V){let W=V.split(";").filter(Boolean),_=W.shift()||V,G=[],z="",ae="";for(let Ge of W){if(Ge.startsWith("g="))continue;let je=Ge.indexOf("=");if(je>0){let De=Ge.slice(0,je),Ie=Ge.slice(je+1);if((De==="ref"||De==="symbol")&&!z)z=Ie;if(De==="net"&&!ae)ae=Ie;G.push([De,Ie])}else G.push([Ge,""])}let q=document.createElement("div");q.className="bp-v-info-head";let ye=document.createElement("span");ye.className="bp-v-info-title",ye.textContent=_;let ke=document.createElement("button");ke.type="button",ke.className="bp-v-info-x",ke.textContent="×",ke.setAttribute("aria-label","Clear selection"),ke.addEventListener("click",rt),q.append(ye,ke);let Ae=document.createElement("div");Ae.className="bp-v-info-rows";for(let[Ge,je]of G){let De=document.createElement("span");De.className="bp-v-info-chip",De.textContent=je?`${Ge}: ${je}`:Ge,Ae.append(De)}return f.replaceChildren(q,...G.length>0?[Ae]:[]),f.hidden=!1,{ref:z||void 0,net:ae||void 0}}async function It(V){if(!V){rt();return}let W=Array.from(L)[0]||"";if(!W)return;let _=E;try{let G=await t.hub.rpc("viewer.info",{key:W,at:V.at,idx:V.idx});if(_!==E)return;let z=typeof G.info==="string"?G.info:"";if(!z){rt();return}let{ref:ae,net:q}=Zt(z),ye=[];if(ae)ye.push(["ref",ae]);if(q)ye.push(["net",q]);let ke=[[V.at,V.idx]];for(let[Ae,Ge]of ye){let je=await t.hub.rpc("viewer.probe",{key:W,name:Ae,value:Ge});if(_!==E)return;if(Array.isArray(je.matches))for(let De of je.matches)ke.push(De)}ue?.setHighlights(ke)}catch{rt()}}function ve(){ee?.destroy(),ee=null,ge?.destroy(),ge=null,ue?.destroy(),ue=null,de?.destroy(),de=null,h.replaceChildren(),Pe=!1,u.hidden=!0,f.hidden=!0,f.replaceChildren(),He("",!1),le("none")}function we(){M=[],A=0}async function ht(V){if(!v||!w)return;let W=++E;if(L.clear(),k=!1,we(),ve(),Oe(),ne(),Le(),(w==="board"||w==="schematic")&&v)Be(v);if(Ko(w)){if(t.hub.rpc("viewer.watch",{thread:v,kind:""}).catch(()=>{}),w==="files")ee=pr(h,t,v,(z,ae)=>{if(w=z,Y=ae,z==="mech")P=ae;ht(!1)});else if(w==="diff")ee=hr(h,t,v);else if(w==="review")ee=mr(h,t,v);else if(w==="browser")ee=lr(h,t,v);else if(w==="terminal")le("loading","Loading terminal…"),import("/assets/terminal.js").then((ae)=>{if(W!==E)return;if(le("none"),ae?.mountTerminalPane)ge=ae.mountTerminalPane(h,t,v,K());else le("error","Terminal chunk missing",!0)},(ae)=>{if(W!==E)return;le("error",ae instanceof Error?ae.message:String(ae),!0)});return}if(le("loading","Loading…"),!H.root)try{let z=await t.hub.rpc("viewer.files",{thread:v});if(W!==E)return;H=z||{},Oe()}catch{}if(w==="gerbers"&&H.hasGerbers===!1){le("empty","No Gerbers in this project",!1);return}let _=K();if(w==="3d"||w==="mech")de=new hi(h,{onStatus:(z,ae)=>{if(ae)le("none"),He(z,!1);else if(z)le("loading",z);else le("none"),He("",!1)},onUserMove:()=>void ze()}),de.setTheme(_);else if(w==="board"||w==="schematic"||w==="gerbers")ue=new li(h,{onPick:(z)=>void It(z),onUserMove:()=>void ze()}),ue.setTheme(_);else{le("empty",`${Cr(w)} is not available in this viewer`,!1);return}let G={thread:v};if(V)G.force=!0;if(w==="mech"){if(O.length===0)try{let z=await t.hub.rpc("mech.list",{thread:v});if(W!==E)return;if(O=Array.isArray(z.parts)?z.parts:[],!P)P=z.primary||O[0]||"";Oe()}catch(z){if(W!==E)return;le("error",z instanceof Error?z.message:String(z),!0);return}if(!P){le("empty",m("gpui.rail.no.mech","No mechanical parts in this project"),!1);return}G.kind="3d",G.path=P}else{if(G.kind=w,Y&&(w==="board"||w==="schematic"))G.path=Y;if(w==="3d"&&!V&&de){let z=de.keptToken();if(z)G.kept=z}if((w==="board"||w==="schematic"||w==="gerbers")&&!V&&t.hub.hasFeature("keptChunks"))G.keptChunks=Array.from(T.keys())}k=!0,I="",J="",se="",Ee="";try{let z=await t.hub.rpc("viewer.watch",G);if(W!==E)return;L=new Set(Array.isArray(z.keys)?z.keys:[]),k=!1;let ae=M;we();for(let q of ae)if(q.kind==="bin")tt(q.buf);else et(q.key,q.none,q.retryable,q.big)}catch(z){if(W!==E)return;k=!1,L.clear(),we();let ae=z instanceof Error?z.message:String(z),q=/no gerbers|not in this project|another machine/i.test(ae);le(q?"empty":"error",ae,!q)}}function et(V,W,_,G=!1){if(k){if(M.length{if(V.t==="plot"&&typeof V.none==="string"&&typeof V.key==="string")et(V.key,V.none,V.retryable===!0)}),ot=rn(()=>{if(w)Oe()}),en=(V)=>{if(V.key==="Escape"&&w&&!f.hidden)rt()};return window.addEventListener("keydown",en),{open(V,W){if(W!==v){if(v=W,H={},O=[],P="",B.clear(),re=!1,ie=!1,me=0,Ce=0,te="",oe=0,R=null,t.hub.hasFeature("follow"))t.hub.rpc("viewer.follow",{thread:W}).then((_)=>{if(W!==v)return;if(re=!!_.on,ie=!!_.paused,me=Number(_.seq)||0,w)Oe()}).catch(()=>{})}if(V!==w)D(),C.goLive(),Ce=0,te="",oe=0,R=null;w=V,Y="",ht(!1)},reconcileHas(V){if(w&&!qo(w,V))t.closeViewer()},close(){if(E++,k=!1,D(),F=!1,I="",J="",se="",Ee="",C.goLive(),c.hidden=!0,b.hidden=!0,we(),v)t.hub.rpc("viewer.watch",{thread:v,kind:""}).catch(()=>{});w="",L.clear(),ve()}}}var kr="http://www.w3.org/2000/svg";function Yt(e){let t=document.createElementNS(kr,"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(kr,"path");i.setAttribute("d",n),t.appendChild(i)}return t}function xr(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 Jo(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 Pr(e,t){if(!e)return!0;if(t==="board"||t==="3d")return e.board!==!1;if(t==="schematic")return e.schematic!==!1;if(t==="mech")return e.mech!==!1;if(t==="gerbers")return e.gerbers!==!1;return!0}var Xt="dark",vn=(()=>{try{return Gs(localStorage.getItem("bp.theme.pref"))}catch{return"auto"}})(),bi=null,Bt=(()=>{try{return Vs(localStorage.getItem("bp.locale"))}catch{return"auto"}})();function Nr(){let e=Wt(vn,Xt);document.documentElement.classList.toggle("light",e==="light");try{localStorage.setItem("bp.theme",e)}catch{}}function Sr(e){if(!e)return;Xt=e==="light"?"light":"dark",Nr()}function Lr(){if(Bt!=="auto")kt(Bt);else if(bi)kt(bi);else if(typeof navigator<"u"&&navigator.language){if(!kt(navigator.language))kt("en")}}function Yo(){return`web-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`}function Ar(){let e=document.getElementById("root");if(!e)return;try{if(localStorage.getItem("bp.theme")==="light")Xt="light";if(Wt(vn,Xt)==="light")document.documentElement.classList.add("light");if(Bt!=="auto")kt(Bt)}catch{}let t=document.createElement("header");t.className="bp-topbar",t.setAttribute("data-testid","topbar");let n=document.createElement("button");n.type="button",n.className="icon bp-side-toggle",n.textContent="☰",n.title="Toggle sidebar",n.setAttribute("aria-label","Toggle sidebar");let i=document.createElement("div");i.className="bp-brand";let s=document.createElement("img");s.src="/assets/favicon.svg",s.alt="Backplane",s.className="bp-logo";let r=document.createElement("span");r.className="bp-brand-name bp-hide-phone",r.textContent="Backplane";let o=document.createElement("span");o.className="bp-crumb-sep bp-hide-phone",o.textContent="/";let a=document.createElement("span");a.className="bp-crumb-proj bp-hide-phone";let c=document.createElement("span");c.className="bp-crumb-sep bp-hide-phone",c.textContent="/";let p=document.createElement("span");p.className="bp-crumb-thread",p.setAttribute("data-testid","thread-title");let l=document.createElement("span");l.className="bp-plan-top-badge bp-hidden",l.setAttribute("data-testid","plan-top-badge"),i.append(s,r,o,a,c,p,l);let h=document.createElement("div");h.className="bp-top-state bp-hide-phone bp-hidden";let d=document.createElement("span");d.className="bp-top-state-lbl",d.textContent="STATE";let u=document.createElement("span");u.className="bp-dot bp-dot-idle";let f=document.createElement("span");f.className="bp-top-state-word",h.append(d,u,f);let b=document.createElement("div");b.className="bp-top-acts bp-hide-phone bp-hidden";let v=document.createElement("button");v.type="button",v.className="bp-btn-ghost bp-top-act";let w=document.createElement("span");w.textContent=m("menu.pin","Pin"),v.append(Yt(["M12 17v5","M9 3h6l1 7 3 3H5l3-3 1-7z"]),w);let E=document.createElement("button");E.type="button",E.className="bp-btn-ghost bp-top-act";let k=document.createElement("span");k.textContent=m("menu.settle","Settle"),E.append(Yt(["M12 22a10 10 0 1 0 0-20 10 10 0 0 0 0 20z","M9 12l2 2 4-4"]),k);let L=document.createElement("div");L.className="bp-menu-wrap";let M=document.createElement("button");M.type="button",M.className="bp-btn-ghost bp-top-act",M.textContent="▾",M.title="Thread menu",M.setAttribute("aria-label","Thread menu"),M.setAttribute("data-testid","thread-menu-btn");let A=document.createElement("div");A.className="bp-popover bp-hidden",A.setAttribute("data-testid","thread-menu"),L.append(M,A),b.append(v,E,L);let B=document.createElement("div");B.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 H=document.createElement("span");H.textContent=m("gpui.improvements","Improvements"),T.append(Yt(["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"]),H);let O=document.createElement("button");O.type="button",O.className="bp-cmd-box bp-hide-tablet",O.textContent="> Jump or run a command";let P=document.createElement("button");P.type="button",P.className="icon bp-top-icon",P.title="Search",P.setAttribute("aria-label","Search"),P.appendChild(Yt(["M11 19a8 8 0 1 0 0-16 8 8 0 0 0 0 16z","M21 21l-4.3-4.3"]));let Y=document.createElement("button");Y.type="button",Y.className="icon bp-top-icon",Y.title=m("palette.settings","Settings"),Y.setAttribute("aria-label",m("palette.settings","Settings")),Y.setAttribute("data-testid","settings-btn"),Y.appendChild(Yt(["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"])),B.append(T,O,P,Y),t.append(n,i,h,b,B);let re=document.createElement("div");re.className="bp-body";let ie=document.createElement("aside");ie.className="bp-sidebar",ie.setAttribute("data-testid","sidebar");let me=document.createElement("main");me.className="bp-center";let Pe=document.createElement("div");Pe.className="bp-right-area bp-hidden",Pe.setAttribute("data-testid","right-area");let Ce=document.createElement("div");Ce.className="bp-right-top";let te=document.createElement("section");te.className="bp-viewer-pane bp-hidden",te.setAttribute("data-testid","viewer-pane"),Ce.appendChild(te),Pe.appendChild(Ce);let oe=document.createElement("nav");oe.className="bp-rail",oe.setAttribute("aria-label","Viewer rail"),oe.setAttribute("data-testid","viewer-rail"),re.append(ie,me,Pe,oe),e.append(t,re);let R=new oi,ue=null,de=new Set,ee=0,ge=null,C=[],x=[],F=[],I=[],J=[],se=[],Ee=[],D="",ne=0,Te=0,Le=null,Be=null,K="",fe=null,le=20,He={},$e=new Map;function Oe(g,y){$e.delete(g),$e.set(g,y);while($e.size>le){let S=$e.keys().next().value;if(S!==void 0)$e.delete(S);else break}}let Ne="",We=0,ze=new Wn(me,{onNewThread:(g)=>{ut(g)},onOpenThread:(g)=>{qe(g)},onOpenViewer:(g,y)=>{qe(g).then(()=>{if(D===g)mt(y)})},onRetry:(g)=>{It(g)}});function Qt(){if(!Ne)return;Ne="",We++,me.classList.remove("bp-home-open"),ze.hide(),ve.setSelectedProject(""),Ie()}function rt(g){return C.find((y)=>y.id===g)??C.find((y)=>Un(y.id)===g)}async function Zt(g,y){try{let S=await R.rpc("threads.list",{project:g,limit:50,archived:!1});if(y!==We||Ne!==g)return;let N=(S.threads??[]).filter((j)=>!j.swarm).map((j)=>({id:j.id,title:j.title,dot:xr(j),status:j.status||j.state||"",age:Jo(j.updatedAt),settled:j.settled}));ze.setThreads(N)}catch{if(y===We&&Ne===g)ze.setThreads([])}}function It(g){if(!g||!R.hasFeature("projecthome"))return!1;tt.cancel(),pe.closeModelPicker(),Ne=g;let y=++We,S=rt(g);return me.classList.add("bp-home-open"),ie.classList.remove("bp-sidebar-open"),ze.show({id:g,title:S?.title??g}),ve.setSelectedProject(g),Ie(),Zt(g,y),R.rpc("project.home",{project:g}).then((N)=>{if(y===We&&Ne===g)ze.setData(Ns(N))}).catch((N)=>{if(y!==We||Ne!==g)return;ze.setError(N instanceof Error&&N.message?N.message:m("web.home.error","Could not load this project."))}),!0}let ve=new ii(ie,{onSelectThread:(g)=>{if(g===D&&Le!==null){Qt(),ie.classList.remove("bp-sidebar-open");return}qe(g)},onNewThread:(g)=>{ut(g)},onOpenProject:(g)=>It(Un(g)),canOpenProject:()=>R.hasFeature("projecthome"),onSelectBot:(g)=>{qe(g.thread)},onQuickOpenViewer:(g,y)=>{let S=x.find((j)=>j.project===g&&!j.archived&&!j.swarm);(async()=>{if(S)await qe(S.id);else await ut(g);if(D)K=y,G.setActive(y),fe?.open(y,D)})()},onThreadAct:(g,y)=>{bt(g,y)},onSnoozeRow:(g)=>{R.rpc("sidebar.act",{action:"row-snooze",value:g}).then(()=>Xe()).catch(()=>{})},onToggleSection:(g)=>{if(de.has(g))de.delete(g);else de.add(g);Xe()},onToggleProjectFold:(g)=>{R.rpc("sidebar.act",{action:"project-fold",value:g}).then(()=>Xe()).catch(()=>{})},onCollapseSidebar:()=>{ie.classList.remove("bp-sidebar-open"),ie.classList.add("bp-sidebar-collapsed")},onNeedAct:async(g)=>{let y=un(g,!1);if(!y)return;if(y.kind==="thread"){qe(y.id);return}if(y.kind!=="call")return;let S=Os(await R.rpc(y.method,y.params));if(S?.kind==="thread")qe(S.id);Xe()},hasRoomView:!1,onAddProject:()=>_.open({mode:"folder"}),onSettleSwarm:(g)=>{R.rpc("sidebar.act",{action:"swarm-settle",value:g}).then(()=>Xe()).catch(()=>{})},onNewChat:()=>{ut(yt)},onMoveToProject:(g)=>De(g),onDismissHomeMove:()=>{R.rpc("home.move.dismiss",{}).then((g)=>{if(g?.home!==void 0){if(z=g.home??null,ve.setHome(z),q.isOpen())q.refresh()}}).catch(()=>{})}}),we=new An(me,{onLoadOlder:()=>{wi()},onGoToEntry:(g)=>{vi(g)},onOpenAccounts:()=>{ke()},onAnswerAsk:(g,y)=>{R.rpc("ask.answer",{ask:g,answer:y}).catch((S)=>{pe.showError(S instanceof Error?S.message:"Could not send answer")})},onToggleReview:(g)=>{if(!D)return;let y=ne;R.rpc("thread.review",{thread:D,on:g}).then((S)=>{if(y===ne)we.setReview(S.review??null)}).catch(()=>{})},onUnansweredAction:(g,y)=>{if(!D)return;if(g==="again"||g==="thread-again")R.rpc("thread.again",{thread:D,value:y}).catch(()=>{});else R.rpc("thread.act",{thread:D,action:g,value:y}).catch(()=>{})},onReplyEntry:(g)=>{if(!R.hasFeature("reply")){let y=(g.text||"").split(` `)[0]?.slice(0,100)??"";if(y)pe.prependDraft(`> ${y} -`);return}if(!g.text||!g.text.trim()||g.live||g.id.startsWith("local-"))return;jt({id:g.id,text:g.text,role:g.kind==="user"?"user":"assistant"})},onLoadImage:async(g,y)=>{try{let S={entry:g,path:y};if(R.hasFeature("blobs"))S.metaOnly=!0;let N=await R.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 ht(g){if(!g)return null;if(g.planMode)return g.planMode;if(g.provider==="claude")return{phase:"off",interaction:"default",once:!1};return null}function et(g,y){if(!D)return;let S=ne,N=D;R.rpc(g,y).then((j)=>{if(S!==ne||D!==N)return;if(j.thread){let Q=x.findIndex((ce)=>ce.id===j.thread.id);if(Q>=0)x[Q]=j.thread;else x.unshift(j.thread);Ee.setData(C,x,F,I),ve.updateThreadMeta(j.thread),Ie(),pe.setState(!0,j.thread.state==="working")}}).catch((j)=>{if(S===ne&&D===N)pe.showError(j instanceof Error?j.message:"Could not change Plan mode")})}let tt,pe=new Tn(ue,{onSend:(g,y)=>{Ei(g,y)},onRunCommand:(g)=>{Ci(g)},onInterrupt:()=>{if(D)R.rpc("turn.interrupt",{thread:D}).catch(()=>{})},onQueryMentions:async(g,y)=>{try{return(await R.rpc("mentions.list",{q:g,kind:y,limit:10})).items??[]}catch{return[]}},onToggleVoice:()=>{tt.toggle()},onCyclePlanMode:()=>{let g=x.find((S)=>S.id===D)??null,y=ht(g);if(!y||!D)return;if(y.interaction!=="plan")et("thread.planonce",{thread:D,on:!0});else if(y.once)et("thread.pick",{thread:D,action:"interaction",value:"plan"});else et("thread.pick",{thread:D,action:"interaction",value:"default"})},onSetPlanMode:(g)=>{if(!D)return;if(g==="once")et("thread.planonce",{thread:D,on:!0});else if(g==="always")et("thread.pick",{thread:D,action:"interaction",value:"plan"});else et("thread.pick",{thread:D,action:"interaction",value:"default"})},getFavoriteModels:()=>J,onLoadModelPicker:async()=>{if(!D)return null;return R.rpc("thread.picker",{thread:D})},onSelectModel:async(g,y)=>{if(!D)return;let S=ne,N=D;try{let j=await R.rpc("thread.model",{thread:N,provider:g,model:y});if(S!==ne||D!==N)return;if(j.thread){let Q=x.findIndex((ce)=>ce.id===j.thread.id);if(Q>=0)x[Q]=j.thread;else x.unshift(j.thread);Ee.setData(C,x,F,I),ve.updateThreadMeta(j.thread),Ie(),pe.setState(!0,j.thread.state==="working")}}catch(j){if(S===ne&&D===N)pe.showError(j instanceof Error?j.message:"Could not switch model")}},onSelectEffort:async(g)=>{if(!D)return;let y=ne,S=D;try{let N=await R.rpc("thread.pick",{thread:S,action:"effort",value:g});if(y!==ne||D!==S)return;if(N.thread){let j=x.findIndex((Q)=>Q.id===N.thread.id);if(j>=0)x[j]=N.thread;else x.unshift(N.thread);Ee.setData(C,x,F,I),ve.updateThreadMeta(N.thread),Ie()}}catch(N){if(y===ne&&D===S)pe.showError(N instanceof Error?N.message:"Could not set effort")}},onToggleFavorite:async(g,y,S)=>{let N=await R.rpc("models.favorite",{provider:g,model:y,on:S});if(Array.isArray(N.favorites))return J=N.favorites,J;return null}});tt=new si(R,{getThreadId:()=>D,getDraft:()=>pe.getDraft(),getCaret:()=>pe.getCaret(),setDraft:(g)=>pe.setDraft(g),setRecording:(g)=>pe.setVoiceRecording(g),setLevel:(g)=>pe.setVoiceLevel(g),showError:(g)=>pe.showError(g)});function Rt(){let g=q!=="",y=ot.isOpen();Pe.classList.toggle("bp-hidden",!g&&!y),Pe.classList.toggle("bp-has-viewer",g),Pe.classList.toggle("bp-has-mgmt",y)}let ot=new $n(Ce,Pe,{hub:R,getThreadId:()=>D,getThreadGen:()=>ne,onSendText:(g)=>{Ei(g)},onOpenChange:()=>Rt()});function en(g){let y=window.prompt("Rename thread",g.title||"");if(!y||!y.trim())return;R.rpc("thread.act",{thread:g.id,action:"rename",title:y.trim()}).then((S)=>{if(S.thread)x=x.map((N)=>N.id===S.thread.id?S.thread:N),Ie(),Xe()}).catch((S)=>{pe.showError(S instanceof Error?S.message:"Could not rename thread")})}function V(g){switch(g.type){case"thread":qe(g.id);break;case"rail":if(!D&&g.id!=="terminal")break;if(q===g.id)Ve();else ut(g.id);break;case"thread-act":if(D)bt(D,g.action);break;case"new-thread":mt(g.projectId);break;case"new-chat":mt(yt);break;case"move-project":if(D)De(D);break;case"rename":{let y=x.find((S)=>S.id===D);if(y)en(y);break}case"prev-thread":case"next-thread":{let y=x.filter((Q)=>!Q.archived&&!Q.swarm);if(y.length<2)break;let S=y.findIndex((Q)=>Q.id===D),N=g.type==="next-thread"?1:-1,j=y[(S<0?0:S+N+y.length)%y.length];if(j)qe(j.id);break}case"command":if(g.runDirectly)Ci(g.word);else pe.setDraft(`${g.word} `),pe.focus();break;case"improvements":je();break;case"settings":K.open();break;case"sidebar":ie.classList.toggle("bp-sidebar-open"),ie.classList.toggle("bp-sidebar-collapsed");break}}let W=new On(e,{getState:()=>({selectedThreadId:D,threads:x,projects:C,bots:F,railItems:se,commands:ye}),onSearch:async(g)=>{if(!R.hasFeature("search"))return{threads:[],projects:[],messages:[]};return R.rpc("search",{q:g,limit:20})},onExecute:V}),_=new Pn(e,{hub:R,onProjectAdded:(g)=>{if(Xe(),g.id)mt(g.id)},onCloneDone:(g)=>{if(Xe(),g.thread)qe(g.thread)}}),G=new qn(oe,(g)=>{if(g==="commands"){W.open();return}if(!D)return;if(q===g)Ve();else ut(g)}),z=null,ae=null,K=new Zn(e,{onLoadDevices:async()=>(await R.rpc("devices.page",{})).rows??[],onDevicesAct:async(g,y)=>{await R.rpc("devices.page.act",{action:g,value:y})},onGetHome:()=>z,onMoveHomeHere:async()=>{await R.rpc("home.move",{to:"back"})},onGetNoProvider:()=>ae,onGetThemePref:()=>vn,onSetThemePref:(g)=>{vn=g;try{if(g==="auto")localStorage.removeItem("bp.theme.pref");else localStorage.setItem("bp.theme.pref",g)}catch{}Nr()},onGetHubTheme:()=>Xt,onGetLocalePref:()=>Bt,onSetLocalePref:(g)=>{Bt=g;try{if(g==="auto")localStorage.removeItem("bp.locale");else localStorage.setItem("bp.locale",g)}catch{}Lr()},hasRing:()=>R.hasFeature("ringnotes"),onRingList:async(g)=>Is(await R.rpc("ring.list",{q:g})),onRingHear:async(g,y)=>{await R.rpc("ring.hear",{note:g,engine:y})},onOpenThread:(g)=>{qe(g)},onLogout:()=>_i(()=>{R.disconnect(),window.location.replace("/")})});function we(g){if(ae=g,ve.setNoProvider(g),K.isOpen())K.refresh()}function ke(){K.openToAccounts()}function Ae(g,y){let S=g instanceof Error?g.message:y,N=g instanceof Kt?g:null,j=N?.code,Q=N?.machine,ce=j==="no_provider_remote"&&Q?u("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;pe.showError(ce,Bs(S,j)?{label:u("provider.notice.button","Open Settings → Accounts"),onClick:ke}:void 0)}v.addEventListener("click",()=>{let g=x.find((y)=>y.id===D);if(g)bt(g.id,g.pinned?"unpin":"pin")}),E.addEventListener("click",()=>{let g=x.find((y)=>y.id===D);if(g)bt(g.id,g.settled?"unsettle":"settle")});let Ge=new ti(e,(g,y)=>y?R.rpc("thread.context.mcp",{thread:g,...y}):R.rpc("thread.context",{thread:g}));M.addEventListener("click",(g)=>{g.stopPropagation();let y=x.find((j)=>j.id===D);if(!y)return;if(!A.classList.contains("bp-hidden")){A.classList.add("bp-hidden");return}let S=[{label:"Rename…",run:()=>en(y)},{label:y.pinned?u("menu.unpin","Unpin"):u("menu.pin","Pin"),run:()=>{bt(y.id,y.pinned?"unpin":"pin")}},{label:y.settled?u("phone.unsettle","Unsettle"):u("menu.settle","Settle"),run:()=>{bt(y.id,y.settled?"unsettle":"settle")}},{label:y.archived?"Unarchive":"Archive",run:()=>{bt(y.id,y.archived?"unarchive":"archive")}},{label:"Delete",danger:!0,run:()=>{if(window.confirm("Delete this thread?"))bt(y.id,"delete")}}];if(R.hasFeature("threadContext"))S.unshift({label:u("thread.context.title","Context & Prompt"),run:()=>Ge.open(y.id)});let N=document.createDocumentFragment();for(let j of S){let Q=document.createElement("button");Q.type="button",Q.className="bp-popover-item"+(j.danger?" danger":""),Q.textContent=j.label,Q.addEventListener("click",()=>{A.classList.add("bp-hidden"),j.run()}),N.appendChild(Q)}A.replaceChildren(N),A.classList.remove("bp-hidden")}),document.addEventListener("click",()=>A.classList.add("bp-hidden"));async function je(){let g=document.createElement("div");g.className="bp-modal-backdrop",g.setAttribute("data-testid","improvements-modal");let y=document.createElement("div");y.className="bp-modal";let S=document.createElement("div");S.className="bp-modal-head";let N=document.createElement("h2");N.textContent=u("gpui.improvements","Improvements");let j=document.createElement("button");j.type="button",j.className="icon",j.textContent="×",j.addEventListener("click",()=>g.remove()),S.append(N,j);let Q=document.createElement("div");Q.className="bp-modal-body",Q.textContent="Loading…",y.append(S,Q),g.appendChild(y),g.addEventListener("click",(ce)=>{if(ce.target===g)g.remove()}),e.appendChild(g);try{let ce=await R.rpc("improvements.projects",{}),Fe=ce.projects??[];if(Fe.length===0){Q.textContent="No projects available for Improvements.";return}let Je=document.createDocumentFragment();for(let Ye of Fe){let Me=document.createElement("div");Me.className="bp-set-row";let Z=document.createElement("div");Z.className="bp-set-info",Z.textContent=Ye.title||Ye.name||Ye.id;let Ue=document.createElement("button");Ue.type="button",Ue.className=Ye.id===ce.project?"primary":"",Ue.textContent=Ye.id===ce.project?"Active":"Select",Ue.addEventListener("click",()=>{R.rpc("improvements.project",{project:Ye.id}).then(()=>g.remove()).catch(()=>{})}),Me.append(Z,Ue),Je.appendChild(Me)}Q.replaceChildren(Je)}catch(ce){Q.textContent=ce instanceof Error?ce.message:"Could not load Improvements."}}function De(g){let y=x.find((Z)=>Z.id===g),S=document.createElement("div");S.className="bp-modal-backdrop",S.setAttribute("data-testid","move-project-modal");let N=document.createElement("div");N.className="bp-modal";let j=document.createElement("div");j.className="bp-modal-head";let Q=document.createElement("h2");Q.textContent=u("chats.move","Move to project…");let ce=document.createElement("button");ce.type="button",ce.className="icon",ce.textContent="×",ce.addEventListener("click",()=>S.remove()),j.append(Q,ce);let Fe=document.createElement("div");Fe.className="bp-modal-body";let Je=document.createElement("div");Je.className="bp-move-note",Je.textContent=y?.title||"";let Ye=document.createElement("div");Ye.className="bp-move-err",Fe.append(Je);let Me=Js(C);if(Me.length===0){let Z=document.createElement("div");Z.textContent=u("chats.move.none","No project to move it to. Add a project first."),Fe.appendChild(Z)}for(let Z of Me){let Ue=document.createElement("button");Ue.type="button",Ue.className="bp-move-row",Ue.textContent=Z.title||Z.id,Ue.setAttribute("data-testid",`move-project-${Z.id}`),Ue.addEventListener("click",()=>{R.rpc("thread.move_project",{thread:g,project:Z.id}).then((lt)=>{if(lt.thread)x=x.map((ct)=>ct.id===lt.thread.id?lt.thread:ct);else x=x.map((ct)=>ct.id===g?{...ct,project:Z.id}:ct);Ee.setData(C,x,F,I),Ie(),Xe(),S.remove()}).catch((lt)=>{Ye.textContent=lt instanceof Error?lt.message:"Could not move the chat"})}),Fe.appendChild(Ue)}Fe.appendChild(Ye),N.append(j,Fe),S.appendChild(N),S.addEventListener("click",(Z)=>{if(Z.target===S)S.remove()}),e.appendChild(S)}T.addEventListener("click",()=>{je()}),O.addEventListener("click",()=>W.open()),P.addEventListener("click",()=>W.open()),Y.addEventListener("click",()=>{K.open()}),n.addEventListener("click",()=>{ie.classList.toggle("bp-sidebar-open"),ie.classList.toggle("bp-sidebar-collapsed")});function Ie(){let g=Ne?null:x.find((j)=>j.id===D)??null,y=Ne?rt(Ne)??{id:Ne,title:Ne}:g?rt(g.project):void 0;if(Ne&&y)ze.setTitle(y.title);let S=!Ne&&g?.project===yt;a.textContent=S?u("chats.title","Chats"):y?.title??"",o.classList.toggle("bp-hidden",!y&&!S),c.classList.toggle("bp-hidden",!g),p.textContent=g?g.title||"Untitled thread":"";let N=ht(g);if(pe.setPlanMode(N),!N||N.phase==="off")l.classList.add("bp-hidden"),l.classList.remove("is-exec"),l.textContent="";else l.classList.remove("bp-hidden"),l.classList.toggle("is-exec",N.phase==="executing"),l.title=u("gpui.planmode.tip","Plan before acting (1 turn, always, or off)"),l.textContent=N.phase==="armed"&&N.once?u("gpui.planmode.top.once","Plan (1 turn)"):N.phase==="armed"?u("gpui.mgmt.plan.tab","Plan"):N.phase==="planning"?u("gpui.planmode.top.planning","Planning"):N.phase==="pending"?u("gpui.planmode.top.pending","Review plan"):u("gpui.planmode.top.executing","Building plan");if(h.classList.toggle("bp-hidden",!g),b.classList.toggle("bp-hidden",!g),g){m.className=`bp-dot ${xr(g)}`,f.textContent=g.status||g.state||"idle",w.textContent=g.pinned?u("menu.unpin","Unpin"):u("menu.pin","Pin"),k.textContent=g.settled?u("phone.unsettle","Unsettle"):u("menu.settle","Settle");let j=g;pe.setModelChip(g.chip||g.model||"default",g.provider,j.ctxPct??j.contextPct),pe.setMemory(g.memory)}else pe.setModelChip("default"),pe.setMemory(null)}function Ve(g=!0){if(Te++,q="",G.setActive(""),te.classList.add("bp-hidden"),fe?.close(),Rt(),g&&D&&R.getState()==="connected")R.rpc("viewer.watch",{thread:D,kind:""}).catch(()=>{})}function ut(g){if(Te++,q=g,G.setActive(g),te.classList.remove("bp-hidden"),Rt(),!fe&&typeof mi==="function")fe=mi(te,{hub:R,getThreadId:()=>D,closeViewer:()=>Ve(!0)});if(fe)fe.open(g,D);else{let y=document.createElement("div");y.className="bp-viewer-placeholder";let S=document.createElement("div");S.className="bp-viewer-bar";let N=document.createElement("span");N.textContent=g.toUpperCase();let j=document.createElement("button");j.type="button",j.className="icon",j.textContent="×",j.addEventListener("click",()=>Ve(!0)),S.append(N,j);let Q=document.createElement("div");Q.className="bp-dim bp-viewer-msg",Q.textContent=`Viewer pane (${g}).`,y.append(S,Q),te.replaceChildren(y)}}async function tn(g,y){if(!g||!R.hasFeature("rail")){if(y===ne)se=[],G.setItems([]);return}let S=++Te;try{let N=await R.rpc("viewer.rail",{thread:g,page:q});if(y!==ne||S!==Te)return;let j=Array.isArray(N.rail)?N.rail:Array.isArray(N.items)?N.items:[];if(se=j,G.setItems(j),N.has){if(fe?.reconcileHas?.(N.has),q&&!Pr(N.has,q))Ve(!0)}}catch{if(y===ne&&S===Te)se=[],G.setItems([])}}function at(g){for(let y of g)if(y.kind==="threads"){for(let S of y.rows)if(!S.off&&(S.nav||S.id)&&!(S.nav||"").startsWith("@room:"))return S.nav||S.id}else if(y.kind==="projects"){for(let S of y.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 gi(g,y){for(let S of g)if(S.kind==="threads"){if(S.rows.some((N)=>(N.nav||N.id)===y))return!0}else if(S.kind==="projects"){for(let N of S.rows)if((N.threads??[]).some((j)=>(j.nav||j.id)===y))return!0}return!1}function wn(g){let y=[];for(let S of g){if(S.kind!=="projects")continue;for(let N of S.rows)y.push({id:N.id,title:N.title,css:N.css,color:N.color})}if(y.length>0)C=y}async function Xe(){if(!R.hasFeature("sections"))return!1;let g=++ee;try{let y=await R.rpc("sidebar.sections",{open:Array.from(de)});if(g!==ee)return!0;let S=Array.isArray(y.sections)?y.sections:[];if(me=S,wn(S),Ee.setData(C,x,F,I),Ee.setSections(S,F,I),Ie(),Ne)Zt(Ne,We);return!0}catch{return!1}}function nn(){if(!R.hasFeature("sections"))return;if(ge!==null)window.clearTimeout(ge);ge=window.setTimeout(()=>{ge=null,Xe()},150)}async function Mr(){if(Le=null,R.hasFeature("bots"))try{let y=await R.rpc("bots.list",{});F=y.bots??[],I=y.rooms??[]}catch{}if(R.hasFeature("shell")){let y=await R.rpc("shell.sync",{have:He,settled:25}),S=new Set(y.removed??[]),N=new Set((y.projects??[]).map((j)=>j.id));if(S.size>0||N.size>0)C=[...C.filter((j)=>!S.has(j.id)&&!N.has(j.id)),...y.projects??[]],x=[...x.filter((j)=>!S.has(j.project)&&!N.has(j.project)),...y.threads??[]];else if(Array.isArray(y.threads)&&y.threads.length>0){let j=new Map(x.map((Q)=>[Q.id,Q]));for(let Q of y.threads)j.set(Q.id,Q);x=Array.from(j.values())}if(y.sections!==void 0){let j=Array.isArray(y.sections)?y.sections:Array.isArray(y.sections?.sections)?y.sections.sections:null;if(j)me=j,wn(j)}if(y.h)He=y.h;Ee.setData(C,x,F,I),Ee.setSections(me,F,I)}else if(R.hasFeature("sections")){let[y,S]=await Promise.all([R.rpc("sidebar.sections",{open:Array.from(de)}).catch(()=>null),R.rpc("threads.list",{limit:200,archived:!1}).catch(()=>({threads:[]}))]);if(x=S.threads??[],y&&Array.isArray(y.sections)){let N=y.sections;if(!N.some((Q)=>Q.kind==="projects"&&Q.rows.length>0)){let Q=N.find((ce)=>ce.kind==="projects"&&ce.fold&&ce.toggle&&(ce.count??0)>0);if(Q?.toggle&&!de.has(Q.toggle)){de.add(Q.toggle);let ce=await R.rpc("sidebar.sections",{open:Array.from(de)}).catch(()=>null);if(ce&&Array.isArray(ce.sections))N=ce.sections}}me=N,wn(N),Ee.setData(C,x,F,I),Ee.setSections(N,F,I)}else me=null,C=(await R.rpc("projects.list",{limit:100})).projects??[],Ee.setSections(null,F,I),Ee.setData(C,x,F,I);await R.rpc("subscribe",{topic:"lists"}).catch(()=>{})}else{me=null;let[y,S]=await Promise.all([R.rpc("projects.list",{limit:100}),R.rpc("threads.list",{limit:200,archived:!1})]);C=y.projects??[],x=S.threads??[],Ee.setSections(null,F,I),Ee.setData(C,x,F,I),await R.rpc("subscribe",{topic:"lists"}).catch(()=>{})}let g=D;if(!g){let y="";try{y=localStorage.getItem("bp.lastThread")||""}catch{}if(y&&(me&&gi(me,y)||x.some((S)=>S.id===y)))g=y;else if(me)g=at(me);if(!g)g=(x.find((N)=>!N.archived&&!N.swarm&&!N.settled)??x.find((N)=>!N.archived&&!N.swarm))?.id??""}if(g&&(me&&gi(me,g)||x.some((y)=>y.id===g)))await qe(g,Ne!=="");else D="",se=[],G.setItems([]),pe.setState(!1,!1),Ie();if(Ne)It(Ne)}async function qe(g,y=!1){if(!y)Qt();if(D&&D!==g){tt.cancel();let Me=ve.getEntries();if(Me.length>0){let Z=$e.get(D);Oe(D,{entries:Me,ids:Z?.ids??Me.map((Ue)=>Ue.id),olderCursor:Be,review:Z?.review??null,unanswered:Z?.unanswered??null,rail:Z?.rail??se,hashes:Z?.hashes??{}})}}let S=++ne;Te++,jt(null);let N=Le;if(Le=null,N!==null)R.rpc("unsubscribe",{sub:N}).catch(()=>{});D=g,pe.closeModelPicker();let j=$e.get(g);Be=j?.olderCursor??null;try{localStorage.setItem("bp.lastThread",g)}catch{}Ee.setSelected(g),ie.classList.remove("bp-sidebar-open"),Ie();let Q=x.find((Me)=>Me.id===g)??null;if(j)ve.setThread(Q,j.entries,Boolean(j.olderCursor),j.review,j.unanswered),se=j.rail,G.setItems(j.rail);else ve.setLoading(Q),se=[],G.setItems([]);if(pe.setState(!0,Q?.state==="working"),R.hasFeature("open")){let Me={};if(j){for(let[Re,Dt]of Object.entries(j.hashes))Me[Re]=Dt;for(let Re of j.entries)if(Re.h)Me[Re.id]=Re.h}let Z;try{Z=await R.rpc("thread.open",{thread:g,limit:40,have:Me})}catch(Re){if(S===ne){let Dt=Re instanceof Error&&Re.message?Re.message:"Could not load messages.";ve.setError(Q,Dt,()=>{qe(g)})}return}if(S!==ne){if(Z.sub!==void 0&&Z.sub!==null)R.rpc("unsubscribe",{sub:Z.sub}).catch(()=>{});return}if(Le=Z.sub??null,Z.thread){Q=Z.thread;let Re=x.findIndex((Dt)=>Dt.id===Z.thread.id);if(Re>=0)x[Re]=Z.thread;else x.unshift(Z.thread);Ie(),pe.setState(!0,Q.state==="working")}if("next"in Z)Be=Z.next??null;let Ue=new Map;if(j)for(let Re of j.entries)Ue.set(Re.id,Re);for(let Re of Z.entries??[])Ue.set(Re.id,Re);let lt=Z.ids??j?.ids??(Z.entries??[]).map((Re)=>Re.id),ct=lt.map((Re)=>Ue.get(Re)).filter((Re)=>Boolean(Re)),Ht=j?.rail??[];if(Z.rail!==void 0){if(Array.isArray(Z.rail))Ht=Z.rail;else if(Ht=Array.isArray(Z.rail?.rail)?Z.rail.rail:Array.isArray(Z.rail?.items)?Z.rail.items:[],Z.rail?.has){if(fe?.reconcileHas?.(Z.rail.has),q&&!Pr(Z.rail.has,q))Ve(!0)}}se=Ht,G.setItems(Ht);let yn=j?.review??null;if(R.hasFeature("reviewmode"))try{let Re=await R.rpc("thread.review",{thread:g});if(S!==ne)return;yn=Re.review??null}catch{}if(S!==ne)return;let xi="unanswered"in Z?Z.unanswered??null:j?.unanswered??null,Tr=Z.h??j?.hashes??{};if(Oe(g,{entries:ct,ids:lt,olderCursor:Be,review:yn,unanswered:xi,rail:Ht,hashes:Tr}),ve.setThread(Q,ct,Boolean(Be),yn,xi),fi(g,S),q)ut(q);return}let ce;try{ce=await R.rpc("thread.entries",{thread:g,limit:40})}catch(Me){if(S===ne){let Z=Me instanceof Error&&Me.message?Me.message:"Could not load messages.";ve.setError(Q,Z,()=>{qe(g)})}return}if(S!==ne)return;if(ce.thread){let Me=x.findIndex((Z)=>Z.id===ce.thread.id);if(Me>=0)x[Me]=ce.thread;else x.unshift(ce.thread);Ie()}Be=ce.next??null;let Fe=null;if(R.hasFeature("reviewmode"))try{let Me=await R.rpc("thread.review",{thread:g});if(S!==ne)return;Fe=Me.review??null}catch{}if(S!==ne)return;let Je=ce.entries??[],Ye=ce.unanswered??null;Oe(g,{entries:Je,ids:Je.map((Me)=>Me.id),olderCursor:Be,review:Fe,unanswered:Ye,rail:j?.rail??[],hashes:j?.hashes??{}}),ve.setThread(Q,Je,Boolean(Be),Fe,Ye);try{let Z=(await R.rpc("subscribe",{topic:"thread",thread:g})).sub??null;if(Z!==null){if(S!==ne){R.rpc("unsubscribe",{sub:Z}).catch(()=>{});return}Le=Z}}catch{}if(S!==ne)return;if(tn(g,S),fi(g,S),q)ut(q)}async function fi(g,y){if(!g||!R.hasFeature("mgmt")){if(y===ne)ot.clear();return}let S=x.find((j)=>j.id===g),N=S?.project?C.find((j)=>j.id===S.project)?.root??"":"";if(!N&&R.hasFeature("viewers"))try{let j=await R.rpc("viewer.files",{thread:g});if(y!==ne)return;N=j.pcb||j.sch||j.root||""}catch{}if(y!==ne)return;if(N)await ot.watchProject(N);else ot.clear()}async function vi(g){let y=ne;for(let S=0;S<25&&y===ne;S++){if(ve.goTo(g))return;if(!Be)return;let N=Be;if(await wi(),Be===N)return}}async function wi(){if(!D||!Be){ve.clearLoadingOlder();return}let g=ne,y=D,S=Be;try{let N=await R.rpc("thread.entries",{thread:y,limit:40,before:S});if(g!==ne||D!==y)return;Be=N.next??null,ve.prependEntries(N.entries??[],Boolean(Be))}catch{if(g===ne)ve.clearLoadingOlder()}}async function mt(g){try{let y=await R.rpc("thread.create",{project:g});if(y.thread)x=[y.thread,...x.filter((S)=>S.id!==y.thread.id)],Ee.setData(C,x,F,I),Xe(),await qe(y.thread.id),pe.focus()}catch(y){Ae(y,"Could not create thread")}}let Et=null;function yi(g){return(g.split(` -`).map((y)=>y.trim()).find((y)=>y.length>0)??"").slice(0,200)}function jt(g){Et=g,pe.setReply(g?{who:g.role==="user"?u("secret.you","You"):u("model.col.agent","Agent"),line:yi(g.text)}:null,()=>{if(Et)vi(Et.id)},()=>jt(null))}async function Ei(g,y=[]){if(!D)return;let S=ne,N=D,j=Jo(),Q=`local-${j}`,ce=Et&&g.trim()&&R.hasFeature("reply")?Et:null;if(ce)jt(null);ve.upsertEntry({id:Q,kind:"user",text:g,at:Date.now(),clientId:j,...ce?{replyTo:{id:ce.id,quote:yi(ce.text)}}:{},attachments:y.map((Fe)=>({name:Fe.name,mime:Fe.mime,previewUrl:`data:${Fe.mime};base64,${Fe.data}`}))});try{let Fe={thread:N,text:g,clientId:j};if(y.length>0)Fe.attachments=y;if(ce)Fe.replyTo={id:ce.id,text:ce.text};let Je=await R.rpc("message.send",Fe);if(S!==ne||D!==N)return;if(Je.entry)ve.upsertEntry(Je.entry)}catch(Fe){if(S===ne&&D===N){if(ve.removeEntry(Q),pe.setDraft(g),ce&&!Et)jt(ce);Ae(Fe,"Failed to send message")}}}async function Ci(g){if(!D)return;let y=ne,S=D;try{let N=await R.rpc("composer.run",{thread:S,text:g});if(y!==ne||D!==S)return;if(N.error)pe.setDraft(g),Ae(new Kt(N.error,{code:N.errorCode,machine:N.machine}),N.error);else if(N.kind==="btw"&&typeof N.a==="string")ve.showBtw(N.q??"",N.a);else if(N.kind==="edit"&&typeof N.text==="string")pe.setDraft(N.text);else if(N.kind==="project")_.open({mode:"folder"});else if(N.kind==="clone")_.open({mode:"clone",repo:N.repo??"",text:N.text??""})}catch(N){if(y===ne&&D===S)pe.setDraft(g),Ae(N,"Command refused")}}async function bt(g,y){try{let S=await R.rpc("thread.act",{thread:g,action:y});if(S.thread){if(x=x.map((N)=>N.id===S.thread.id?S.thread:N),Ee.setData(C,x,F,I),S.thread.id===D)ve.updateThreadMeta(S.thread),Ie()}Xe()}catch(S){pe.showError(S instanceof Error?S.message:`Action "${y}" not allowed`)}}function ki(g,y){if(!g||!g.text||y-g.at>=300000)return"";let S=g.build.split("-").pop()??"";if(g.reason==="build"&&S)return u("hub.restarting.build",g.text,{build:S});if(g.reason==="stop")return u("hub.stopped",g.text);return u("hub.restarting",g.text)}function sn(g){if(g==="connected")Ee.setConnStatus(u("gpui.acct.connected","Connected"),"bp-ok");else if(g==="reconnecting"&&ki(R.restarting,Date.now()))Ee.setConnStatus(ki(R.restarting,Date.now()),"");else if(g==="reconnecting")Ee.setConnStatus("Reconnecting…","bp-warn");else if(g==="revoked")Ee.setConnStatus(u("gpui.acct.sign.in.expired","Sign-in expired"),"bp-bad");else Ee.setConnStatus("Connecting…","")}rn(()=>{sn(R.getState()),H.textContent=u("gpui.improvements","Improvements"),Y.title=u("palette.settings","Settings"),Y.setAttribute("aria-label",u("palette.settings","Settings")),Ie(),Ee.refreshLocale(),ve.refreshLocale(),pe.refreshLocale(),G.render(),K.refreshLocale(),ze.refreshLocale(),_.refreshLocale()}),R.onState((g,y)=>{if(g==="connected"&&y){if(y.locale)bi=y.locale,Lr();if(y.theme)Sr(y.theme);if(y.name)Ee.setHostName(y.name);if(Array.isArray(y.favoriteModels))J=y.favoriteModels,pe.updateFavoriteModels(J);if(z=y.home??null,Ee.setHome(z),we(_n(y.noProvider)),K.isOpen())K.refresh();sn(g);let S=typeof y.hubBack==="string"?String(y.hubBack):"";if(S)try{let N=JSON.parse(S);if(N.reason==="crash")Ee.setConnStatus(u("hub.back.crash",N.text??""),"bp-warn"),window.setTimeout(()=>sn(R.getState()),6000)}catch{}if(pe.setFeatures(R.hasFeature("images"),R.hasFeature("voice")),Array.isArray(y.commands))ye=y.commands,pe.setCommands(ye);else ye=[];Mr(),_.reconcile()}else tt.cancel(),sn(g)}),R.onFrame((g)=>{if(g.t==="voice"){tt.handleFrame(g);return}if(g.t==="info"&&g.info&&typeof g.info==="object"){let S=g.info;if(Object.prototype.hasOwnProperty.call(S,"provider.notice"))we(_n(S["provider.notice"]));ot.handleInfo(S);return}if(g.t!=="d")return;let y=g;if(y.k==="clone"||y.k==="clone.repos"||y.k==="clone.signin"){_.handleFrame(y);return}switch(y.k){case"project":{let S=y.project;if(!S)break;let N=C.findIndex((j)=>j.id===S.id);if(N>=0)C[N]=S;else C.unshift(S);Ee.setData(C,x,F,I),Ie(),nn();break}case"thread":{let S=y.thread;if(!S)break;let N=x.findIndex((j)=>j.id===S.id);if(N>=0)x[N]=S;else x.unshift(S);if(Ee.setData(C,x,F,I),S.id===D)ve.updateThreadMeta(S),Ie(),pe.setState(!0,S.state==="working");nn();break}case"thread.removed":{let S=String(y.id??"");x=x.filter((N)=>N.id!==S),Ee.setData(C,x,F,I),nn();break}case"entry":{if(y.thread===D&&y.entry)ve.upsertEntry(y.entry);break}case"text":{if(y.thread===D)ve.appendLiveText(String(y.entry??""),String(y.append??""),Number(y.at??Date.now()));break}case"turn":{if(y.thread===D){let S=String(y.state??"idle");pe.setState(!0,S==="working"),tn(D,ne)}nn();break}case"btw":{if(y.thread===D)ve.showBtw(String(y.q??""),String(y.a??""));break}case"unanswered":{if(y.thread===D)ve.setUnanswered(y.unanswered??null);break}case"theme":{if(typeof y.theme==="string")Sr(y.theme);break}case"home":{if(z=y.home??null,Ee.setHome(z),K.isOpen())K.refresh();break}case"favorites":{if(Array.isArray(y.favorites))J=y.favorites.filter((S)=>typeof S==="string"),pe.updateFavoriteModels(J);break}default:break}}),window.addEventListener("keydown",(g)=>{let y=g.key.toLowerCase();if((g.ctrlKey||g.metaKey)&&(y==="k"||g.shiftKey&&y==="p"))if(g.preventDefault(),W.isOpen())W.close();else W.open();else if(g.shiftKey&&g.code==="KeyN"&&(g.altKey||g.ctrlKey||g.metaKey))g.preventDefault(),mt(yt);else if(g.key==="Escape"){let S=document.querySelector('[data-testid="move-project-modal"]');if(S){S.remove();return}if(W.isOpen())W.close();else if(pe.isModelPickerOpen())pe.closeModelPicker();else if(_.isOpen())_.escape();else if(K.isOpen())K.handleEscape();else if(ve.closePlanRevise());else if(ot.isOpen())ot.closePanel()}}),R.connect()}if(document.readyState==="loading")document.addEventListener("DOMContentLoaded",Ar);else Ar(); +`);return}if(!g.text||!g.text.trim()||g.live||g.id.startsWith("local-"))return;jt({id:g.id,text:g.text,role:g.kind==="user"?"user":"assistant"})},onLoadImage:async(g,y)=>{try{let S={entry:g,path:y};if(R.hasFeature("blobs"))S.metaOnly=!0;let N=await R.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 ht(g){if(!g)return null;if(g.planMode)return g.planMode;if(g.provider==="claude")return{phase:"off",interaction:"default",once:!1};return null}function et(g,y){if(!D)return;let S=ne,N=D;R.rpc(g,y).then((j)=>{if(S!==ne||D!==N)return;if(j.thread){let Q=x.findIndex((ce)=>ce.id===j.thread.id);if(Q>=0)x[Q]=j.thread;else x.unshift(j.thread);ve.setData(C,x,F,I),we.updateThreadMeta(j.thread),Ie(),pe.setState(!0,j.thread.state==="working")}}).catch((j)=>{if(S===ne&&D===N)pe.showError(j instanceof Error?j.message:"Could not change Plan mode")})}let tt,pe=new Tn(me,{onSend:(g,y)=>{Ei(g,y)},onRunCommand:(g)=>{Ci(g)},onInterrupt:()=>{if(D)R.rpc("turn.interrupt",{thread:D}).catch(()=>{})},onQueryMentions:async(g,y)=>{try{return(await R.rpc("mentions.list",{q:g,kind:y,limit:10})).items??[]}catch{return[]}},onToggleVoice:()=>{tt.toggle()},onCyclePlanMode:()=>{let g=x.find((S)=>S.id===D)??null,y=ht(g);if(!y||!D)return;if(y.interaction!=="plan")et("thread.planonce",{thread:D,on:!0});else if(y.once)et("thread.pick",{thread:D,action:"interaction",value:"plan"});else et("thread.pick",{thread:D,action:"interaction",value:"default"})},onSetPlanMode:(g)=>{if(!D)return;if(g==="once")et("thread.planonce",{thread:D,on:!0});else if(g==="always")et("thread.pick",{thread:D,action:"interaction",value:"plan"});else et("thread.pick",{thread:D,action:"interaction",value:"default"})},getFavoriteModels:()=>J,onLoadModelPicker:async()=>{if(!D)return null;return R.rpc("thread.picker",{thread:D})},onSelectModel:async(g,y)=>{if(!D)return;let S=ne,N=D;try{let j=await R.rpc("thread.model",{thread:N,provider:g,model:y});if(S!==ne||D!==N)return;if(j.thread){let Q=x.findIndex((ce)=>ce.id===j.thread.id);if(Q>=0)x[Q]=j.thread;else x.unshift(j.thread);ve.setData(C,x,F,I),we.updateThreadMeta(j.thread),Ie(),pe.setState(!0,j.thread.state==="working")}}catch(j){if(S===ne&&D===N)pe.showError(j instanceof Error?j.message:"Could not switch model")}},onSelectEffort:async(g)=>{if(!D)return;let y=ne,S=D;try{let N=await R.rpc("thread.pick",{thread:S,action:"effort",value:g});if(y!==ne||D!==S)return;if(N.thread){let j=x.findIndex((Q)=>Q.id===N.thread.id);if(j>=0)x[j]=N.thread;else x.unshift(N.thread);ve.setData(C,x,F,I),we.updateThreadMeta(N.thread),Ie()}}catch(N){if(y===ne&&D===S)pe.showError(N instanceof Error?N.message:"Could not set effort")}},onToggleFavorite:async(g,y,S)=>{let N=await R.rpc("models.favorite",{provider:g,model:y,on:S});if(Array.isArray(N.favorites))return J=N.favorites,J;return null}});tt=new si(R,{getThreadId:()=>D,getDraft:()=>pe.getDraft(),getCaret:()=>pe.getCaret(),setDraft:(g)=>pe.setDraft(g),setRecording:(g)=>pe.setVoiceRecording(g),setLevel:(g)=>pe.setVoiceLevel(g),showError:(g)=>pe.showError(g)});function Rt(){let g=K!=="",y=ot.isOpen();Pe.classList.toggle("bp-hidden",!g&&!y),Pe.classList.toggle("bp-has-viewer",g),Pe.classList.toggle("bp-has-mgmt",y)}let ot=new $n(Ce,Pe,{hub:R,getThreadId:()=>D,getThreadGen:()=>ne,onSendText:(g)=>{Ei(g)},onOpenChange:()=>Rt()});function en(g){let y=window.prompt("Rename thread",g.title||"");if(!y||!y.trim())return;R.rpc("thread.act",{thread:g.id,action:"rename",title:y.trim()}).then((S)=>{if(S.thread)x=x.map((N)=>N.id===S.thread.id?S.thread:N),Ie(),Xe()}).catch((S)=>{pe.showError(S instanceof Error?S.message:"Could not rename thread")})}function V(g){switch(g.type){case"thread":qe(g.id);break;case"rail":if(!D&&g.id!=="terminal")break;if(K===g.id)Ve();else mt(g.id);break;case"thread-act":if(D)bt(D,g.action);break;case"new-thread":ut(g.projectId);break;case"new-chat":ut(yt);break;case"move-project":if(D)De(D);break;case"rename":{let y=x.find((S)=>S.id===D);if(y)en(y);break}case"prev-thread":case"next-thread":{let y=x.filter((Q)=>!Q.archived&&!Q.swarm);if(y.length<2)break;let S=y.findIndex((Q)=>Q.id===D),N=g.type==="next-thread"?1:-1,j=y[(S<0?0:S+N+y.length)%y.length];if(j)qe(j.id);break}case"command":if(g.runDirectly)Ci(g.word);else pe.setDraft(`${g.word} `),pe.focus();break;case"improvements":je();break;case"settings":q.open();break;case"sidebar":ie.classList.toggle("bp-sidebar-open"),ie.classList.toggle("bp-sidebar-collapsed");break}}let W=new On(e,{getState:()=>({selectedThreadId:D,threads:x,projects:C,bots:F,railItems:se,commands:Ee}),onSearch:async(g)=>{if(!R.hasFeature("search"))return{threads:[],projects:[],messages:[]};return R.rpc("search",{q:g,limit:20})},onExecute:V}),_=new Pn(e,{hub:R,onProjectAdded:(g)=>{if(Xe(),g.id)ut(g.id)},onCloneDone:(g)=>{if(Xe(),g.thread)qe(g.thread)}}),G=new qn(oe,(g)=>{if(g==="commands"){W.open();return}if(!D)return;if(K===g)Ve();else mt(g)}),z=null,ae=null,q=new Zn(e,{onLoadDevices:async()=>(await R.rpc("devices.page",{})).rows??[],onDevicesAct:async(g,y)=>{await R.rpc("devices.page.act",{action:g,value:y})},onGetHome:()=>z,onMoveHomeHere:async()=>{await R.rpc("home.move",{to:"back"})},onGetNoProvider:()=>ae,onGetThemePref:()=>vn,onSetThemePref:(g)=>{vn=g;try{if(g==="auto")localStorage.removeItem("bp.theme.pref");else localStorage.setItem("bp.theme.pref",g)}catch{}Nr()},onGetHubTheme:()=>Xt,onGetLocalePref:()=>Bt,onSetLocalePref:(g)=>{Bt=g;try{if(g==="auto")localStorage.removeItem("bp.locale");else localStorage.setItem("bp.locale",g)}catch{}Lr()},hasRing:()=>R.hasFeature("ringnotes"),onRingList:async(g)=>Is(await R.rpc("ring.list",{q:g})),onRingHear:async(g,y)=>{await R.rpc("ring.hear",{note:g,engine:y})},onOpenThread:(g)=>{qe(g)},onLogout:()=>_i(()=>{R.disconnect(),window.location.replace("/")})});function ye(g){if(ae=g,we.setNoProvider(g),q.isOpen())q.refresh()}function ke(){q.openToAccounts()}function Ae(g,y){let S=g instanceof Error?g.message:y,N=g instanceof Kt?g:null,j=N?.code,Q=N?.machine,ce=j==="no_provider_remote"&&Q?m("provider.notice.senderr.remote","No AI provider connected on {machine}. Open Settings → Accounts on {machine} to connect Claude, Codex, Antigravity, or another provider.").replaceAll("{machine}",Q):S;pe.showError(ce,Bs(S,j)?{label:m("provider.notice.button","Open Settings → Accounts"),onClick:ke}:void 0)}v.addEventListener("click",()=>{let g=x.find((y)=>y.id===D);if(g)bt(g.id,g.pinned?"unpin":"pin")}),E.addEventListener("click",()=>{let g=x.find((y)=>y.id===D);if(g)bt(g.id,g.settled?"unsettle":"settle")});let Ge=new ti(e,(g,y)=>y?R.rpc("thread.context.mcp",{thread:g,...y}):R.rpc("thread.context",{thread:g}));M.addEventListener("click",(g)=>{g.stopPropagation();let y=x.find((j)=>j.id===D);if(!y)return;if(!A.classList.contains("bp-hidden")){A.classList.add("bp-hidden");return}let S=[{label:"Rename…",run:()=>en(y)},{label:y.pinned?m("menu.unpin","Unpin"):m("menu.pin","Pin"),run:()=>{bt(y.id,y.pinned?"unpin":"pin")}},{label:y.settled?m("phone.unsettle","Unsettle"):m("menu.settle","Settle"),run:()=>{bt(y.id,y.settled?"unsettle":"settle")}},{label:y.archived?"Unarchive":"Archive",run:()=>{bt(y.id,y.archived?"unarchive":"archive")}},{label:"Delete",danger:!0,run:()=>{if(window.confirm("Delete this thread?"))bt(y.id,"delete")}}];if(R.hasFeature("threadContext"))S.unshift({label:m("thread.context.title","Context & Prompt"),run:()=>Ge.open(y.id)});let N=document.createDocumentFragment();for(let j of S){let Q=document.createElement("button");Q.type="button",Q.className="bp-popover-item"+(j.danger?" danger":""),Q.textContent=j.label,Q.addEventListener("click",()=>{A.classList.add("bp-hidden"),j.run()}),N.appendChild(Q)}A.replaceChildren(N),A.classList.remove("bp-hidden")}),document.addEventListener("click",()=>A.classList.add("bp-hidden"));async function je(){let g=document.createElement("div");g.className="bp-modal-backdrop",g.setAttribute("data-testid","improvements-modal");let y=document.createElement("div");y.className="bp-modal";let S=document.createElement("div");S.className="bp-modal-head";let N=document.createElement("h2");N.textContent=m("gpui.improvements","Improvements");let j=document.createElement("button");j.type="button",j.className="icon",j.textContent="×",j.addEventListener("click",()=>g.remove()),S.append(N,j);let Q=document.createElement("div");Q.className="bp-modal-body",Q.textContent="Loading…",y.append(S,Q),g.appendChild(y),g.addEventListener("click",(ce)=>{if(ce.target===g)g.remove()}),e.appendChild(g);try{let ce=await R.rpc("improvements.projects",{}),Fe=ce.projects??[];if(Fe.length===0){Q.textContent="No projects available for Improvements.";return}let Je=document.createDocumentFragment();for(let Ye of Fe){let Me=document.createElement("div");Me.className="bp-set-row";let Z=document.createElement("div");Z.className="bp-set-info",Z.textContent=Ye.title||Ye.name||Ye.id;let Ue=document.createElement("button");Ue.type="button",Ue.className=Ye.id===ce.project?"primary":"",Ue.textContent=Ye.id===ce.project?"Active":"Select",Ue.addEventListener("click",()=>{R.rpc("improvements.project",{project:Ye.id}).then(()=>g.remove()).catch(()=>{})}),Me.append(Z,Ue),Je.appendChild(Me)}Q.replaceChildren(Je)}catch(ce){Q.textContent=ce instanceof Error?ce.message:"Could not load Improvements."}}function De(g){let y=x.find((Z)=>Z.id===g),S=document.createElement("div");S.className="bp-modal-backdrop",S.setAttribute("data-testid","move-project-modal");let N=document.createElement("div");N.className="bp-modal";let j=document.createElement("div");j.className="bp-modal-head";let Q=document.createElement("h2");Q.textContent=m("chats.move","Move to project…");let ce=document.createElement("button");ce.type="button",ce.className="icon",ce.textContent="×",ce.addEventListener("click",()=>S.remove()),j.append(Q,ce);let Fe=document.createElement("div");Fe.className="bp-modal-body";let Je=document.createElement("div");Je.className="bp-move-note",Je.textContent=y?.title||"";let Ye=document.createElement("div");Ye.className="bp-move-err",Fe.append(Je);let Me=Js(C);if(Me.length===0){let Z=document.createElement("div");Z.textContent=m("chats.move.none","No project to move it to. Add a project first."),Fe.appendChild(Z)}for(let Z of Me){let Ue=document.createElement("button");Ue.type="button",Ue.className="bp-move-row",Ue.textContent=Z.title||Z.id,Ue.setAttribute("data-testid",`move-project-${Z.id}`),Ue.addEventListener("click",()=>{R.rpc("thread.move_project",{thread:g,project:Z.id}).then((lt)=>{if(lt.thread)x=x.map((ct)=>ct.id===lt.thread.id?lt.thread:ct);else x=x.map((ct)=>ct.id===g?{...ct,project:Z.id}:ct);ve.setData(C,x,F,I),Ie(),Xe(),S.remove()}).catch((lt)=>{Ye.textContent=lt instanceof Error?lt.message:"Could not move the chat"})}),Fe.appendChild(Ue)}Fe.appendChild(Ye),N.append(j,Fe),S.appendChild(N),S.addEventListener("click",(Z)=>{if(Z.target===S)S.remove()}),e.appendChild(S)}T.addEventListener("click",()=>{je()}),O.addEventListener("click",()=>W.open()),P.addEventListener("click",()=>W.open()),Y.addEventListener("click",()=>{q.open()}),n.addEventListener("click",()=>{ie.classList.toggle("bp-sidebar-open"),ie.classList.toggle("bp-sidebar-collapsed")});function Ie(){let g=Ne?null:x.find((j)=>j.id===D)??null,y=Ne?rt(Ne)??{id:Ne,title:Ne}:g?rt(g.project):void 0;if(Ne&&y)ze.setTitle(y.title);let S=!Ne&&g?.project===yt;a.textContent=S?m("chats.title","Chats"):y?.title??"",o.classList.toggle("bp-hidden",!y&&!S),c.classList.toggle("bp-hidden",!g),p.textContent=g?g.title||"Untitled thread":"";let N=ht(g);if(pe.setPlanMode(N),!N||N.phase==="off")l.classList.add("bp-hidden"),l.classList.remove("is-exec"),l.textContent="";else l.classList.remove("bp-hidden"),l.classList.toggle("is-exec",N.phase==="executing"),l.title=m("gpui.planmode.tip","Plan before acting (1 turn, always, or off)"),l.textContent=N.phase==="armed"&&N.once?m("gpui.planmode.top.once","Plan (1 turn)"):N.phase==="armed"?m("gpui.mgmt.plan.tab","Plan"):N.phase==="planning"?m("gpui.planmode.top.planning","Planning"):N.phase==="pending"?m("gpui.planmode.top.pending","Review plan"):m("gpui.planmode.top.executing","Building plan");if(h.classList.toggle("bp-hidden",!g),b.classList.toggle("bp-hidden",!g),g){u.className=`bp-dot ${xr(g)}`,f.textContent=g.status||g.state||"idle",w.textContent=g.pinned?m("menu.unpin","Unpin"):m("menu.pin","Pin"),k.textContent=g.settled?m("phone.unsettle","Unsettle"):m("menu.settle","Settle");let j=g;pe.setModelChip(g.chip||g.model||"default",g.provider,j.ctxPct??j.contextPct),pe.setMemory(g.memory)}else pe.setModelChip("default"),pe.setMemory(null)}function Ve(g=!0){if(Te++,K="",G.setActive(""),te.classList.add("bp-hidden"),fe?.close(),Rt(),g&&D&&R.getState()==="connected")R.rpc("viewer.watch",{thread:D,kind:""}).catch(()=>{})}function mt(g){if(Te++,K=g,G.setActive(g),te.classList.remove("bp-hidden"),Rt(),!fe&&typeof ui==="function")fe=ui(te,{hub:R,getThreadId:()=>D,closeViewer:()=>Ve(!0)});if(fe)fe.open(g,D);else{let y=document.createElement("div");y.className="bp-viewer-placeholder";let S=document.createElement("div");S.className="bp-viewer-bar";let N=document.createElement("span");N.textContent=g.toUpperCase();let j=document.createElement("button");j.type="button",j.className="icon",j.textContent="×",j.addEventListener("click",()=>Ve(!0)),S.append(N,j);let Q=document.createElement("div");Q.className="bp-dim bp-viewer-msg",Q.textContent=`Viewer pane (${g}).`,y.append(S,Q),te.replaceChildren(y)}}async function tn(g,y){if(!g||!R.hasFeature("rail")){if(y===ne)se=[],G.setItems([]);return}let S=++Te;try{let N=await R.rpc("viewer.rail",{thread:g,page:K});if(y!==ne||S!==Te)return;let j=Array.isArray(N.rail)?N.rail:Array.isArray(N.items)?N.items:[];if(se=j,G.setItems(j),N.has){if(fe?.reconcileHas?.(N.has),K&&!Pr(N.has,K))Ve(!0)}}catch{if(y===ne&&S===Te)se=[],G.setItems([])}}function at(g){for(let y of g)if(y.kind==="threads"){for(let S of y.rows)if(!S.off&&(S.nav||S.id)&&!(S.nav||"").startsWith("@room:"))return S.nav||S.id}else if(y.kind==="projects"){for(let S of y.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 gi(g,y){for(let S of g)if(S.kind==="threads"){if(S.rows.some((N)=>(N.nav||N.id)===y))return!0}else if(S.kind==="projects"){for(let N of S.rows)if((N.threads??[]).some((j)=>(j.nav||j.id)===y))return!0}return!1}function wn(g){let y=[];for(let S of g){if(S.kind!=="projects")continue;for(let N of S.rows)y.push({id:N.id,title:N.title,css:N.css,color:N.color})}if(y.length>0)C=y}async function Xe(){if(!R.hasFeature("sections"))return!1;let g=++ee;try{let y=await R.rpc("sidebar.sections",{open:Array.from(de)});if(g!==ee)return!0;let S=Array.isArray(y.sections)?y.sections:[];if(ue=S,wn(S),ve.setData(C,x,F,I),ve.setSections(S,F,I),Ie(),Ne)Zt(Ne,We);return!0}catch{return!1}}function nn(){if(!R.hasFeature("sections"))return;if(ge!==null)window.clearTimeout(ge);ge=window.setTimeout(()=>{ge=null,Xe()},150)}async function Mr(){if(Le=null,R.hasFeature("bots"))try{let y=await R.rpc("bots.list",{});F=y.bots??[],I=y.rooms??[]}catch{}if(R.hasFeature("shell")){let y=await R.rpc("shell.sync",{have:He,settled:25}),S=new Set(y.removed??[]),N=new Set((y.projects??[]).map((j)=>j.id));if(S.size>0||N.size>0)C=[...C.filter((j)=>!S.has(j.id)&&!N.has(j.id)),...y.projects??[]],x=[...x.filter((j)=>!S.has(j.project)&&!N.has(j.project)),...y.threads??[]];else if(Array.isArray(y.threads)&&y.threads.length>0){let j=new Map(x.map((Q)=>[Q.id,Q]));for(let Q of y.threads)j.set(Q.id,Q);x=Array.from(j.values())}if(y.sections!==void 0){let j=Array.isArray(y.sections)?y.sections:Array.isArray(y.sections?.sections)?y.sections.sections:null;if(j)ue=j,wn(j)}if(y.h)He=y.h;ve.setData(C,x,F,I),ve.setSections(ue,F,I)}else if(R.hasFeature("sections")){let[y,S]=await Promise.all([R.rpc("sidebar.sections",{open:Array.from(de)}).catch(()=>null),R.rpc("threads.list",{limit:200,archived:!1}).catch(()=>({threads:[]}))]);if(x=S.threads??[],y&&Array.isArray(y.sections)){let N=y.sections;if(!N.some((Q)=>Q.kind==="projects"&&Q.rows.length>0)){let Q=N.find((ce)=>ce.kind==="projects"&&ce.fold&&ce.toggle&&(ce.count??0)>0);if(Q?.toggle&&!de.has(Q.toggle)){de.add(Q.toggle);let ce=await R.rpc("sidebar.sections",{open:Array.from(de)}).catch(()=>null);if(ce&&Array.isArray(ce.sections))N=ce.sections}}ue=N,wn(N),ve.setData(C,x,F,I),ve.setSections(N,F,I)}else ue=null,C=(await R.rpc("projects.list",{limit:100})).projects??[],ve.setSections(null,F,I),ve.setData(C,x,F,I);await R.rpc("subscribe",{topic:"lists"}).catch(()=>{})}else{ue=null;let[y,S]=await Promise.all([R.rpc("projects.list",{limit:100}),R.rpc("threads.list",{limit:200,archived:!1})]);C=y.projects??[],x=S.threads??[],ve.setSections(null,F,I),ve.setData(C,x,F,I),await R.rpc("subscribe",{topic:"lists"}).catch(()=>{})}let g=D;if(!g){let y="";try{y=localStorage.getItem("bp.lastThread")||""}catch{}if(y&&(ue&&gi(ue,y)||x.some((S)=>S.id===y)))g=y;else if(ue)g=at(ue);if(!g)g=(x.find((N)=>!N.archived&&!N.swarm&&!N.settled)??x.find((N)=>!N.archived&&!N.swarm))?.id??""}if(g&&(ue&&gi(ue,g)||x.some((y)=>y.id===g)))await qe(g,Ne!=="");else D="",se=[],G.setItems([]),pe.setState(!1,!1),Ie();if(Ne)It(Ne)}async function qe(g,y=!1){if(!y)Qt();if(D&&D!==g){tt.cancel();let Me=we.getEntries();if(Me.length>0){let Z=$e.get(D);Oe(D,{entries:Me,ids:Z?.ids??Me.map((Ue)=>Ue.id),olderCursor:Be,review:Z?.review??null,unanswered:Z?.unanswered??null,rail:Z?.rail??se,hashes:Z?.hashes??{}})}}let S=++ne;Te++,jt(null);let N=Le;if(Le=null,N!==null)R.rpc("unsubscribe",{sub:N}).catch(()=>{});D=g,pe.closeModelPicker();let j=$e.get(g);Be=j?.olderCursor??null;try{localStorage.setItem("bp.lastThread",g)}catch{}ve.setSelected(g),ie.classList.remove("bp-sidebar-open"),Ie();let Q=x.find((Me)=>Me.id===g)??null;if(j)we.setThread(Q,j.entries,Boolean(j.olderCursor),j.review,j.unanswered),se=j.rail,G.setItems(j.rail);else we.setLoading(Q),se=[],G.setItems([]);if(pe.setState(!0,Q?.state==="working"),R.hasFeature("open")){let Me={};if(j){for(let[Re,Dt]of Object.entries(j.hashes))Me[Re]=Dt;for(let Re of j.entries)if(Re.h)Me[Re.id]=Re.h}let Z;try{Z=await R.rpc("thread.open",{thread:g,limit:40,have:Me})}catch(Re){if(S===ne){let Dt=Re instanceof Error&&Re.message?Re.message:"Could not load messages.";we.setError(Q,Dt,()=>{qe(g)})}return}if(S!==ne){if(Z.sub!==void 0&&Z.sub!==null)R.rpc("unsubscribe",{sub:Z.sub}).catch(()=>{});return}if(Le=Z.sub??null,Z.thread){Q=Z.thread;let Re=x.findIndex((Dt)=>Dt.id===Z.thread.id);if(Re>=0)x[Re]=Z.thread;else x.unshift(Z.thread);Ie(),pe.setState(!0,Q.state==="working")}if("next"in Z)Be=Z.next??null;let Ue=new Map;if(j)for(let Re of j.entries)Ue.set(Re.id,Re);for(let Re of Z.entries??[])Ue.set(Re.id,Re);let lt=Z.ids??j?.ids??(Z.entries??[]).map((Re)=>Re.id),ct=lt.map((Re)=>Ue.get(Re)).filter((Re)=>Boolean(Re)),Ht=j?.rail??[];if(Z.rail!==void 0){if(Array.isArray(Z.rail))Ht=Z.rail;else if(Ht=Array.isArray(Z.rail?.rail)?Z.rail.rail:Array.isArray(Z.rail?.items)?Z.rail.items:[],Z.rail?.has){if(fe?.reconcileHas?.(Z.rail.has),K&&!Pr(Z.rail.has,K))Ve(!0)}}se=Ht,G.setItems(Ht);let yn=j?.review??null;if(R.hasFeature("reviewmode"))try{let Re=await R.rpc("thread.review",{thread:g});if(S!==ne)return;yn=Re.review??null}catch{}if(S!==ne)return;let xi="unanswered"in Z?Z.unanswered??null:j?.unanswered??null,Tr=Z.h??j?.hashes??{};if(Oe(g,{entries:ct,ids:lt,olderCursor:Be,review:yn,unanswered:xi,rail:Ht,hashes:Tr}),we.setThread(Q,ct,Boolean(Be),yn,xi),fi(g,S),K)mt(K);return}let ce;try{ce=await R.rpc("thread.entries",{thread:g,limit:40})}catch(Me){if(S===ne){let Z=Me instanceof Error&&Me.message?Me.message:"Could not load messages.";we.setError(Q,Z,()=>{qe(g)})}return}if(S!==ne)return;if(ce.thread){let Me=x.findIndex((Z)=>Z.id===ce.thread.id);if(Me>=0)x[Me]=ce.thread;else x.unshift(ce.thread);Ie()}Be=ce.next??null;let Fe=null;if(R.hasFeature("reviewmode"))try{let Me=await R.rpc("thread.review",{thread:g});if(S!==ne)return;Fe=Me.review??null}catch{}if(S!==ne)return;let Je=ce.entries??[],Ye=ce.unanswered??null;Oe(g,{entries:Je,ids:Je.map((Me)=>Me.id),olderCursor:Be,review:Fe,unanswered:Ye,rail:j?.rail??[],hashes:j?.hashes??{}}),we.setThread(Q,Je,Boolean(Be),Fe,Ye);try{let Z=(await R.rpc("subscribe",{topic:"thread",thread:g})).sub??null;if(Z!==null){if(S!==ne){R.rpc("unsubscribe",{sub:Z}).catch(()=>{});return}Le=Z}}catch{}if(S!==ne)return;if(tn(g,S),fi(g,S),K)mt(K)}async function fi(g,y){if(!g||!R.hasFeature("mgmt")){if(y===ne)ot.clear();return}let S=x.find((j)=>j.id===g),N=S?.project?C.find((j)=>j.id===S.project)?.root??"":"";if(!N&&R.hasFeature("viewers"))try{let j=await R.rpc("viewer.files",{thread:g});if(y!==ne)return;N=j.pcb||j.sch||j.root||""}catch{}if(y!==ne)return;if(N)await ot.watchProject(N);else ot.clear()}async function vi(g){let y=ne;for(let S=0;S<25&&y===ne;S++){if(we.goTo(g))return;if(!Be)return;let N=Be;if(await wi(),Be===N)return}}async function wi(){if(!D||!Be){we.clearLoadingOlder();return}let g=ne,y=D,S=Be;try{let N=await R.rpc("thread.entries",{thread:y,limit:40,before:S});if(g!==ne||D!==y)return;Be=N.next??null,we.prependEntries(N.entries??[],Boolean(Be))}catch{if(g===ne)we.clearLoadingOlder()}}async function ut(g){try{let y=await R.rpc("thread.create",{project:g});if(y.thread)x=[y.thread,...x.filter((S)=>S.id!==y.thread.id)],ve.setData(C,x,F,I),Xe(),await qe(y.thread.id),pe.focus()}catch(y){Ae(y,"Could not create thread")}}let Et=null;function yi(g){return(g.split(` +`).map((y)=>y.trim()).find((y)=>y.length>0)??"").slice(0,200)}function jt(g){Et=g,pe.setReply(g?{who:g.role==="user"?m("secret.you","You"):m("model.col.agent","Agent"),line:yi(g.text)}:null,()=>{if(Et)vi(Et.id)},()=>jt(null))}async function Ei(g,y=[]){if(!D)return;let S=ne,N=D,j=Yo(),Q=`local-${j}`,ce=Et&&g.trim()&&R.hasFeature("reply")?Et:null;if(ce)jt(null);we.upsertEntry({id:Q,kind:"user",text:g,at:Date.now(),clientId:j,...ce?{replyTo:{id:ce.id,quote:yi(ce.text)}}:{},attachments:y.map((Fe)=>({name:Fe.name,mime:Fe.mime,previewUrl:`data:${Fe.mime};base64,${Fe.data}`}))});try{let Fe={thread:N,text:g,clientId:j};if(y.length>0)Fe.attachments=y;if(ce)Fe.replyTo={id:ce.id,text:ce.text};let Je=await R.rpc("message.send",Fe);if(S!==ne||D!==N)return;if(Je.entry)we.upsertEntry(Je.entry)}catch(Fe){if(S===ne&&D===N){if(we.removeEntry(Q),pe.setDraft(g),ce&&!Et)jt(ce);Ae(Fe,"Failed to send message")}}}async function Ci(g){if(!D)return;let y=ne,S=D;try{let N=await R.rpc("composer.run",{thread:S,text:g});if(y!==ne||D!==S)return;if(N.error)pe.setDraft(g),Ae(new Kt(N.error,{code:N.errorCode,machine:N.machine}),N.error);else if(N.kind==="btw"&&typeof N.a==="string")we.showBtw(N.q??"",N.a);else if(N.kind==="edit"&&typeof N.text==="string")pe.setDraft(N.text);else if(N.kind==="project")_.open({mode:"folder"});else if(N.kind==="clone")_.open({mode:"clone",repo:N.repo??"",text:N.text??""})}catch(N){if(y===ne&&D===S)pe.setDraft(g),Ae(N,"Command refused")}}async function bt(g,y){try{let S=await R.rpc("thread.act",{thread:g,action:y});if(S.thread){if(x=x.map((N)=>N.id===S.thread.id?S.thread:N),ve.setData(C,x,F,I),S.thread.id===D)we.updateThreadMeta(S.thread),Ie()}Xe()}catch(S){pe.showError(S instanceof Error?S.message:`Action "${y}" not allowed`)}}function ki(g,y){if(!g||!g.text||y-g.at>=300000)return"";let S=g.build.split("-").pop()??"";if(g.reason==="build"&&S)return m("hub.restarting.build",g.text,{build:S});if(g.reason==="stop")return m("hub.stopped",g.text);return m("hub.restarting",g.text)}function sn(g){if(g==="connected")ve.setConnStatus(m("gpui.acct.connected","Connected"),"bp-ok");else if(g==="reconnecting"&&ki(R.restarting,Date.now()))ve.setConnStatus(ki(R.restarting,Date.now()),"");else if(g==="reconnecting")ve.setConnStatus("Reconnecting…","bp-warn");else if(g==="revoked")ve.setConnStatus(m("gpui.acct.sign.in.expired","Sign-in expired"),"bp-bad");else ve.setConnStatus("Connecting…","")}rn(()=>{sn(R.getState()),H.textContent=m("gpui.improvements","Improvements"),Y.title=m("palette.settings","Settings"),Y.setAttribute("aria-label",m("palette.settings","Settings")),Ie(),ve.refreshLocale(),we.refreshLocale(),pe.refreshLocale(),G.render(),q.refreshLocale(),ze.refreshLocale(),_.refreshLocale()}),R.onState((g,y)=>{if(g==="connected"&&y){if(y.locale)bi=y.locale,Lr();if(y.theme)Sr(y.theme);if(y.name)ve.setHostName(y.name);if(Array.isArray(y.favoriteModels))J=y.favoriteModels,pe.updateFavoriteModels(J);if(z=y.home??null,ve.setHome(z),ye(_n(y.noProvider)),q.isOpen())q.refresh();sn(g);let S=typeof y.hubBack==="string"?String(y.hubBack):"";if(S)try{let N=JSON.parse(S);if(N.reason==="crash")ve.setConnStatus(m("hub.back.crash",N.text??""),"bp-warn"),window.setTimeout(()=>sn(R.getState()),6000)}catch{}if(pe.setFeatures(R.hasFeature("images"),R.hasFeature("voice")),Array.isArray(y.commands))Ee=y.commands,pe.setCommands(Ee);else Ee=[];Mr(),_.reconcile()}else tt.cancel(),sn(g)}),R.onFrame((g)=>{if(g.t==="voice"){tt.handleFrame(g);return}if(g.t==="info"&&g.info&&typeof g.info==="object"){let S=g.info;if(Object.prototype.hasOwnProperty.call(S,"provider.notice"))ye(_n(S["provider.notice"]));ot.handleInfo(S);return}if(g.t!=="d")return;let y=g;if(y.k==="clone"||y.k==="clone.repos"||y.k==="clone.signin"){_.handleFrame(y);return}switch(y.k){case"project":{let S=y.project;if(!S)break;let N=C.findIndex((j)=>j.id===S.id);if(N>=0)C[N]=S;else C.unshift(S);ve.setData(C,x,F,I),Ie(),nn();break}case"thread":{let S=y.thread;if(!S)break;let N=x.findIndex((j)=>j.id===S.id);if(N>=0)x[N]=S;else x.unshift(S);if(ve.setData(C,x,F,I),S.id===D)we.updateThreadMeta(S),Ie(),pe.setState(!0,S.state==="working");nn();break}case"thread.removed":{let S=String(y.id??"");x=x.filter((N)=>N.id!==S),ve.setData(C,x,F,I),nn();break}case"entry":{if(y.thread===D&&y.entry)we.upsertEntry(y.entry);break}case"text":{if(y.thread===D)we.appendLiveText(String(y.entry??""),String(y.append??""),Number(y.at??Date.now()));break}case"turn":{if(y.thread===D){let S=String(y.state??"idle");pe.setState(!0,S==="working"),tn(D,ne)}nn();break}case"btw":{if(y.thread===D)we.showBtw(String(y.q??""),String(y.a??""));break}case"unanswered":{if(y.thread===D)we.setUnanswered(y.unanswered??null);break}case"theme":{if(typeof y.theme==="string")Sr(y.theme);break}case"home":{if(z=y.home??null,ve.setHome(z),q.isOpen())q.refresh();break}case"favorites":{if(Array.isArray(y.favorites))J=y.favorites.filter((S)=>typeof S==="string"),pe.updateFavoriteModels(J);break}default:break}}),window.addEventListener("keydown",(g)=>{let y=g.key.toLowerCase();if((g.ctrlKey||g.metaKey)&&(y==="k"||g.shiftKey&&y==="p"))if(g.preventDefault(),W.isOpen())W.close();else W.open();else if(g.shiftKey&&g.code==="KeyN"&&(g.altKey||g.ctrlKey||g.metaKey))g.preventDefault(),ut(yt);else if(g.key==="Escape"){let S=document.querySelector('[data-testid="move-project-modal"]');if(S){S.remove();return}if(W.isOpen())W.close();else if(pe.isModelPickerOpen())pe.closeModelPicker();else if(_.isOpen())_.escape();else if(q.isOpen())q.handleEscape();else if(we.closePlanRevise());else if(ot.isOpen())ot.closePanel()}}),R.connect()}if(document.readyState==="loading")document.addEventListener("DOMContentLoaded",Ar);else Ar(); diff --git a/web/dist/assets/style.css b/web/dist/assets/style.css index fe35f865d5..2618ad6b9a 100644 --- a/web/dist/assets/style.css +++ b/web/dist/assets/style.css @@ -329,6 +329,27 @@ button.primary.stop { padding: 8px 10px; border-bottom: 1px solid var(--line); } +.bp-side-home { + display: flex; + align-items: center; + justify-content: space-between; + gap: 6px; + padding: 6px 10px; + font-size: 11px; + border-bottom: 1px solid var(--line); + background: var(--panel); +} +.bp-side-home.bp-bad { color: var(--bad); } +.bp-side-home.bp-dim { color: var(--dim); } +.bp-side-home-text { flex: 1; min-width: 0; } +.bp-side-home-dismiss { + flex-shrink: 0; + padding: 0 4px; + line-height: 1.2; + color: var(--dim); + cursor: pointer; +} +.bp-side-home-dismiss:hover { color: var(--text); background: var(--raise); } .bp-side-search { flex: 1; min-width: 0; font-size: 12px; padding: 5px 8px; background: var(--panel); } .bp-side-add { font-size: 15px; line-height: 1; padding: 3px 7px; color: var(--dim); border: 1px solid var(--line); background: var(--panel); } .bp-side-add:hover { color: var(--text); border-color: var(--faint); } diff --git a/web/dist/manifest.json b/web/dist/manifest.json index 4eac383fc7..20a620ccbe 100644 --- a/web/dist/manifest.json +++ b/web/dist/manifest.json @@ -1,6 +1,6 @@ { "version": 1, - "totalAssetGzipBytes": 237355, + "totalAssetGzipBytes": 237496, "styleTokensSha256": "a4fed1b1c7bc676acc328907343eb5dcf87e426383d05617c632e48c0c3f2b80", "i18nKeys": [ "agy.signout", @@ -347,7 +347,7 @@ "i18nSubsetSha256": "ad3083cc73511c7876092934bbfa1a26823b509f16985a9cf924cf2136eff864", "inputs": { "web/src/addproject.ts": "06a7ff3e13cd78d993ebca7f638d5d623da06c0099186ad534bae8f184dbe44f", - "web/src/app.ts": "266280ec582ff9db7a0800134c813cf5a62f7f6962a0d4083b1e636a639d4cad", + "web/src/app.ts": "bdcd9cb1bc3517282752c8b6757802e5c1a43077e675a32cff83b2d6c777a38d", "web/src/chat.ts": "639e3af0791aedcde788c1a76aee6ea07cf96f5749d6a3564898c2beb8bd7337", "web/src/clone-model.ts": "d265df49436e14f415bbeb2a271ffa3552f9163be62bdc0158cecc10c3cdae45", "web/src/composer.ts": "63a5e9d7acfd321007c0a18880ee0ba055506335fcf4808154febc2b380f91a8", @@ -373,8 +373,8 @@ "web/src/ring-model.ts": "66368ffe8996138d4e73f041e50ac4fa573cf20ee59571af5fd1f320e29a895d", "web/src/settings-model.ts": "2f8f64cc93ee54c1bf45d918d8568eec2457970db7b3c43e926b2b4c45dcd5f6", "web/src/settings.ts": "8d4c24f554ba9c7ba4c4a96098fe25eea68b91f41489aee4d2b01b616f41f507", - "web/src/shell.css": "0fc26ae8ba27a25dff78a10523e89880db122cd9b1ccbcd972b6457df1eafcd8", - "web/src/sidebar.ts": "ee2e10c0fdde6e1f2807e72199bce3a85379244fc550acedd4f35b76c1369fc4", + "web/src/shell.css": "15c189efe5a2ed0b2e85bee37b3439ec9f2a60f462fbc5e8665721580ccd1e60", + "web/src/sidebar.ts": "857243b9136fcae26a7d30e2e7d406eb3fc25c2c081238ad5175636f72c5412d", "web/src/swarm-need.ts": "503bbf5ffe0389f068847571c792321b0ad5c8d26a18c73b8e41c0a8989e227f", "web/src/thread-context.ts": "b9fbd5b3ef0b1357b5a4444a1e9a0ac0606afe1c8a5377c4777752e918af0ac2", "web/src/user-refs.ts": "56bcf0dc116d5f14260606f07cf9af9becbbd7cbb102dc9e0687a4ea5f894011", @@ -411,9 +411,9 @@ }, "outputs": { "assets/app.js": { - "bytes": 439731, - "gzipBytes": 123684, - "sha256": "7d68d5f26a82d1143218aa7c226e3ab5db7ba0221a0a134af296ee467509d547" + "bytes": 440245, + "gzipBytes": 123764, + "sha256": "f82de1e9fd0ebc95f4cc4fef3c97b3f476b4e451d2bd235167042d52a30c0590" }, "assets/favicon-light.svg": { "bytes": 1207, @@ -436,9 +436,9 @@ "sha256": "1667d584f1306cc34069c62ca91e4aa78a1286d0875d1f12657817aa1a70a475" }, "assets/style.css": { - "bytes": 100512, - "gzipBytes": 16547, - "sha256": "7d61c5023e532d5b8ac18015e107b26b6d2bcaa455a8e5f669c0c7fede529b80" + "bytes": 101058, + "gzipBytes": 16608, + "sha256": "5e580f41510a298f1e422b9b4d20cb99313c9ca23566f00db92ecdd719f1f316" }, "assets/terminal.js": { "bytes": 296616, diff --git a/web/src/app.ts b/web/src/app.ts index a7d5425741..dc0d5e8dbc 100644 --- a/web/src/app.ts +++ b/web/src/app.ts @@ -500,6 +500,17 @@ function mountApp(): void { }, onNewChat: () => { void createThread(CHATS); }, onMoveToProject: (id) => openMoveToProject(id), + onDismissHomeMove: () => { + void hub.rpc<{ home?: HomeInfo }>("home.move.dismiss", {}) + .then((res) => { + if (res?.home !== undefined) { + homeInfo = res.home ?? null; + sidebar.setHome(homeInfo); + if (settings.isOpen()) void settings.refresh(); + } + }) + .catch(() => {}); + }, }); const chat = new ChatView(centerEl, { diff --git a/web/src/shell.css b/web/src/shell.css index eb41b1943f..3c874e137c 100644 --- a/web/src/shell.css +++ b/web/src/shell.css @@ -236,6 +236,27 @@ button.primary.stop { padding: 8px 10px; border-bottom: 1px solid var(--line); } +.bp-side-home { + display: flex; + align-items: center; + justify-content: space-between; + gap: 6px; + padding: 6px 10px; + font-size: 11px; + border-bottom: 1px solid var(--line); + background: var(--panel); +} +.bp-side-home.bp-bad { color: var(--bad); } +.bp-side-home.bp-dim { color: var(--dim); } +.bp-side-home-text { flex: 1; min-width: 0; } +.bp-side-home-dismiss { + flex-shrink: 0; + padding: 0 4px; + line-height: 1.2; + color: var(--dim); + cursor: pointer; +} +.bp-side-home-dismiss:hover { color: var(--text); background: var(--raise); } .bp-side-search { flex: 1; min-width: 0; font-size: 12px; padding: 5px 8px; background: var(--panel); } .bp-side-add { font-size: 15px; line-height: 1; padding: 3px 7px; color: var(--dim); border: 1px solid var(--line); background: var(--panel); } .bp-side-add:hover { color: var(--text); border-color: var(--faint); } diff --git a/web/src/sidebar.ts b/web/src/sidebar.ts index 8cbe934f19..2e966ff4ab 100644 --- a/web/src/sidebar.ts +++ b/web/src/sidebar.ts @@ -183,6 +183,54 @@ export interface SidebarCallbacks { onNewChat?: () => void; /** A chat row's Move to project…: the app asks which project. */ onMoveToProject?: (threadId: string) => void; + /** Dismiss a failed home move banner (`home.move.dismiss`). */ + onDismissHomeMove?: () => void; +} + +export interface HomeBannerState { + text: string; + isError: boolean; + dismissible: boolean; +} + +/** Pure presentation state for the sidebar home status banner. */ +export function homeBannerState(home: HomeInfo | null): HomeBannerState | null { + if (!home) return null; + if (home.moving?.state === "moving") { + const text = home.moving.step + ? t("home.moving.step", "Moving home to {to}: {step}").replace("{to}", home.moving.to).replace("{step}", home.moving.step) + : t("home.moving", "Moving home to {to}…").replace("{to}", home.moving.to); + return { text, isError: false, dismissible: false }; + } + if (home.moving?.state === "failed") { + const text = home.moving.note + ? t("home.move.failed.note", "Home move failed: {note}").replace("{note}", home.moving.note) + : t("home.move.failed", "Home move failed"); + return { text, isError: true, dismissible: true }; + } + if (!home.online) { + const name = home.name || "home"; + let time = ""; + if (home.awaySince && home.awaySince > 0) { + const d = new Date(home.awaySince); + time = `${String(d.getHours()).padStart(2, "0")}:${String(d.getMinutes()).padStart(2, "0")}`; + } + let text = ""; + if (time && home.queuedCount > 0) { + text = t("home.away.since.queued", "Home ({name}) is away since {time} · {n} queued") + .replace("{name}", name).replace("{time}", time).replace("{n}", String(home.queuedCount)); + } else if (time) { + text = t("home.away.since", "Home ({name}) is away since {time}") + .replace("{name}", name).replace("{time}", time); + } else if (home.queuedCount > 0) { + text = t("home.away.queued", "Home ({name}) is away · {n} queued") + .replace("{name}", name).replace("{n}", String(home.queuedCount)); + } else { + text = t("home.away", "Home ({name}) is away").replace("{name}", name); + } + return { text, isError: false, dismissible: false }; + } + return null; } /** Whether a swarm row under a project should be shown in the sidebar. */ @@ -461,9 +509,6 @@ export class SidebarView { 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)"; // Sticky Crew band: Bub + Bots strip + Rooms strip (never scrolls away) this.crewEl = document.createElement("div"); @@ -486,50 +531,30 @@ export class SidebarView { } public setHome(home: HomeInfo | null): void { - if (!home) { - this.homeBanner.classList.add("bp-hidden"); - this.homeBanner.textContent = ""; + const st = homeBannerState(home); + if (!st) { + this.homeBanner.className = "bp-side-home bp-hidden"; + this.homeBanner.replaceChildren(); return; } - let text = ""; - let isErr = false; - if (home.moving?.state === "moving") { - text = home.moving.step - ? t("home.moving.step", "Moving home to {to}: {step}").replace("{to}", home.moving.to).replace("{step}", home.moving.step) - : t("home.moving", "Moving home to {to}…").replace("{to}", home.moving.to); - } else if (home.moving?.state === "failed") { - text = home.moving.note - ? t("home.move.failed.note", "Home move failed: {note}").replace("{note}", home.moving.note) - : t("home.move.failed", "Home move failed"); - isErr = true; - } else if (!home.online) { - const name = home.name || "home"; - let time = ""; - if (home.awaySince && home.awaySince > 0) { - const d = new Date(home.awaySince); - time = `${String(d.getHours()).padStart(2, "0")}:${String(d.getMinutes()).padStart(2, "0")}`; - } - if (time && home.queuedCount > 0) { - text = t("home.away.since.queued", "Home ({name}) is away since {time} · {n} queued") - .replace("{name}", name).replace("{time}", time).replace("{n}", String(home.queuedCount)); - } else if (time) { - text = t("home.away.since", "Home ({name}) is away since {time}") - .replace("{name}", name).replace("{time}", time); - } else if (home.queuedCount > 0) { - text = t("home.away.queued", "Home ({name}) is away · {n} queued") - .replace("{name}", name).replace("{n}", String(home.queuedCount)); - } else { - text = t("home.away", "Home ({name}) is away").replace("{name}", name); - } - } - if (!text) { - this.homeBanner.classList.add("bp-hidden"); - this.homeBanner.textContent = ""; - } else { - this.homeBanner.textContent = text; - this.homeBanner.className = isErr ? "bp-side-home bp-bad" : "bp-side-home bp-dim"; - this.homeBanner.classList.remove("bp-hidden"); + this.homeBanner.className = st.isError ? "bp-side-home bp-bad" : "bp-side-home bp-dim"; + const textEl = document.createElement("span"); + textEl.className = "bp-side-home-text"; + textEl.textContent = st.text; + if (!st.dismissible) { + this.homeBanner.replaceChildren(textEl); + return; } + const dismissBtn = document.createElement("button"); + dismissBtn.type = "button"; + dismissBtn.className = "icon bp-side-home-dismiss"; + dismissBtn.textContent = "×"; + dismissBtn.setAttribute("data-testid", "home-move-dismiss"); + const label = t("approval.dismiss", "Dismiss"); + dismissBtn.title = label; + dismissBtn.setAttribute("aria-label", label); + dismissBtn.addEventListener("click", () => this.cb.onDismissHomeMove?.()); + this.homeBanner.replaceChildren(textEl, dismissBtn); } public setHostName(name: string): void { diff --git a/web/test/sidebar.test.ts b/web/test/sidebar.test.ts index 3c385d2f45..5611f4ccf4 100644 --- a/web/test/sidebar.test.ts +++ b/web/test/sidebar.test.ts @@ -3,10 +3,11 @@ import { readFileSync } from "node:fs"; import { join } from "node:path"; mock.module("virtual:i18n", () => ({ CATALOGS: {} })); -const { statusPillOf, isSwarmVisibleUnderProject, moveTargets, CHATS } = await import("../src/sidebar"); +const { statusPillOf, isSwarmVisibleUnderProject, moveTargets, homeBannerState, CHATS } = await import("../src/sidebar"); const root = join(import.meta.dir, ".."); const sidebarSrc = readFileSync(join(root, "src/sidebar.ts"), "utf8"); +const appSrc = readFileSync(join(root, "src/app.ts"), "utf8"); const shellCss = readFileSync(join(root, "src/shell.css"), "utf8"); describe("SidebarView Crew / Inbox / Bench + Status Pills + Snooze", () => { @@ -71,4 +72,27 @@ describe("SidebarView Crew / Inbox / Bench + Status Pills + Snooze", () => { expect(shellCss).toContain(".bp-proj-head:hover button.bp-proj-quick"); expect(sidebarSrc).not.toContain('className = "icon bp-proj-quick"'); }); + + test("homeBannerState marks only failed home moves as dismissible and wires dismiss RPC", () => { + expect(homeBannerState(null)).toBeNull(); + expect(homeBannerState({ kind: "local", id: "m1", name: "desk", online: true, queuedCount: 0, canMoveHere: false })).toBeNull(); + expect(homeBannerState({ + kind: "peer", id: "m2", name: "boat", online: true, queuedCount: 0, canMoveHere: false, + moving: { to: "boat", state: "moving", step: "copying" }, + })).toEqual({ text: "Moving home to boat: copying", isError: false, dismissible: false }); + expect(homeBannerState({ + kind: "peer", id: "m2", name: "boat", online: true, queuedCount: 0, canMoveHere: true, + moving: { to: "boat", state: "failed", note: "that machine is away" }, + })).toEqual({ text: "Home move failed: that machine is away", isError: true, dismissible: true }); + expect(homeBannerState({ + kind: "peer", id: "m2", name: "boat", online: true, queuedCount: 0, canMoveHere: true, + moving: { to: "boat", state: "failed" }, + })).toEqual({ text: "Home move failed", isError: true, dismissible: true }); + expect(homeBannerState({ + kind: "peer", id: "m2", name: "boat", online: false, queuedCount: 2, canMoveHere: false, + })).toEqual({ text: "Home (boat) is away · 2 queued", isError: false, dismissible: false }); + expect(sidebarSrc).toContain('"home-move-dismiss"'); + expect(sidebarSrc).toContain("this.cb.onDismissHomeMove?.()"); + expect(appSrc).toContain('"home.move.dismiss"'); + }); });