From 401ac59707cec06290c95c5b281743d3583b34da Mon Sep 17 00:00:00 2001 From: i2cjak Date: Sun, 22 Nov 2026 14:42:50 -0500 Subject: [PATCH 1/2] Notify and guard sends when no AI provider is configured --- i18n/en.msg | 7 + i18n/es.msg | 7 + i18n/ja.msg | 7 + .../java/dev/backplane/mobile/DataActivity.kt | 4 +- .../java/dev/backplane/mobile/DataClient.kt | 28 ++- .../java/dev/backplane/mobile/DataLinks.kt | 8 +- .../java/dev/backplane/mobile/DataViews.kt | 22 +- .../src/main/java/dev/backplane/mobile/Msg.kt | 44 +++- mobile/ios/Backplane/DataClient.swift | 7 +- mobile/ios/Backplane/DataLinks.swift | 10 +- mobile/ios/Backplane/DataModels.swift | 21 ++ mobile/ios/Backplane/DataViews.swift | 37 ++- mobile/ios/Shared/TrCatalog.swift | 7 + native/gpui/src/main.rs | 16 +- native/gpui/src/pairing.rs | 4 +- native/gpui/src/screens/linkroute.rs | 18 +- native/gpui/src/screens/mod.rs | 1 + native/gpui/src/screens/pair.rs | 7 +- native/gpui/src/screens/provider_notice.rs | 89 +++++++ native/gpui/src/screens/timeline.rs | 4 + native/gpui/src/ui.rs | 9 +- native/host/src/agents/mod.rs | 10 + native/host/src/bots/rpc.rs | 9 + native/host/src/data/link.rs | 1 + native/host/src/data/mod.rs | 7 +- native/host/src/data/tests.rs | 20 +- native/host/src/hub.rs | 2 +- native/host/src/present/screen.rs | 25 +- native/host/src/settings/accounts_hub.rs | 1 + native/host/src/settings/mod.rs | 1 + native/host/src/settings/models_probe.rs | 8 +- native/host/src/settings/provider_notice.rs | 233 ++++++++++++++++++ web/build.ts | 5 + web/dist/assets/app.js | 36 +-- web/dist/assets/pair.js | 2 +- web/dist/assets/style.css | 36 ++- web/dist/manifest.json | 46 ++-- web/src/app.ts | 34 ++- web/src/chat.ts | 35 +++ web/src/composer.ts | 20 +- web/src/provider-notice.ts | 39 +++ web/src/settings.ts | 46 +++- web/src/shell.css | 36 ++- web/src/ws.ts | 2 + web/test/provider-notice.test.ts | 29 +++ 45 files changed, 956 insertions(+), 84 deletions(-) create mode 100644 native/gpui/src/screens/provider_notice.rs create mode 100644 native/host/src/settings/provider_notice.rs create mode 100644 web/src/provider-notice.ts create mode 100644 web/test/provider-notice.test.ts diff --git a/i18n/en.msg b/i18n/en.msg index 864331243c..9a3fb04d5e 100644 --- a/i18n/en.msg +++ b/i18n/en.msg @@ -5041,3 +5041,10 @@ mobile.plan.touchhint = Drag waypoints to steer · Tap + to add · Tap point to mobile.plan.copied = Copied mobile.plan.widthmm = {v} mm mobile.plan.coord = ({x}, {y} mm) +provider.notice.head = No AI provider connected +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. +provider.notice.button = Open Settings → Accounts +provider.notice.senderr = No AI provider connected yet. Open Settings → Accounts to connect Claude, Codex, Antigravity, or another provider. +web.settings.providers = AI providers +web.settings.providers.browser = Connect a provider in the Backplane desktop or mobile app under Settings → Accounts. diff --git a/i18n/es.msg b/i18n/es.msg index 6e6629959e..5953df5dce 100644 --- a/i18n/es.msg +++ b/i18n/es.msg @@ -5041,3 +5041,10 @@ mobile.plan.touchhint = Arrastra vértices para guiar · Toca + para añadir · mobile.plan.copied = Copiado mobile.plan.widthmm = {v} mm mobile.plan.coord = ({x}, {y} mm) +provider.notice.head = No hay ningún proveedor de IA conectado +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. +provider.notice.button = Abrir Configuración → Cuentas +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. +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. diff --git a/i18n/ja.msg b/i18n/ja.msg index 57d22f0dad..4f9f69370f 100644 --- a/i18n/ja.msg +++ b/i18n/ja.msg @@ -5064,3 +5064,10 @@ mobile.plan.touchhint = 頂点をドラッグして誘導 · + をタップで mobile.plan.copied = コピーしました mobile.plan.widthmm = {v} mm mobile.plan.coord = ({x}, {y} mm) +provider.notice.head = AI プロバイダーが接続されていません +provider.notice.text.none = チャットを始めるには、Claude、Codex、Antigravity などのプロバイダーを接続してください。 +provider.notice.text.signedout = チャットを始めるには、設定 → アカウントで Claude、Codex などのプロバイダーにサインインしてください。 +provider.notice.button = 設定 → アカウントを開く +provider.notice.senderr = AI プロバイダーがまだ接続されていません。設定 → アカウントを開いて、Claude、Codex、Antigravity などのプロバイダーを接続してください。 +web.settings.providers = AI プロバイダー +web.settings.providers.browser = Backplane のデスクトップまたはモバイルアプリの設定 → アカウントからプロバイダーを接続してください。 diff --git a/mobile/android/app/src/main/java/dev/backplane/mobile/DataActivity.kt b/mobile/android/app/src/main/java/dev/backplane/mobile/DataActivity.kt index bf6a023404..6e68666fc4 100644 --- a/mobile/android/app/src/main/java/dev/backplane/mobile/DataActivity.kt +++ b/mobile/android/app/src/main/java/dev/backplane/mobile/DataActivity.kt @@ -46,7 +46,9 @@ class DataActivity : ComponentActivity() { if (BuildConfig.DEBUG && u.host == "unpair") { DataClient.unpair(); return } // (a thread of another machine, `desktop~t9` or a link id: the hub says which thread it is; this machine's own opens as it did) if (u.host == "thread") u.pathSegments.firstOrNull()?.let { if (it.contains('~')) DataClient.openLink(u.toString(), "") else DataClient.openFromIntent = it } - else if (u.host == "account") u.pathSegments.firstOrNull()?.let { DataClient.openAccount = it } else DataClient.askLink = u.toString() + else if (u.host == "account") u.pathSegments.firstOrNull()?.let { DataClient.openAccount = it } + else if (u.host == "settings") { if (u.pathSegments.firstOrNull() == "accounts") DataClient.openAccounts = true else DataClient.openSettings = true } + else DataClient.askLink = u.toString() } override fun onResume() { super.onResume(); DataClient.foreground = true; DataClient.foreground(); DataVoice.background(false) } override fun onPause() { super.onPause(); DataClient.foreground = false; DataVoice.background(true) } diff --git a/mobile/android/app/src/main/java/dev/backplane/mobile/DataClient.kt b/mobile/android/app/src/main/java/dev/backplane/mobile/DataClient.kt index ebcaf57569..d0f91b68f0 100644 --- a/mobile/android/app/src/main/java/dev/backplane/mobile/DataClient.kt +++ b/mobile/android/app/src/main/java/dev/backplane/mobile/DataClient.kt @@ -44,6 +44,10 @@ object DataClient { /** the strip's words (the hub's English) in place of its usual look, or null */ val restartText: String? get() = RestartStrip.text(restarting, hubBack, conn == Conn.ONLINE, stripNow) var telemetryNotice by mutableStateOf(null); private set // the one-time telemetry notice (feature "telemetryNotice"): shown while the hub says so + /** Hub notice when zero AI providers / accounts are configured or signed in (`hello.noProvider` / `info["provider.notice"]`) */ + var noProvider by mutableStateOf(null); private set + var openAccounts by mutableStateOf(false) + var openSettings by mutableStateOf(false) /** Alerts not allowed yet (Android 13+): AlertsBanner offers them, with the reason, instead of the system asking at start. Not now hides it until the next launch. */ var alertsAsk by mutableStateOf(false) var migrating by mutableStateOf(null); private set // a 0.14 home coming across: hello `migrating`, then each `migrating` frame (DataMigrate.kt) @@ -168,9 +172,9 @@ object DataClient { private fun reset(clearDisk: Boolean = false) { saveJob?.cancel() shellHashes.clear(); threadHashes.clear(); threadIds.clear(); subEntriesById.clear(); subEntryIds = emptyList() - Swarms.reset(); restarting = null; hubBack = null; notice = HubNotice(); star = null; telemetryNotice = null; migrating = null; migrateOpen = false; projects = emptyList(); threads = emptyList(); entries = emptyMap(); older = emptyMap(); listsLoaded = false; open = null + Swarms.reset(); restarting = null; hubBack = null; notice = HubNotice(); star = null; telemetryNotice = null; noProvider = null; migrating = null; migrateOpen = false; projects = emptyList(); threads = emptyList(); entries = emptyMap(); older = emptyMap(); listsLoaded = false; open = null home = null - Swarms.reset(); notice = HubNotice(); star = null; telemetryNotice = null; migrating = null; migrateOpen = false; projects = emptyList(); threads = emptyList(); entries = emptyMap(); older = emptyMap(); listsLoaded = false; open = null + Swarms.reset(); notice = HubNotice(); star = null; telemetryNotice = null; noProvider = null; migrating = null; migrateOpen = false; projects = emptyList(); threads = emptyList(); entries = emptyMap(); older = emptyMap(); listsLoaded = false; open = null if (clearDisk) link?.let { Pairing.key(it) }?.let { cacheFile(it).delete() } } @@ -268,6 +272,7 @@ object DataClient { scope.launch { synchronise(g) } scope.launch { Clones.reconcile() } // a clone followed across the reconnect: its pushes meanwhile were missed heardOffer(o.optString("hubOffer")) + noProvider = DNoProvider.of(o.opt("noProvider")) } "reply" -> { val d = calls.remove(o.optInt("id", -1)) ?: return @@ -283,7 +288,7 @@ object DataClient { "hub.restarting" -> { o.optString("text").takeIf { it.isNotEmpty() }?.let { restarting = RestartNote(it, System.currentTimeMillis()); strip() } } "telemetry.notice" -> { telemetryNotice = DTelemetryNotice.of(o.optJSONObject("notice")) } "migrating" -> heardMigrating(o) - "info" -> o.optJSONObject("info")?.let { if (it.has("hub.offer")) heardOffer(it.optString("hub.offer")); if (it.has("hub.back")) heardBack(it.optString("hub.back")); heardMgmt(it) } + "info" -> o.optJSONObject("info")?.let { if (it.has("hub.offer")) heardOffer(it.optString("hub.offer")); if (it.has("hub.back")) heardBack(it.optString("hub.back")); if (it.has("provider.notice")) noProvider = DNoProvider.of(it.opt("provider.notice")); heardMgmt(it) } "shot" -> { shotBot = o.optString("bot"); shot = o.optLong("n") } } } @@ -1405,3 +1410,20 @@ data class DTelemetryNotice(val token: String, val text: String, val off: String fun act(token: String, action: String): JSONObject = JSONObject().put("token", token).put("action", action) } } + +/** Hub notice shown when zero AI providers / accounts are configured or signed in. */ +data class DNoProvider(val reason: String, val head: String, val text: String, val button: String, val url: String) { + companion object { + fun of(v: Any?): DNoProvider? { + val o = when (v) { + is JSONObject -> v + is String -> v.trim().takeIf { it.isNotEmpty() }?.let { runCatching { JSONObject(it) }.getOrNull() } + else -> null + } ?: return null + val head = o.optString("head").trim() + if (head.isEmpty()) return null + return DNoProvider(o.optString("reason"), head, o.optString("text"), o.optString("button"), o.optString("url")) + } + fun isSendError(msg: String): Boolean = msg.contains("No AI provider connected") + } +} diff --git a/mobile/android/app/src/main/java/dev/backplane/mobile/DataLinks.kt b/mobile/android/app/src/main/java/dev/backplane/mobile/DataLinks.kt index 19d354cc51..f81be93cbb 100644 --- a/mobile/android/app/src/main/java/dev/backplane/mobile/DataLinks.kt +++ b/mobile/android/app/src/main/java/dev/backplane/mobile/DataLinks.kt @@ -28,7 +28,7 @@ import org.json.JSONObject // phone numbers in the dialer. A backplane:// link or a path is asked of the hub (link.resolve), which says what it opens: a thread (also one on a linked machine), a // project, a room, a file at a line, or a short note why not. DataRoot follows `DataClient.linkTarget`. data class LinkTarget(val kind: Kind, val id: String, val path: String = "", val line: Int = 0, val n: Long = System.nanoTime()) { - enum class Kind { THREAD, PROJECT, ROOM, FILE } + enum class Kind { THREAD, PROJECT, ROOM, FILE, SETTINGS } } /** What to ask the hub for a tapped link: a backplane:// address (this build's own scheme counts as it), or the path a bppath: link carries. */ @@ -59,7 +59,10 @@ fun DataClient.openLink(url: String, thread: String) { // a hub that does not know link.resolve: a thread link as before, the rest says so if (!has("links")) { val id = if (text.startsWith("backplane://thread/")) text.removePrefix("backplane://thread/").substringBefore('#').substringBefore('/') else "" - if (id.isNotEmpty()) linkTarget = LinkTarget(LinkTarget.Kind.THREAD, id) else say(Msg.android_link_old) + val page = if (text.startsWith("backplane://settings/")) text.removePrefix("backplane://settings/").substringBefore('#').substringBefore('?').trimEnd('/') else null + if (id.isNotEmpty()) linkTarget = LinkTarget(LinkTarget.Kind.THREAD, id) + else if (page != null) linkTarget = LinkTarget(LinkTarget.Kind.SETTINGS, page) + else say(Msg.android_link_old) return@launch } try { @@ -69,6 +72,7 @@ fun DataClient.openLink(url: String, thread: String) { "project" -> LinkTarget(LinkTarget.Kind.PROJECT, r.optString("project")) "room" -> LinkTarget(LinkTarget.Kind.ROOM, r.optString("room")) "file" -> LinkTarget(LinkTarget.Kind.FILE, r.optString("thread"), r.optString("path"), r.optInt("line")) + "settings" -> LinkTarget(LinkTarget.Kind.SETTINGS, r.optString("page")) else -> { // a file the reply lists that no viewer here opens is downloaded instead val f = pathOf(url)?.let { p -> FileFetch.find(p, entries[thread].orEmpty().flatMap { it.files }) } diff --git a/mobile/android/app/src/main/java/dev/backplane/mobile/DataViews.kt b/mobile/android/app/src/main/java/dev/backplane/mobile/DataViews.kt index 51bdc9b4e5..59570bedd3 100644 --- a/mobile/android/app/src/main/java/dev/backplane/mobile/DataViews.kt +++ b/mobile/android/app/src/main/java/dev/backplane/mobile/DataViews.kt @@ -108,6 +108,8 @@ fun DataRoot() { var page by remember { mutableStateOf(DataClient.openFromIntent?.let { if (DataClient.openViewerTab != null) Page.Viewer(it) else Page.Thread(it) } ?: Page.Home) } // an expired sign-in's alert: that account, its sign-in started LaunchedEffect(DataClient.openAccount) { DataClient.openAccount?.let { page = Page.Account(it, true); DataClient.openAccount = null } } + LaunchedEffect(DataClient.openAccounts) { if (DataClient.openAccounts) { DataClient.openAccounts = false; page = Page.Accounts } } + LaunchedEffect(DataClient.openSettings) { if (DataClient.openSettings) { DataClient.openSettings = false; page = Page.Settings } } LaunchedEffect(DataClient.openFromIntent) { DataClient.openFromIntent?.let { page = if (DataClient.openViewerTab != null) Page.Viewer(it) else Page.Thread(it); DataClient.openFromIntent = null } } // a link the hub resolved (DataLinks.kt): its screen LaunchedEffect(DataClient.openAddProject) { if (DataClient.openAddProject) { DataClient.openAddProject = false; page = Page.Folders() } } @@ -120,6 +122,7 @@ fun DataRoot() { LinkTarget.Kind.THREAD -> page = Page.Thread(t.id) LinkTarget.Kind.FILE -> page = Page.Viewer(t.id, t.path, t.line) LinkTarget.Kind.PROJECT -> { DataClient.focusProject = t.id; page = Page.Home } + LinkTarget.Kind.SETTINGS -> page = if (t.id == "accounts") Page.Accounts else Page.Settings LinkTarget.Kind.ROOM -> { if (Swarms.on() && !Swarms.isSwarm(t.id)) Swarms.load() if (Swarms.isSwarm(t.id)) { page = Page.Swarm(t.id); return@LaunchedEffect } // a swarm's page is its room's @@ -351,6 +354,7 @@ private fun HomeScreen(open: (String) -> Unit, settings: () -> Unit, hub: () -> IconButton(onClick = settings, modifier = Modifier.testTag("home.settings")) { Icon(Icons.Default.Settings, Msg.palette_settings, tint = dcs.onSurfaceVariant) } } ConnBanner(hub, settings) + NoProviderBanner { DataClient.openAccounts = true } Row(Modifier.fillMaxWidth().padding(start = 10.dp, end = 4.dp, top = 8.dp, bottom = 8.dp), verticalAlignment = Alignment.CenterVertically) { if (DataClient.has("search")) Box(Modifier.weight(1f)) { DField(q, { q = it }, Msg.android_search_hint, Modifier.testTag("home.searchfield")) } else Spacer(Modifier.weight(1f)) IconButton(onClick = addProject, modifier = Modifier.testTag("home.add")) { Icon(Icons.Default.Add, Msg.sidebar_add_project, tint = dcs.onSurfaceVariant) } @@ -741,6 +745,7 @@ private fun ThreadBody(id: String, viewer: () -> Unit, hub: () -> Unit, go: (Str if (thread?.state == "working") item("working") { WorkingRow() } } DLine() + if (!id.contains('~')) NoProviderBanner { DataClient.openAccounts = true } review?.let { r -> ReviewBar(r, !reviewing) { if (!reviewing) { reviewing = true; scope.launch { try { review = DataClient.reviewSet(id, r.value) } catch (e: Exception) { notice = e.message ?: "" } finally { reviewing = false } } } } } order?.let { OrderCard(it) } MentionPopup(draft) { put(it) } @@ -752,7 +757,10 @@ private fun ThreadBody(id: String, viewer: () -> Unit, hub: () -> Unit, go: (Str if (notice.isNotEmpty()) DMono(Tr.t(notice), dwarn, 12) existing?.let { dir -> DBtn(Msg.android_hub_cmd_project_existing, false, true, Modifier.testTag("thread.project.existing")) { scope.launch { try { DataClient.addProject(dir); existing = null; notice = ""; put("") } catch (e: Exception) { notice = e.message ?: Msg.android_failed_generic } } } } thread?.mark?.let { m -> DMono(Tr.t(m.runs) + if (m.away) " · " + Msg.android_away else "", dfaint, 11, Modifier.testTag("thread.runs")) } - DataClient.sendError[id]?.let { DMono(Tr.t(it), dcs.error, 12, Modifier.testTag("thread.refused")) } + DataClient.sendError[id]?.let { + DMono(Tr.t(it), dcs.error, 12, Modifier.testTag("thread.refused")) + if (DNoProvider.isSendError(it)) DBtn(Msg.provider_notice_button, false, true, Modifier.testTag("thread.refused.accounts")) { DataClient.openAccounts = true } + } if (pending.isNotEmpty()) Row(Modifier.fillMaxWidth().horizontalScroll(rememberScrollState()), horizontalArrangement = Arrangement.spacedBy(8.dp)) { pending.toList().forEach { b -> Box(Modifier.testTag("thread.pending").clickable { pending.remove(b) }) { Pic(b, 64) }; } } @@ -1534,6 +1542,18 @@ internal fun ReviewBar(r: DReviewBar, enabled: Boolean, press: () -> Unit) { } } +/** Proactive banner shown when the hub has zero AI providers configured or signed in. */ +@Composable +internal fun NoProviderBanner(onOpenAccounts: () -> Unit) { + val n = DataClient.noProvider ?: return + Column(Modifier.fillMaxWidth().padding(horizontal = 12.dp, vertical = 6.dp).border(BorderStroke(1.dp, dwarn)).background(dcs.surfaceVariant).padding(horizontal = 10.dp, vertical = 8.dp).testTag("provider.notice"), + verticalArrangement = Arrangement.spacedBy(6.dp)) { + DMono(Tr.t(n.head), dcs.onSurface, 12, bold = true) + if (n.text.isNotEmpty()) DMono(Tr.t(n.text), dcs.onSurfaceVariant, 11, lines = 3) + DBtn(if (n.button.isNotEmpty()) Tr.t(n.button) else Msg.provider_notice_button, true, modifier = Modifier.testTag("provider.notice.button")) { onOpenAccounts() } + } +} + /** A buy thread's Order card: the steps, the hub's line, the total and what it covers about customs, and Buy now (the hub's link, opened in the browser). */ @Composable private fun OrderCard(o: DataClient.Order) { diff --git a/mobile/android/app/src/main/java/dev/backplane/mobile/Msg.kt b/mobile/android/app/src/main/java/dev/backplane/mobile/Msg.kt index f761fa9cd2..290461128b 100644 --- a/mobile/android/app/src/main/java/dev/backplane/mobile/Msg.kt +++ b/mobile/android/app/src/main/java/dev/backplane/mobile/Msg.kt @@ -4940,6 +4940,13 @@ object Msg { "mobile.plan.copied", "mobile.plan.widthmm", "mobile.plan.coord", + "provider.notice.head", + "provider.notice.text.none", + "provider.notice.text.signedout", + "provider.notice.button", + "provider.notice.senderr", + "web.settings.providers", + "web.settings.providers.browser", ) internal val keys: Array by lazy { arrayOf(*keys0(), *keys1(), *keys2(), *keys3(), *keys4(), *keys5(), *keys6(), *keys7(), *keys8(), *keys9(), *keys10(), *keys11(), *keys12(), *keys13(), *keys14(), *keys15(), *keys16(), *keys17(), *keys18(), *keys19()) } private fun en0(): Array = arrayOf( @@ -9879,6 +9886,13 @@ object Msg { "Copied", "{v} mm", "({x}, {y} mm)", + "No AI provider connected", + "Connect Claude, Codex, Antigravity, or another provider to start chatting.", + "Sign in to Claude, Codex, or another provider in Settings → Accounts to start chatting.", + "Open Settings → Accounts", + "No AI provider connected yet. Open Settings → Accounts to connect Claude, Codex, Antigravity, or another provider.", + "AI providers", + "Connect a provider in the Backplane desktop or mobile app under Settings → Accounts.", ) internal val en: Array by lazy { arrayOf(*en0(), *en1(), *en2(), *en3(), *en4(), *en5(), *en6(), *en7(), *en8(), *en9(), *en10(), *en11(), *en12(), *en13(), *en14(), *en15(), *en16(), *en17(), *en18(), *en19()) } private fun ja0(): Array = arrayOf( @@ -14818,6 +14832,13 @@ object Msg { "コピーしました", "{v} mm", "({x}, {y} mm)", + "AI プロバイダーが接続されていません", + "チャットを始めるには、Claude、Codex、Antigravity などのプロバイダーを接続してください。", + "チャットを始めるには、設定 → アカウントで Claude、Codex などのプロバイダーにサインインしてください。", + "設定 → アカウントを開く", + "AI プロバイダーがまだ接続されていません。設定 → アカウントを開いて、Claude、Codex、Antigravity などのプロバイダーを接続してください。", + "AI プロバイダー", + "Backplane のデスクトップまたはモバイルアプリの設定 → アカウントからプロバイダーを接続してください。", ) internal val ja: Array by lazy { arrayOf(*ja0(), *ja1(), *ja2(), *ja3(), *ja4(), *ja5(), *ja6(), *ja7(), *ja8(), *ja9(), *ja10(), *ja11(), *ja12(), *ja13(), *ja14(), *ja15(), *ja16(), *ja17(), *ja18(), *ja19()) } private fun es0(): Array = arrayOf( @@ -19757,6 +19778,13 @@ object Msg { "Copiado", "{v} mm", "({x}, {y} mm)", + "No hay ningún proveedor de IA conectado", + "Conecta Claude, Codex, Antigravity u otro proveedor para empezar a chatear.", + "Inicia sesión en Claude, Codex u otro proveedor en Configuración → Cuentas para empezar a chatear.", + "Abrir Configuración → Cuentas", + "Aún no hay ningún proveedor de IA conectado. Abre Configuración → Cuentas para conectar Claude, Codex, Antigravity u otro proveedor.", + "Proveedores de IA", + "Conecta un proveedor en la aplicación de escritorio o móvil de Backplane en Configuración → Cuentas.", ) internal val es: Array by lazy { arrayOf(*es0(), *es1(), *es2(), *es3(), *es4(), *es5(), *es6(), *es7(), *es8(), *es9(), *es10(), *es11(), *es12(), *es13(), *es14(), *es15(), *es16(), *es17(), *es18(), *es19()) } private fun exactText0(): Array = arrayOf( @@ -23145,9 +23173,16 @@ object Msg { "Plan · review", "Remove point", "Drag waypoints to steer · Tap + to add · Tap point to remove", + "No AI provider connected", + "Connect Claude, Codex, Antigravity, or another provider to start chatting.", + "Sign in to Claude, Codex, or another provider in Settings → Accounts to start chatting.", + "Open Settings → Accounts", + "No AI provider connected yet. Open Settings → Accounts to connect Claude, Codex, Antigravity, or another provider.", + "AI providers", + "Connect a provider in the Backplane desktop or mobile app under Settings → Accounts.", ) internal val exactText: Array by lazy { arrayOf(*exactText0(), *exactText1(), *exactText2(), *exactText3(), *exactText4(), *exactText5(), *exactText6(), *exactText7(), *exactText8(), *exactText9(), *exactText10(), *exactText11(), *exactText12(), *exactText13()) } - internal val exactKey: IntArray by lazy { intArrayOf(0, 1, 2, 3, 4, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 3152, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 43, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 3720, 61, 62, 63, 64, 66, 68, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 84, 85, 3759, 87, 88, 98, 99, 3081, 3758, 102, 103, 105, 106, 107, 109, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 155, 156, 157, 159, 161, 162, 163, 3201, 165, 166, 3203, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 3162, 183, 187, 189, 193, 194, 195, 197, 198, 199, 200, 201, 202, 206, 209, 213, 215, 216, 217, 219, 220, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 234, 235, 2968, 237, 238, 239, 240, 3719, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255, 256, 260, 262, 263, 264, 265, 266, 267, 270, 271, 272, 273, 275, 279, 280, 281, 282, 286, 287, 289, 290, 291, 292, 293, 294, 295, 296, 297, 298, 300, 301, 3173, 305, 306, 307, 308, 309, 310, 311, 313, 314, 315, 317, 319, 333, 3767, 336, 3766, 3769, 340, 3779, 342, 343, 344, 345, 354, 3150, 357, 358, 359, 360, 361, 362, 363, 364, 365, 366, 367, 368, 369, 370, 371, 372, 373, 2971, 376, 377, 378, 379, 380, 381, 382, 383, 384, 385, 386, 387, 388, 389, 390, 391, 392, 393, 394, 395, 396, 397, 398, 399, 400, 401, 402, 403, 404, 405, 406, 407, 408, 409, 410, 411, 412, 413, 414, 415, 416, 417, 419, 420, 421, 422, 423, 424, 425, 426, 427, 428, 429, 2963, 2964, 432, 433, 434, 435, 436, 437, 438, 439, 440, 441, 442, 443, 444, 445, 446, 447, 448, 449, 450, 451, 453, 454, 455, 3180, 457, 458, 459, 460, 461, 2953, 463, 464, 465, 3083, 467, 468, 469, 470, 471, 472, 473, 474, 475, 476, 477, 478, 479, 480, 481, 482, 483, 484, 485, 486, 487, 488, 489, 490, 491, 492, 493, 494, 495, 496, 497, 498, 499, 500, 501, 502, 503, 504, 505, 506, 507, 508, 509, 510, 511, 512, 513, 514, 515, 516, 517, 518, 519, 520, 521, 522, 523, 524, 525, 526, 527, 528, 529, 530, 531, 532, 533, 534, 535, 536, 537, 538, 539, 540, 541, 542, 543, 544, 545, 546, 547, 548, 549, 550, 551, 552, 553, 554, 556, 557, 558, 559, 560, 561, 562, 563, 565, 566, 567, 568, 569, 570, 571, 572, 573, 574, 575, 576, 577, 578, 592, 628, 629, 630, 3188, 3189, 636, 637, 638, 639, 640, 641, 642, 643, 644, 645, 646, 647, 651, 652, 3832, 654, 656, 657, 659, 663, 664, 665, 666, 667, 668, 669, 670, 671, 672, 673, 674, 675, 676, 677, 678, 680, 681, 682, 683, 684, 686, 687, 689, 690, 692, 693, 694, 695, 698, 704, 724, 728, 729, 730, 731, 732, 3764, 734, 735, 736, 737, 3187, 739, 740, 741, 742, 743, 744, 745, 746, 747, 748, 749, 750, 751, 752, 753, 754, 755, 756, 757, 758, 759, 760, 761, 762, 763, 764, 765, 766, 767, 768, 769, 770, 771, 772, 773, 774, 775, 776, 777, 778, 779, 780, 781, 782, 783, 784, 785, 786, 787, 788, 789, 790, 791, 792, 793, 794, 795, 796, 797, 798, 799, 800, 801, 802, 803, 3747, 805, 806, 807, 808, 809, 810, 811, 812, 813, 814, 815, 816, 817, 818, 819, 820, 821, 822, 823, 824, 825, 826, 827, 828, 829, 832, 833, 834, 835, 836, 837, 838, 839, 840, 841, 843, 844, 845, 847, 848, 3183, 850, 852, 853, 854, 857, 858, 859, 860, 861, 862, 863, 864, 865, 866, 867, 3757, 869, 870, 871, 872, 873, 874, 875, 876, 877, 878, 879, 880, 881, 882, 883, 884, 885, 886, 887, 888, 889, 890, 891, 892, 893, 894, 895, 896, 897, 898, 899, 900, 901, 3834, 903, 904, 907, 908, 909, 910, 911, 912, 913, 914, 915, 916, 917, 918, 919, 920, 921, 922, 923, 924, 925, 926, 927, 928, 929, 930, 931, 932, 933, 934, 935, 936, 937, 938, 939, 940, 941, 942, 943, 944, 945, 946, 947, 948, 949, 950, 951, 952, 953, 954, 955, 956, 957, 958, 959, 960, 961, 962, 3153, 964, 965, 966, 967, 968, 969, 3782, 971, 3008, 3065, 974, 975, 976, 978, 979, 987, 988, 989, 991, 992, 993, 995, 996, 997, 998, 999, 1000, 1001, 1002, 1003, 1005, 1006, 1007, 1008, 1009, 1010, 1011, 1012, 1013, 1014, 1015, 1016, 1017, 1018, 3785, 1020, 1021, 1022, 1025, 1029, 1030, 1031, 2960, 3034, 1034, 1035, 1036, 1037, 1038, 1039, 1040, 1041, 1042, 1043, 1045, 1046, 1049, 1050, 1051, 1052, 1053, 1054, 1055, 1056, 1057, 1058, 1059, 1060, 1061, 1062, 1063, 1064, 1065, 1066, 1067, 1068, 1069, 1070, 1071, 1072, 1074, 1082, 1083, 1086, 1087, 1088, 1090, 1091, 1092, 3799, 1094, 1095, 1098, 1099, 1100, 3182, 1102, 1103, 1104, 1105, 1106, 1107, 1108, 1110, 1111, 1112, 1113, 1114, 1115, 1116, 3784, 1120, 1123, 1124, 1125, 1127, 1128, 1129, 1130, 1131, 1132, 1133, 1134, 1135, 1136, 1137, 1138, 1139, 1140, 1141, 1142, 1143, 1144, 1145, 1146, 1150, 1151, 1152, 1153, 1154, 1155, 1158, 1162, 1163, 1165, 1170, 1171, 1172, 1173, 1176, 1178, 1180, 1181, 1182, 1184, 1185, 1186, 1187, 1188, 1189, 1190, 1191, 1192, 1193, 1194, 1195, 1197, 1198, 1199, 1200, 1201, 1202, 1203, 1206, 1207, 1208, 1209, 1210, 1211, 1212, 1213, 1214, 1215, 1216, 1217, 1218, 1220, 1222, 1223, 2962, 1225, 1226, 1227, 1228, 1229, 1230, 1231, 1232, 1233, 1234, 1235, 1236, 1237, 1240, 1241, 1244, 1245, 1246, 1247, 1248, 1250, 1253, 1254, 1255, 1256, 1257, 1258, 1260, 1261, 1262, 1263, 1264, 1265, 1266, 1267, 1269, 1270, 1271, 1272, 1273, 1274, 1275, 1277, 1278, 1279, 1280, 1281, 1288, 1289, 1290, 1291, 1294, 1296, 1297, 1298, 1299, 1301, 1305, 1306, 1308, 1309, 1310, 1311, 1315, 1316, 1318, 1319, 1320, 1322, 1323, 1324, 1325, 1326, 1327, 1328, 1329, 1330, 1335, 1338, 1339, 1340, 1341, 1344, 1347, 1348, 1356, 1357, 3497, 1361, 1362, 1363, 1364, 1365, 1366, 3564, 1373, 1375, 1380, 1384, 1385, 3038, 1387, 1388, 1389, 1390, 1391, 1392, 1393, 1394, 1395, 1396, 1397, 1398, 1399, 1400, 1401, 1402, 1403, 1404, 1405, 1406, 1407, 1408, 1409, 1410, 1411, 1412, 2965, 1417, 1418, 1419, 1420, 1421, 1422, 1423, 1424, 1425, 1426, 1427, 1428, 1429, 1430, 1431, 1432, 1433, 3082, 3575, 1436, 1438, 1439, 1440, 1441, 1442, 1443, 1444, 1445, 1446, 1447, 1448, 1449, 1450, 1451, 1452, 1453, 1454, 1455, 1456, 1457, 1458, 1459, 1460, 1461, 1462, 1463, 1464, 1465, 1466, 1467, 1468, 1469, 3577, 1473, 1474, 1475, 1477, 1478, 1479, 1480, 1481, 1482, 1483, 1484, 1485, 1486, 1487, 1488, 1489, 1490, 1493, 1494, 3722, 1496, 1497, 1498, 3734, 3740, 1501, 1502, 1503, 1504, 1505, 1507, 1508, 1509, 1510, 1511, 1512, 1513, 1514, 1515, 1516, 1523, 1525, 1526, 1527, 1528, 1529, 1530, 1531, 1532, 1533, 1534, 1535, 1536, 1537, 1538, 1539, 1540, 1541, 1542, 1543, 1544, 1545, 1546, 1547, 1548, 1549, 1550, 1551, 1552, 1553, 1554, 1555, 1556, 1557, 1558, 1559, 1560, 1561, 1562, 1563, 1564, 1565, 1566, 1568, 1569, 1570, 1571, 1573, 1574, 1575, 1576, 1577, 1580, 1581, 1582, 1583, 1584, 1585, 1586, 1587, 1589, 1590, 1591, 1592, 1593, 1594, 1595, 1596, 1597, 1598, 1599, 1600, 1601, 1602, 1603, 1604, 1605, 1606, 1607, 1608, 1609, 1610, 1611, 1612, 1613, 1614, 1615, 1616, 1617, 1618, 1619, 1620, 1622, 1623, 1624, 1625, 1626, 1627, 1628, 1629, 3041, 1631, 1632, 1633, 1634, 1635, 1636, 1637, 1638, 1639, 1640, 1641, 1642, 1643, 1645, 1646, 1647, 1648, 1649, 1650, 1651, 1656, 1657, 1658, 1659, 1660, 1661, 1662, 1663, 3451, 1665, 1666, 1667, 1668, 3452, 1670, 1671, 1672, 1673, 1674, 1675, 1676, 1677, 1678, 1679, 1680, 1681, 2974, 1687, 1689, 1691, 1693, 1697, 1701, 1707, 1709, 1710, 1711, 1713, 1714, 1715, 1716, 1717, 1718, 1720, 1722, 1723, 1724, 1725, 1726, 1728, 1729, 3746, 1731, 1732, 1733, 1734, 1735, 1736, 1737, 1739, 1740, 1742, 1743, 1744, 1745, 1746, 1747, 1748, 1749, 1750, 1751, 1752, 1753, 1754, 1755, 1756, 1757, 1760, 1761, 1762, 1763, 1764, 1765, 1766, 1767, 1768, 1769, 1770, 1771, 1772, 1773, 1774, 1775, 1776, 1777, 1778, 1779, 1780, 1781, 1782, 1783, 1784, 1785, 1786, 1787, 1788, 1789, 1790, 1791, 1792, 1793, 1794, 1795, 1796, 1797, 1798, 1799, 1800, 1801, 1802, 1803, 1804, 1805, 1806, 1807, 1808, 1809, 1810, 1811, 1812, 1813, 1814, 1815, 1816, 1817, 1818, 1819, 1821, 1822, 3017, 1831, 1833, 1837, 2999, 1839, 1840, 3000, 1842, 1843, 1847, 3064, 1849, 1850, 1851, 1852, 1853, 1854, 1855, 1856, 1857, 1859, 1864, 1866, 1867, 1868, 1869, 1870, 1871, 3079, 1873, 1874, 1877, 1878, 1888, 1889, 1893, 1894, 1895, 1896, 1897, 1898, 1899, 1900, 1902, 1903, 1904, 1905, 1906, 1907, 1908, 1909, 1910, 1911, 1912, 1913, 1914, 1915, 1916, 1917, 1922, 1923, 1924, 1925, 1926, 1927, 1928, 1929, 1930, 1931, 1932, 1933, 1934, 1935, 1937, 1938, 1940, 1941, 1951, 1953, 1954, 1957, 1958, 1961, 1962, 1963, 1965, 1966, 1967, 1968, 1969, 1970, 1971, 1972, 1973, 1974, 1975, 1976, 1977, 1978, 1979, 1980, 1981, 1983, 1989, 1990, 1991, 1992, 1996, 3140, 2002, 2003, 2005, 2006, 2007, 2008, 3792, 3793, 2017, 2019, 2020, 2021, 2023, 2024, 2025, 2026, 2027, 2028, 2029, 2030, 2031, 2034, 2035, 2037, 2038, 2041, 2042, 3125, 3126, 3127, 2050, 3353, 2052, 2054, 2055, 2056, 2057, 2058, 2059, 2060, 2061, 2062, 2063, 2064, 2065, 2066, 2069, 2070, 2071, 2072, 2073, 2074, 2078, 2079, 2080, 2081, 2082, 2083, 2084, 2085, 2086, 2087, 2088, 2089, 2090, 2091, 2092, 2093, 2094, 2095, 2097, 2098, 2099, 2100, 2101, 2102, 2103, 2104, 2105, 2107, 2113, 2114, 2115, 2116, 2117, 2118, 2119, 2120, 3067, 2125, 2126, 2127, 2129, 2131, 2132, 2133, 2134, 2990, 3115, 3116, 3117, 3118, 3119, 2141, 2142, 2143, 2145, 2992, 2993, 2983, 2982, 2151, 2984, 2153, 2988, 2155, 3351, 2160, 2164, 2166, 2167, 2168, 2169, 2170, 2171, 2172, 2173, 2174, 2175, 2176, 3018, 2180, 2181, 2182, 2183, 3051, 2185, 2186, 2187, 2188, 2189, 2190, 2191, 2192, 2193, 2196, 3364, 2198, 2199, 2200, 2201, 3033, 2203, 2204, 2205, 2206, 2981, 2208, 3096, 2211, 2215, 2216, 3641, 2218, 2219, 3728, 3729, 2223, 3178, 2226, 3717, 2229, 2230, 2231, 2232, 2233, 3777, 2235, 3148, 2237, 3147, 2239, 2241, 2243, 2244, 2245, 2249, 2252, 2254, 2256, 2257, 2258, 2259, 2260, 2261, 2262, 2263, 2264, 2265, 2266, 2268, 2269, 2270, 3735, 2272, 2273, 2275, 3025, 3023, 3027, 2281, 2283, 2284, 2290, 2291, 2292, 2293, 3063, 2298, 2299, 2301, 2306, 2307, 3007, 3576, 2970, 2969, 2972, 3092, 3095, 2320, 2321, 2323, 2324, 2326, 2327, 2328, 2329, 2330, 2331, 2332, 2333, 2334, 3796, 2338, 2339, 2340, 2341, 2342, 2343, 2344, 2345, 2346, 2347, 2348, 2349, 2350, 2351, 2352, 2357, 2359, 2360, 2361, 2365, 2366, 2369, 2370, 2377, 2378, 2379, 2380, 2381, 2382, 2383, 2384, 2385, 2386, 2387, 2388, 2389, 2391, 2392, 2393, 2394, 2395, 2396, 2418, 2419, 2422, 2423, 2424, 2425, 2426, 2427, 2428, 2438, 2442, 2443, 2444, 2445, 2446, 2447, 2448, 2449, 2450, 2452, 2453, 2454, 2455, 2457, 2458, 2459, 2461, 2464, 2465, 2466, 2469, 2470, 2471, 2472, 2473, 2474, 2475, 2476, 2482, 2483, 2484, 2485, 2486, 2487, 2488, 2489, 2490, 2491, 2492, 2493, 2494, 2495, 2496, 2497, 2498, 2499, 2500, 2501, 2502, 2503, 2504, 2506, 2507, 2508, 2509, 2510, 2511, 2512, 2513, 2514, 2515, 2516, 2517, 2518, 2519, 2520, 2521, 2522, 2523, 2524, 2525, 2526, 2527, 2529, 2530, 2531, 2532, 3129, 2534, 2536, 2537, 2539, 2540, 2541, 2542, 2543, 2544, 2545, 2548, 2549, 2550, 2551, 2554, 2555, 2556, 2557, 2558, 2559, 2560, 2561, 2562, 2570, 2571, 2572, 2573, 2576, 2577, 2578, 2579, 2580, 2581, 2582, 2583, 2584, 2586, 2587, 2588, 2589, 2590, 2591, 2592, 2593, 2594, 2597, 2599, 2600, 2603, 2604, 2605, 2606, 2607, 2608, 2609, 2610, 2611, 2613, 2614, 2616, 2617, 2618, 2619, 2620, 2621, 2622, 2623, 2624, 2625, 2626, 2628, 2630, 2633, 2635, 3725, 2640, 2641, 2642, 2643, 2644, 2645, 2646, 2650, 2651, 2653, 2654, 2655, 2656, 2657, 2658, 2659, 2661, 2662, 2663, 2668, 2669, 2670, 2672, 2673, 2674, 2675, 2677, 2678, 2679, 2680, 2681, 2682, 2683, 2684, 2685, 2686, 2687, 2688, 2689, 3698, 2691, 2692, 2694, 3695, 2696, 2697, 3699, 3696, 2709, 2713, 3706, 3202, 3707, 2717, 3708, 2719, 2721, 3710, 2723, 3711, 2725, 2727, 3715, 3693, 3686, 3694, 2746, 2747, 2749, 2750, 2760, 2761, 2763, 2764, 2765, 2766, 2767, 2768, 2769, 2770, 2771, 2775, 2778, 2781, 2783, 2785, 2791, 2792, 2793, 2794, 2795, 2796, 2797, 2798, 2799, 2800, 2801, 2802, 2803, 3373, 2805, 2806, 2807, 2808, 2809, 2811, 2813, 2814, 3405, 2820, 2821, 2822, 2823, 2824, 2825, 2826, 2827, 2828, 2829, 2830, 2831, 2833, 2834, 2835, 2836, 2839, 2840, 2842, 2843, 2844, 2845, 2997, 2847, 2849, 2850, 2852, 2853, 2854, 2855, 2856, 2858, 2859, 2863, 2866, 2867, 2868, 2870, 2871, 2872, 2874, 2875, 2876, 2877, 2879, 2880, 2883, 2886, 2887, 2888, 2889, 2890, 2892, 2894, 2895, 2897, 2898, 2899, 2900, 2901, 2902, 2903, 2904, 2906, 2907, 2908, 2909, 2910, 2911, 2912, 2913, 2914, 2915, 2916, 2917, 2918, 2919, 2920, 2921, 2922, 2923, 2924, 2925, 2931, 2932, 2933, 2935, 2936, 2937, 2941, 2942, 2943, 2944, 2945, 2949, 2950, 2954, 2955, 2956, 2957, 2958, 2959, 2961, 2966, 2967, 2973, 2978, 2980, 2985, 2986, 2987, 2989, 2991, 2994, 2995, 2996, 2998, 3002, 3009, 3010, 3011, 3012, 3013, 3014, 3015, 3016, 3019, 3020, 3021, 3022, 3026, 3028, 3029, 3030, 3031, 3035, 3036, 3040, 3042, 3043, 3044, 3046, 3047, 3048, 3049, 3050, 3053, 3054, 3055, 3056, 3057, 3058, 3059, 3060, 3061, 3068, 3069, 3070, 3071, 3076, 3077, 3078, 3080, 3084, 3085, 3086, 3087, 3088, 3091, 3093, 3094, 3097, 3098, 3099, 3100, 3101, 3102, 3103, 3104, 3105, 3107, 3109, 3110, 3111, 3112, 3113, 3114, 3120, 3121, 3122, 3123, 3124, 3128, 3130, 3131, 3132, 3133, 3134, 3135, 3136, 3138, 3139, 3142, 3144, 3145, 3146, 3149, 3154, 3155, 3156, 3158, 3161, 3163, 3164, 3166, 3167, 3168, 3170, 3171, 3172, 3174, 3175, 3176, 3177, 3181, 3186, 3191, 3192, 3193, 3194, 3195, 3196, 3197, 3199, 3204, 3205, 3206, 3207, 3208, 3209, 3210, 3211, 3212, 3213, 3214, 3215, 3216, 3219, 3220, 3223, 3224, 3225, 3226, 3227, 3228, 3229, 3230, 3233, 3234, 3235, 3236, 3237, 3238, 3239, 3240, 3241, 3242, 3243, 3246, 3247, 3249, 3250, 3251, 3252, 3253, 3254, 3255, 3256, 3257, 3258, 3259, 3260, 3261, 3262, 3263, 3264, 3265, 3266, 3267, 3268, 3269, 3270, 3271, 3272, 3273, 3274, 3275, 3278, 3279, 3280, 3281, 3282, 3283, 3284, 3285, 3286, 3287, 3289, 3290, 3291, 3292, 3293, 3294, 3295, 3296, 3297, 3298, 3299, 3300, 3301, 3302, 3303, 3304, 3305, 3306, 3307, 3308, 3309, 3310, 3311, 3312, 3313, 3314, 3315, 3316, 3317, 3318, 3319, 3320, 3321, 3324, 3325, 3326, 3327, 3328, 3329, 3330, 3331, 3332, 3333, 3334, 3335, 3336, 3337, 3338, 3339, 3340, 3341, 3342, 3343, 3344, 3345, 3347, 3348, 3352, 3354, 3355, 3356, 3358, 3359, 3360, 3363, 3365, 3366, 3367, 3368, 3369, 3372, 3374, 3377, 3379, 3380, 3385, 3386, 3387, 3388, 3391, 3398, 3399, 3400, 3401, 3402, 3403, 3406, 3407, 3408, 3409, 3412, 3413, 3414, 3415, 3416, 3417, 3418, 3419, 3420, 3421, 3423, 3424, 3425, 3426, 3427, 3428, 3430, 3431, 3433, 3434, 3435, 3436, 3437, 3443, 3444, 3445, 3446, 3447, 3448, 3449, 3450, 3453, 3456, 3459, 3460, 3461, 3462, 3463, 3464, 3465, 3466, 3467, 3468, 3469, 3470, 3471, 3472, 3473, 3474, 3475, 3476, 3477, 3479, 3480, 3481, 3482, 3483, 3484, 3485, 3487, 3488, 3489, 3490, 3491, 3492, 3493, 3494, 3496, 3501, 3507, 3509, 3510, 3511, 3512, 3513, 3514, 3515, 3516, 3517, 3518, 3519, 3520, 3521, 3522, 3523, 3525, 3526, 3527, 3528, 3529, 3530, 3534, 3535, 3539, 3540, 3546, 3547, 3548, 3549, 3550, 3551, 3552, 3553, 3554, 3556, 3557, 3558, 3559, 3562, 3563, 3565, 3566, 3578, 3579, 3580, 3581, 3582, 3583, 3584, 3585, 3586, 3587, 3588, 3589, 3590, 3591, 3592, 3593, 3594, 3595, 3597, 3598, 3599, 3603, 3604, 3605, 3606, 3612, 3613, 3614, 3615, 3619, 3621, 3622, 3623, 3625, 3628, 3629, 3633, 3640, 3642, 3645, 3647, 3648, 3649, 3650, 3651, 3652, 3654, 3655, 3656, 3657, 3658, 3659, 3660, 3661, 3662, 3663, 3664, 3665, 3666, 3667, 3668, 3669, 3670, 3671, 3672, 3673, 3674, 3675, 3676, 3677, 3678, 3679, 3680, 3681, 3682, 3683, 3684, 3685, 3703, 3718, 3721, 3723, 3724, 3726, 3730, 3732, 3736, 3745, 3748, 3749, 3750, 3751, 3752, 3753, 3755, 3761, 3762, 3765, 3768, 3770, 3771, 3772, 3773, 3774, 3775, 3778, 3781, 3783, 3787, 3788, 3789, 3790, 3791, 3794, 3795, 3797, 3798, 3800, 3801, 3802, 3803, 3804, 3805, 3806, 3807, 3809, 3810, 3811, 3812, 3813, 3814, 3815, 3816, 3817, 3818, 3819, 3820, 3821, 3822, 3823, 3824, 3825, 3826, 3829, 3831, 3833, 3842, 3843, 3845, 3846, 3855, 3861, 3867, 3876, 3878, 3879, 3880, 3881, 3884, 3885, 3887, 3893, 3897, 3901, 3906, 3907, 3909, 3910, 3911, 3913, 3914, 3915, 3920, 3921, 3922, 3923, 3924, 3925, 3926, 3927, 3928, 3931, 3932, 3933, 3978, 3979, 3984, 3986, 3987, 3989, 3995, 3998, 4013, 4014, 4015, 4016, 4017, 4018, 4020, 4021, 4023, 4024, 4026, 4028, 4029, 4042, 4045, 4046, 4048, 4049, 4053, 4058, 4061, 4062, 4064, 4065, 4071, 4073, 4074, 4077, 4079, 4084, 4085, 4086, 4091, 4102, 4125, 4141, 4149, 4158, 4159, 4163, 4168, 4184, 4185, 4186, 4187, 4189, 4191, 4192, 4194, 4197, 4201, 4204, 4207, 4208, 4209, 4210, 4214, 4215, 4216, 4217, 4220, 4221, 4222, 4223, 4224, 4225, 4226, 4227, 4228, 4229, 4230, 4231, 4232, 4233, 4234, 4235, 4236, 4237, 4238, 4239, 4240, 4241, 4242, 4243, 4251, 4254, 4255, 4261, 4266, 4267, 4268, 4269, 4273, 4277, 4279, 4280, 4281, 4282, 4283, 4284, 4285, 4286, 4288, 4289, 4290, 4291, 4293, 4294, 4295, 4296, 4297, 4298, 4299, 4309, 4321, 4322, 4324, 4325, 4326, 4327, 4331, 4332, 4333, 4334, 4335, 4336, 4338, 4339, 4340, 4346, 4347, 4348, 4349, 4350, 4351, 4355, 4359, 4360, 4362, 4363, 4364, 4365, 4366, 4368, 4378, 4380, 4385, 4386, 4387, 4388, 4389, 4390, 4391, 4392, 4393, 4394, 4395, 4396, 4397, 4398, 4399, 4400, 4402, 4403, 4404, 4405, 4406, 4407, 4408, 4413, 4416, 4417, 4418, 4419, 4420, 4421, 4422, 4423, 4424, 4425, 4426, 4427, 4428, 4429, 4430, 4431, 4432, 4433, 4434, 4435, 4436, 4438, 4439, 4440, 4442, 4443, 4444, 4445, 4448, 4449, 4450, 4452, 4453, 4454, 4456, 4457, 4458, 4459, 4460, 4461, 4463, 4465, 4468, 4469, 4470, 4471, 4473, 4474, 4475, 4476, 4477, 4478, 4479, 4480, 4481, 4482, 4483, 4487, 4489, 4490, 4491, 4492, 4493, 4497, 4498, 4502, 4503, 4504, 4506, 4508, 4509, 4510, 4511, 4512, 4513, 4514, 4516, 4517, 4518, 4519, 4520, 4521, 4522, 4529, 4530, 4531, 4532, 4533, 4534, 4535, 4536, 4537, 4538, 4539, 4540, 4546, 4547, 4549, 4550, 4551, 4552, 4553, 4554, 4555, 4556, 4557, 4558, 4559, 4560, 4561, 4562, 4563, 4564, 4568, 4569, 4570, 4571, 4572, 4573, 4574, 4575, 4576, 4581, 4582, 4585, 4586, 4587, 4588, 4589, 4590, 4591, 4592, 4593, 4594, 4595, 4596, 4597, 4598, 4600, 4601, 4602, 4603, 4612, 4613, 4614, 4615, 4616, 4617, 4619, 4622, 4623, 4624, 4626, 4627, 4628, 4629, 4630, 4631, 4632, 4633, 4634, 4635, 4636, 4637, 4638, 4639, 4640, 4641, 4642, 4643, 4644, 4645, 4646, 4647, 4648, 4649, 4650, 4651, 4652, 4653, 4654, 4655, 4656, 4657, 4658, 4659, 4660, 4661, 4662, 4663, 4664, 4665, 4666, 4667, 4668, 4669, 4670, 4671, 4672, 4673, 4674, 4675, 4676, 4677, 4678, 4679, 4680, 4681, 4682, 4683, 4684, 4685, 4686, 4687, 4688, 4689, 4690, 4691, 4692, 4693, 4694, 4695, 4696, 4697, 4698, 4699, 4700, 4701, 4702, 4703, 4704, 4705, 4706, 4707, 4708, 4709, 4710, 4711, 4712, 4713, 4714, 4715, 4716, 4717, 4718, 4719, 4720, 4721, 4722, 4723, 4724, 4725, 4726, 4727, 4732, 4733, 4734, 4740, 4753, 4757, 4758, 4759, 4760, 4761, 4762, 4763, 4764, 4765, 4766, 4767, 4768, 4769, 4770, 4771, 4772, 4774, 4775, 4776, 4777, 4778, 4780, 4781, 4782, 4783, 4784, 4785, 4786, 4789, 4790, 4792, 4793, 4794, 4797, 4798, 4799, 4800, 4801, 4802, 4803, 4804, 4805, 4806, 4807, 4808, 4809, 4810, 4811, 4812, 4813, 4814, 4815, 4816, 4817, 4818, 4819, 4820, 4821, 4822, 4823, 4825, 4826, 4827, 4828, 4829, 4830, 4831, 4832, 4833, 4834, 4835, 4836, 4837, 4838, 4839, 4840, 4841, 4842, 4843, 4844, 4845, 4846, 4847, 4848, 4849, 4850, 4851, 4852, 4853, 4854, 4855, 4856, 4858, 4859, 4860, 4862, 4864, 4866, 4867, 4868, 4869, 4872, 4874, 4875, 4876, 4877, 4879, 4880, 4881, 4882, 4883, 4884, 4885, 4886, 4889, 4893, 4894) } + internal val exactKey: IntArray by lazy { intArrayOf(0, 1, 2, 3, 4, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 3152, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 43, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 3720, 61, 62, 63, 64, 66, 68, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 84, 85, 3759, 87, 88, 98, 99, 3081, 3758, 102, 103, 105, 106, 107, 109, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 155, 156, 157, 159, 161, 162, 163, 3201, 165, 166, 3203, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 3162, 183, 187, 189, 193, 194, 195, 197, 198, 199, 200, 201, 202, 206, 209, 213, 215, 216, 217, 219, 220, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 234, 235, 2968, 237, 238, 239, 240, 3719, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255, 256, 260, 262, 263, 264, 265, 266, 267, 270, 271, 272, 273, 275, 279, 280, 281, 282, 286, 287, 289, 290, 291, 292, 293, 294, 295, 296, 297, 298, 300, 301, 3173, 305, 306, 307, 308, 309, 310, 311, 313, 314, 315, 317, 319, 333, 3767, 336, 3766, 3769, 340, 3779, 342, 343, 344, 345, 354, 3150, 357, 358, 359, 360, 361, 362, 363, 364, 365, 366, 367, 368, 369, 370, 371, 372, 373, 2971, 376, 377, 378, 379, 380, 381, 382, 383, 384, 385, 386, 387, 388, 389, 390, 391, 392, 393, 394, 395, 396, 397, 398, 399, 400, 401, 402, 403, 404, 405, 406, 407, 408, 409, 410, 411, 412, 413, 414, 415, 416, 417, 419, 420, 421, 422, 423, 424, 425, 426, 427, 428, 429, 2963, 2964, 432, 433, 434, 435, 436, 437, 438, 439, 440, 441, 442, 443, 444, 445, 446, 447, 448, 449, 450, 451, 453, 454, 455, 3180, 457, 458, 459, 460, 461, 2953, 463, 464, 465, 3083, 467, 468, 469, 470, 471, 472, 473, 474, 475, 476, 477, 478, 479, 480, 481, 482, 483, 484, 485, 486, 487, 488, 489, 490, 491, 492, 493, 494, 495, 496, 497, 498, 499, 500, 501, 502, 503, 504, 505, 506, 507, 508, 509, 510, 511, 512, 513, 514, 515, 516, 517, 518, 519, 520, 521, 522, 523, 524, 525, 526, 527, 528, 529, 530, 531, 532, 533, 534, 535, 536, 537, 538, 539, 540, 541, 542, 543, 544, 545, 546, 547, 548, 549, 550, 551, 552, 553, 554, 556, 557, 558, 559, 560, 561, 562, 563, 565, 566, 567, 568, 569, 570, 571, 572, 573, 574, 575, 576, 577, 578, 592, 628, 629, 630, 3188, 3189, 636, 637, 638, 639, 640, 641, 642, 643, 644, 645, 646, 647, 651, 652, 3832, 654, 656, 657, 659, 663, 664, 665, 666, 667, 668, 669, 670, 671, 672, 673, 674, 675, 676, 677, 678, 680, 681, 682, 683, 684, 686, 687, 689, 690, 692, 693, 694, 695, 698, 704, 724, 728, 729, 730, 731, 732, 3764, 734, 735, 736, 737, 3187, 739, 740, 741, 742, 743, 744, 745, 746, 747, 748, 749, 750, 751, 752, 753, 754, 755, 756, 757, 758, 759, 760, 761, 762, 763, 764, 765, 766, 767, 768, 769, 770, 771, 772, 773, 774, 775, 776, 777, 778, 779, 780, 781, 782, 783, 784, 785, 786, 787, 788, 789, 790, 791, 792, 793, 794, 795, 796, 797, 798, 799, 800, 801, 802, 803, 3747, 805, 806, 807, 808, 809, 810, 811, 812, 813, 814, 815, 816, 817, 818, 819, 820, 821, 822, 823, 824, 825, 826, 827, 828, 829, 832, 833, 834, 835, 836, 837, 838, 839, 840, 841, 843, 844, 845, 847, 848, 3183, 850, 852, 853, 854, 857, 858, 859, 860, 861, 862, 863, 864, 865, 866, 867, 3757, 869, 870, 871, 872, 873, 874, 875, 876, 877, 878, 879, 880, 881, 882, 883, 884, 885, 886, 887, 888, 889, 890, 891, 892, 893, 894, 895, 896, 897, 898, 899, 900, 901, 3834, 903, 904, 907, 908, 909, 910, 911, 912, 913, 914, 915, 916, 917, 918, 919, 920, 921, 922, 923, 924, 925, 926, 927, 928, 929, 930, 931, 932, 933, 934, 935, 936, 937, 938, 939, 940, 941, 942, 943, 944, 945, 946, 947, 948, 949, 950, 951, 952, 953, 954, 955, 956, 957, 958, 959, 960, 961, 962, 3153, 964, 965, 966, 967, 968, 969, 3782, 971, 3008, 3065, 974, 975, 976, 978, 979, 987, 988, 989, 991, 992, 993, 995, 996, 997, 998, 999, 1000, 1001, 1002, 1003, 1005, 1006, 1007, 1008, 1009, 1010, 1011, 1012, 1013, 1014, 1015, 1016, 1017, 1018, 3785, 1020, 1021, 1022, 1025, 1029, 1030, 1031, 2960, 3034, 1034, 1035, 1036, 1037, 1038, 1039, 1040, 1041, 1042, 1043, 1045, 1046, 1049, 1050, 1051, 1052, 1053, 1054, 1055, 1056, 1057, 1058, 1059, 1060, 1061, 1062, 1063, 1064, 1065, 1066, 1067, 1068, 1069, 1070, 1071, 1072, 1074, 1082, 1083, 1086, 1087, 1088, 1090, 1091, 1092, 3799, 1094, 1095, 1098, 1099, 1100, 3182, 1102, 1103, 1104, 1105, 1106, 1107, 1108, 1110, 1111, 1112, 1113, 1114, 1115, 1116, 3784, 1120, 1123, 1124, 1125, 1127, 1128, 1129, 1130, 1131, 1132, 1133, 1134, 1135, 1136, 1137, 1138, 1139, 1140, 1141, 1142, 1143, 1144, 1145, 1146, 1150, 1151, 1152, 1153, 1154, 1155, 1158, 1162, 1163, 1165, 1170, 1171, 1172, 1173, 1176, 1178, 1180, 1181, 1182, 1184, 1185, 1186, 1187, 1188, 1189, 1190, 1191, 1192, 1193, 1194, 1195, 1197, 1198, 1199, 1200, 1201, 1202, 1203, 1206, 1207, 1208, 1209, 1210, 1211, 1212, 1213, 1214, 1215, 1216, 1217, 1218, 1220, 1222, 1223, 2962, 1225, 1226, 1227, 1228, 1229, 1230, 1231, 1232, 1233, 1234, 1235, 1236, 1237, 1240, 1241, 1244, 1245, 1246, 1247, 1248, 1250, 1253, 1254, 1255, 1256, 1257, 1258, 1260, 1261, 1262, 1263, 1264, 1265, 1266, 1267, 1269, 1270, 1271, 1272, 1273, 1274, 1275, 1277, 1278, 1279, 1280, 1281, 1288, 1289, 1290, 1291, 1294, 1296, 1297, 1298, 1299, 1301, 1305, 1306, 1308, 1309, 1310, 1311, 1315, 1316, 1318, 1319, 1320, 1322, 1323, 1324, 1325, 1326, 1327, 1328, 1329, 1330, 1335, 1338, 1339, 1340, 1341, 1344, 1347, 1348, 1356, 1357, 3497, 1361, 1362, 1363, 1364, 1365, 1366, 3564, 1373, 1375, 1380, 1384, 1385, 3038, 1387, 1388, 1389, 1390, 1391, 1392, 1393, 1394, 1395, 1396, 1397, 1398, 1399, 1400, 1401, 1402, 1403, 1404, 1405, 1406, 1407, 1408, 1409, 1410, 1411, 1412, 2965, 1417, 1418, 1419, 1420, 1421, 1422, 1423, 1424, 1425, 1426, 1427, 1428, 1429, 1430, 1431, 1432, 1433, 3082, 3575, 1436, 1438, 1439, 1440, 1441, 1442, 1443, 1444, 1445, 1446, 1447, 1448, 1449, 1450, 1451, 1452, 1453, 1454, 1455, 1456, 1457, 1458, 1459, 1460, 1461, 1462, 1463, 1464, 1465, 1466, 1467, 1468, 1469, 3577, 1473, 1474, 1475, 1477, 1478, 1479, 1480, 1481, 1482, 1483, 1484, 1485, 1486, 1487, 1488, 1489, 1490, 1493, 1494, 3722, 1496, 1497, 1498, 3734, 3740, 1501, 1502, 1503, 1504, 1505, 1507, 1508, 1509, 1510, 1511, 1512, 1513, 1514, 1515, 1516, 1523, 1525, 1526, 1527, 1528, 1529, 1530, 1531, 1532, 1533, 1534, 1535, 1536, 1537, 1538, 1539, 1540, 1541, 1542, 1543, 1544, 1545, 1546, 1547, 1548, 1549, 1550, 1551, 1552, 1553, 1554, 1555, 1556, 1557, 1558, 1559, 1560, 1561, 1562, 1563, 1564, 1565, 1566, 1568, 1569, 1570, 1571, 1573, 1574, 1575, 1576, 1577, 1580, 1581, 1582, 1583, 1584, 1585, 1586, 1587, 1589, 1590, 1591, 1592, 1593, 1594, 1595, 1596, 1597, 1598, 1599, 1600, 1601, 1602, 1603, 1604, 1605, 1606, 1607, 1608, 1609, 1610, 1611, 1612, 1613, 1614, 1615, 1616, 1617, 1618, 1619, 1620, 1622, 1623, 1624, 1625, 1626, 1627, 1628, 1629, 3041, 1631, 1632, 1633, 1634, 1635, 1636, 1637, 1638, 1639, 1640, 1641, 1642, 1643, 1645, 1646, 1647, 1648, 1649, 1650, 1651, 1656, 1657, 1658, 1659, 1660, 1661, 1662, 1663, 3451, 1665, 1666, 1667, 1668, 3452, 1670, 1671, 1672, 1673, 1674, 1675, 1676, 1677, 1678, 1679, 1680, 1681, 2974, 1687, 1689, 1691, 1693, 1697, 1701, 1707, 1709, 1710, 1711, 1713, 1714, 1715, 1716, 1717, 1718, 1720, 1722, 1723, 1724, 1725, 1726, 1728, 1729, 3746, 1731, 1732, 1733, 1734, 1735, 1736, 1737, 1739, 1740, 1742, 1743, 1744, 1745, 1746, 1747, 1748, 1749, 1750, 1751, 1752, 1753, 1754, 1755, 1756, 1757, 1760, 1761, 1762, 1763, 1764, 1765, 1766, 1767, 1768, 1769, 1770, 1771, 1772, 1773, 1774, 1775, 1776, 1777, 1778, 1779, 1780, 1781, 1782, 1783, 1784, 1785, 1786, 1787, 1788, 1789, 1790, 1791, 1792, 1793, 1794, 1795, 1796, 1797, 1798, 1799, 1800, 1801, 1802, 1803, 1804, 1805, 1806, 1807, 1808, 1809, 1810, 1811, 1812, 1813, 1814, 1815, 1816, 1817, 1818, 1819, 1821, 1822, 3017, 1831, 1833, 1837, 2999, 1839, 1840, 3000, 1842, 1843, 1847, 3064, 1849, 1850, 1851, 1852, 1853, 1854, 1855, 1856, 1857, 1859, 1864, 1866, 1867, 1868, 1869, 1870, 1871, 3079, 1873, 1874, 1877, 1878, 1888, 1889, 1893, 1894, 1895, 1896, 1897, 1898, 1899, 1900, 1902, 1903, 1904, 1905, 1906, 1907, 1908, 1909, 1910, 1911, 1912, 1913, 1914, 1915, 1916, 1917, 1922, 1923, 1924, 1925, 1926, 1927, 1928, 1929, 1930, 1931, 1932, 1933, 1934, 1935, 1937, 1938, 1940, 1941, 1951, 1953, 1954, 1957, 1958, 1961, 1962, 1963, 1965, 1966, 1967, 1968, 1969, 1970, 1971, 1972, 1973, 1974, 1975, 1976, 1977, 1978, 1979, 1980, 1981, 1983, 1989, 1990, 1991, 1992, 1996, 3140, 2002, 2003, 2005, 2006, 2007, 2008, 3792, 3793, 2017, 2019, 2020, 2021, 2023, 2024, 2025, 2026, 2027, 2028, 2029, 2030, 2031, 2034, 2035, 2037, 2038, 2041, 2042, 3125, 3126, 3127, 2050, 3353, 2052, 2054, 2055, 2056, 2057, 2058, 2059, 2060, 2061, 2062, 2063, 2064, 2065, 2066, 2069, 2070, 2071, 2072, 2073, 2074, 2078, 2079, 2080, 2081, 2082, 2083, 2084, 2085, 2086, 2087, 2088, 2089, 2090, 2091, 2092, 2093, 2094, 2095, 2097, 2098, 2099, 2100, 2101, 2102, 2103, 2104, 2105, 2107, 2113, 2114, 2115, 2116, 2117, 2118, 2119, 2120, 3067, 2125, 2126, 2127, 2129, 2131, 2132, 2133, 2134, 2990, 3115, 3116, 3117, 3118, 3119, 2141, 2142, 2143, 2145, 2992, 2993, 2983, 2982, 2151, 2984, 2153, 2988, 2155, 3351, 2160, 2164, 2166, 2167, 2168, 2169, 2170, 2171, 2172, 2173, 2174, 2175, 2176, 3018, 2180, 2181, 2182, 2183, 3051, 2185, 2186, 2187, 2188, 2189, 2190, 2191, 2192, 2193, 2196, 3364, 2198, 2199, 2200, 2201, 3033, 2203, 2204, 2205, 2206, 2981, 2208, 3096, 2211, 2215, 2216, 3641, 2218, 2219, 3728, 3729, 2223, 3178, 2226, 3717, 2229, 2230, 2231, 2232, 2233, 3777, 2235, 3148, 2237, 3147, 2239, 2241, 2243, 2244, 2245, 2249, 2252, 2254, 2256, 2257, 2258, 2259, 2260, 2261, 2262, 2263, 2264, 2265, 2266, 2268, 2269, 2270, 3735, 2272, 2273, 2275, 3025, 3023, 3027, 2281, 2283, 2284, 2290, 2291, 2292, 2293, 3063, 2298, 2299, 2301, 2306, 2307, 3007, 3576, 2970, 2969, 2972, 3092, 3095, 2320, 2321, 2323, 2324, 2326, 2327, 2328, 2329, 2330, 2331, 2332, 2333, 2334, 3796, 2338, 2339, 2340, 2341, 2342, 2343, 2344, 2345, 2346, 2347, 2348, 2349, 2350, 2351, 2352, 2357, 2359, 2360, 2361, 2365, 2366, 2369, 2370, 2377, 2378, 2379, 2380, 2381, 2382, 2383, 2384, 2385, 2386, 2387, 2388, 2389, 2391, 2392, 2393, 2394, 2395, 2396, 2418, 2419, 2422, 2423, 2424, 2425, 2426, 2427, 2428, 2438, 2442, 2443, 2444, 2445, 2446, 2447, 2448, 2449, 2450, 2452, 2453, 2454, 2455, 2457, 2458, 2459, 2461, 2464, 2465, 2466, 2469, 2470, 2471, 2472, 2473, 2474, 2475, 2476, 2482, 2483, 2484, 2485, 2486, 2487, 2488, 2489, 2490, 2491, 2492, 2493, 2494, 2495, 2496, 2497, 2498, 2499, 2500, 2501, 2502, 2503, 2504, 2506, 2507, 2508, 2509, 2510, 2511, 2512, 2513, 2514, 2515, 2516, 2517, 2518, 2519, 2520, 2521, 2522, 2523, 2524, 2525, 2526, 2527, 2529, 2530, 2531, 2532, 3129, 2534, 2536, 2537, 2539, 2540, 2541, 2542, 2543, 2544, 2545, 2548, 2549, 2550, 2551, 2554, 2555, 2556, 2557, 2558, 2559, 2560, 2561, 2562, 2570, 2571, 2572, 2573, 2576, 2577, 2578, 2579, 2580, 2581, 2582, 2583, 2584, 2586, 2587, 2588, 2589, 2590, 2591, 2592, 2593, 2594, 2597, 2599, 2600, 2603, 2604, 2605, 2606, 2607, 2608, 2609, 2610, 2611, 2613, 2614, 2616, 2617, 2618, 2619, 2620, 2621, 2622, 2623, 2624, 2625, 2626, 2628, 2630, 2633, 2635, 3725, 2640, 2641, 2642, 2643, 2644, 2645, 2646, 2650, 2651, 2653, 2654, 2655, 2656, 2657, 2658, 2659, 2661, 2662, 2663, 2668, 2669, 2670, 2672, 2673, 2674, 2675, 2677, 2678, 2679, 2680, 2681, 2682, 2683, 2684, 2685, 2686, 2687, 2688, 2689, 3698, 2691, 2692, 2694, 3695, 2696, 2697, 3699, 3696, 2709, 2713, 3706, 3202, 3707, 2717, 3708, 2719, 2721, 3710, 2723, 3711, 2725, 2727, 3715, 3693, 3686, 3694, 2746, 2747, 2749, 2750, 2760, 2761, 2763, 2764, 2765, 2766, 2767, 2768, 2769, 2770, 2771, 2775, 2778, 2781, 2783, 2785, 2791, 2792, 2793, 2794, 2795, 2796, 2797, 2798, 2799, 2800, 2801, 2802, 2803, 3373, 2805, 2806, 2807, 2808, 2809, 2811, 2813, 2814, 3405, 2820, 2821, 2822, 2823, 2824, 2825, 2826, 2827, 2828, 2829, 2830, 2831, 2833, 2834, 2835, 2836, 2839, 2840, 2842, 2843, 2844, 2845, 2997, 2847, 2849, 2850, 2852, 2853, 2854, 2855, 2856, 2858, 2859, 2863, 2866, 2867, 2868, 2870, 2871, 2872, 2874, 2875, 2876, 2877, 2879, 2880, 2883, 2886, 2887, 2888, 2889, 2890, 2892, 2894, 2895, 2897, 2898, 2899, 2900, 2901, 2902, 2903, 2904, 2906, 2907, 2908, 2909, 2910, 2911, 2912, 2913, 2914, 2915, 2916, 2917, 2918, 2919, 2920, 2921, 2922, 2923, 2924, 2925, 2931, 2932, 2933, 2935, 2936, 2937, 2941, 2942, 2943, 2944, 2945, 2949, 2950, 2954, 2955, 2956, 2957, 2958, 2959, 2961, 2966, 2967, 2973, 2978, 2980, 2985, 2986, 2987, 2989, 2991, 2994, 2995, 2996, 2998, 3002, 3009, 3010, 3011, 3012, 3013, 3014, 3015, 3016, 3019, 3020, 3021, 3022, 3026, 3028, 3029, 3030, 3031, 3035, 3036, 3040, 3042, 3043, 3044, 3046, 3047, 3048, 3049, 3050, 3053, 3054, 3055, 3056, 3057, 3058, 3059, 3060, 3061, 3068, 3069, 3070, 3071, 3076, 3077, 3078, 3080, 3084, 3085, 3086, 3087, 3088, 3091, 3093, 3094, 3097, 3098, 3099, 3100, 3101, 3102, 3103, 3104, 3105, 3107, 3109, 3110, 3111, 3112, 3113, 3114, 3120, 3121, 3122, 3123, 3124, 3128, 3130, 3131, 3132, 3133, 3134, 3135, 3136, 3138, 3139, 3142, 3144, 3145, 3146, 3149, 3154, 3155, 3156, 3158, 3161, 3163, 3164, 3166, 3167, 3168, 3170, 3171, 3172, 3174, 3175, 3176, 3177, 3181, 3186, 3191, 3192, 3193, 3194, 3195, 3196, 3197, 3199, 3204, 3205, 3206, 3207, 3208, 3209, 3210, 3211, 3212, 3213, 3214, 3215, 3216, 3219, 3220, 3223, 3224, 3225, 3226, 3227, 3228, 3229, 3230, 3233, 3234, 3235, 3236, 3237, 3238, 3239, 3240, 3241, 3242, 3243, 3246, 3247, 3249, 3250, 3251, 3252, 3253, 3254, 3255, 3256, 3257, 3258, 3259, 3260, 3261, 3262, 3263, 3264, 3265, 3266, 3267, 3268, 3269, 3270, 3271, 3272, 3273, 3274, 3275, 3278, 3279, 3280, 3281, 3282, 3283, 3284, 3285, 3286, 3287, 3289, 3290, 3291, 3292, 3293, 3294, 3295, 3296, 3297, 3298, 3299, 3300, 3301, 3302, 3303, 3304, 3305, 3306, 3307, 3308, 3309, 3310, 3311, 3312, 3313, 3314, 3315, 3316, 3317, 3318, 3319, 3320, 3321, 3324, 3325, 3326, 3327, 3328, 3329, 3330, 3331, 3332, 3333, 3334, 3335, 3336, 3337, 3338, 3339, 3340, 3341, 3342, 3343, 3344, 3345, 3347, 3348, 3352, 3354, 3355, 3356, 3358, 3359, 3360, 3363, 3365, 3366, 3367, 3368, 3369, 3372, 3374, 3377, 3379, 3380, 3385, 3386, 3387, 3388, 3391, 3398, 3399, 3400, 3401, 3402, 3403, 3406, 3407, 3408, 3409, 3412, 3413, 3414, 3415, 3416, 3417, 3418, 3419, 3420, 3421, 3423, 3424, 3425, 3426, 3427, 3428, 3430, 3431, 3433, 3434, 3435, 3436, 3437, 3443, 3444, 3445, 3446, 3447, 3448, 3449, 3450, 3453, 3456, 3459, 3460, 3461, 3462, 3463, 3464, 3465, 3466, 3467, 3468, 3469, 3470, 3471, 3472, 3473, 3474, 3475, 3476, 3477, 3479, 3480, 3481, 3482, 3483, 3484, 3485, 3487, 3488, 3489, 3490, 3491, 3492, 3493, 3494, 3496, 3501, 3507, 3509, 3510, 3511, 3512, 3513, 3514, 3515, 3516, 3517, 3518, 3519, 3520, 3521, 3522, 3523, 3525, 3526, 3527, 3528, 3529, 3530, 3534, 3535, 3539, 3540, 3546, 3547, 3548, 3549, 3550, 3551, 3552, 3553, 3554, 3556, 3557, 3558, 3559, 3562, 3563, 3565, 3566, 3578, 3579, 3580, 3581, 3582, 3583, 3584, 3585, 3586, 3587, 3588, 3589, 3590, 3591, 3592, 3593, 3594, 3595, 3597, 3598, 3599, 3603, 3604, 3605, 3606, 3612, 3613, 3614, 3615, 3619, 3621, 3622, 3623, 3625, 3628, 3629, 3633, 3640, 3642, 3645, 3647, 3648, 3649, 3650, 3651, 3652, 3654, 3655, 3656, 3657, 3658, 3659, 3660, 3661, 3662, 3663, 3664, 3665, 3666, 3667, 3668, 3669, 3670, 3671, 3672, 3673, 3674, 3675, 3676, 3677, 3678, 3679, 3680, 3681, 3682, 3683, 3684, 3685, 3703, 3718, 3721, 3723, 3724, 3726, 3730, 3732, 3736, 3745, 3748, 3749, 3750, 3751, 3752, 3753, 3755, 3761, 3762, 3765, 3768, 3770, 3771, 3772, 3773, 3774, 3775, 3778, 3781, 3783, 3787, 3788, 3789, 3790, 3791, 3794, 3795, 3797, 3798, 3800, 3801, 3802, 3803, 3804, 3805, 3806, 3807, 3809, 3810, 3811, 3812, 3813, 3814, 3815, 3816, 3817, 3818, 3819, 3820, 3821, 3822, 3823, 3824, 3825, 3826, 3829, 3831, 3833, 3842, 3843, 3845, 3846, 3855, 3861, 3867, 3876, 3878, 3879, 3880, 3881, 3884, 3885, 3887, 3893, 3897, 3901, 3906, 3907, 3909, 3910, 3911, 3913, 3914, 3915, 3920, 3921, 3922, 3923, 3924, 3925, 3926, 3927, 3928, 3931, 3932, 3933, 3978, 3979, 3984, 3986, 3987, 3989, 3995, 3998, 4013, 4014, 4015, 4016, 4017, 4018, 4020, 4021, 4023, 4024, 4026, 4028, 4029, 4042, 4045, 4046, 4048, 4049, 4053, 4058, 4061, 4062, 4064, 4065, 4071, 4073, 4074, 4077, 4079, 4084, 4085, 4086, 4091, 4102, 4125, 4141, 4149, 4158, 4159, 4163, 4168, 4184, 4185, 4186, 4187, 4189, 4191, 4192, 4194, 4197, 4201, 4204, 4207, 4208, 4209, 4210, 4214, 4215, 4216, 4217, 4220, 4221, 4222, 4223, 4224, 4225, 4226, 4227, 4228, 4229, 4230, 4231, 4232, 4233, 4234, 4235, 4236, 4237, 4238, 4239, 4240, 4241, 4242, 4243, 4251, 4254, 4255, 4261, 4266, 4267, 4268, 4269, 4273, 4277, 4279, 4280, 4281, 4282, 4283, 4284, 4285, 4286, 4288, 4289, 4290, 4291, 4293, 4294, 4295, 4296, 4297, 4298, 4299, 4309, 4321, 4322, 4324, 4325, 4326, 4327, 4331, 4332, 4333, 4334, 4335, 4336, 4338, 4339, 4340, 4346, 4347, 4348, 4349, 4350, 4351, 4355, 4359, 4360, 4362, 4363, 4364, 4365, 4366, 4368, 4378, 4380, 4385, 4386, 4387, 4388, 4389, 4390, 4391, 4392, 4393, 4394, 4395, 4396, 4397, 4398, 4399, 4400, 4402, 4403, 4404, 4405, 4406, 4407, 4408, 4413, 4416, 4417, 4418, 4419, 4420, 4421, 4422, 4423, 4424, 4425, 4426, 4427, 4428, 4429, 4430, 4431, 4432, 4433, 4434, 4435, 4436, 4438, 4439, 4440, 4442, 4443, 4444, 4445, 4448, 4449, 4450, 4452, 4453, 4454, 4456, 4457, 4458, 4459, 4460, 4461, 4463, 4465, 4468, 4469, 4470, 4471, 4473, 4474, 4475, 4476, 4477, 4478, 4479, 4480, 4481, 4482, 4483, 4487, 4489, 4490, 4491, 4492, 4493, 4497, 4498, 4502, 4503, 4504, 4506, 4508, 4509, 4510, 4511, 4512, 4513, 4514, 4516, 4517, 4518, 4519, 4520, 4521, 4522, 4529, 4530, 4531, 4532, 4533, 4534, 4535, 4536, 4537, 4538, 4539, 4540, 4546, 4547, 4549, 4550, 4551, 4552, 4553, 4554, 4555, 4556, 4557, 4558, 4559, 4560, 4561, 4562, 4563, 4564, 4568, 4569, 4570, 4571, 4572, 4573, 4574, 4575, 4576, 4581, 4582, 4585, 4586, 4587, 4588, 4589, 4590, 4591, 4592, 4593, 4594, 4595, 4596, 4597, 4598, 4600, 4601, 4602, 4603, 4612, 4613, 4614, 4615, 4616, 4617, 4619, 4622, 4623, 4624, 4626, 4627, 4628, 4629, 4630, 4631, 4632, 4633, 4634, 4635, 4636, 4637, 4638, 4639, 4640, 4641, 4642, 4643, 4644, 4645, 4646, 4647, 4648, 4649, 4650, 4651, 4652, 4653, 4654, 4655, 4656, 4657, 4658, 4659, 4660, 4661, 4662, 4663, 4664, 4665, 4666, 4667, 4668, 4669, 4670, 4671, 4672, 4673, 4674, 4675, 4676, 4677, 4678, 4679, 4680, 4681, 4682, 4683, 4684, 4685, 4686, 4687, 4688, 4689, 4690, 4691, 4692, 4693, 4694, 4695, 4696, 4697, 4698, 4699, 4700, 4701, 4702, 4703, 4704, 4705, 4706, 4707, 4708, 4709, 4710, 4711, 4712, 4713, 4714, 4715, 4716, 4717, 4718, 4719, 4720, 4721, 4722, 4723, 4724, 4725, 4726, 4727, 4732, 4733, 4734, 4740, 4753, 4757, 4758, 4759, 4760, 4761, 4762, 4763, 4764, 4765, 4766, 4767, 4768, 4769, 4770, 4771, 4772, 4774, 4775, 4776, 4777, 4778, 4780, 4781, 4782, 4783, 4784, 4785, 4786, 4789, 4790, 4792, 4793, 4794, 4797, 4798, 4799, 4800, 4801, 4802, 4803, 4804, 4805, 4806, 4807, 4808, 4809, 4810, 4811, 4812, 4813, 4814, 4815, 4816, 4817, 4818, 4819, 4820, 4821, 4822, 4823, 4825, 4826, 4827, 4828, 4829, 4830, 4831, 4832, 4833, 4834, 4835, 4836, 4837, 4838, 4839, 4840, 4841, 4842, 4843, 4844, 4845, 4846, 4847, 4848, 4849, 4850, 4851, 4852, 4853, 4854, 4855, 4856, 4858, 4859, 4860, 4862, 4864, 4866, 4867, 4868, 4869, 4872, 4874, 4875, 4876, 4877, 4879, 4880, 4881, 4882, 4883, 4884, 4885, 4886, 4889, 4893, 4894, 4898, 4899, 4900, 4901, 4902, 4903, 4904) } internal val templates: IntArray by lazy { intArrayOf(2358, 2837, 2649, 2648, 2647, 2869, 2891, 3371, 2612, 418, 2782, 2780, 2676, 2367, 2373, 2784, 2881, 2596, 2595, 285, 2325, 2786, 2893, 3221, 4173, 2535, 2585, 2045, 2363, 3705, 2110, 2712, 2368, 3222, 1336, 4193, 4213, 3704, 2553, 2710, 1862, 4188, 2121, 2159, 2165, 4542, 283, 2111, 4484, 3383, 3404, 2068, 2336, 3701, 452, 2744, 2776, 2777, 3384, 3700, 2745, 3632, 609, 1706, 3709, 1863, 2720, 3712, 2726, 3375, 616, 617, 2762, 3073, 3687, 1654, 2779, 3631, 303, 614, 69, 711, 621, 2335, 4211, 1121, 2477, 3454, 3827, 1242, 2194, 2564, 3376, 2157, 3716, 714, 1758, 1959, 2732, 2741, 2952, 4218, 3378, 3390, 136, 594, 596, 2552, 2707, 1860, 4206, 3024, 610, 2278, 2575, 3864, 1302, 4205, 3500, 3637, 3638, 158, 2075, 2077, 2112, 2832, 4341, 2163, 2362, 2505, 3626, 214, 284, 1276, 2009, 4773, 3495, 3504, 3505, 67, 83, 218, 619, 4578, 3524, 1360, 4300, 3349, 3714, 726, 1023, 1372, 2376, 2468, 2730, 4343, 89, 2375, 2390, 2905, 624, 1652, 1949, 2819, 4472, 3397, 1572, 2096, 2282, 2566, 4524, 3392, 3458, 3508, 650, 1883, 3919, 3157, 3499, 3545, 3609, 3828, 1317, 1861, 2040, 2414, 2701, 3847, 4543, 3411, 3457, 1836, 1858, 3346, 593, 1292, 1346, 1371, 1948, 3486, 3688, 221, 1696, 2733, 2930, 3075, 3143, 3432, 258, 591, 1026, 1379, 1960, 1984, 4126, 3429, 3555, 655, 1342, 1712, 2046, 3151, 3350, 3611, 3630, 710, 1283, 1370, 1382, 1653, 1727, 1890, 2364, 2467, 2565, 3934, 4212, 4409, 3410, 3478, 3624, 649, 699, 1044, 2601, 3169, 3288, 3691, 108, 184, 606, 721, 1081, 1964, 2044, 2106, 2161, 2400, 2481, 2737, 2773, 2817, 3939, 4455, 4796, 3370, 3441, 3602, 160, 623, 701, 1332, 1333, 1345, 1520, 1655, 2158, 2162, 2255, 2399, 2627, 4181, 4485, 3106, 3198, 3245, 3323, 3537, 3692, 3702, 703, 1183, 1567, 1892, 2250, 2253, 2480, 2738, 2758, 2759, 2927, 2928, 3949, 3969, 4202, 4446, 4779, 4795, 3610, 3627, 3733, 1378, 1492, 1579, 1698, 1950, 2420, 2432, 2757, 4145, 4203, 4486, 4577, 3072, 3074, 3089, 3607, 3620, 3786, 723, 1024, 1827, 2130, 2195, 2410, 2753, 2754, 3954, 4200, 4276, 4287, 3276, 3396, 91, 93, 595, 715, 1027, 1350, 1355, 2015, 2322, 2415, 2700, 2752, 2756, 3916, 4525, 4857, 3003, 3004, 3506, 3570, 3713, 94, 1251, 1259, 1353, 1377, 1519, 1578, 1875, 2178, 2210, 2460, 2478, 2728, 3856, 3857, 4199, 4352, 4415, 4861, 3322, 3361, 3362, 3440, 3596, 299, 599, 618, 700, 1109, 1117, 1175, 1367, 1518, 1621, 1943, 2122, 2128, 2146, 2213, 2430, 2435, 2437, 2660, 2693, 2751, 2929, 2946, 2947, 4170, 4196, 4313, 3005, 3159, 3536, 3569, 3738, 211, 585, 590, 605, 717, 720, 906, 990, 1084, 1159, 1334, 1470, 1524, 1700, 1881, 1901, 1921, 1956, 1986, 2067, 2305, 2413, 2479, 2934, 3883, 3935, 4153, 4526, 4544, 4545, 4744, 3066, 3422, 3617, 3618, 92, 96, 269, 603, 648, 712, 980, 1331, 1702, 1882, 1939, 2109, 2408, 2434, 2436, 2439, 2528, 2666, 2702, 2884, 2896, 4244, 4528, 4756, 2979, 3244, 3277, 3357, 3455, 3574, 3608, 208, 277, 316, 329, 330, 1287, 1352, 1376, 1521, 1522, 1944, 2014, 2039, 2108, 2212, 2240, 2288, 2402, 2417, 2429, 2703, 2706, 2787, 2788, 3854, 4541, 4739, 3001, 3389, 3393, 3442, 3498, 3653, 3690, 3743, 6, 244, 304, 600, 604, 1047, 1221, 1286, 1354, 1359, 1703, 1704, 1879, 1952, 1955, 2013, 2016, 2144, 2179, 2227, 2401, 2409, 2629, 2735, 2774, 2851, 3851, 3852, 3912, 4169, 4742, 4754, 4755, 3439, 3561, 3568, 3573, 3635, 3643, 268, 318, 322, 331, 583, 707, 722, 1076, 1160, 1164, 1284, 1285, 1312, 1517, 1705, 1823, 1884, 2004, 2214, 2220, 2372, 2398, 2404, 2431, 2563, 2664, 3917, 4142, 4195, 4258, 4344, 4414, 4625, 4743, 3052, 3137, 3502, 3503, 3601, 3634, 65, 210, 274, 587, 608, 613, 708, 713, 984, 1075, 1167, 1369, 1708, 1738, 1824, 1829, 1844, 1880, 2043, 2076, 2267, 2285, 2294, 2397, 2451, 2463, 2755, 4180, 3032, 3382, 3567, 3636, 3644, 3689, 90, 207, 288, 320, 323, 324, 349, 597, 607, 709, 855, 905, 1166, 1169, 1252, 1437, 1885, 2000, 2010, 2403, 2412, 2456, 2734, 2772, 2926, 2940, 3889, 4787, 4788, 4791, 4887, 3006, 3037, 3090, 3160, 3218, 3231, 3232, 3395, 3543, 3544, 3616, 3639, 3646, 3697, 110, 186, 190, 191, 212, 321, 327, 328, 352, 375, 580, 582, 589, 625, 727, 851, 977, 1077, 1118, 1147, 1243, 1304, 1314, 1741, 1825, 1826, 1834, 1945, 1946, 1947, 2036, 2246, 2248, 2274, 2286, 2287, 2309, 2371, 2405, 2406, 2462, 2568, 2569, 2652, 2667, 2699, 2704, 2705, 2742, 2789, 2790, 3835, 3853, 3899, 3953, 4198, 4292, 4310, 4342, 4412, 4447, 4499, 4523, 4584, 4824, 3039, 3141, 3165, 3179, 3200, 3381, 3394, 3538, 3542, 3572, 3600, 3731, 3741, 3742, 3754, 3756, 3763, 5, 8, 82, 185, 188, 192, 257, 276, 325, 326, 348, 351, 356, 598, 620, 658, 696, 705, 856, 985, 1048, 1122, 1148, 1149, 1168, 1179, 1239, 1383, 1491, 1644, 1688, 1699, 1845, 1876, 1942, 1988, 2001, 2022, 2242, 2247, 2297, 2303, 2304, 2311, 2416, 2602, 2638, 2812, 3900, 3908, 3938, 3955, 4122, 4157, 4171, 4219, 4259, 4311, 4337, 4500, 4527, 3062, 3108, 3184, 3185, 3190, 3248, 3532, 154, 259, 261, 347, 350, 353, 579, 602, 612, 702, 706, 982, 1078, 1381, 1588, 1828, 1920, 1982, 1985, 2295, 2308, 2374, 2421, 2567, 2615, 2857, 3858, 3905, 3971, 4138, 4496, 4583, 3438, 3531, 3533, 3541, 3560, 3571, 3739, 3760, 3780, 95, 196, 203, 204, 205, 242, 243, 346, 581, 586, 601, 615, 622, 626, 627, 691, 716, 725, 983, 986, 1085, 1089, 1161, 1174, 1204, 1349, 1471, 1506, 1683, 1684, 1686, 1721, 1846, 1886, 2225, 2300, 2310, 2411, 2433, 2441, 2948, 4124, 4154, 4155, 4245, 4270, 4308, 4410, 4466, 4507, 4863, 4888) } internal val argNames: Map> by lazy { mapOf(5 to arrayOf("n"), 6 to arrayOf("n"), 7 to arrayOf("who"), 8 to arrayOf("title"), 65 to arrayOf("state"), 67 to arrayOf("listen"), 69 to arrayOf("listen"), 82 to arrayOf("version"), 83 to arrayOf("count", "plural"), 89 to arrayOf("size", "limit"), 90 to arrayOf("name"), 91 to arrayOf("dir"), 92 to arrayOf("dir"), 93 to arrayOf("name"), 94 to arrayOf("name"), 95 to arrayOf("path"), 96 to arrayOf("path"), 97 to arrayOf("name"), 108 to arrayOf("first"), 110 to arrayOf("n"), 136 to arrayOf("count", "plural"), 154 to arrayOf("tool"), 158 to arrayOf("n"), 160 to arrayOf("name"), 184 to arrayOf("pid", "cmd"), 185 to arrayOf("title", "ago"), 186 to arrayOf("name", "who", "n"), 188 to arrayOf("line"), 190 to arrayOf("n"), 191 to arrayOf("n"), 192 to arrayOf("n"), 196 to arrayOf("name"), 203 to arrayOf("when"), 204 to arrayOf("text", "when"), 205 to arrayOf("when"), 207 to arrayOf("count", "plural"), 208 to arrayOf("count", "plural"), 210 to arrayOf("took", "ago"), 211 to arrayOf("ago"), 212 to arrayOf("kind"), 214 to arrayOf("kind", "code", "why"), 218 to arrayOf("clock"), 221 to arrayOf("build"), 242 to arrayOf("step"), 243 to arrayOf("turn"), 244 to arrayOf("branch"), 257 to arrayOf("step", "total"), 258 to arrayOf("step", "total"), 259 to arrayOf("when"), 261 to arrayOf("tool"), 268 to arrayOf("count", "plural"), 269 to arrayOf("count", "total"), 274 to arrayOf("old", "new"), 276 to arrayOf("version"), 277 to arrayOf("count"), 278 to arrayOf("tag"), 283 to arrayOf("version"), 284 to arrayOf("old", "version"), 285 to arrayOf("version"), 288 to arrayOf("version"), 299 to arrayOf("project", "location"), 303 to arrayOf("account"), 304 to arrayOf("account"), 316 to arrayOf("n"), 318 to arrayOf("n"), 320 to arrayOf("minute"), 321 to arrayOf("time"), 322 to arrayOf("time"), 323 to arrayOf("clock"), 324 to arrayOf("clock", "took"), 325 to arrayOf("clock"), 326 to arrayOf("clock", "took"), 327 to arrayOf("clock"), 328 to arrayOf("clock", "took"), 329 to arrayOf("clock"), 330 to arrayOf("clock", "took"), 331 to arrayOf("clock"), 346 to arrayOf("target"), 347 to arrayOf("target"), 348 to arrayOf("target"), 349 to arrayOf("target"), 350 to arrayOf("target"), 351 to arrayOf("target"), 352 to arrayOf("target"), 353 to arrayOf("target"), 356 to arrayOf("name"), 375 to arrayOf("t"), 418 to arrayOf("minutes", "plural"), 452 to arrayOf("path"), 579 to arrayOf("count"), 580 to arrayOf("count"), 581 to arrayOf("title"), 582 to arrayOf("path"), 583 to arrayOf("path", "error"), 584 to arrayOf("first", "last", "count"), 585 to arrayOf("task", "step"), 586 to arrayOf("count"), 587 to arrayOf("path"), 588 to arrayOf("count", "plural"), 589 to arrayOf("label"), 590 to arrayOf("provider"), 591 to arrayOf("version"), 593 to arrayOf("key"), 594 to arrayOf("device"), 595 to arrayOf("kind", "device"), 596 to arrayOf("status"), 597 to arrayOf("kind", "title"), 598 to arrayOf("layer"), 599 to arrayOf("error"), 600 to arrayOf("page"), 601 to arrayOf("page", "kind", "total"), 602 to arrayOf("reason"), 603 to arrayOf("tag"), 604 to arrayOf("tag"), 605 to arrayOf("title"), 606 to arrayOf("title"), 607 to arrayOf("text", "time"), 608 to arrayOf("kind", "device"), 609 to arrayOf("device"), 610 to arrayOf("device"), 611 to arrayOf("word"), 612 to arrayOf("word", "kind", "count"), 613 to arrayOf("error"), 614 to arrayOf("count"), 615 to arrayOf("time", "relative", "rel", "zoned", "zone"), 616 to arrayOf("zone"), 617 to arrayOf("zone"), 618 to arrayOf("id", "state", "count", "age"), 619 to arrayOf("id"), 620 to arrayOf("name"), 621 to arrayOf("name"), 622 to arrayOf("clock", "count", "plural"), 623 to arrayOf("name"), 624 to arrayOf("name"), 625 to arrayOf("name"), 626 to arrayOf("count"), 627 to arrayOf("count"), 631 to arrayOf("name", "state"), 632 to arrayOf("author", "place", "state"), 633 to arrayOf("title", "state"), 648 to arrayOf("error"), 649 to arrayOf("error"), 650 to arrayOf("host"), 655 to arrayOf("email"), 658 to arrayOf("version"), 660 to arrayOf("first", "last", "count"), 661 to arrayOf("n"), 662 to arrayOf("n"), 691 to arrayOf("ref"), 696 to arrayOf("name"), 697 to arrayOf("name"), 699 to arrayOf("name"), 700 to arrayOf("name"), 701 to arrayOf("action"), 702 to arrayOf("label"), 703 to arrayOf("count", "plural"), 705 to arrayOf("path"), 706 to arrayOf("word", "kind", "count"), 707 to arrayOf("name"), 708 to arrayOf("name"), 709 to arrayOf("name"), 710 to arrayOf("name"), 711 to arrayOf("url"), 712 to arrayOf("count"), 713 to arrayOf("count"), 714 to arrayOf("device"), 715 to arrayOf("device"), 716 to arrayOf("count"), 717 to arrayOf("label"), 718 to arrayOf("label"), 719 to arrayOf("label"), 720 to arrayOf("title"), 721 to arrayOf("title"), 722 to arrayOf("state"), 723 to arrayOf("open", "kind"), 725 to arrayOf("count"), 726 to arrayOf("email"), 727 to arrayOf("email"), 851 to arrayOf("at", "count"), 855 to arrayOf("name"), 856 to arrayOf("name"), 905 to arrayOf("name"), 906 to arrayOf("name"), 977 to arrayOf("count"), 980 to arrayOf("name"), 981 to arrayOf("name", "count"), 982 to arrayOf("label", "n"), 983 to arrayOf("action"), 984 to arrayOf("count", "plural"), 985 to arrayOf("count"), 986 to arrayOf("waiting", "busy", "done"), 990 to arrayOf("count", "plural"), 1023 to arrayOf("name"), 1024 to arrayOf("name"), 1026 to arrayOf("seconds", "long"), 1027 to arrayOf("size", "triangles", "delayed", "waited", "built"), 1028 to arrayOf("size", "delayed", "waited"), 1044 to arrayOf("name"), 1047 to arrayOf("name"), 1048 to arrayOf("count"), 1075 to arrayOf("state"), 1076 to arrayOf("bytes"), 1077 to arrayOf("count"), 1078 to arrayOf("when"), 1079 to arrayOf("state", "name"), 1080 to arrayOf("name", "state"), 1081 to arrayOf("reason", "code"), 1084 to arrayOf("kind", "code"), 1085 to arrayOf("number"), 1089 to arrayOf("x", "y"), 1096 to arrayOf("state"), 1097 to arrayOf("label", "example"), 1109 to arrayOf("text"), 1117 to arrayOf("error"), 1118 to arrayOf("kind", "count"), 1121 to arrayOf("name"), 1122 to arrayOf("n"), 1147 to arrayOf("ago"), 1148 to arrayOf("name"), 1149 to arrayOf("kind", "place", "hub"), 1159 to arrayOf("label"), 1160 to arrayOf("word"), 1161 to arrayOf("count"), 1164 to arrayOf("hub"), 1166 to arrayOf("count"), 1167 to arrayOf("state"), 1168 to arrayOf("label"), 1169 to arrayOf("label"), 1174 to arrayOf("state", "text"), 1175 to arrayOf("text"), 1177 to arrayOf("question"), 1179 to arrayOf("label"), 1183 to arrayOf("title"), 1204 to arrayOf("count"), 1205 to arrayOf("name", "counts"), 1219 to arrayOf("n"), 1221 to arrayOf("mode"), 1238 to arrayOf("first", "last", "total"), 1239 to arrayOf("count"), 1242 to arrayOf("n"), 1243 to arrayOf("who", "name"), 1251 to arrayOf("name"), 1252 to arrayOf("when"), 1259 to arrayOf("why"), 1276 to arrayOf("name"), 1283 to arrayOf("kind"), 1284 to arrayOf("title"), 1285 to arrayOf("title"), 1286 to arrayOf("title"), 1287 to arrayOf("title"), 1292 to arrayOf("name"), 1302 to arrayOf("heard"), 1303 to arrayOf("out", "heard"), 1304 to arrayOf("heard"), 1312 to arrayOf("name", "mb"), 1314 to arrayOf("name"), 1317 to arrayOf("platform"), 1321 to arrayOf("heard", "out", "yes"), 1331 to arrayOf("name", "done", "total", "percent"), 1332 to arrayOf("name", "done"), 1333 to arrayOf("name"), 1334 to arrayOf("error"), 1336 to arrayOf("mb"), 1342 to arrayOf("mb"), 1345 to arrayOf("n"), 1346 to arrayOf("n"), 1349 to arrayOf("n"), 1350 to arrayOf("pct"), 1351 to arrayOf("px"), 1352 to arrayOf("version"), 1353 to arrayOf("tag"), 1354 to arrayOf("tag"), 1355 to arrayOf("hub"), 1359 to arrayOf("tag"), 1360 to arrayOf("tag"), 1367 to arrayOf("when"), 1369 to arrayOf("tag"), 1370 to arrayOf("tag", "when"), 1371 to arrayOf("tag"), 1372 to arrayOf("tag", "when"), 1376 to arrayOf("channel"), 1377 to arrayOf("tag"), 1378 to arrayOf("app", "hub"), 1379 to arrayOf("hub", "app"), 1381 to arrayOf("key"), 1382 to arrayOf("key"), 1383 to arrayOf("why"), 1437 to arrayOf("n"), 1470 to arrayOf("title"), 1471 to arrayOf("note"), 1491 to arrayOf("title"), 1492 to arrayOf("more"), 1506 to arrayOf("bots"), 1517 to arrayOf("name"), 1518 to arrayOf("name", "time"), 1519 to arrayOf("name", "n"), 1520 to arrayOf("name", "time", "n"), 1521 to arrayOf("to"), 1522 to arrayOf("to", "step"), 1524 to arrayOf("note"), 1567 to arrayOf("why"), 1572 to arrayOf("e"), 1578 to arrayOf("max"), 1579 to arrayOf("secs", "max", "mib"), 1588 to arrayOf("path"), 1621 to arrayOf("secs"), 1644 to arrayOf("pct", "scope"), 1652 to arrayOf("n"), 1653 to arrayOf("n"), 1654 to arrayOf("n"), 1655 to arrayOf("n"), 1683 to arrayOf("d", "h"), 1684 to arrayOf("h", "m"), 1685 to arrayOf("m"), 1686 to arrayOf("window", "pct"), 1688 to arrayOf("when"), 1690 to arrayOf("label", "e"), 1692 to arrayOf("from", "to", "total"), 1696 to arrayOf("messages", "lines", "left"), 1698 to arrayOf("pct", "view", "max"), 1699 to arrayOf("pct"), 1700 to arrayOf("done", "total"), 1702 to arrayOf("n"), 1703 to arrayOf("n"), 1704 to arrayOf("time"), 1705 to arrayOf("view", "max"), 1706 to arrayOf("view", "max"), 1708 to arrayOf("more"), 1712 to arrayOf("n"), 1721 to arrayOf("n"), 1727 to arrayOf("page"), 1738 to arrayOf("title"), 1741 to arrayOf("n"), 1758 to arrayOf("name"), 1823 to arrayOf("line"), 1824 to arrayOf("quote"), 1825 to arrayOf("n"), 1826 to arrayOf("n"), 1827 to arrayOf("n"), 1828 to arrayOf("n"), 1829 to arrayOf("n"), 1834 to arrayOf("held"), 1835 to arrayOf("machine"), 1836 to arrayOf("machine"), 1844 to arrayOf("count", "total"), 1845 to arrayOf("count"), 1846 to arrayOf("n"), 1858 to arrayOf("name"), 1860 to arrayOf("n", "c", "total"), 1861 to arrayOf("n", "c"), 1862 to arrayOf("n", "c", "total", "before"), 1863 to arrayOf("n", "c", "before"), 1875 to arrayOf("name"), 1876 to arrayOf("path"), 1879 to arrayOf("file"), 1880 to arrayOf("path", "n"), 1881 to arrayOf("why"), 1882 to arrayOf("n"), 1883 to arrayOf("name"), 1884 to arrayOf("name"), 1885 to arrayOf("name"), 1886 to arrayOf("n"), 1887 to arrayOf("shown", "n"), 1890 to arrayOf("path"), 1892 to arrayOf("n"), 1901 to arrayOf("status"), 1918 to arrayOf("name", "pct"), 1919 to arrayOf("name", "mb"), 1920 to arrayOf("name"), 1921 to arrayOf("name", "why"), 1939 to arrayOf("machine"), 1942 to arrayOf("n"), 1943 to arrayOf("ref"), 1944 to arrayOf("ref", "sheet"), 1945 to arrayOf("name"), 1946 to arrayOf("name"), 1947 to arrayOf("file", "folder"), 1948 to arrayOf("name", "error"), 1949 to arrayOf("name", "status"), 1950 to arrayOf("name", "error"), 1952 to arrayOf("name"), 1955 to arrayOf("code"), 1956 to arrayOf("error"), 1959 to arrayOf("error"), 1960 to arrayOf("error"), 1964 to arrayOf("error"), 1982 to arrayOf("done", "of"), 1984 to arrayOf("why"), 1985 to arrayOf("path"), 1986 to arrayOf("error"), 1987 to arrayOf("secs"), 1988 to arrayOf("secs"), 2000 to arrayOf("code"), 2001 to arrayOf("code"), 2004 to arrayOf("state"), 2009 to arrayOf("hide", "copy", "paste"), 2010 to arrayOf("n"), 2013 to arrayOf("name"), 2014 to arrayOf("name", "folder"), 2015 to arrayOf("name"), 2016 to arrayOf("name", "percent"), 2022 to arrayOf("folder"), 2032 to arrayOf("w", "h"), 2036 to arrayOf("path"), 2039 to arrayOf("why"), 2040 to arrayOf("mb"), 2043 to arrayOf("n"), 2044 to arrayOf("delete", "undo"), 2045 to arrayOf("delete", "undo"), 2046 to arrayOf("undo"), 2067 to arrayOf("what", "secs"), 2068 to arrayOf("file", "holder"), 2075 to arrayOf("what"), 2076 to arrayOf("what"), 2077 to arrayOf("editor", "why"), 2096 to arrayOf("files"), 2106 to arrayOf("why"), 2108 to arrayOf("title"), 2109 to arrayOf("title"), 2110 to arrayOf("version"), 2111 to arrayOf("version", "size", "folder"), 2112 to arrayOf("version", "size", "folder"), 2121 to arrayOf("title"), 2122 to arrayOf("dir", "files"), 2128 to arrayOf("why"), 2130 to arrayOf("code"), 2144 to arrayOf("origin"), 2146 to arrayOf("why"), 2157 to arrayOf("dir"), 2158 to arrayOf("path"), 2159 to arrayOf("home", "other"), 2161 to arrayOf("path"), 2162 to arrayOf("code", "log"), 2163 to arrayOf("log"), 2165 to arrayOf("addr"), 2178 to arrayOf("home"), 2179 to arrayOf("addr"), 2194 to arrayOf("dir", "why"), 2195 to arrayOf("dir"), 2210 to arrayOf("phase"), 2212 to arrayOf("why"), 2213 to arrayOf("what"), 2214 to arrayOf("code"), 2220 to arrayOf("label"), 2225 to arrayOf("kind"), 2227 to arrayOf("project"), 2240 to arrayOf("what"), 2242 to arrayOf("when"), 2246 to arrayOf("n"), 2247 to arrayOf("n"), 2248 to arrayOf("n"), 2250 to arrayOf("agent"), 2251 to arrayOf("effort"), 2253 to arrayOf("n"), 2255 to arrayOf("model"), 2267 to arrayOf("word"), 2274 to arrayOf("more", "step"), 2278 to arrayOf("name"), 2282 to arrayOf("max", "skipped"), 2285 to arrayOf("name"), 2286 to arrayOf("n"), 2287 to arrayOf("name"), 2288 to arrayOf("name"), 2294 to arrayOf("n"), 2295 to arrayOf("name"), 2297 to arrayOf("price"), 2300 to arrayOf("name"), 2302 to arrayOf("name"), 2303 to arrayOf("name"), 2304 to arrayOf("name"), 2305 to arrayOf("text"), 2308 to arrayOf("key"), 2309 to arrayOf("key"), 2310 to arrayOf("pct"), 2311 to arrayOf("when"), 2322 to arrayOf("n", "upstream"), 2325 to arrayOf("mb"), 2335 to arrayOf("path"), 2336 to arrayOf("path"), 2358 to arrayOf("id"), 2362 to arrayOf("model"), 2363 to arrayOf("platform"), 2364 to arrayOf("version"), 2367 to arrayOf("version", "from", "into"), 2368 to arrayOf("version", "from"), 2371 to arrayOf("version", "path"), 2372 to arrayOf("version", "path"), 2373 to arrayOf("version", "pin", "from"), 2374 to arrayOf("path"), 2375 to arrayOf("version", "path"), 2376 to arrayOf("version", "path", "set"), 2390 to arrayOf("turns", "input", "cread", "cwrite", "output", "cost"), 2397 to arrayOf("tool"), 2398 to arrayOf("tool"), 2399 to arrayOf("tool", "word"), 2400 to arrayOf("tool", "word"), 2401 to arrayOf("tool"), 2402 to arrayOf("tool"), 2403 to arrayOf("due"), 2404 to arrayOf("due"), 2405 to arrayOf("due"), 2406 to arrayOf("due"), 2407 to arrayOf("zone"), 2408 to arrayOf("zone"), 2409 to arrayOf("zone"), 2410 to arrayOf("zone"), 2411 to arrayOf("n"), 2412 to arrayOf("who"), 2413 to arrayOf("n", "who"), 2414 to arrayOf("harness"), 2415 to arrayOf("path"), 2416 to arrayOf("path"), 2417 to arrayOf("path"), 2420 to arrayOf("error", "line"), 2421 to arrayOf("label"), 2429 to arrayOf("who"), 2430 to arrayOf("who"), 2431 to arrayOf("label", "left", "when"), 2432 to arrayOf("left"), 2433 to arrayOf("name", "left"), 2434 to arrayOf("used"), 2435 to arrayOf("used", "limit"), 2436 to arrayOf("used", "reason"), 2437 to arrayOf("used", "limit", "reason"), 2439 to arrayOf("provider"), 2440 to arrayOf("used", "window", "pct"), 2441 to arrayOf("rate"), 2451 to arrayOf("n", "r"), 2456 to arrayOf("time", "n"), 2460 to arrayOf("n", "m"), 2462 to arrayOf("pct"), 2463 to arrayOf("cost", "n"), 2467 to arrayOf("in", "out", "cread", "cwrite"), 2468 to arrayOf("in", "out", "cread", "cwrite", "n"), 2477 to arrayOf("turns", "input", "cread", "cwrite", "output"), 2478 to arrayOf("left", "when"), 2479 to arrayOf("left", "when"), 2480 to arrayOf("left", "when"), 2481 to arrayOf("left", "when"), 2505 to arrayOf("n"), 2528 to arrayOf("when"), 2535 to arrayOf("phrase", "now"), 2546 to arrayOf("s"), 2552 to arrayOf("now"), 2553 to arrayOf("now", "nudge", "sent", "undone"), 2563 to arrayOf("e"), 2564 to arrayOf("a", "ams", "b", "bms"), 2565 to arrayOf("ms"), 2566 to arrayOf("e"), 2567 to arrayOf("t"), 2568 to arrayOf("t"), 2569 to arrayOf("t"), 2575 to arrayOf("why"), 2585 to arrayOf("apps"), 2595 to arrayOf("n"), 2596 to arrayOf("n", "k"), 2601 to arrayOf("stt", "conf"), 2602 to arrayOf("words"), 2612 to arrayOf("into"), 2615 to arrayOf("origin"), 2627 to arrayOf("url"), 2629 to arrayOf("url"), 2637 to arrayOf("i", "n"), 2638 to arrayOf("d", "n"), 2647 to arrayOf("version"), 2648 to arrayOf("version"), 2649 to arrayOf("version"), 2652 to arrayOf("path"), 2660 to arrayOf("addr"), 2664 to arrayOf("label"), 2666 to arrayOf("label"), 2667 to arrayOf("label"), 2671 to arrayOf("label"), 2676 to arrayOf("from"), 2693 to arrayOf("done", "of"), 2699 to arrayOf("n"), 2700 to arrayOf("t", "m"), 2701 to arrayOf("m"), 2702 to arrayOf("b", "m"), 2703 to arrayOf("r", "p"), 2704 to arrayOf("n"), 2705 to arrayOf("n"), 2706 to arrayOf("n"), 2707 to arrayOf("n"), 2710 to arrayOf("n"), 2712 to arrayOf("n"), 2720 to arrayOf("n"), 2726 to arrayOf("name", "gb", "path"), 2728 to arrayOf("path", "why"), 2730 to arrayOf("names"), 2732 to arrayOf("why"), 2733 to arrayOf("p", "pn", "t", "tn", "e", "en"), 2734 to arrayOf("done", "total"), 2735 to arrayOf("n"), 2736 to arrayOf("what"), 2737 to arrayOf("n"), 2738 to arrayOf("n"), 2741 to arrayOf("what"), 2742 to arrayOf("n"), 2744 to arrayOf("why", "from"), 2745 to arrayOf("why"), 2751 to arrayOf("path"), 2752 to arrayOf("path", "who"), 2753 to arrayOf("path"), 2754 to arrayOf("path", "cmd"), 2755 to arrayOf("version", "path"), 2756 to arrayOf("version", "path"), 2757 to arrayOf("version", "path", "who"), 2758 to arrayOf("version", "path"), 2759 to arrayOf("version", "path", "cmd"), 2762 to arrayOf("cmd"), 2772 to arrayOf("name", "version", "path"), 2773 to arrayOf("path", "why"), 2774 to arrayOf("name"), 2776 to arrayOf("version", "cli"), 2777 to arrayOf("cli"), 2779 to arrayOf("version"), 2780 to arrayOf("version"), 2782 to arrayOf("version"), 2784 to arrayOf("version"), 2786 to arrayOf("computer"), 2787 to arrayOf("version", "cli"), 2788 to arrayOf("cli"), 2789 to arrayOf("version", "cli"), 2790 to arrayOf("cli"), 2812 to arrayOf("n"), 2817 to arrayOf("code"), 2819 to arrayOf("e"), 2832 to arrayOf("n"), 2837 to arrayOf("channel"), 2851 to arrayOf("project"), 2857 to arrayOf("n"), 2869 to arrayOf("m"), 2881 to arrayOf("m"), 2884 to arrayOf("m"), 2891 to arrayOf("pages"), 2893 to arrayOf("name"), 2896 to arrayOf("name"), 2905 to arrayOf("d", "n"), 2926 to arrayOf("n", "tools"), 2927 to arrayOf("n", "tools", "d"), 2928 to arrayOf("n", "d"), 2929 to arrayOf("n", "what"), 2930 to arrayOf("n", "d", "what"), 2934 to arrayOf("head"), 2940 to arrayOf("name", "path"), 2946 to arrayOf("page", "net", "near"), 2947 to arrayOf("page", "what"), 2948 to arrayOf("ref"), 2952 to arrayOf("page"), 2975 to arrayOf("n"), 2976 to arrayOf("n"), 2977 to arrayOf("n"), 2979 to arrayOf("hub"), 3001 to arrayOf("project"), 3003 to arrayOf("n"), 3004 to arrayOf("n"), 3005 to arrayOf("word"), 3006 to arrayOf("n"), 3024 to arrayOf("name"), 3032 to arrayOf("answer"), 3037 to arrayOf("why"), 3039 to arrayOf("hub"), 3045 to arrayOf("from", "to"), 3052 to arrayOf("project"), 3062 to arrayOf("name"), 3066 to arrayOf("n"), 3072 to arrayOf("code"), 3073 to arrayOf("hub"), 3074 to arrayOf("hub"), 3075 to arrayOf("hub"), 3089 to arrayOf("n"), 3090 to arrayOf("n"), 3106 to arrayOf("status"), 3108 to arrayOf("status"), 3137 to arrayOf("project"), 3141 to arrayOf("code"), 3143 to arrayOf("why"), 3151 to arrayOf("title"), 3157 to arrayOf("title"), 3159 to arrayOf("q"), 3160 to arrayOf("title"), 3165 to arrayOf("room"), 3169 to arrayOf("q"), 3179 to arrayOf("title"), 3184 to arrayOf("n"), 3185 to arrayOf("n"), 3190 to arrayOf("at"), 3198 to arrayOf("size"), 3200 to arrayOf("n", "total"), 3217 to arrayOf("n"), 3218 to arrayOf("what"), 3221 to arrayOf("device"), 3222 to arrayOf("device"), 3231 to arrayOf("word", "count"), 3232 to arrayOf("heard"), 3244 to arrayOf("files"), 3245 to arrayOf("files"), 3248 to arrayOf("name"), 3276 to arrayOf("n"), 3277 to arrayOf("n"), 3288 to arrayOf("n"), 3322 to arrayOf("root"), 3323 to arrayOf("path"), 3346 to arrayOf("name"), 3349 to arrayOf("until"), 3350 to arrayOf("error"), 3357 to arrayOf("url"), 3361 to arrayOf("name"), 3362 to arrayOf("name"), 3370 to arrayOf("code", "hub", "until"), 3371 to arrayOf("url"), 3375 to arrayOf("kinds"), 3376 to arrayOf("address"), 3378 to arrayOf("address"), 3381 to arrayOf("url"), 3382 to arrayOf("url"), 3383 to arrayOf("url"), 3384 to arrayOf("url", "via"), 3389 to arrayOf("name"), 3390 to arrayOf("url", "check", "left"), 3392 to arrayOf("check"), 3393 to arrayOf("address"), 3394 to arrayOf("name"), 3395 to arrayOf("error"), 3396 to arrayOf("url"), 3397 to arrayOf("url"), 3404 to arrayOf("code", "address", "left"), 3410 to arrayOf("name"), 3411 to arrayOf("name"), 3422 to arrayOf("address"), 3429 to arrayOf("code", "body"), 3432 to arrayOf("code", "body"), 3438 to arrayOf("window", "used"), 3439 to arrayOf("window", "used", "when"), 3440 to arrayOf("window", "used"), 3441 to arrayOf("window", "used", "when"), 3442 to arrayOf("provider"), 3454 to arrayOf("label"), 3455 to arrayOf("when"), 3457 to arrayOf("provider"), 3458 to arrayOf("provider", "title", "why"), 3478 to arrayOf("reason"), 3486 to arrayOf("code"), 3495 to arrayOf("name"), 3498 to arrayOf("version"), 3499 to arrayOf("version"), 3500 to arrayOf("version"), 3502 to arrayOf("version"), 3503 to arrayOf("version"), 3504 to arrayOf("version"), 3505 to arrayOf("version", "why"), 3506 to arrayOf("version"), 3508 to arrayOf("code"), 3524 to arrayOf("name"), 3531 to arrayOf("count"), 3532 to arrayOf("title"), 3533 to arrayOf("name"), 3536 to arrayOf("n", "holder"), 3537 to arrayOf("n", "title"), 3538 to arrayOf("title"), 3541 to arrayOf("n"), 3542 to arrayOf("n"), 3543 to arrayOf("n"), 3544 to arrayOf("n"), 3545 to arrayOf("harness", "typed", "type", "remote", "host", "wt", "branch"), 3555 to arrayOf("pid"), 3560 to arrayOf("left"), 3561 to arrayOf("left"), 3567 to arrayOf("left"), 3568 to arrayOf("left"), 3569 to arrayOf("left"), 3570 to arrayOf("left"), 3571 to arrayOf("label", "left"), 3572 to arrayOf("when"), 3573 to arrayOf("used"), 3574 to arrayOf("used", "limit"), 3596 to arrayOf("tracking"), 3600 to arrayOf("total"), 3601 to arrayOf("price"), 3602 to arrayOf("price"), 3607 to arrayOf("n"), 3608 to arrayOf("parts"), 3609 to arrayOf("note"), 3610 to arrayOf("error"), 3611 to arrayOf("error", "parts"), 3616 to arrayOf("state"), 3617 to arrayOf("name", "path"), 3618 to arrayOf("name", "path", "why"), 3620 to arrayOf("code"), 3624 to arrayOf("detail"), 3626 to arrayOf("why"), 3627 to arrayOf("parts"), 3630 to arrayOf("build", "to"), 3631 to arrayOf("build"), 3632 to arrayOf("build", "skip"), 3634 to arrayOf("why"), 3635 to arrayOf("why"), 3636 to arrayOf("build"), 3637 to arrayOf("build", "why"), 3638 to arrayOf("build"), 3639 to arrayOf("build"), 3643 to arrayOf("build"), 3644 to arrayOf("build"), 3646 to arrayOf("build"), 3653 to arrayOf("build"), 3687 to arrayOf("step"), 3688 to arrayOf("p", "pt", "t", "tt", "e", "et"), 3689 to arrayOf("done", "total"), 3690 to arrayOf("n"), 3691 to arrayOf("n"), 3692 to arrayOf("n"), 3697 to arrayOf("n"), 3700 to arrayOf("why"), 3701 to arrayOf("why", "from"), 3702 to arrayOf("error"), 3704 to arrayOf("n"), 3705 to arrayOf("n"), 3709 to arrayOf("n"), 3712 to arrayOf("name", "gb", "path"), 3713 to arrayOf("path", "why"), 3714 to arrayOf("names"), 3716 to arrayOf("why"), 3727 to arrayOf("n", "total"), 3731 to arrayOf("title"), 3733 to arrayOf("n"), 3737 to arrayOf("name"), 3738 to arrayOf("title"), 3739 to arrayOf("note"), 3741 to arrayOf("machine"), 3742 to arrayOf("machines"), 3743 to arrayOf("machine"), 3754 to arrayOf("n"), 3756 to arrayOf("n"), 3760 to arrayOf("name"), 3763 to arrayOf("name"), 3780 to arrayOf("why"), 3786 to arrayOf("project"), 3827 to arrayOf("path"), 3828 to arrayOf("path"), 3830 to arrayOf("have", "total"), 3835 to arrayOf("n"), 3844 to arrayOf("hub"), 3847 to arrayOf("title"), 3851 to arrayOf("project"), 3852 to arrayOf("project"), 3853 to arrayOf("n"), 3854 to arrayOf("hub"), 3856 to arrayOf("n"), 3857 to arrayOf("n"), 3858 to arrayOf("model"), 3864 to arrayOf("name"), 3883 to arrayOf("word"), 3889 to arrayOf("answer"), 3899 to arrayOf("version", "build"), 3900 to arrayOf("hub"), 3905 to arrayOf("name"), 3908 to arrayOf("when", "who", "mark"), 3912 to arrayOf("who"), 3916 to arrayOf("time"), 3917 to arrayOf("address"), 3919 to arrayOf("kind", "name"), 3934 to arrayOf("title"), 3935 to arrayOf("query"), 3938 to arrayOf("room"), 3939 to arrayOf("query"), 3941 to arrayOf("n"), 3942 to arrayOf("n"), 3943 to arrayOf("n"), 3949 to arrayOf("size"), 3953 to arrayOf("n"), 3954 to arrayOf("n"), 3955 to arrayOf("n"), 3969 to arrayOf("status"), 3971 to arrayOf("status"), 4122 to arrayOf("code"), 4124 to arrayOf("n"), 4126 to arrayOf("why"), 4138 to arrayOf("done", "of"), 4142 to arrayOf("thread"), 4145 to arrayOf("n"), 4153 to arrayOf("title"), 4154 to arrayOf("note"), 4155 to arrayOf("label"), 4156 to arrayOf("machine"), 4157 to arrayOf("machine"), 4164 to arrayOf("at", "total"), 4165 to arrayOf("at", "total"), 4169 to arrayOf("machine"), 4170 to arrayOf("machine"), 4171 to arrayOf("machines"), 4173 to arrayOf("device"), 4180 to arrayOf("price"), 4181 to arrayOf("price"), 4188 to arrayOf("home"), 4193 to arrayOf("from"), 4195 to arrayOf("note"), 4196 to arrayOf("note"), 4198 to arrayOf("v"), 4199 to arrayOf("v"), 4200 to arrayOf("v", "who"), 4202 to arrayOf("who"), 4203 to arrayOf("v"), 4205 to arrayOf("v", "cmd"), 4206 to arrayOf("cmd"), 4211 to arrayOf("v", "path"), 4212 to arrayOf("v", "note"), 4213 to arrayOf("v"), 4218 to arrayOf("tool"), 4219 to arrayOf("tool"), 4244 to arrayOf("n", "w"), 4245 to arrayOf("why"), 4246 to arrayOf("state", "why"), 4258 to arrayOf("project"), 4259 to arrayOf("n"), 4270 to arrayOf("why"), 4276 to arrayOf("name"), 4287 to arrayOf("project"), 4292 to arrayOf("n"), 4300 to arrayOf("names"), 4308 to arrayOf("dest"), 4310 to arrayOf("repo"), 4311 to arrayOf("repo"), 4313 to arrayOf("url"), 4337 to arrayOf("group"), 4341 to arrayOf("project"), 4342 to arrayOf("n"), 4343 to arrayOf("n"), 4344 to arrayOf("n"), 4352 to arrayOf("n"), 4409 to arrayOf("n"), 4410 to arrayOf("n"), 4411 to arrayOf("a", "b"), 4412 to arrayOf("n"), 4414 to arrayOf("parts", "lines"), 4415 to arrayOf("n"), 4446 to arrayOf("what", "project", "fab"), 4447 to arrayOf("rev", "day"), 4455 to arrayOf("n"), 4466 to arrayOf("layer"), 4467 to arrayOf("n"), 4472 to arrayOf("board"), 4484 to arrayOf("others"), 4485 to arrayOf("must", "should", "notes"), 4486 to arrayOf("id", "w"), 4496 to arrayOf("what"), 4499 to arrayOf("why"), 4500 to arrayOf("why"), 4507 to arrayOf("n"), 4523 to arrayOf("price", "n"), 4524 to arrayOf("n", "need"), 4525 to arrayOf("n"), 4526 to arrayOf("n"), 4527 to arrayOf("cost"), 4528 to arrayOf("cost"), 4541 to arrayOf("day", "n"), 4542 to arrayOf("day"), 4543 to arrayOf("cost", "n", "lines"), 4544 to arrayOf("stock", "price"), 4545 to arrayOf("lines"), 4566 to arrayOf("host"), 4577 to arrayOf("n"), 4578 to arrayOf("a", "b"), 4579 to arrayOf("n"), 4580 to arrayOf("n"), 4583 to arrayOf("day"), 4584 to arrayOf("n"), 4625 to arrayOf("turn"), 4739 to arrayOf("text"), 4742 to arrayOf("repo", "dest"), 4743 to arrayOf("repo", "dest"), 4744 to arrayOf("repo"), 4749 to arrayOf("dir"), 4750 to arrayOf("dir"), 4754 to arrayOf("editor", "job", "secs"), 4755 to arrayOf("editor", "secs"), 4756 to arrayOf("editor"), 4773 to arrayOf("time"), 4779 to arrayOf("status"), 4787 to arrayOf("time"), 4788 to arrayOf("time", "dur"), 4791 to arrayOf("answer"), 4795 to arrayOf("type"), 4796 to arrayOf("max"), 4824 to arrayOf("bytes", "tokens"), 4857 to arrayOf("what"), 4861 to arrayOf("n"), 4863 to arrayOf("n"), 4887 to arrayOf("n"), 4888 to arrayOf("done", "total"), 4896 to arrayOf("v"), 4897 to arrayOf("x", "y")) } @@ -28049,4 +28084,11 @@ object Msg { val mobile_plan_copied: String get() = Tr.s(4895) fun mobile_plan_widthmm(v: Any): String = Tr.f(4896, arrayOf(v)) fun mobile_plan_coord(x: Any, y: Any): String = Tr.f(4897, arrayOf(x, y)) + val provider_notice_head: String get() = Tr.s(4898) + val provider_notice_text_none: String get() = Tr.s(4899) + val provider_notice_text_signedout: String get() = Tr.s(4900) + val provider_notice_button: String get() = Tr.s(4901) + val provider_notice_senderr: String get() = Tr.s(4902) + val web_settings_providers: String get() = Tr.s(4903) + val web_settings_providers_browser: String get() = Tr.s(4904) } diff --git a/mobile/ios/Backplane/DataClient.swift b/mobile/ios/Backplane/DataClient.swift index 76a56d8cf1..e52c962b68 100644 --- a/mobile/ios/Backplane/DataClient.swift +++ b/mobile/ios/Backplane/DataClient.swift @@ -146,6 +146,9 @@ final class DataClient { private(set) var telemetryNotice: DTelemetryNotice? /// the notice's Settings link: the root view opens Settings and sets it back var openSettings = false + /// Hub notice when zero AI providers / accounts are configured or signed in (`hello.noProvider` / `info["provider.notice"]`) + private(set) var noProvider: DNoProvider? + var openAccounts = false var canSendImages: Bool { features.contains("images") } // the composer's own commands (hello.commands): the hub's table; none of them is ever a message struct Word: Equatable { let word, label, desc: String } @@ -321,7 +324,7 @@ final class DataClient { shellHashes = [:]; threadHashes = [:]; threadIds = [:]; subEntriesById = [:]; subEntryIds = [] restarting = nil; hubBack = nil; restartStrip() home = nil - notice = HubNotice(); star = nil; telemetryNotice = nil; migration = DMigration(); migrationOpen = false; migrationError = "" + notice = HubNotice(); star = nil; telemetryNotice = nil; noProvider = nil; migration = DMigration(); migrationOpen = false; migrationError = "" dueThreads = []; dueProjects = [] projects = []; threads = []; entries = [:]; older = [:]; loadedThreads = []; listsLoaded = false; open = nil; queues = [:]; queueError = [:] mgmt = [:]; mgmtDigest = ""; mgmtProject = ""; mgmtAsked = ""; mgmtRev += 1 @@ -533,6 +536,7 @@ final class DataClient { if !onHome { downSince = nil } Task { await self.synchronise(g) } heardOffer(o["hubOffer"] as? String ?? "") + noProvider = DNoProvider.of(o["noProvider"]) case "reply": guard let id = o["id"] as? Int ?? (o["id"] as? Double).map(Int.init), let k = calls.removeValue(forKey: id) else { return } if o["ok"] as? Bool == true { @@ -552,6 +556,7 @@ final class DataClient { case "info": if let info = o["info"] as? [String: Any] { if let v = info["hub.offer"] as? String { heardOffer(v) } + if info.keys.contains("provider.notice") { noProvider = DNoProvider.of(info["provider.notice"]) } heardMgmt(info) } case "shot": shotBot = o["bot"] as? String ?? ""; shot = (o["n"] as? Int) ?? ((o["n"] as? Double).map(Int.init) ?? 0) diff --git a/mobile/ios/Backplane/DataLinks.swift b/mobile/ios/Backplane/DataLinks.swift index a6ad2cac05..897c44cc51 100644 --- a/mobile/ios/Backplane/DataLinks.swift +++ b/mobile/ios/Backplane/DataLinks.swift @@ -5,17 +5,17 @@ import UIKit // (SwiftUI's openURL; a long press shows the system's Open / Copy / Share menu). A backplane:// link or a path is asked of the hub (link.resolve), which says // what it opens: a thread (also one on a linked machine), a project, a room, a file at a line, or a short note why not. The root screen follows `linkTarget`. struct DLinkTarget: Equatable { - enum Kind { case thread, project, room, file } + enum Kind { case thread, project, room, file, settings } var kind: Kind; var id: String; var path = ""; var line = 0 var n = UUID() } struct DLinkReply: Decodable { - var kind: String; var thread: String; var project: String; var room: String; var path: String; var line: Int; var note: String - enum CodingKeys: String, CodingKey { case kind, thread, project, room, path, line, note } + var kind: String; var thread: String; var project: String; var room: String; var path: String; var line: Int; var note: String; var page: String + enum CodingKeys: String, CodingKey { case kind, thread, project, room, path, line, note, page } init(from d: Decoder) throws { let c = try d.container(keyedBy: CodingKeys.self) - kind = c.str(.kind); thread = c.str(.thread); project = c.str(.project); room = c.str(.room); path = c.str(.path); line = c.int(.line); note = c.str(.note) + kind = c.str(.kind); thread = c.str(.thread); project = c.str(.project); room = c.str(.room); path = c.str(.path); line = c.int(.line); note = c.str(.note); page = c.str(.page) } } @@ -47,6 +47,7 @@ extension DataClient { // a hub that does not know link.resolve: a thread link as before, the rest says so guard has("links") else { if let u = URL(string: text), u.host == "thread", let id = u.pathComponents.dropFirst().first, !id.isEmpty { linkTarget = DLinkTarget(kind: .thread, id: id) } + else if let u = URL(string: text), u.host == "settings" { linkTarget = DLinkTarget(kind: .settings, id: u.pathComponents.dropFirst().first ?? "") } else { say("Update the hub to open this link.") } return } @@ -57,6 +58,7 @@ extension DataClient { case "project": linkTarget = DLinkTarget(kind: .project, id: r.project) case "room": linkTarget = DLinkTarget(kind: .room, id: r.room) case "file": linkTarget = DLinkTarget(kind: .file, id: r.thread, path: r.path, line: r.line) + case "settings": linkTarget = DLinkTarget(kind: .settings, id: r.page) default: // a file the reply lists that no viewer here opens is downloaded instead if let p = dPathFrom(url), download(p, thread: thread, viewToo: true) { break } diff --git a/mobile/ios/Backplane/DataModels.swift b/mobile/ios/Backplane/DataModels.swift index 725232e431..226b333955 100644 --- a/mobile/ios/Backplane/DataModels.swift +++ b/mobile/ios/Backplane/DataModels.swift @@ -661,3 +661,24 @@ struct DTelemetryNotice: Codable, Equatable { } } struct DTelemetryNoticeReply: Decodable { var notice: DTelemetryNotice? } + +/// Hub notice shown when zero AI providers / accounts are configured or signed in. +struct DNoProvider: Equatable { + let reason: String, head: String, text: String, button: String, url: String + static func of(_ v: Any?) -> DNoProvider? { + var obj = v as? [String: Any] + if obj == nil, let s = v as? String, !s.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty, + let d = s.data(using: .utf8) { + obj = (try? JSONSerialization.jsonObject(with: d)) as? [String: Any] + } + guard let o = obj, let head = (o["head"] as? String)?.trimmingCharacters(in: .whitespacesAndNewlines), !head.isEmpty else { return nil } + return DNoProvider( + reason: o["reason"] as? String ?? "", + head: head, + text: o["text"] as? String ?? "", + button: o["button"] as? String ?? "", + url: o["url"] as? String ?? "backplane://settings/accounts" + ) + } + static func isSendError(_ msg: String) -> Bool { msg.contains("No AI provider connected") } +} diff --git a/mobile/ios/Backplane/DataViews.swift b/mobile/ios/Backplane/DataViews.swift index e9e1ae75e6..8918282640 100644 --- a/mobile/ios/Backplane/DataViews.swift +++ b/mobile/ios/Backplane/DataViews.swift @@ -70,6 +70,7 @@ struct DataRoot: View { .onOpenURL { route($0) } // the telemetry notice's Settings link: Settings over what is open .onChange(of: client.openSettings) { _, v in if v { path.append(DPage(name: "settings")); client.openSettings = false } } + .onChange(of: client.openAccounts, initial: true) { _, v in if v { path.append(DPage(name: "settings")); path.append(DPage(name: "accounts")); client.openAccounts = false } } .onChange(of: client.pushThread, initial: true) { _, t in if !t.isEmpty { var p = NavigationPath(); p.append(t); path = p; client.pushThread = "" } } // an alert that a sign-in expired: Settings, Accounts, that account, its sign-in started .onChange(of: client.pushAccount, initial: true) { _, a in if !a.isEmpty { var p = NavigationPath(); p.append(DPage(name: "settings")); p.append(DPage(name: "accounts")); p.append(DAccountRoute(id: a, start: true)); path = p; client.pushAccount = "" } } @@ -84,6 +85,9 @@ struct DataRoot: View { case .thread: path.append(t.id) case .file: path.append(DViewerRoute(id: t.id, file: t.path, line: t.line)) case .project: path = NavigationPath(); client.focusProject = t.id + case .settings: + path.append(DPage(name: "settings")) + if t.id == "accounts" { path.append(DPage(name: "accounts")) } case .room: Task { if !client.rooms.contains(where: { $0.id == t.id }) { await client.loadBots() } @@ -99,7 +103,9 @@ struct DataRoot: View { // (a thread link from outside: the hub says which thread it is, so `desktop~t9` and a link id both open the one on that machine) if url.host == "thread" { client.openLink(url, thread: "") } else if url.host == "google" { return } // the end of a Google sign-in (GoogleLoop): not a pairing link - else if url.host == "account" { if let id = url.pathComponents.dropFirst().first { client.pushAccount = id } } else { client.opened(url) } + else if url.host == "account" { if let id = url.pathComponents.dropFirst().first { client.pushAccount = id } } + else if url.host == "settings" { if url.pathComponents.dropFirst().first == "accounts" { client.openAccounts = true } else { client.openSettings = true } } + else { client.opened(url) } } // a picture from another app (Open in / Share, Files): a copy in the app's Inbox, or a file it may read for a moment private func take(_ url: URL) { @@ -155,6 +161,7 @@ struct DataThreadsView: View { DataTelemetryBanner(client: client) DataStarBanner(client: client) DataAlertsBanner(client: client) + DataNoProviderBanner(client: client) if client.restartLine != .none { DataConnectionBanner(client: client) } HStack(spacing: 8) { if client.has("search") { @@ -873,6 +880,7 @@ struct DataThreadView: View { findGo = nil } } + if !id.contains("~") { DataNoProviderBanner(client: client) } if let review { DataReviewBar(bar: review, enabled: !reviewing) { press(review) } } if let order { DataOrderCard(order: order) } if let m = thread?.mark { Text(dAway(Tr.t(m.runs), m.away)).dmono(11).foregroundStyle(BackplaneDesign.faint).frame(maxWidth: .infinity, alignment: .leading).padding(.horizontal, 14).padding(.top, 4).accessibilityIdentifier("data.thread.runs") } @@ -1311,7 +1319,14 @@ struct DataQueueStrip: View { } }.accessibilityElement(children: .contain).accessibilityIdentifier("queue.row") } - if let e = client.queueError[thread] { Text(Tr.t(e)).dmono(11).foregroundStyle(BackplaneDesign.bad).accessibilityIdentifier("queue.error") } + if let e = client.queueError[thread] { + HStack(spacing: 8) { + Text(Tr.t(e)).dmono(11).foregroundStyle(BackplaneDesign.bad).frame(maxWidth: .infinity, alignment: .leading).accessibilityIdentifier("queue.error") + if DNoProvider.isSendError(e) { + Button(Tr.t("Open Settings → Accounts")) { client.openAccounts = true }.buttonStyle(DButton(compact: true)).accessibilityIdentifier("queue.error.accounts") + } + } + } } .padding(.horizontal, 14).padding(.vertical, 6).frame(maxWidth: .infinity, alignment: .leading).background(BackplaneDesign.panel) .overlay(alignment: .top) { DLine() } @@ -1902,6 +1917,24 @@ struct DataReviewBar: View { } } +/// Proactive banner shown when the hub has zero AI providers configured or signed in. +struct DataNoProviderBanner: View { + let client: DataClient + var body: some View { + if let n = client.noProvider { + VStack(alignment: .leading, spacing: 6) { + Text(Tr.t(n.head)).dmono(12, bold: true).foregroundStyle(BackplaneDesign.text).accessibilityIdentifier("provider.notice.head") + if !n.text.isEmpty { Text(Tr.t(n.text)).dmono(11).foregroundStyle(BackplaneDesign.dim).accessibilityIdentifier("provider.notice.text") } + Button(n.button.isEmpty ? Tr.t("Open Settings → Accounts") : Tr.t(n.button)) { client.openAccounts = true } + .buttonStyle(DButton(primary: true, compact: true)).accessibilityIdentifier("provider.notice.button") + } + .frame(maxWidth: .infinity, alignment: .leading) + .padding(.horizontal, 10).padding(.vertical, 8).background(BackplaneDesign.panel).overlay(Rectangle().strokeBorder(BackplaneDesign.warn, lineWidth: 1)) + .padding(.horizontal, 12).padding(.vertical, 6).accessibilityElement(children: .contain).accessibilityIdentifier("provider.notice") + } + } +} + /// A buy thread's Order card: the steps, the hub's line, the total and what it covers about customs, and Buy now (the hub's link, opened in the browser). As the Android app's OrderCard. struct DataOrderCard: View { let order: DOrder diff --git a/mobile/ios/Shared/TrCatalog.swift b/mobile/ios/Shared/TrCatalog.swift index e33a80f534..5c4ed34ccd 100644 --- a/mobile/ios/Shared/TrCatalog.swift +++ b/mobile/ios/Shared/TrCatalog.swift @@ -4901,6 +4901,13 @@ mobile.plan.touchhint Drag waypoints to steer · Tap + to add · Tap point to re mobile.plan.copied Copied コピーしました Copiado mobile.plan.widthmm {v} mm {v} mm {v} mm mobile.plan.coord ({x}, {y} mm) ({x}, {y} mm) ({x}, {y} mm) +provider.notice.head No AI provider connected AI プロバイダーが接続されていません No hay ningún proveedor de IA conectado +provider.notice.text.none Connect Claude, Codex, Antigravity, or another provider to start chatting. チャットを始めるには、Claude、Codex、Antigravity などのプロバイダーを接続してください。 Conecta Claude, Codex, Antigravity u otro proveedor para empezar a chatear. +provider.notice.text.signedout Sign in to Claude, Codex, or another provider in Settings → Accounts to start chatting. チャットを始めるには、設定 → アカウントで Claude、Codex などのプロバイダーにサインインしてください。 Inicia sesión en Claude, Codex u otro proveedor en Configuración → Cuentas para empezar a chatear. +provider.notice.button Open Settings → Accounts 設定 → アカウントを開く Abrir Configuración → Cuentas +provider.notice.senderr No AI provider connected yet. Open Settings → Accounts to connect Claude, Codex, Antigravity, or another provider. AI プロバイダーがまだ接続されていません。設定 → アカウントを開いて、Claude、Codex、Antigravity などのプロバイダーを接続してください。 Aún no hay ningún proveedor de IA conectado. Abre Configuración → Cuentas para conectar Claude, Codex, Antigravity u otro proveedor. +web.settings.providers AI providers AI プロバイダー Proveedores de IA +web.settings.providers.browser Connect a provider in the Backplane desktop or mobile app under Settings → Accounts. Backplane のデスクトップまたはモバイルアプリの設定 → アカウントからプロバイダーを接続してください。 Conecta un proveedor en la aplicación de escritorio o móvil de Backplane en Configuración → Cuentas. """# /// thread.count = {n, plural, one {# thread} other {# threads}} diff --git a/native/gpui/src/main.rs b/native/gpui/src/main.rs index e372dda586..b85e6fd477 100644 --- a/native/gpui/src/main.rs +++ b/native/gpui/src/main.rs @@ -109,7 +109,11 @@ impl Backplane { let(hub_at,token_file)=(screens::attach::Target::from(&config.hub,&config.token_file),config.token_file.clone()); let elsewhere=hubs::elsewhere(&config.hub);let(tx,events)=hub::connect(config); // started with a thread's link (the system's handler for backplane://): the hub opens it once the window is up - if let Some(l)=open_link {let _=tx.try_send(Command::Action("link-open".into(),l));} + if let Some(l)=open_link { + if screens::linkroute::settings_page(&l).as_deref()==Some("accounts") { + cx.spawn(async move |weak,cx|{let _=weak.update(cx,|this,cx|this.open_accounts(cx));}).detach(); + } else { let _=tx.try_send(Command::Action("link-open".into(),l)); } + } screens::place::watch(cx);screens::devbar::watch(cx);screens::hubbar::watch(cx,hub_at,&token_file); cx.spawn(async move |weak,cx|{while let Ok(event)=events.recv().await {if weak.update(cx,|this,cx|this.receive(event,cx)).is_err(){break;}}}).detach(); // the keys held show their hints only in the window in use (keys::hint_mode): its focus coming or going draws them again @@ -350,6 +354,16 @@ impl Backplane { if ui.open_local||hub_open{ui.open_local=false;ui.device=false;ui.accounts=false;} else {ui.open_local=true;ui.device=true;self.screens.focus_settings=true;} let _=self.tx.try_send(Command::Action("flag".into(),"settings".into()));cx.notify(); } + /// Open Settings directly on the client-rendered Accounts tab. + pub fn open_accounts(&mut self,cx:&mut Context){ + self.want_focus=true; + if !screens::settings::is_open(self){self.open_settings(cx);} + self.screens.settings_ui.device=false; + self.screens.settings_ui.hubs=false; + self.screens.settings_ui.accounts=true; + screens::accounts::open_page(self,cx); + cx.notify(); + } /// Search threads (the top bar's button; Ctrl+Shift+F is Find across threads, palette.rs): the sidebar's box takes the keys; a sidebar folded to its strip, by hand or for want of room, unfolds first /// (the box is not drawn there: `sidebar_open` alone missed the fold for room, and the press did nothing) pub fn focus_search(&mut self,cx:&mut Context){if !self.sidebar_open{self.screens.side_force=false;self.sidebar_toggle(cx);}else if !self.screens.side_shown{self.screens.side_force=true;}self.ui_epoch+=1;self.screens.projects.focus=Some("search");cx.notify();} diff --git a/native/gpui/src/pairing.rs b/native/gpui/src/pairing.rs index 9881dc70b1..48b1364cb2 100644 --- a/native/gpui/src/pairing.rs +++ b/native/gpui/src/pairing.rs @@ -8,7 +8,7 @@ const SCHEMES: [&str; 3] = ["backplane://", "bpgpui://", "backplane-gpui://"]; pub fn is_link(s: &str) -> bool { SCHEMES.iter().any(|p| s.starts_with(p)) } /// A link to something to open, not a pairing: `backplane://thread/` (a thread of another machine `~` too) or `backplane://project/`. /// The hub decides what it opens (`link-open`); this only tells it from a pairing link. -pub fn is_open_link(s: &str) -> bool { SCHEMES.iter().any(|p| s.strip_prefix(p).map_or(false, |r| r.starts_with("thread/") || r.starts_with("project/"))) } +pub fn is_open_link(s: &str) -> bool { SCHEMES.iter().any(|p| s.strip_prefix(p).map_or(false, |r| r.starts_with("thread/") || r.starts_with("project/") || r.starts_with("settings/"))) } #[derive(Debug, PartialEq, Clone)] pub struct Invitation { pub origin: String, pub secret: String, /** every address to try, in order (the link's own first) */ pub routes: Vec, /** a link, not an address typed by the person */ pub from_link: bool } @@ -252,7 +252,7 @@ mod tests { fn inv(origin: &str, secret: &str) -> Option { Some(Invitation { origin: origin.into(), secret: secret.into(), routes: vec![origin.into()], from_link: true }) } fn code(origin: &str, secret: &str) -> Option { inv(origin, secret).map(|i| Invitation { from_link: false, ..i }) } #[test] fn a_thread_link_is_opened_not_paired() { - for l in ["backplane://thread/t1", "backplane://thread/lap~t9#m3", "backplane://project/p1", "bpgpui://thread/t1"] { assert!(is_open_link(l) && is_link(l), "{l}"); } + for l in ["backplane://thread/t1", "backplane://thread/lap~t9#m3", "backplane://project/p1", "backplane://settings/accounts", "bpgpui://thread/t1"] { assert!(is_open_link(l) && is_link(l), "{l}"); } for l in ["backplane://pair?url=x", "https://x/thread/t1", "backplane://person"] { assert!(!is_open_link(l), "{l}"); } } #[test] fn a_link_gives_its_hub_and_secret() { diff --git a/native/gpui/src/screens/linkroute.rs b/native/gpui/src/screens/linkroute.rs index e198a44b7a..33d94f2941 100644 --- a/native/gpui/src/screens/linkroute.rs +++ b/native/gpui/src/screens/linkroute.rs @@ -3,10 +3,19 @@ //! its project's thread and the viewer tab that draws it, never the system's app for a design file), anything else says so. #[derive(Clone, Debug, PartialEq)] -pub enum Route { Web(String), Hub(String), File(String), /** a part, pin or net of the thread's design (screens/xprobe.rs) */ Design(String), Note(&'static str), +pub enum Route { Web(String), Hub(String), File(String), Settings(String), /** a part, pin or net of the thread's design (screens/xprobe.rs) */ Design(String), Note(&'static str), /** an agent's plan review (`backplane://plan/`, the hub's plan/mod.rs `review_link`): that board with its Plan panel */ Plan(String), /** a file an agent shared (`/s//`, the hub's files/share.rs `share_route`): it downloads from the hub */ Share(String) } +/// Match `backplane://settings/` (or app scheme alias) and return the normalized page name. +pub fn settings_page(href: &str) -> Option { + let h = href.trim(); + let rest = ["backplane://settings/", "bpgpui://settings/", "backplane-gpui://settings/"] + .iter().find_map(|p| h.strip_prefix(p))?; + let page = rest.split(['#', '?']).next().unwrap_or("").trim_end_matches('/'); + (!page.is_empty()).then(|| page.to_string()) +} + /// `%XX` decoded (a link's path segments, as the hub's md/refs.rs `uri` writes them); a bad escape is kept as it is. fn unpct(s: &str) -> String { let b = s.as_bytes(); let mut out = Vec::with_capacity(b.len()); let mut i = 0; @@ -18,6 +27,7 @@ fn unpct(s: &str) -> String { pub fn route(href: &str, file: bool) -> Route { let h = href.trim(); if let Some(rel) = h.strip_prefix("backplane://plan/").map(|r| r.split(['#', '?']).next().unwrap_or("")).filter(|r| !r.is_empty()) { return Route::Plan(rel.split('/').map(unpct).collect::>().join("/")) } + if let Some(page) = settings_page(h) { return Route::Settings(page) } if let Some(w) = h.strip_prefix(super::xprobe::HREF).filter(|w| !w.is_empty()) { return Route::Design(w.to_string()) } if h.starts_with("backplane://") || crate::pairing::is_open_link(h) { return Route::Hub(h.to_string()) } if h.starts_with("https://") || h.starts_with("http://") || h.starts_with("mailto:") { return Route::Web(h.to_string()) } @@ -180,4 +190,10 @@ mod tests { #[test] fn the_hover_target_drops_a_message_anchor_only_on_backplane_links() { assert_eq!(target("backplane://thread/t1#m3"), "backplane://thread/t1"); assert_eq!(target("https://a.io/#x"), "https://a.io/#x"); } + #[test] fn settings_links_route_to_settings_page() { + assert_eq!(route("backplane://settings/accounts", false), Route::Settings("accounts".into())); + assert_eq!(route("bpgpui://settings/accounts/", false), Route::Settings("accounts".into())); + assert_eq!(route("backplane://settings/agents?x=1", false), Route::Settings("agents".into())); + assert_eq!(settings_page("https://example.com/settings/accounts"), None); + } } diff --git a/native/gpui/src/screens/mod.rs b/native/gpui/src/screens/mod.rs index 2a815e5eb4..e90953baf5 100644 --- a/native/gpui/src/screens/mod.rs +++ b/native/gpui/src/screens/mod.rs @@ -11,6 +11,7 @@ pub mod handoff; pub mod thought; pub mod halt; pub mod unanswered; +pub mod provider_notice; pub mod google; pub mod migrate; pub mod voice; diff --git a/native/gpui/src/screens/pair.rs b/native/gpui/src/screens/pair.rs index 1474ac71fc..543d5b738c 100644 --- a/native/gpui/src/screens/pair.rs +++ b/native/gpui/src/screens/pair.rs @@ -27,8 +27,11 @@ pub fn start(unpaired: bool, link: Option<&str>, cx: &mut Context) -> } /// A link the system handed the running app. pub fn incoming(this: &mut Backplane, link: &str, cx: &mut Context) { - // a thread or project to open (one of another machine too): the hub says what it opens - if pairing::is_open_link(link) { let _ = this.tx.try_send(crate::hub::Command::Action("link-open".into(), link.to_string())); cx.notify(); return } + // a thread, project, or settings link to open: Settings → Accounts opens directly, the rest goes to the hub + if pairing::is_open_link(link) { + if crate::screens::linkroute::settings_page(link).as_deref() == Some("accounts") { this.open_accounts(cx); return } + let _ = this.tx.try_send(crate::hub::Command::Action("link-open".into(), link.to_string())); cx.notify(); return + } if this.pair.is_none() { this.pair = Some(Ui::new(false, cx)); } if let Some(ui) = &mut this.pair { asked(ui, link) } cx.notify(); diff --git a/native/gpui/src/screens/provider_notice.rs b/native/gpui/src/screens/provider_notice.rs new file mode 100644 index 0000000000..3ba140a411 --- /dev/null +++ b/native/gpui/src/screens/provider_notice.rs @@ -0,0 +1,89 @@ +//! Proactive zero-provider notice over the composer (`shown["noProvider"]`), plus the one-click Accounts action +//! beside no-provider send-guard errors (`crate::settings::provider_notice`). +use crate::{i18n::{t, trs}, string, theme, ui::{ic, with_rect}, Backplane}; +use gpui::{prelude::*, *}; +use serde_json::Value; + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Notice { + pub head: String, + pub text: String, + pub button: String, + pub url: String, +} + +/// Parse the hub's `shown["noProvider"]` object; None when null or empty. +pub fn parse(v: &Value) -> Option { + let head = v["head"].as_str().filter(|h| !h.trim().is_empty())?.to_string(); + let text = string(v, "text"); + let button = v["button"].as_str().filter(|b| !b.trim().is_empty()).map(str::to_string).unwrap_or_else(|| t("provider.notice.button")); + let url = v["url"].as_str().filter(|u| !u.trim().is_empty()).unwrap_or("backplane://settings/accounts").to_string(); + Some(Notice { head, text, button, url }) +} + +pub fn is_send_error(err: &str) -> bool { + err.contains("No AI provider connected") +} + +pub fn view(cx: &mut Context, light: bool, v: &Value, hidden: bool) -> Option { + if hidden { return None } + let n = parse(v)?; + let c = |k: &str| theme::color(light, k); + let top = div().flex().items_center().gap_2() + .child(ic(light, "plug", 14., "warn")) + .child(div().text_size(px(13.)).font_weight(FontWeight::SEMIBOLD).text_color(c("text")).child(trs(&n.head))); + let btn = with_rect(div().id("no-provider-open-accounts"), || "no-provider:accounts".to_string()) + .px_3().py_1().text_size(px(12.)).cursor_pointer() + .bg(c("accent")).text_color(c("on-accent")).hover(|s| s.opacity(0.9)) + .child(trs(&n.button)) + .on_click(cx.listener(|this, _, _, cx| { this.open_accounts(cx); })); + let acts = div().flex().flex_wrap().items_center().gap_2().mt_1().child(btn); + let mut body = div().flex_1().min_w_0().flex().flex_col().gap_1().px_3().py_2().child(top); + if !n.text.is_empty() { + body = body.child(div().text_size(px(12.)).text_color(c("dim")).child(trs(&n.text))); + } + Some(with_rect(div().id("no-provider"), || "no-provider".to_string()) + .w_full().flex().border_1().border_color(c("line")).bg(c("panel")) + .child(div().w(px(3.)).flex_shrink_0().bg(c("warn"))) + .child(body.child(acts)) + .into_any_element()) +} + +pub fn error_action(cx: &mut Context, light: bool, err: &str) -> Option { + if !is_send_error(err) { return None } + let c = |k: &str| theme::color(light, k); + Some(with_rect(div().id("no-provider-error-accounts"), || "no-provider:error-accounts".to_string()) + .px_2().py(px(2.)).border_1().border_color(c("line")).bg(c("panel")).text_size(px(11.)).text_color(c("accent")).cursor_pointer() + .hover(|s| s.bg(c("raise"))) + .child(t("provider.notice.button")) + .on_click(cx.listener(|this, _, _, cx| { this.open_accounts(cx); })) + .into_any_element()) +} + +#[cfg(test)] +mod tests { + use super::*; + use core::prelude::v1::test; + + #[test] + fn parses_hub_notice_and_detects_send_error() { + let v = serde_json::json!({ + "reason": "none_installed", + "head": "No AI provider connected", + "text": "Connect Claude, Codex, Antigravity, or another provider to start chatting.", + "button": "Open Settings → Accounts", + "url": "backplane://settings/accounts", + }); + let n = parse(&v).unwrap(); + assert_eq!(n.head, "No AI provider connected"); + assert_eq!(n.text, "Connect Claude, Codex, Antigravity, or another provider to start chatting."); + assert_eq!(n.button, "Open Settings → Accounts"); + assert_eq!(n.url, "backplane://settings/accounts"); + assert_eq!(parse(&Value::Null), None); + assert_eq!(parse(&serde_json::json!({"head": ""})), None); + assert!(is_send_error("No AI provider connected yet. Open Settings → Accounts to connect Claude, Codex, Antigravity, or another provider.")); + assert!(!is_send_error("Some other error")); + let icons: serde_json::Map = serde_json::from_str(include_str!("../../../../assets/icons.json")).unwrap(); + assert!(icons.contains_key("plug")); + } +} diff --git a/native/gpui/src/screens/timeline.rs b/native/gpui/src/screens/timeline.rs index f6d68612d8..fd5ad089e4 100644 --- a/native/gpui/src/screens/timeline.rs +++ b/native/gpui/src/screens/timeline.rs @@ -696,6 +696,10 @@ impl Backplane { } } super::linkroute::Route::Share(u) => { self.note.clear(); let name = super::linkroute::share_name(&u).unwrap_or_default(); self.download(u, name, super::dlbar::From::Other, cx) } super::linkroute::Route::Web(u) => cx.open_url(&u), + super::linkroute::Route::Settings(page) => { + self.note.clear(); + if page == "accounts" { self.open_accounts(cx); } else { self.go("link-open", format!("backplane://settings/{page}"), cx); } + } super::linkroute::Route::Hub(u) => { self.note.clear(); self.go("link-open", u, cx); } super::linkroute::Route::Note(n) => self.note = n.to_string(), super::linkroute::Route::Design(w) => super::xprobe::clicked(self, &w), diff --git a/native/gpui/src/ui.rs b/native/gpui/src/ui.rs index 48453445dd..d6fce1a720 100644 --- a/native/gpui/src/ui.rs +++ b/native/gpui/src/ui.rs @@ -1251,10 +1251,13 @@ impl Render for Backplane { .when(has_home && !page_list, |d| d.child(div().id("home").track_scroll(&self.screens.home_scroll).overflow_y_scroll().flex_1().min_h_0().flex().flex_col().items_center().child(div().w_full().flex_none().max_w(px(930.)).p_4().flex().flex_col().gap_3().children(home_els)))) // a list: only the rows on screen are drawn, however much of the thread is held, and it keeps the reader's place as rows land above them .when(!has_home, |d| d.child(self.screens.parts.el(Backplane::timeline_part, StyleRefinement::default().flex_1().min_h_0(), cx))) - .when(!self.error.is_empty(), |d| d.child(div().px_5().py_2().text_color(c("bad")).child(crate::i18n::trs(&self.error)))) + .when(!self.error.is_empty(), |d| d.child(div().px_5().py_2().flex().flex_wrap().items_center().gap_2() + .child(div().text_color(c("bad")).child(crate::i18n::trs(&self.error))) + .children(crate::screens::provider_notice::error_action(cx, light, &self.error)))) .when(!self.note.is_empty(), |d| d.child(div().px_5().py_2().text_color(c("dim")).child(crate::i18n::trs(&self.note)))) .child(div().flex_shrink_0().relative().child(art::probe("composer")).children(crate::perf::mark("composer")).border_t_1().border_color(c("rule")).flex().justify_center().child(div().w_full().max_w(px(930.)).px_4().py_3().flex().flex_col().gap_2() .when(show_popup, |d| d.child(div().relative().border_1().border_color(c("line")).bg(c("panel")).child(popup).children(popup_bar))) + .children(crate::screens::provider_notice::view(cx, light, &self.data["noProvider"], self.data["tour"].is_object() || (self.project_page.is_none() && thread["mark"].is_object()))) .children(crate::screens::review::view(cx, light, &thread["review"])) .children(crate::screens::planmode::bar(cx, light, thread)) .children(crate::screens::order::view(cx, light, &thread["order"])) @@ -1273,7 +1276,9 @@ impl Render for Backplane { // another machine's thread: where an agent sent from here runs .children(if self.project_page.is_some() { None } else { crate::screens::badge::runs_text(&thread["mark"]).map(|r| div().id("runs-on").flex().items_center().gap(px(3.)).text_size(crate::scale::tpx(11.)).text_color(c("dim")).child(ic(light, "link", 11., "dim")).child(r)) }) // a project's page: what the hub said when it would not do what the page asked (a New thread refused), one line by the box - .children((self.project_page.is_some() && !self.screens.projects.refused.is_empty()).then(|| div().id("page-error").text_size(crate::scale::tpx(11.)).text_color(c("bad")).child(self.screens.projects.refused.clone()))) + .children((self.project_page.is_some() && !self.screens.projects.refused.is_empty()).then(|| div().id("page-error").flex().flex_wrap().items_center().gap_2() + .child(div().text_size(crate::scale::tpx(11.)).text_color(c("bad")).child(crate::i18n::trs(&self.screens.projects.refused))) + .children(crate::screens::provider_notice::error_action(cx, light, &self.screens.projects.refused)))) // text a page's Send could not deliver while the box held new text: offered back, never merged (Restore puts it in the box, what was there is kept to restore) .children(self.screens.projects.restore.clone().map(|t| { let preview: String = t.chars().take(60).collect(); /* i18n-ok: a ctl id the drivers press */ with_rect(div().id("restore-unsent"), || "ui:restore unsent".to_string()).flex().items_center().gap(px(6.)).text_size(crate::scale::tpx(11.)).text_color(c("dim")).cursor_pointer().hover(|s| s.text_color(c("text"))) diff --git a/native/host/src/agents/mod.rs b/native/host/src/agents/mod.rs index 490f369b76..ec5d600ac2 100644 --- a/native/host/src/agents/mod.rs +++ b/native/host/src/agents/mod.rs @@ -555,6 +555,11 @@ impl RpcHandler for Rpc { if method == "thread.btw" { let q = p.get("q").and_then(Value::as_str).unwrap_or("").trim().to_string(); if q.is_empty() { return vec![err(id, crate::session::composer::BTW_EMPTY)] } + if who.client > 0 { + if let Some(why) = crate::settings::provider_notice::send_guard(hub).await { + return vec![err(id, why)]; + } + } let (ag, th, id2) = (self.0.clone(), th.to_string(), id.clone()); let answer = async move { let a = ag.side_answer(&th, &q).await; json!({"t":"reply","id":id2,"ok":true,"result":{"thread":th,"q":q,"btw":a}}) }; // nothing is logged and no turn sees it. The model may take a minute: a connection answers everything else meanwhile, and its reply comes when it comes. A caller with no socket of its own (a linked machine's) waits. @@ -612,6 +617,11 @@ impl Agents { let attached: Vec = p.get("attachments").filter(|a| a.as_array().map_or(false, |x| !x.is_empty())).map(|a| vec![json!({"$":"MessageAttached","thread":th,"msg":msg,"attachments":a,"at":now_s()})]).unwrap_or_default(); // `/restore [turn]` from the person: the hub puts the project back to before that turn itself, no agent turn (snapguard.rs) if who.client > 0 && !retry { if let Some(n) = snapguard::restore_command(text) { return self.restore_command(th, n).await } } + if who.client > 0 && !retry && (!text.trim().is_empty() || !attached.is_empty()) { + if let Some(why) = crate::settings::provider_notice::send_guard(&self.hub).await { + return Err(why.to_string()); + } + } if who.client > 0 && !retry && !text.trim().is_empty() { // the star nudge counts this prompt in the same commit; the offer (the fifth) goes to this connection after it let (mut extra, offer) = crate::statehost::policies().map(|p| p.star_prompt(&msg, now_s())).unwrap_or((vec![], None)); diff --git a/native/host/src/bots/rpc.rs b/native/host/src/bots/rpc.rs index df3898c7de..a9977079ef 100644 --- a/native/host/src/bots/rpc.rs +++ b/native/host/src/bots/rpc.rs @@ -339,6 +339,15 @@ impl Bots { if !w.live(bot) { return vec![err(id, "no such bot")] } let th = w.bot(bot).map(|b| b.thread.clone()).unwrap_or_default(); if !msg.is_empty() && (w.has_msg(&th, msg) || w.inflight.contains(&(th.clone(), msg.to_string()))) { return vec![ok(id)] } + if star.is_some() && !text.trim().is_empty() { + drop(w); + if let Some(why) = crate::settings::provider_notice::send_guard(&self.hub).await { + return vec![err(id, why)]; + } + w = self.world().await; + if !w.live(bot) { return vec![err(id, "no such bot")] } + if !msg.is_empty() && (w.has_msg(&th, msg) || w.inflight.contains(&(th.clone(), msg.to_string()))) { return vec![ok(id)] } + } let q = if to.is_empty() { None } else { self.quoted(&w, &th, to) }; let text = reply::resolve(to, q.as_deref(), text); let now = now_s(); let mid = if msg.is_empty() { self.id("m", now) } else { msg.to_string() }; diff --git a/native/host/src/data/link.rs b/native/host/src/data/link.rs index 39818845d8..5e02c4893a 100644 --- a/native/host/src/data/link.rs +++ b/native/host/src/data/link.rs @@ -58,6 +58,7 @@ pub(super) async fn resolve(hub: &Arc, p: &Value) -> Result { if kind == "bot" { if let Some(b) = dir["bots"].as_array().and_then(|a| a.iter().find(|x| x["id"] == bid.as_str())) { return Ok(json!({"kind":"thread","thread":b["thread"]})) } return none("That conversation is not on this hub.") } none("That conversation has no screen on the phone.") } + "settings" => Ok(json!({"kind":"settings","page":id})), _ => none("The phone has no screen for that link."), }; } diff --git a/native/host/src/data/mod.rs b/native/host/src/data/mod.rs index 0c50ea6680..63d2dc2f6e 100644 --- a/native/host/src/data/mod.rs +++ b/native/host/src/data/mod.rs @@ -24,7 +24,7 @@ use tokio_tungstenite::tungstenite::{protocol::WebSocketConfig, Message}; pub const PROTO: &str = "data/1"; /// What this hub does beyond the base of data/1; a hub from before an addition does not list it (the app can warn instead of sending what would be dropped). -pub const FEATURES: &[&str] = &["images", "actions", "search", "models", "mentions", "bots", "notify", "viewers", "files", "browser", "diff", "review", "fold", "picker", "voice", "order", "layers", "onboard", "push", "settled", "commands", "work", "star", "accounts", "machines", "history", "terms", "links", "devices", "queue", "buy", "status", "subview", "find", "notifysettings", "ring", "hubOffer", "swarm", "sections", "telemetryNotice", "mcpsettings", "fabprofile", "plan", "mgmt", "replyImages", "cats", "projectcard", "termChat", "copy", "reviewmode", "rail", "gerbers", "follow", "unanswered", "browserstart", "restarting", "fileLinks", "layout", "clone", "reply", "deflate", "open", "shell", "home", "fork", "blobs", "keptChunks", "threadContext"]; +pub const FEATURES: &[&str] = &["images", "actions", "search", "models", "mentions", "bots", "notify", "viewers", "files", "browser", "diff", "review", "fold", "picker", "voice", "order", "layers", "onboard", "push", "settled", "commands", "work", "star", "accounts", "machines", "history", "terms", "links", "devices", "queue", "buy", "status", "subview", "find", "notifysettings", "ring", "hubOffer", "swarm", "sections", "telemetryNotice", "mcpsettings", "fabprofile", "plan", "mgmt", "replyImages", "cats", "projectcard", "termChat", "copy", "reviewmode", "rail", "gerbers", "follow", "unanswered", "browserstart", "restarting", "fileLinks", "layout", "clone", "reply", "deflate", "open", "shell", "home", "fork", "blobs", "keptChunks", "threadContext", "noProvider"]; const PREVIEW: usize = 140; const ASK_SCAN: usize = 4000; @@ -867,7 +867,7 @@ pub fn phone_info_frame(v: &Value) -> Option { let keep: serde_json::Map = v["info"].as_object()?.iter().filter(|(k, _)| phone_info(k)).map(|(k, v)| (k.clone(), v.clone())).collect(); (!keep.is_empty()).then(|| json!({"t":"info","info":keep})) } -pub fn phone_info(key: &str) -> bool { key == "hub.offer" || key == "hub.back" || key.starts_with("mgmt.") || key.starts_with("kicad.checks.") || key.starts_with("review.") } +pub fn phone_info(key: &str) -> bool { key == "hub.offer" || key == "hub.back" || key == crate::settings::provider_notice::INFO_KEY || key.starts_with("mgmt.") || key.starts_with("kicad.checks.") || key.starts_with("review.") } async fn handle(hub: &Arc, c: &mut Conn, subs: &mut Subs, v: &Value) -> Value { handle_for(hub, c, subs, v, false).await @@ -1009,7 +1009,8 @@ async fn socket_with_reg( crate::import014::phone_state(&hub).await, ) }; - let mut hello = json!({"t":"hello","proto":PROTO,"hub":host,"name":name,"version":hub.cfg.version,"epoch":hub.epoch,"now":now_ms(),"features":FEATURES,"theme":theme,"locale":locale,"hubOffer":hub_offer,"hubBack":hub.info_now()["hub.back"].as_str().unwrap_or(""),"commands":crate::session::composer::words(),"notice":notice,"migrating":migrating}); if let Some(c) = z { hello["z"] = json!(c) } + let no_provider = crate::settings::provider_notice::for_hub(&hub).await.map_or(Value::Null, |n| n.json()); + let mut hello = json!({"t":"hello","proto":PROTO,"hub":host,"name":name,"version":hub.cfg.version,"epoch":hub.epoch,"now":now_ms(),"features":FEATURES,"theme":theme,"locale":locale,"hubOffer":hub_offer,"hubBack":hub.info_now()["hub.back"].as_str().unwrap_or(""),"commands":crate::session::composer::words(),"notice":notice,"migrating":migrating,"noProvider":no_provider}); if let Some(c) = z { hello["z"] = json!(c) } // the home (feature "home", net/home.rs): where the uberbot lives, as this hub sees it; `k:"home"` pushes follow it on a lists subscription let mut home_sent = crate::net::home::now(&hub).await; hello["home"] = home_sent.clone(); tx.send(pack(&hello, json_mode)).await?; diff --git a/native/host/src/data/tests.rs b/native/host/src/data/tests.rs index db620454bb..3ae816b561 100644 --- a/native/host/src/data/tests.rs +++ b/native/host/src/data/tests.rs @@ -65,10 +65,10 @@ async fn ask(ws: &mut Ws, id: u64, m: &str, p: Value) -> Value { } #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn data_hello_capabilities_and_both_encodings() { - assert_eq!(crate::hub::capabilities()["data"]["proto"], "data/1"); assert_eq!(crate::hub::capabilities()["data"]["features"], json!(["images", "actions", "search", "models", "mentions", "bots", "notify", "viewers", "files", "browser", "diff", "review", "fold", "picker", "voice", "order", "layers", "onboard", "push", "settled", "commands", "work", "star", "accounts", "machines", "history", "terms", "links", "devices", "queue", "buy", "status", "subview", "find", "notifysettings", "ring", "hubOffer", "swarm", "sections", "telemetryNotice", "mcpsettings", "fabprofile", "plan", "mgmt", "replyImages", "cats", "projectcard", "termChat", "copy", "reviewmode", "rail", "gerbers", "follow", "unanswered", "browserstart", "restarting", "fileLinks", "layout", "clone", "reply", "deflate", "open", "shell", "home", "fork", "blobs", "keptChunks", "threadContext"])); + assert_eq!(crate::hub::capabilities()["data"]["proto"], "data/1"); assert_eq!(crate::hub::capabilities()["data"]["features"], json!(["images", "actions", "search", "models", "mentions", "bots", "notify", "viewers", "files", "browser", "diff", "review", "fold", "picker", "voice", "order", "layers", "onboard", "push", "settled", "commands", "work", "star", "accounts", "machines", "history", "terms", "links", "devices", "queue", "buy", "status", "subview", "find", "notifysettings", "ring", "hubOffer", "swarm", "sections", "telemetryNotice", "mcpsettings", "fabprofile", "plan", "mgmt", "replyImages", "cats", "projectcard", "termChat", "copy", "reviewmode", "rail", "gerbers", "follow", "unanswered", "browserstart", "restarting", "fileLinks", "layout", "clone", "reply", "deflate", "open", "shell", "home", "fork", "blobs", "keptChunks", "threadContext", "noProvider"])); let (_h, port) = up("hello").await; let mut ws = open(port, "&enc=json").await; let v = next(&mut ws).await; - assert_eq!((v["t"].as_str(), v["proto"].as_str()), (Some("hello"), Some("data/1"))); assert_eq!(v["hub"], format!("127.0.0.1:{port}"), "the hub as asked (the Host header)"); assert!(v["name"].is_string(), "the machine's name: {v}"); assert_eq!(v["features"], json!(["images", "actions", "search", "models", "mentions", "bots", "notify", "viewers", "files", "browser", "diff", "review", "fold", "picker", "voice", "order", "layers", "onboard", "push", "settled", "commands", "work", "star", "accounts", "machines", "history", "terms", "links", "devices", "queue", "buy", "status", "subview", "find", "notifysettings", "ring", "hubOffer", "swarm", "sections", "telemetryNotice", "mcpsettings", "fabprofile", "plan", "mgmt", "replyImages", "cats", "projectcard", "termChat", "copy", "reviewmode", "rail", "gerbers", "follow", "unanswered", "browserstart", "restarting", "fileLinks", "layout", "clone", "reply", "deflate", "open", "shell", "home", "fork", "blobs", "keptChunks", "threadContext"]), "a hub from before images does not list it"); assert!(v["now"].as_u64().unwrap() > 1_600_000_000_000); + assert_eq!((v["t"].as_str(), v["proto"].as_str()), (Some("hello"), Some("data/1"))); assert_eq!(v["hub"], format!("127.0.0.1:{port}"), "the hub as asked (the Host header)"); assert!(v["name"].is_string(), "the machine's name: {v}"); assert_eq!(v["features"], json!(["images", "actions", "search", "models", "mentions", "bots", "notify", "viewers", "files", "browser", "diff", "review", "fold", "picker", "voice", "order", "layers", "onboard", "push", "settled", "commands", "work", "star", "accounts", "machines", "history", "terms", "links", "devices", "queue", "buy", "status", "subview", "find", "notifysettings", "ring", "hubOffer", "swarm", "sections", "telemetryNotice", "mcpsettings", "fabprofile", "plan", "mgmt", "replyImages", "cats", "projectcard", "termChat", "copy", "reviewmode", "rail", "gerbers", "follow", "unanswered", "browserstart", "restarting", "fileLinks", "layout", "clone", "reply", "deflate", "open", "shell", "home", "fork", "blobs", "keptChunks", "threadContext", "noProvider"]), "a hub from before images does not list it"); assert!(v["now"].as_u64().unwrap() > 1_600_000_000_000); // the default is binary CBOR with plain string keys let mut c = open(port, "").await; let m = tokio::time::timeout(Duration::from_secs(5), c.next()).await.unwrap().unwrap().unwrap(); let Message::Binary(b) = m else { panic!("binary") }; assert!(b.windows(5).any(|w| w == b"proto"), "plain keys, not the hub's dictionary"); @@ -802,12 +802,13 @@ fn a_reply_reaches_a_phone_as_its_body_and_reply_to() { } #[test] fn phones_get_the_management_panels_and_checks_info() { use super::phone_info; - for k in ["hub.offer", "mgmt.state.abc", "mgmt.bom.abc", "mgmt.life.abc", "mgmt.fab.abc", "kicad.checks.abc"] { assert!(phone_info(k), "{k}") } + for k in ["hub.offer", "provider.notice", "mgmt.state.abc", "mgmt.bom.abc", "mgmt.life.abc", "mgmt.fab.abc", "kicad.checks.abc"] { assert!(phone_info(k), "{k}") } for k in ["editor.kicad.abc", "kicad.progress.abc", "browser.tabs.x", "terms"] { assert!(!phone_info(k), "{k}") } assert!(super::FEATURES.contains(&"mgmt")); + assert!(super::FEATURES.contains(&"noProvider")); // a set_info frame as the hub pushes it: the phone's keys kept, the rest left out - let f = super::phone_info_frame(&json!({"t":"info","info":{"mgmt.bom.d1":"{}","editor.kicad.d1":"x"}})).unwrap(); - assert_eq!(f, json!({"t":"info","info":{"mgmt.bom.d1":"{}"}})); + let f = super::phone_info_frame(&json!({"t":"info","info":{"mgmt.bom.d1":"{}","provider.notice":"{\"head\":\"x\"}","editor.kicad.d1":"x"}})).unwrap(); + assert_eq!(f, json!({"t":"info","info":{"mgmt.bom.d1":"{}","provider.notice":"{\"head\":\"x\"}"}})); assert!(super::phone_info_frame(&json!({"t":"info","info":{"terms":"[]"}})).is_none()); } @@ -1483,3 +1484,12 @@ async fn viewer_layout_over_a_socket_is_per_device_pushed_and_refuses_in_code_ke assert_eq!(got["sub"], sub); assert_eq!((got["home"]["kind"].as_str(), got["home"]["name"].as_str(), got["home"]["online"].as_bool(), got["home"]["canMoveHere"].as_bool()), (Some("peer"), Some("desktop"), Some(true), Some(true)), "{got}"); } + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn settings_accounts_link_resolves_for_phones_and_hello_carries_no_provider() { + let (_h, port) = up("link-settings").await; + let mut ws = open(port, "&enc=json").await; + let hello = next(&mut ws).await; + assert!(hello.get("noProvider").is_some(), "hello carries noProvider field: {hello}"); + let r = ask(&mut ws, 1, "link.resolve", json!({"url":"backplane://settings/accounts","thread":""})).await; + assert_eq!(r["result"], json!({"kind":"settings","page":"accounts"})); +} diff --git a/native/host/src/hub.rs b/native/host/src/hub.rs index 1d3793324c..7335aaf6c7 100644 --- a/native/host/src/hub.rs +++ b/native/host/src/hub.rs @@ -548,7 +548,7 @@ impl Hub { pub fn view_info_frame(&self) -> Option { let mut i = serde_json::Map::new(); for (k, v) in self.extra_info.lock().unwrap().iter() { - if !v.is_empty() && (k == "hub.offer" || k == "hub.back" || k == "kicad.update" || k == "kicad.install" || k.starts_with("editor.kicad.") || k.starts_with("kicad.reload.") || k.starts_with("kicad.sel.") || k.starts_with("kicad.coedit.") || k.starts_with("kicad.progress.") || k.starts_with("kicad.checks.") || k.starts_with("browser.tabs.")) { + if !v.is_empty() && (k == "hub.offer" || k == "hub.back" || k == crate::settings::provider_notice::INFO_KEY || k == "kicad.update" || k == "kicad.install" || k.starts_with("editor.kicad.") || k.starts_with("kicad.reload.") || k.starts_with("kicad.sel.") || k.starts_with("kicad.coedit.") || k.starts_with("kicad.progress.") || k.starts_with("kicad.checks.") || k.starts_with("browser.tabs.")) { i.insert(k.clone(), json!(v)); } } diff --git a/native/host/src/present/screen.rs b/native/host/src/present/screen.rs index 2f32c3ac0b..9cccff23fa 100644 --- a/native/host/src/present/screen.rs +++ b/native/host/src/present/screen.rs @@ -31,7 +31,7 @@ impl super::Screen for Recent { // a revoked device gone); opening the page reads it too (the page in the session is still the one before the press) let devpage=super::settings::page(¶ms["session"])=="devices" || (text(params,"action")=="settings-page" && text(params,"value")=="devices"); let acted; let params=if devpage && text(params,"action").starts_with("device-") { match super::settings::device_act(text(params,"action"),text(params,"value")) { Some(patch)=>{ let mut c=params.clone(); crate::session::patch::merge(&mut c["session"],&patch); c["action"]=json!(""); c["value"]=json!(""); acted=c; &acted } None=>params } } else { params }; - let withinfo; let params=if super::settings::is_open(¶ms["session"]) || shows_thread(params) || shows_swarm_models(params) || setup { let mut c=params.clone(); c["hubInfo"]=_hub.info_now(); c["hubInfo"]["client"]=params["client"].clone(); if devpage { if let Some(r)=crate::net::start::routes() { c["hubInfo"]["devices"]=r.devices(); } c["hubInfo"]["shares"]=json!(crate::files::share::listed_now()); } if setup || super::settings::page(¶ms["session"])=="machines" { if let Some(p)=crate::net::start::peering() { c["hubInfo"]["machines"]=p.page_data(); } } withinfo=c; &withinfo } else { params }; + let withinfo; let params=if super::settings::is_open(¶ms["session"]) || shows_thread(params) || shows_swarm_models(params) || setup { let mut c=params.clone(); c["hubInfo"]=_hub.info_now(); c["hubInfo"]["client"]=params["client"].clone(); if devpage { if let Some(r)=crate::net::start::routes() { c["hubInfo"]["devices"]=r.devices(); } c["hubInfo"]["shares"]=json!(crate::files::share::listed_now()); } if setup || super::settings::page(¶ms["session"])=="machines" { if let Some(p)=crate::net::start::peering() { c["hubInfo"]["machines"]=p.page_data(); } } withinfo=c; &withinfo } else { let mut c=params.clone(); c["hubInfo"]=json!({"models":crate::settings::models::info()}); withinfo=c; &withinfo }; // a 0.14 import of this hub: its card goes over any page (present/onboard.rs import_overlay) let withmig; let params=match crate::import014::last_published(&_hub.cfg.home) { Some(v) => { let mut c=params.clone(); c["importV014"]=v; withmig=c; &withmig } None => params }; let m=_hub.mirrors(); @@ -938,6 +938,8 @@ pub fn recent_unified(st: &State,far: &[(String,&State)],un: &Unified,p: &Value) let shown=json!({"projects":projects,"sidebarPages":pages,"nativeSidebar":1,"active":[],"legacy":[],"thread":shown_thread,"rooms":rooms(st,far,un,hub),"bots":bots(st,far,un,hub,opts.now),"theme":setting(st,"ui.theme"),"mouse":json!({"2d":setting(st,"mouse.2d"),"3d":setting(st,"mouse.3d"),"invert":setting(st,"mouse.invert")}),"browserStart":crate::settings::browser_start::url(setting(st,crate::settings::browser_start::KEY)), "renaming":renaming,"deleting":deleting,"bot":null,"settings":if super::settings::is_open(&session) { super::settings::view(st,&session,p.get("hubInfo").unwrap_or(&Value::Null)) }else{Value::Null},"newRoom":super::botforms::new_room(st,hub,&session).unwrap_or(Value::Null),"newBot":super::botforms::new_bot(&session).unwrap_or(Value::Null),"projectHome":null}); let mut shown=shown; + let no_provider=crate::settings::provider_notice::from_screen(p.get("hubInfo").and_then(|h|h["models"].as_str()),setting(st,"accounts.inventory")); + if !no_provider.is_null() { shown["noProvider"]=no_provider; } if !far.is_empty() { shown["machines"]=machine_switch(far,un,&mpick); } // the sections (docs/ALWAYS-ON.md section 8): Bub, Needs you, Pinned, Active, groups, Quiet; the project page; Ctrl+K's list { let rows=merged_here(st,far,un); let open=super::sections::opened(&session); @@ -1782,4 +1784,25 @@ mod selected_thread_tests { assert_eq!(chosen["threads"].as_array().unwrap().last().unwrap()["id"],"h|t0-0"); assert_eq!(out["shown"]["thread"]["id"],"h|t0-0"); } + #[test] fn zero_provider_notice_is_shown_only_when_probed_and_unusable() { + let mut st=State::new(); st.lean=true; + st.apply(&json!({"$":"ProjectCreated","id":"p1","title":"P","root":"/tmp/synthetic","at":1})); + st.apply(&json!({"$":"ThreadCreated","id":"t1","project":"p1","title":"T","provider":"claude","model":"","at":2})); + let base=json!({"target":{"kind":"thread","id":"t1"},"nativeSidebar":1,"nativeKey":"00112233445566778899aabbccddeeff", + "hub":"h","generation":"g","epoch":"e","viewId":"v","revision":st.seq,"now":1000000,"session":{"drafts":{},"open":{}}, + "window":{"remaining":0},"page":{"thread":"t1","rows":[]}}); + assert!(recent(&st,&base).unwrap()["shown"].get("noProvider").is_none(), "unprobed builtin omits noProvider"); + let mut none=base.clone(); + none["hubInfo"]=json!({"models":json!({"probed":true,"about":{"claude":{"cli":""},"codex":{"cli":""}}}).to_string()}); + let np=recent(&st,&none).unwrap()["shown"]["noProvider"].clone(); + assert_eq!(np["reason"],"none_installed"); + assert_eq!(np["url"],"backplane://settings/accounts"); + let mut have=base.clone(); + have["hubInfo"]=json!({"models":json!({"probed":true,"about":{"claude":{"cli":"/usr/bin/claude"},"codex":{"cli":""}}}).to_string()}); + assert!(recent(&st,&have).unwrap()["shown"].get("noProvider").is_none()); + st.apply(&json!({"$":"SettingSet","key":"accounts.inventory","value":json!({"defaultLogin":{"claude":{"state":"signed-out"}}}).to_string(),"at":3})); + have["revision"]=json!(st.seq); + let so=recent(&st,&have).unwrap()["shown"]["noProvider"].clone(); + assert_eq!(so["reason"],"signed_out"); + } } diff --git a/native/host/src/settings/accounts_hub.rs b/native/host/src/settings/accounts_hub.rs index e76786ce43..168487e37b 100644 --- a/native/host/src/settings/accounts_hub.rs +++ b/native/host/src/settings/accounts_hub.rs @@ -155,6 +155,7 @@ pub async fn found_seen(hub: &Arc, agents: &Option>, snapshot: if !evs.is_empty() { let _ = hub.commit_many(&evs).await; } // a sign-in or sign-out: the CLI that did it is found again at once (one installed by hand since the last detection shows in the picker now) if evs.iter().any(|e| e["key"] == "accounts.inventory") { super::models_probe::refresh_soon(hub); } + super::provider_notice::publish(hub).await; let inventory = public(snapshot); // not broadcast: the live profiles go only to clients granted account access (the `accounts` request) // threads whose account changed under them diff --git a/native/host/src/settings/mod.rs b/native/host/src/settings/mod.rs index b3306fdcb8..739eebe7aa 100644 --- a/native/host/src/settings/mod.rs +++ b/native/host/src/settings/mod.rs @@ -46,6 +46,7 @@ pub mod models; pub mod models_probe; pub mod agent_versions; pub mod privacy; +pub mod provider_notice; pub mod provider_usage; pub mod proposal; pub mod secret; diff --git a/native/host/src/settings/models_probe.rs b/native/host/src/settings/models_probe.rs index 22a066c1bb..cef1920360 100644 --- a/native/host/src/settings/models_probe.rs +++ b/native/host/src/settings/models_probe.rs @@ -263,6 +263,7 @@ pub async fn refresh(hub: &Arc) -> bool { if !super::models::set_live(&info) { return false } let _ = std::fs::write(hub.cfg.home.join("models.cache.part"), cache_text(&info)).and_then(|_| std::fs::rename(hub.cfg.home.join("models.cache.part"), hub.cfg.home.join("models.cache"))); hub.push_all(&json!({"t":"info","info":{"models":super::models::info(),"models.all":super::models::all()}})); + super::provider_notice::publish(hub).await; hub.bump_views(); // a thread made before its agent was found (onboarding's first thread, on Claude, with only Codex installed) moves to one that is here if let Some(h) = hub.rpc_for("agents.fresh") { let _ = h.call(hub, &crate::api::Caller { gen: String::new(), client: 0 }, &json!(0), "agents.fresh", &json!({})).await; } @@ -289,7 +290,12 @@ pub fn refresh_soon(hub: &Arc) { /// At start: the list found last time at once, then a detection (after the window is up) and one every 15 minutes. A copy of a real log with no stand-ins probes nothing. pub fn start(hub: Arc) { - if let Some(i) = std::fs::read_to_string(hub.cfg.home.join("models.cache")).ok().as_deref().and_then(cache_read) { super::models::set_live(&i); } + let cached = std::fs::read_to_string(hub.cfg.home.join("models.cache")).ok().as_deref().and_then(cache_read); + if let Some(i) = &cached { + super::models::set_live(i); + let h = hub.clone(); + tokio::spawn(async move { super::provider_notice::publish(&h).await; }); + } if crate::copy::on() && std::env::var("BACKPLANE_AGENTS").map_or(true, |d| d.is_empty()) { return } super::models::set_detects(); tokio::spawn(async move { diff --git a/native/host/src/settings/provider_notice.rs b/native/host/src/settings/provider_notice.rs new file mode 100644 index 0000000000..82c867b2cf --- /dev/null +++ b/native/host/src/settings/provider_notice.rs @@ -0,0 +1,233 @@ +//! Clear zero-provider notification and actionable send guard across desktop, web, iOS, and Android. +//! Pure detection over `(models, accounts.inventory)` so every client renders the hub's single source of truth +//! without false positives during startup or in test fixtures before CLI detection completes. +use crate::hub::Hub; +use serde_json::{json, Value}; +use std::sync::Arc; + +pub const INFO_KEY: &str = "provider.notice"; +pub const ACCOUNTS_URL: &str = "backplane://settings/accounts"; +pub const HEAD: &str = "No AI provider connected"; +pub const TEXT_NONE_INSTALLED: &str = "Connect Claude, Codex, Antigravity, or another provider to start chatting."; +pub const TEXT_SIGNED_OUT: &str = "Sign in to Claude, Codex, or another provider in Settings → Accounts to start chatting."; +pub const BUTTON: &str = "Open Settings → Accounts"; +pub const SEND_GUARD_ERROR: &str = "No AI provider connected yet. Open Settings → Accounts to connect Claude, Codex, Antigravity, or another provider."; + +const NON_ACCOUNT_PROVIDERS: &[&str] = &["grok", "muse", "antigravity", "opencode", "pi", "omp"]; + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Notice { + pub reason: &'static str, // "none_installed" | "signed_out" + pub head: &'static str, + pub text: &'static str, + pub button: &'static str, + pub url: &'static str, +} + +impl Notice { + pub fn json(&self) -> Value { + json!({ + "reason": self.reason, + "head": self.head, + "text": self.text, + "button": self.button, + "url": self.url, + }) + } +} + +fn provider_usable(inv: &Value, provider: &str) -> bool { + let profiles = inv["profiles"].as_array(); + if profiles.into_iter().flatten().any(|p| { + p["provider"].as_str() == Some(provider) + && matches!(p["state"].as_str(), Some("connected" | "unchecked")) + }) { + return true; + } + match inv["defaultLogin"][provider]["state"].as_str() { + Some("signed-out") => false, + // Not yet checked, known login, or unknown auth (e.g. API key / env var): never false-positive. + None | Some(_) => true, + } +} + +/// Pure zero-provider check over probed `models` info and `accounts.inventory`. +pub fn check(models: &Value, inventory: &str) -> Option { + if models["probed"] != true { + return None; + } + if NON_ACCOUNT_PROVIDERS.iter().any(|p| crate::present::keys::is_installed(models, p)) { + return None; + } + let claude_cli = crate::present::keys::is_installed(models, "claude"); + let codex_cli = crate::present::keys::is_installed(models, "codex"); + if !claude_cli && !codex_cli { + return Some(Notice { + reason: "none_installed", + head: HEAD, + text: TEXT_NONE_INSTALLED, + button: BUTTON, + url: ACCOUNTS_URL, + }); + } + let inv: Value = serde_json::from_str(inventory).unwrap_or(Value::Null); + if !inv["error"].as_str().unwrap_or("").is_empty() { + return None; + } + if (claude_cli && provider_usable(&inv, "claude")) || (codex_cli && provider_usable(&inv, "codex")) { + return None; + } + Some(Notice { + reason: "signed_out", + head: HEAD, + text: TEXT_SIGNED_OUT, + button: BUTTON, + url: ACCOUNTS_URL, + }) +} + +/// Pure JSON value for presenter `shown["noProvider"]` (Null when a provider is usable or detection has not run). +pub fn from_screen(models_raw: Option<&str>, inventory: &str) -> Value { + let models = models_raw + .and_then(|s| serde_json::from_str::(s).ok()) + .unwrap_or(Value::Null); + check(&models, inventory).map_or(Value::Null, |n| n.json()) +} + +/// Pure send guard predicate for testability without mutating process-global `models` state. +pub fn guard_for(models: &Value, inventory: &str, client: u64, retry: bool, has_content: bool) -> Option<&'static str> { + if client == 0 || retry || !has_content { + return None; + } + check(models, inventory).map(|_| SEND_GUARD_ERROR) +} + +pub async fn for_hub(hub: &Arc) -> Option { + let models: Value = serde_json::from_str(&super::models::info()).unwrap_or(Value::Null); + let inventory = hub.setting("accounts.inventory").await.unwrap_or_default(); + check(&models, &inventory) +} + +pub async fn send_guard(hub: &Arc) -> Option<&'static str> { + for_hub(hub).await.map(|_| SEND_GUARD_ERROR) +} + +pub async fn publish(hub: &Arc) { + let val = for_hub(hub).await.map_or_else(String::new, |n| n.json().to_string()); + let _ = hub.set_info(INFO_KEY, &val).await; +} + +#[cfg(test)] +mod tests { + use super::*; + + fn probed_with(installed: &[&str]) -> Value { + let mut about = serde_json::Map::new(); + for (agent, _) in crate::present::keys::AGENTS { + let cli = if installed.contains(agent) { format!("/usr/bin/{agent}") } else { String::new() }; + about.insert((*agent).to_string(), json!({"cli": cli})); + } + json!({"probed": true, "about": about}) + } + + #[test] + fn unprobed_models_never_false_positive() { + let builtin: Value = serde_json::from_str(&crate::settings::models::builtin()).unwrap(); + assert_eq!(check(&builtin, ""), None); + assert_eq!(check(&Value::Null, ""), None); + assert_eq!(from_screen(None, ""), Value::Null); + } + + #[test] + fn zero_installed_clis_returns_none_installed_notice() { + let m = probed_with(&[]); + let n = check(&m, "").expect("expected notice with no CLIs installed"); + assert_eq!(n.reason, "none_installed"); + assert_eq!(n.head, HEAD); + assert_eq!(n.text, TEXT_NONE_INSTALLED); + assert_eq!(n.button, BUTTON); + assert_eq!(n.url, ACCOUNTS_URL); + assert_eq!(from_screen(Some(&m.to_string()), ""), n.json()); + } + + #[test] + fn signed_out_claude_and_codex_with_no_connected_profiles_returns_signed_out_notice() { + let m = probed_with(&["claude", "codex"]); + let inv = json!({ + "version": 1, + "revision": 2, + "profiles": [ + {"id": "p1", "provider": "claude", "state": "disconnected"}, + {"id": "p2", "provider": "codex", "state": "expired"} + ], + "defaultLogin": { + "claude": {"state": "signed-out"}, + "codex": {"state": "signed-out"} + }, + "error": "" + }).to_string(); + let n = check(&m, &inv).expect("expected signed_out notice"); + assert_eq!(n.reason, "signed_out"); + assert_eq!(n.text, TEXT_SIGNED_OUT); + assert_eq!(n.url, ACCOUNTS_URL); + } + + #[test] + fn usable_profiles_and_logins_stay_quiet() { + let m = probed_with(&["claude"]); + let inv_signed_out = json!({"defaultLogin": {"claude": {"state": "signed-out"}}}).to_string(); + assert!(check(&m, &inv_signed_out).is_some()); + + // Connected profile overrides signed-out default login + let inv_connected = json!({ + "profiles": [{"id": "w", "provider": "claude", "state": "connected"}], + "defaultLogin": {"claude": {"state": "signed-out"}} + }).to_string(); + assert_eq!(check(&m, &inv_connected), None); + + // Unchecked profile on startup avoids flash + let inv_unchecked = json!({ + "profiles": [{"id": "w", "provider": "claude", "state": "unchecked"}], + "defaultLogin": {"claude": {"state": "signed-out"}} + }).to_string(); + assert_eq!(check(&m, &inv_unchecked), None); + + // Known, unknown, or missing defaultLogin stays quiet + for st in ["known", "unknown"] { + let inv = json!({"defaultLogin": {"claude": {"state": st}}}).to_string(); + assert_eq!(check(&m, &inv), None, "state {st}"); + } + assert_eq!(check(&m, ""), None, "defaultLogin not yet checked"); + + // Inventory error stays quiet + let inv_err = json!({"defaultLogin": {"claude": {"state": "signed-out"}}, "error": "read failed"}).to_string(); + assert_eq!(check(&m, &inv_err), None); + } + + #[test] + fn other_installed_provider_or_codex_connected_stays_quiet() { + let both = probed_with(&["claude", "codex"]); + let inv_codex_ok = json!({ + "profiles": [{"id": "c1", "provider": "codex", "state": "connected"}], + "defaultLogin": {"claude": {"state": "signed-out"}, "codex": {"state": "signed-out"}} + }).to_string(); + assert_eq!(check(&both, &inv_codex_ok), None); + + for p in NON_ACCOUNT_PROVIDERS { + let m = probed_with(&[p]); + assert_eq!(check(&m, ""), None, "non-account provider {p} installed"); + } + } + + #[test] + fn send_guard_triggers_only_for_non_retry_person_messages_with_content() { + let none = probed_with(&[]); + assert_eq!(guard_for(&none, "", 1, false, true), Some(SEND_GUARD_ERROR)); + assert_eq!(guard_for(&none, "", 0, false, true), None, "internal hub sends allowed"); + assert_eq!(guard_for(&none, "", 1, true, true), None, "retry allowed"); + assert_eq!(guard_for(&none, "", 1, false, false), None, "empty allowed"); + + let ok = probed_with(&["grok"]); + assert_eq!(guard_for(&ok, "", 1, false, true), None); + } +} diff --git a/web/build.ts b/web/build.ts index d0a32e18d1..bea9b209c8 100644 --- a/web/build.ts +++ b/web/build.ts @@ -106,6 +106,11 @@ function collectI18nKeys(tsFiles: string[]): string[] { "gpui.mgmt.plan.st.partial", "gpui.mgmt.plan.st.rejected", "gpui.mgmt.plan.st.empty", + "provider.notice.head", + "provider.notice.text.none", + "provider.notice.text.signedout", + "provider.notice.button", + "provider.notice.senderr", ]); const re = /\bt\(\s*["']([a-zA-Z0-9_.-]+)["']/g; for (const f of tsFiles) { diff --git a/web/dist/assets/app.js b/web/dist/assets/app.js index 055b20ace0..7d7634624e 100644 --- a/web/dist/assets/app.js +++ b/web/dist/assets/app.js @@ -1,15 +1,15 @@ -function Ot(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 Pn(e){return e==="done"||e==="failed"||e==="cancelled"}function Nn(e,t){if(!e||e.id!==t.id)return!0;let n=Pn(e.state),i=Pn(t.state);if(n!==i)return i;return(t.ended??0)>=(e.ended??0)}function Mn(e){if(e.state!=="done")return!1;if(typeof e.hold==="boolean")return!e.hold;return(e.notes??[]).length===0}var ht={en:{"agy.signout":"Sign out","android.hub.machines.approve":"Approve","android.load.earlier":"load earlier","approval.dismiss":"Dismiss","approval.implement":"Implement","ask.plan":"Proposed plan","bots.rooms":"Rooms","bots.tab.browser":"Browser","common.cancel":"Cancel","common.close":"Close","common.copy":"Copy","common.delete":"Delete","common.refresh":"Refresh","common.remove":"Remove","common.save":"Save","composer.placeholder":"Ask anything: @bot, >thread, %project, #room, $skill, /btw","composer.send":"Send","composer.stop":"Stop","gpui.acct.connected":"Connected","gpui.acct.not.connected":"Not connected","gpui.acct.sign.in.expired":"Sign-in expired","gpui.ask.plan.ready":"Ready for review","gpui.ask.plan.revise":"Revise","gpui.ask.plan.reviseph":"What should change in the plan?","gpui.ask.plan.sendrev":"Send revision","gpui.b.in.reply.to":"↩ In reply to: {quote}","gpui.b.replying.to":"↩ Replying to: {line}","gpui.bots.recall.off":"Off","gpui.bots.recall.on":"On","gpui.c.term.collapse":"Collapse","gpui.c.term.expand":"Expand","gpui.commands":"Commands","gpui.e.open.folder":"Open folder","gpui.filter.projects.and.threads":"Filter projects and threads","gpui.fold.or.unfold.the.sidebar":"Fold or unfold the sidebar","gpui.follow.paused":"Following paused","gpui.follow.wait":"Following: waiting for the agent's next edit","gpui.gerbers":"Gerbers","gpui.improvements":"Improvements","gpui.jump.to.a.thread.run":"Jump to a thread, run a command or find what was said","gpui.mgmt.bom.dnp":"DNP","gpui.mgmt.bom.nompn":"no MPN","gpui.mgmt.checks.all":"All","gpui.mgmt.checks.fix":"Fix with agent","gpui.mgmt.checks.run":"Run","gpui.mgmt.close":"Close the panel","gpui.mgmt.fab.apply":"Apply","gpui.mgmt.fab.changed":"Changed since you last looked","gpui.mgmt.fab.derived":"* worked out from the fab's page (a mil in mm, a ring from a diameter). Dimmed: the rigid board's value, where this board's page says nothing else. A date opens the page it was read from.","gpui.mgmt.fab.extra":"Costs more","gpui.mgmt.fab.findings":"Findings","gpui.mgmt.fab.free":"Base price","gpui.mgmt.fab.judge":"Datasheets","gpui.mgmt.fab.limit":"Limit","gpui.mgmt.fab.readcol":"Read","gpui.mgmt.fab.refresh":"Refresh","gpui.mgmt.fab.reviewbtn":"Review","gpui.mgmt.fab.seen":"Seen","gpui.mgmt.fab.thefab":"The fab","gpui.mgmt.fab.use":"Use","gpui.mgmt.life.nopart":"No reading of this part yet.","gpui.mgmt.life.reading":"Reading its history…","gpui.mgmt.plan.addnote":"Add note","gpui.mgmt.plan.all":"Approve all","gpui.mgmt.plan.before":"Plan before routing","gpui.mgmt.plan.compact":"Compact","gpui.mgmt.plan.done":"done","gpui.mgmt.plan.drawn":"The plan's corridors and planes are drawn on the board while this panel is open. Close it to hide them.","gpui.mgmt.plan.edited":"Edited","gpui.mgmt.plan.elsewhere":"A routing plan for {board} awaits your approval","gpui.mgmt.plan.emptysub":"Layers, corridors, and planes appear here once a plan is proposed.","gpui.mgmt.plan.expand":"Expand","gpui.mgmt.plan.fit":"Fit","gpui.mgmt.plan.grid.all":"All layers","gpui.mgmt.plan.grid.pair":"Side by side","gpui.mgmt.plan.grid.single":"Single","gpui.mgmt.plan.hide":"Hide done","gpui.mgmt.plan.hint":"Drag waypoints to steer · Click + on edge to insert · Right-click vertex to remove","gpui.mgmt.plan.keysnote":"On this KiCad version, approve from this panel: in plan view KiCad's A, R and W keys aren't the plan's yet (A opens Add Footprint). Update KiCad.","gpui.mgmt.plan.layer":"Approve layer","gpui.mgmt.plan.layer.short":"Layer","gpui.mgmt.plan.lock":"Lock","gpui.mgmt.plan.locked":"Locked","gpui.mgmt.plan.noboard":"No routing plan for this board.","gpui.mgmt.plan.noitems":"No corridors or planes on this layer","gpui.mgmt.plan.note.placeholder":"Steering note for router…","gpui.mgmt.plan.nothing":"Nothing awaits your approval","gpui.mgmt.plan.offwords":"Agents route as you ask. Turn it on to have them propose a routing plan first and route only what you approve here.","gpui.mgmt.plan.onwords":"Before routing a board with 4 or more copper layers or more than 60 nets, the agent proposes corridors and plane regions here. It routes only what you approve.","gpui.mgmt.plan.reading":"Reading the routing plan…","gpui.mgmt.plan.reference":"over {layer}","gpui.mgmt.plan.refused":"KiCad refused","gpui.mgmt.plan.reject":"Reject","gpui.mgmt.plan.rejectlayer":"Reject layer","gpui.mgmt.plan.reqplain":"Approval requested","gpui.mgmt.plan.requested":"Approval requested: {what}","gpui.mgmt.plan.saved":"saved plan","gpui.mgmt.plan.show":"Show done","gpui.mgmt.plan.st.approved":"Approved","gpui.mgmt.plan.st.awaiting":"Awaiting review","gpui.mgmt.plan.st.blocked":"Blocked","gpui.mgmt.plan.st.empty":"Empty","gpui.mgmt.plan.st.partial":"Partial","gpui.mgmt.plan.st.rejected":"Rejected","gpui.mgmt.plan.st.routed":"Routed","gpui.mgmt.plan.st.routing":"Routing","gpui.mgmt.plan.st.verified":"Verified","gpui.mgmt.plan.stackup.short":"Stackup","gpui.mgmt.plan.stop":"Stop routing","gpui.mgmt.plan.sync":"Link zoom","gpui.mgmt.plan.tab":"Plan","gpui.mgmt.plan.unlock":"Unlock","gpui.mgmt.plan.verify":"Verify","gpui.mgmt.plan.view.canvas":"Canvas","gpui.mgmt.plan.view.list":"List","gpui.mgmt.plan.view.split":"Split","gpui.mgmt.plan.width":"Width","gpui.next.thread":"Next thread","gpui.nothing.matches":"Nothing matches","gpui.planmode.bar.always":"Plan mode — explores and proposes a plan before editing","gpui.planmode.bar.executing":"Building the approved plan","gpui.planmode.bar.once":"Plan mode (1 turn) — explores and proposes a plan before editing","gpui.planmode.bar.pending":"Proposed plan awaits review below","gpui.planmode.bar.planning":"Planning — drafting a plan before edits","gpui.planmode.chip.building":"Building","gpui.planmode.chip.once":"Plan · 1t","gpui.planmode.scope.always":"Always","gpui.planmode.scope.once":"1 turn","gpui.planmode.tip":"Plan before acting (1 turn, always, or off)","gpui.planmode.top.executing":"Building plan","gpui.planmode.top.once":"Plan (1 turn)","gpui.planmode.top.pending":"Review plan","gpui.planmode.top.planning":"Planning","gpui.previous.thread":"Previous thread","gpui.rail.no.board":"No board in this project","gpui.rail.no.mech":"No mechanical parts in this project","gpui.rail.no.schematic":"No schematic in this project","gpui.rail.split.needs.both":"Split needs a board and a schematic","home.away":"Home ({name}) is away","home.away.queued":"Home ({name}) is away · {n} queued","home.away.since":"Home ({name}) is away since {time}","home.away.since.queued":"Home ({name}) is away since {time} · {n} queued","home.machine":"Home machine","home.move.failed":"Home move failed","home.move.failed.note":"Home move failed: {note}","home.move.here":"Make this machine the home","home.moving":"Moving home to {to}…","home.moving.step":"Moving home to {to}: {step}","hub.back.crash":"Backplane is back after it stopped unexpectedly","hub.restarting":"Restarting Backplane…","hub.restarting.build":"Restarting Backplane… (new build {build})","hub.stopped":"Backplane stopped","ios.hub.address.field":"Hub address","menu.pin":"Pin","menu.settle":"Settle","menu.unpin":"Unpin","model.col.agent":"Agent","notify.settled":"Settled","palette.archive":"Archive thread","palette.command.placeholder":"Type a command or a thread","palette.diff":"Diff: what this thread changed","palette.newthread":"New thread","palette.settings":"Settings","palette.terminal":"Terminal","palette.unarchive":"Unarchive thread","phone.unsettle":"Unsettle","reply.action":"Reply","reply.cancel":"Cancel reply","reply.to":"In reply to:","secret.you":"You","settings.lang":"Language","sheet.rename":"Rename thread","sidebar.add.project":"Add project","sidebar.search.projects":"Search projects","thread.context.base":"Backplane","thread.context.copied":"Prompt copied.","thread.context.copy":"Copy prompt","thread.context.disable":"Disable","thread.context.enable":"Enable","thread.context.index":"Available skills index","thread.context.injected.label":"Injected project instructions","thread.context.instructions":"Instructions","thread.context.mcp":"Project MCPs","thread.context.native.note":"Backplane’s launch prompt. Native files are loaded by the provider.","thread.context.none.instructions":"No project instructions found.","thread.context.none.mcp":"No project MCP configurations found.","thread.context.reading":"Reading thread context…","thread.context.size":"{bytes} B · ≈{tokens} tokens","thread.context.skills":"Skills","thread.context.system":"System Prompt","thread.context.title":"Context & Prompt","thread.context.trust":"Trust and enable","thread.new":"New thread","tools.pinned":"Pinned","tools.retry":"Retry","tour.title.bots":"Bots","viewer.board":"Board","viewer.diff":"Diff","viewer.files":"Files","viewer.mech":"Mech","viewer.review":"Review","viewer.schematic":"Schematic","viewer.solid":"3D","web.chat.answer.btn":"Answer","web.chat.answer.placeholder":"Type answer…","web.chat.answered":"Answered: {answer}","web.chat.choose":"Choose a project thread on the left to begin.","web.chat.empty":"No messages yet. Type below to start a turn.","web.chat.finished":"Finished {time}","web.chat.finished.dur":"Finished {time} · {dur}","web.chat.loading":"Loading messages…","web.chat.review.mode":"Review mode","web.chat.streaming":"Streaming…","web.clone.add.dir":"Add {dir}","web.clone.back":"Back","web.clone.change.folder":"Change folder","web.clone.cloned":"Cloned {repo} into {dest}","web.clone.cloning":"Cloning {repo} into {dest}","web.clone.copied":"Copied","web.clone.first":"First message: {text}","web.clone.folder.name":"Folder name","web.clone.go":"Clone","web.clone.loading":"Loading…","web.clone.no.folders":"No folders here","web.clone.open.project":"Open the project","web.clone.open.thread":"Open the thread","web.clone.private":"private","web.clone.repo.placeholder":"https or ssh URL, or owner/repo","web.clone.retry":"Try again","web.clone.same":"Already cloned there: it is added as it is.","web.clone.signin":"Sign in to GitHub","web.clone.signin.done":"Signed in to GitHub","web.clone.signin.enter":"Enter this code on GitHub:","web.clone.signin.wait":"Starting GitHub sign-in…","web.clone.start.thread":"Start a thread","web.clone.stopped":"Stopped cloning {repo}","web.clone.tab":"Clone from git","web.clone.up":"Up","web.clone.use.dir":"Use {dir}","web.composer.attach":"Attach image","web.composer.maximages":"At most {max} images per message.","web.composer.unsupported":"Unsupported image type: {type}","web.composer.voice":"Voice dictation","web.logout.failed":"Could not confirm sign-out. Try again.","web.pair.approve.in":"Approve on desktop or paired phone · expires in {time}","web.pair.approved":"Approved. Opening Backplane…","web.pair.cancelled":"Cancelled.","web.pair.code":"Comparison code","web.pair.denied":"Pairing request was denied.","web.pair.expired":"Pairing code expired. Request a new code to try again.","web.pair.failed":"Pairing request failed ({status})","web.pair.name":"Browser name","web.pair.nocode":"Hub did not return a comparison code.","web.pair.ratelimited":"Too many pairing attempts. Wait a moment and try again.","web.pair.request":"Request pairing","web.pair.requesting":"Requesting pairing code…","web.pair.subtitle":"Pair this browser with your hub. Approve the 6-digit code in Backplane › Settings › Devices.","web.pair.unreachable":"Could not reach the hub. Check your tailnet connection.","web.plan.awaiting":"{n} awaiting approval","web.plan.net.one":"1 net","web.plan.nets":"{n} nets"},es:{"agy.signout":"Cerrar sesión","android.hub.machines.approve":"Aprobar","android.load.earlier":"cargar anteriores","approval.dismiss":"Descartar","approval.implement":"Implementar","ask.plan":"Plan propuesto","bots.rooms":"Salas","bots.tab.browser":"Navegador","common.cancel":"Cancelar","common.close":"Cerrar","common.copy":"Copiar","common.delete":"Eliminar","common.refresh":"Actualizar","common.remove":"Quitar","common.save":"Guardar","composer.placeholder":"Pregunta lo que sea: @bot, >hilo, %proyecto, #sala, $skill, /btw","composer.send":"Enviar","composer.stop":"Detener","gpui.acct.connected":"Conectado","gpui.acct.not.connected":"No conectado","gpui.acct.sign.in.expired":"Sesión caducada","gpui.ask.plan.ready":"Listo para revisar","gpui.ask.plan.revise":"Revisar","gpui.ask.plan.reviseph":"¿Qué debería cambiar en el plan?","gpui.ask.plan.sendrev":"Enviar revisión","gpui.b.in.reply.to":"↩ En respuesta a: {quote}","gpui.b.replying.to":"↩ Respondiendo a: {line}","gpui.bots.recall.off":"Desactivado","gpui.bots.recall.on":"Activado","gpui.c.term.collapse":"Contraer","gpui.c.term.expand":"Expandir","gpui.commands":"Comandos","gpui.e.open.folder":"Abrir carpeta","gpui.filter.projects.and.threads":"Filtrar proyectos e hilos","gpui.fold.or.unfold.the.sidebar":"Plegar o desplegar la barra lateral","gpui.follow.paused":"Seguimiento en pausa","gpui.follow.wait":"Siguiendo: esperando la próxima edición del agente","gpui.gerbers":"Gerbers","gpui.improvements":"Mejoras","gpui.jump.to.a.thread.run":"Saltar a un hilo, ejecutar un comando o buscar lo dicho","gpui.mgmt.bom.dnp":"DNP","gpui.mgmt.bom.nompn":"sin MPN","gpui.mgmt.checks.all":"Todas","gpui.mgmt.checks.fix":"Corregir con agente","gpui.mgmt.checks.run":"Ejecutar","gpui.mgmt.close":"Cerrar el panel","gpui.mgmt.fab.apply":"Aplicar","gpui.mgmt.fab.changed":"Cambió desde la última vez que miraste","gpui.mgmt.fab.derived":"* calculado desde la página del fabricante (un mil en mm, un anillo desde un diámetro). Atenuado: el valor de la placa rígida, cuando la página de esta placa no dice otra cosa. Una fecha abre la página de la que se leyó.","gpui.mgmt.fab.extra":"Cuesta más","gpui.mgmt.fab.findings":"Hallazgos","gpui.mgmt.fab.free":"Precio base","gpui.mgmt.fab.judge":"Hojas de datos","gpui.mgmt.fab.limit":"Límite","gpui.mgmt.fab.readcol":"Leído","gpui.mgmt.fab.refresh":"Actualizar","gpui.mgmt.fab.reviewbtn":"Revisar","gpui.mgmt.fab.seen":"Visto","gpui.mgmt.fab.thefab":"El fabricante","gpui.mgmt.fab.use":"Usar","gpui.mgmt.life.nopart":"Sin lectura de esta pieza aún.","gpui.mgmt.life.reading":"Leyendo su historial…","gpui.mgmt.plan.addnote":"Añadir nota","gpui.mgmt.plan.all":"Aprobar todo","gpui.mgmt.plan.before":"Planificar antes de rutear","gpui.mgmt.plan.compact":"Compacto","gpui.mgmt.plan.done":"hecho","gpui.mgmt.plan.drawn":"Los corredores y planos del plan se dibujan en la placa mientras este panel está abierto. Ciérralo para ocultarlos.","gpui.mgmt.plan.edited":"Editado","gpui.mgmt.plan.elsewhere":"Un plan de ruteo para {board} espera tu aprobación","gpui.mgmt.plan.emptysub":"Las capas, corredores y planos aparecerán aquí cuando se proponga un plan.","gpui.mgmt.plan.expand":"Expandir","gpui.mgmt.plan.fit":"Ajustar","gpui.mgmt.plan.grid.all":"Todas las capas","gpui.mgmt.plan.grid.pair":"Lado a lado","gpui.mgmt.plan.grid.single":"Única","gpui.mgmt.plan.hide":"Ocultar hechos","gpui.mgmt.plan.hint":"Arrastra vértices para guiar · Clic en + del borde para insertar · Clic derecho en vértice para quitar","gpui.mgmt.plan.keysnote":"En esta versión de KiCad, aprueba desde este panel: en la vista de plan las teclas A, R y W de KiCad aún no son del plan (A abre Añadir Huella). Actualiza KiCad.","gpui.mgmt.plan.layer":"Aprobar capa","gpui.mgmt.plan.layer.short":"Capa","gpui.mgmt.plan.lock":"Bloquear","gpui.mgmt.plan.locked":"Bloqueado","gpui.mgmt.plan.noboard":"No hay plan de ruteo para esta placa.","gpui.mgmt.plan.noitems":"Sin corredores ni planos en esta capa","gpui.mgmt.plan.note.placeholder":"Nota de guiado para el router…","gpui.mgmt.plan.nothing":"Nada espera tu aprobación","gpui.mgmt.plan.offwords":"Los agentes rutean como les pidas. Actívalo para que primero propongan un plan de ruteo y ruteen solo lo que apruebes aquí.","gpui.mgmt.plan.onwords":"Antes de rutear una placa con 4 o más capas de cobre o más de 60 redes, el agente propone aquí corredores y regiones de plano. Solo rutea lo que apruebes.","gpui.mgmt.plan.reading":"Leyendo el plan de ruteo…","gpui.mgmt.plan.reference":"sobre {layer}","gpui.mgmt.plan.refused":"KiCad lo rechazó","gpui.mgmt.plan.reject":"Rechazar","gpui.mgmt.plan.rejectlayer":"Rechazar capa","gpui.mgmt.plan.reqplain":"Aprobación solicitada","gpui.mgmt.plan.requested":"Aprobación solicitada: {what}","gpui.mgmt.plan.saved":"plan guardado","gpui.mgmt.plan.show":"Mostrar hechos","gpui.mgmt.plan.st.approved":"Aprobado","gpui.mgmt.plan.st.awaiting":"Esperando revisión","gpui.mgmt.plan.st.blocked":"Bloqueado","gpui.mgmt.plan.st.empty":"Vacío","gpui.mgmt.plan.st.partial":"Parcial","gpui.mgmt.plan.st.rejected":"Rechazado","gpui.mgmt.plan.st.routed":"Ruteado","gpui.mgmt.plan.st.routing":"Ruteando","gpui.mgmt.plan.st.verified":"Verificado","gpui.mgmt.plan.stackup.short":"Apilamiento","gpui.mgmt.plan.stop":"Detener ruteo","gpui.mgmt.plan.sync":"Vincular zoom","gpui.mgmt.plan.tab":"Plan","gpui.mgmt.plan.unlock":"Desbloquear","gpui.mgmt.plan.verify":"Verificar","gpui.mgmt.plan.view.canvas":"Lienzo","gpui.mgmt.plan.view.list":"Lista","gpui.mgmt.plan.view.split":"Dividido","gpui.mgmt.plan.width":"Ancho","gpui.next.thread":"Hilo siguiente","gpui.nothing.matches":"Nada coincide","gpui.planmode.bar.always":"Modo plan — explora y propone un plan antes de editar","gpui.planmode.bar.executing":"Ejecutando el plan aprobado","gpui.planmode.bar.once":"Modo plan (1 turno) — explora y propone un plan antes de editar","gpui.planmode.bar.pending":"El plan propuesto espera revisión abajo","gpui.planmode.bar.planning":"Planificando — redactando un plan antes de editar","gpui.planmode.chip.building":"Ejecutando","gpui.planmode.chip.once":"Plan · 1t","gpui.planmode.scope.always":"Siempre","gpui.planmode.scope.once":"1 turno","gpui.planmode.tip":"Planificar antes de actuar (1 turno, siempre u off)","gpui.planmode.top.executing":"Ejecutando plan","gpui.planmode.top.once":"Plan (1 turno)","gpui.planmode.top.pending":"Revisar plan","gpui.planmode.top.planning":"Planificando","gpui.previous.thread":"Hilo anterior","gpui.rail.no.board":"Este proyecto no tiene placa","gpui.rail.no.mech":"Este proyecto no tiene piezas mecánicas","gpui.rail.no.schematic":"Este proyecto no tiene esquema","gpui.rail.split.needs.both":"La vista dividida requiere una placa y un esquema","home.away":"El inicio ({name}) no está disponible","home.away.queued":"El inicio ({name}) no está disponible · {n} en cola","home.away.since":"El inicio ({name}) no está disponible desde las {time}","home.away.since.queued":"El inicio ({name}) no está disponible desde las {time} · {n} en cola","home.machine":"Máquina de inicio","home.move.failed":"No se pudo mover el inicio","home.move.failed.note":"No se pudo mover el inicio: {note}","home.move.here":"Hacer de esta máquina el inicio","home.moving":"Moviendo el inicio a {to}…","home.moving.step":"Moviendo el inicio a {to}: {step}","hub.back.crash":"Backplane volvió tras detenerse de forma inesperada","hub.restarting":"Reiniciando Backplane…","hub.restarting.build":"Reiniciando Backplane… (nueva compilación {build})","hub.stopped":"Backplane se detuvo","ios.hub.address.field":"Dirección del hub","menu.pin":"Fijar","menu.settle":"Cerrar","menu.unpin":"Desfijar","model.col.agent":"Agente","notify.settled":"Cerrado","palette.archive":"Archivar hilo","palette.command.placeholder":"Escribe un comando o un hilo","palette.diff":"Diff: qué cambió este hilo","palette.newthread":"Nuevo hilo","palette.settings":"Ajustes","palette.terminal":"Terminal","palette.unarchive":"Desarchivar hilo","phone.unsettle":"Reabrir","reply.action":"Responder","reply.cancel":"Cancelar respuesta","reply.to":"En respuesta a:","secret.you":"Tú","settings.lang":"Idioma","sheet.rename":"Renombrar hilo","sidebar.add.project":"Añadir proyecto","sidebar.search.projects":"Buscar proyectos","thread.context.base":"Backplane","thread.context.copied":"Se copiaron las instrucciones.","thread.context.copy":"Copiar instrucciones","thread.context.disable":"Desactivar","thread.context.enable":"Activar","thread.context.index":"Índice de habilidades disponibles","thread.context.injected.label":"Instrucciones del proyecto añadidas","thread.context.instructions":"Instrucciones","thread.context.mcp":"MCP del proyecto","thread.context.native.note":"Instrucciones de inicio de Backplane. El proveedor carga los archivos nativos.","thread.context.none.instructions":"No se encontraron instrucciones del proyecto.","thread.context.none.mcp":"No se encontraron configuraciones MCP del proyecto.","thread.context.reading":"Leyendo el contexto del hilo…","thread.context.size":"{bytes} B · ≈{tokens} tokens","thread.context.skills":"Habilidades","thread.context.system":"Instrucciones del sistema","thread.context.title":"Contexto e instrucciones","thread.context.trust":"Confiar y activar","thread.new":"Nuevo hilo","tools.pinned":"Fijado","tools.retry":"Reintentar","tour.title.bots":"Bots","viewer.board":"Placa","viewer.diff":"Diff","viewer.files":"Archivos","viewer.mech":"Mech","viewer.review":"Revisión","viewer.schematic":"Esquemático","viewer.solid":"3D","web.chat.answer.btn":"Responder","web.chat.answer.placeholder":"Escribe una respuesta…","web.chat.answered":"Respondido: {answer}","web.chat.choose":"Elige un hilo de proyecto a la izquierda para empezar.","web.chat.empty":"Aún no hay mensajes. Escribe abajo para iniciar un turno.","web.chat.finished":"Terminado {time}","web.chat.finished.dur":"Terminado {time} · {dur}","web.chat.loading":"Cargando mensajes…","web.chat.review.mode":"Modo de revisión","web.chat.streaming":"Transmitiendo…","web.clone.add.dir":"Añadir {dir}","web.clone.back":"Atrás","web.clone.change.folder":"Cambiar carpeta","web.clone.cloned":"{repo} clonado en {dest}","web.clone.cloning":"Clonando {repo} en {dest}","web.clone.copied":"Copiado","web.clone.first":"Primer mensaje: {text}","web.clone.folder.name":"Nombre de la carpeta","web.clone.go":"Clonar","web.clone.loading":"Cargando…","web.clone.no.folders":"No hay carpetas aquí","web.clone.open.project":"Abrir el proyecto","web.clone.open.thread":"Abrir el hilo","web.clone.private":"privado","web.clone.repo.placeholder":"URL https o ssh, o propietario/repositorio","web.clone.retry":"Reintentar","web.clone.same":"Ya está clonado ahí: se añade tal cual.","web.clone.signin":"Iniciar sesión en GitHub","web.clone.signin.done":"Sesión iniciada en GitHub","web.clone.signin.enter":"Introduce este código en GitHub:","web.clone.signin.wait":"Iniciando sesión en GitHub…","web.clone.start.thread":"Empezar un hilo","web.clone.stopped":"Se detuvo la clonación de {repo}","web.clone.tab":"Clonar desde git","web.clone.up":"Subir","web.clone.use.dir":"Usar {dir}","web.composer.attach":"Adjuntar imagen","web.composer.maximages":"Como máximo {max} imágenes por mensaje.","web.composer.unsupported":"Tipo de imagen no compatible: {type}","web.composer.voice":"Dictado por voz","web.logout.failed":"No se pudo confirmar el cierre de sesión. Inténtalo de nuevo.","web.pair.approve.in":"Aprueba en el escritorio o en un teléfono vinculado · caduca en {time}","web.pair.approved":"Aprobado. Abriendo Backplane…","web.pair.cancelled":"Cancelado.","web.pair.code":"Código de comparación","web.pair.denied":"Se rechazó la solicitud de vinculación.","web.pair.expired":"El código de vinculación caducó. Solicita uno nuevo para intentarlo otra vez.","web.pair.failed":"Falló la solicitud de vinculación ({status})","web.pair.name":"Nombre del navegador","web.pair.nocode":"El hub no devolvió un código de comparación.","web.pair.ratelimited":"Demasiados intentos de vinculación. Espera un momento e inténtalo de nuevo.","web.pair.request":"Solicitar vinculación","web.pair.requesting":"Solicitando código de vinculación…","web.pair.subtitle":"Vincula este navegador con tu hub. Aprueba el código de 6 dígitos en Backplane › Ajustes › Dispositivos.","web.pair.unreachable":"No se pudo conectar con el hub. Comprueba tu conexión de tailnet.","web.plan.awaiting":"{n} esperando aprobación","web.plan.net.one":"1 red","web.plan.nets":"{n} redes"},ja:{"agy.signout":"サインアウト","android.hub.machines.approve":"承認","android.load.earlier":"以前のメッセージを読み込む","approval.dismiss":"閉じる","approval.implement":"実装","ask.plan":"提案されたプラン","bots.rooms":"ルーム","bots.tab.browser":"ブラウザ","common.cancel":"キャンセル","common.close":"閉じる","common.copy":"コピー","common.delete":"削除","common.refresh":"更新","common.remove":"削除","common.save":"保存","composer.placeholder":"何でも質問:@bot、>thread、%project、#room、$skill、/btw","composer.send":"送信","composer.stop":"停止","gpui.acct.connected":"接続済み","gpui.acct.not.connected":"未接続","gpui.acct.sign.in.expired":"サインインの期限切れ","gpui.ask.plan.ready":"確認待ち","gpui.ask.plan.revise":"修正","gpui.ask.plan.reviseph":"計画のどこを変更しますか?","gpui.ask.plan.sendrev":"修正を送る","gpui.b.in.reply.to":"↩ 返信先:{quote}","gpui.b.replying.to":"↩ 返信中:{line}","gpui.bots.recall.off":"オフ","gpui.bots.recall.on":"オン","gpui.c.term.collapse":"折りたたむ","gpui.c.term.expand":"展開","gpui.commands":"コマンド","gpui.e.open.folder":"フォルダを開く","gpui.filter.projects.and.threads":"プロジェクトとスレッドを絞り込む","gpui.fold.or.unfold.the.sidebar":"サイドバーを折りたたむ/開く","gpui.follow.paused":"追従を一時停止中","gpui.follow.wait":"追従中: エージェントの次の編集を待っています","gpui.gerbers":"ガーバー","gpui.improvements":"改善","gpui.jump.to.a.thread.run":"スレッドへ移動、コマンドを実行、または発言を検索","gpui.mgmt.bom.dnp":"実装しない","gpui.mgmt.bom.nompn":"MPNなし","gpui.mgmt.checks.all":"すべて","gpui.mgmt.checks.fix":"エージェントに直してもらう","gpui.mgmt.checks.run":"実行","gpui.mgmt.close":"パネルを閉じる","gpui.mgmt.fab.apply":"適用","gpui.mgmt.fab.changed":"前回見てから変わったところ","gpui.mgmt.fab.derived":"* 製造元のページから計算した値です(milをmmに、径からランドを)。薄い色の項目はリジッド基板の値です(この基板のページに記載がないもの)。日付を押すと読んだページが開きます。","gpui.mgmt.fab.extra":"追加料金","gpui.mgmt.fab.findings":"指摘","gpui.mgmt.fab.free":"基本料金","gpui.mgmt.fab.judge":"データシート","gpui.mgmt.fab.limit":"項目","gpui.mgmt.fab.readcol":"読んだ日","gpui.mgmt.fab.refresh":"再読み込み","gpui.mgmt.fab.reviewbtn":"レビュー","gpui.mgmt.fab.seen":"確認済み","gpui.mgmt.fab.thefab":"製造元","gpui.mgmt.fab.use":"使う","gpui.mgmt.life.nopart":"この部品の記録はまだありません。","gpui.mgmt.life.reading":"履歴を読んでいます…","gpui.mgmt.plan.addnote":"メモを追加","gpui.mgmt.plan.all":"すべて承認","gpui.mgmt.plan.before":"配線前に計画する","gpui.mgmt.plan.compact":"標準","gpui.mgmt.plan.done":"完了","gpui.mgmt.plan.drawn":"計画の配線経路とプレーンは、このパネルを開いている間だけ基板上に表示されます。閉じると消えます。","gpui.mgmt.plan.edited":"編集済み","gpui.mgmt.plan.elsewhere":"{board}の配線計画が承認を待っています","gpui.mgmt.plan.emptysub":"計画が提案されると、レイヤー・コリドー・ベタ領域がここに表示されます。","gpui.mgmt.plan.expand":"拡大","gpui.mgmt.plan.fit":"全体表示","gpui.mgmt.plan.grid.all":"全レイヤー","gpui.mgmt.plan.grid.pair":"並べて表示","gpui.mgmt.plan.grid.single":"単一","gpui.mgmt.plan.hide":"完了を隠す","gpui.mgmt.plan.hint":"頂点をドラッグして誘導 · 辺の + をクリックで追加 · 頂点を右クリックで削除","gpui.mgmt.plan.keysnote":"このバージョンのKiCadでは、このパネルから承認してください。プランビューでのKiCadのA・R・Wキーはまだ計画のものではありません(Aはフットプリントの追加を開きます)。KiCadを更新してください。","gpui.mgmt.plan.layer":"層を承認","gpui.mgmt.plan.layer.short":"レイヤー","gpui.mgmt.plan.lock":"ロック","gpui.mgmt.plan.locked":"ロック中","gpui.mgmt.plan.noboard":"この基板の配線計画はありません。","gpui.mgmt.plan.noitems":"このレイヤーにコリドーまたはプレーンがありません","gpui.mgmt.plan.note.placeholder":"ルーターへの指示メモ…","gpui.mgmt.plan.nothing":"承認待ちはありません","gpui.mgmt.plan.offwords":"エージェントは指示どおりに配線します。オンにすると、まず配線計画を提案し、ここで承認したものだけを配線します。","gpui.mgmt.plan.onwords":"銅箔層が4層以上、またはネットが60本を超える基板では、配線の前にエージェントがここで配線経路とプレーン領域を提案します。承認したものだけを配線します。","gpui.mgmt.plan.reading":"配線計画を読んでいます…","gpui.mgmt.plan.reference":"基準 {layer}","gpui.mgmt.plan.refused":"KiCad が拒否しました","gpui.mgmt.plan.reject":"却下","gpui.mgmt.plan.rejectlayer":"レイヤーを却下","gpui.mgmt.plan.reqplain":"承認が求められています","gpui.mgmt.plan.requested":"承認が求められています: {what}","gpui.mgmt.plan.saved":"保存された計画","gpui.mgmt.plan.show":"完了を表示","gpui.mgmt.plan.st.approved":"承認済み","gpui.mgmt.plan.st.awaiting":"承認待ち","gpui.mgmt.plan.st.blocked":"ブロック","gpui.mgmt.plan.st.empty":"空","gpui.mgmt.plan.st.partial":"一部完了","gpui.mgmt.plan.st.rejected":"却下","gpui.mgmt.plan.st.routed":"配線済み","gpui.mgmt.plan.st.routing":"配線中","gpui.mgmt.plan.st.verified":"検証済み","gpui.mgmt.plan.stackup.short":"スタックアップ","gpui.mgmt.plan.stop":"配線を止める","gpui.mgmt.plan.sync":"ズーム連動","gpui.mgmt.plan.tab":"計画","gpui.mgmt.plan.unlock":"ロック解除","gpui.mgmt.plan.verify":"検証","gpui.mgmt.plan.view.canvas":"キャンバス","gpui.mgmt.plan.view.list":"リスト","gpui.mgmt.plan.view.split":"分割","gpui.mgmt.plan.width":"幅","gpui.next.thread":"次のスレッド","gpui.nothing.matches":"一致するものはありません","gpui.planmode.bar.always":"計画モード — 編集前に調査して計画を提案します","gpui.planmode.bar.executing":"承認された計画を実行しています","gpui.planmode.bar.once":"計画モード (1回) — 編集前に調査して計画を提案します","gpui.planmode.bar.pending":"提案された計画が下のレビューを待っています","gpui.planmode.bar.planning":"計画中 — 編集前の計画を作成しています","gpui.planmode.chip.building":"実行中","gpui.planmode.chip.once":"計画 · 1回","gpui.planmode.scope.always":"常時","gpui.planmode.scope.once":"1回","gpui.planmode.tip":"実行前に計画を作成 (1回・常時・オフ)","gpui.planmode.top.executing":"計画を実行中","gpui.planmode.top.once":"計画 (1回)","gpui.planmode.top.pending":"計画を確認","gpui.planmode.top.planning":"計画中","gpui.previous.thread":"前のスレッド","gpui.rail.no.board":"このプロジェクトには基板がありません","gpui.rail.no.mech":"このプロジェクトには機械部品がありません","gpui.rail.no.schematic":"このプロジェクトには回路図がありません","gpui.rail.split.needs.both":"分割表示には基板と回路図が必要です","home.away":"ホーム({name})はオフラインです","home.away.queued":"ホーム({name})はオフラインです · {n} 件待機中","home.away.since":"ホーム({name})は {time} からオフラインです","home.away.since.queued":"ホーム({name})は {time} からオフラインです · {n} 件待機中","home.machine":"ホームマシン","home.move.failed":"ホームの移動に失敗しました","home.move.failed.note":"ホームの移動に失敗しました: {note}","home.move.here":"このマシンをホームにする","home.moving":"ホームを {to} へ移動中…","home.moving.step":"ホームを {to} へ移動中: {step}","hub.back.crash":"予期せず停止したBackplaneが戻りました","hub.restarting":"Backplaneを再起動しています…","hub.restarting.build":"Backplaneを再起動しています…(新しいビルド {build})","hub.stopped":"Backplaneは停止しました","ios.hub.address.field":"ハブのアドレス","menu.pin":"ピン留め","menu.settle":"完了","menu.unpin":"ピン留めを解除","model.col.agent":"エージェント","notify.settled":"完了","palette.archive":"スレッドをアーカイブ","palette.command.placeholder":"コマンドまたはスレッドを入力","palette.diff":"差分:このスレッドの変更","palette.newthread":"新しいスレッド","palette.settings":"設定","palette.terminal":"ターミナル","palette.unarchive":"スレッドのアーカイブを解除","phone.unsettle":"未完了に戻す","reply.action":"返信","reply.cancel":"返信をやめる","reply.to":"返信先:","secret.you":"あなた","settings.lang":"言語","sheet.rename":"スレッド名を変更","sidebar.add.project":"プロジェクトを追加","sidebar.search.projects":"プロジェクトを検索","thread.context.base":"Backplane","thread.context.copied":"プロンプトをコピーしました。","thread.context.copy":"プロンプトをコピー","thread.context.disable":"無効にする","thread.context.enable":"有効にする","thread.context.index":"利用可能なスキルの一覧","thread.context.injected.label":"追加されたプロジェクトの指示","thread.context.instructions":"指示","thread.context.mcp":"プロジェクトの MCP","thread.context.native.note":"Backplane が起動時に渡すプロンプトです。ネイティブファイルはプロバイダーが読み込みます。","thread.context.none.instructions":"プロジェクトの指示が見つかりません。","thread.context.none.mcp":"プロジェクトの MCP 設定が見つかりません。","thread.context.reading":"スレッドのコンテキストを読み込み中…","thread.context.size":"{bytes} B・約{tokens}トークン","thread.context.skills":"スキル","thread.context.system":"システムプロンプト","thread.context.title":"コンテキストとプロンプト","thread.context.trust":"承認して有効にする","thread.new":"新しいスレッド","tools.pinned":"固定中","tools.retry":"再試行","tour.title.bots":"ボット","viewer.board":"基板","viewer.diff":"差分","viewer.files":"ファイル","viewer.mech":"Mech","viewer.review":"レビュー","viewer.schematic":"回路図","viewer.solid":"3D","web.chat.answer.btn":"回答","web.chat.answer.placeholder":"回答を入力…","web.chat.answered":"回答済み: {answer}","web.chat.choose":"左側からプロジェクトのスレッドを選んで開始してください。","web.chat.empty":"まだメッセージはありません。下に入力して開始してください。","web.chat.finished":"完了 {time}","web.chat.finished.dur":"完了 {time} · {dur}","web.chat.loading":"メッセージを読み込んでいます…","web.chat.review.mode":"レビューモード","web.chat.streaming":"受信中…","web.clone.add.dir":"{dir} を追加","web.clone.back":"戻る","web.clone.change.folder":"フォルダを変更","web.clone.cloned":"{repo} を {dest} にクローンしました","web.clone.cloning":"{repo} を {dest} にクローン中","web.clone.copied":"コピーしました","web.clone.first":"最初のメッセージ: {text}","web.clone.folder.name":"フォルダ名","web.clone.go":"クローン","web.clone.loading":"読み込み中…","web.clone.no.folders":"フォルダがありません","web.clone.open.project":"プロジェクトを開く","web.clone.open.thread":"スレッドを開く","web.clone.private":"非公開","web.clone.repo.placeholder":"https / ssh の URL、または owner/repo","web.clone.retry":"もう一度","web.clone.same":"すでにそこにクローンされています: そのまま追加します。","web.clone.signin":"GitHub にサインイン","web.clone.signin.done":"GitHub にサインインしました","web.clone.signin.enter":"このコードを GitHub に入力してください:","web.clone.signin.wait":"GitHub のサインインを開始しています…","web.clone.start.thread":"スレッドを開始","web.clone.stopped":"{repo} のクローンを中止しました","web.clone.tab":"git からクローン","web.clone.up":"上へ","web.clone.use.dir":"{dir} を使う","web.composer.attach":"画像を添付","web.composer.maximages":"1 件のメッセージに添付できる画像は最大 {max} 枚です。","web.composer.unsupported":"未対応の画像形式です: {type}","web.composer.voice":"音声入力","web.logout.failed":"サインアウトを確認できませんでした。もう一度お試しください。","web.pair.approve.in":"デスクトップまたはペアリング済みの端末で承認してください · 有効期限 {time}","web.pair.approved":"承認されました。Backplane を開いています…","web.pair.cancelled":"キャンセルしました。","web.pair.code":"確認コード","web.pair.denied":"ペアリングのリクエストが拒否されました。","web.pair.expired":"ペアリングコードの有効期限が切れました。新しいコードをリクエストしてください。","web.pair.failed":"ペアリングのリクエストに失敗しました ({status})","web.pair.name":"ブラウザー名","web.pair.nocode":"ハブから確認コードが返されませんでした。","web.pair.ratelimited":"ペアリングの試行回数が多すぎます。しばらく待ってからやり直してください。","web.pair.request":"ペアリングをリクエスト","web.pair.requesting":"ペアリングコードをリクエストしています…","web.pair.subtitle":"このブラウザーをハブとペアリングします。Backplane › 設定 › デバイス で 6 桁のコードを承認してください。","web.pair.unreachable":"ハブに接続できませんでした。tailnet の接続を確認してください。","web.plan.awaiting":"{n} 件が承認待ち","web.plan.net.one":"1 ネット","web.plan.nets":"{n} ネット"}};function Tn(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 bt=ls(),Vt=new Set,Ut=new Map;for(let[e,t]of Object.entries(ht.en||{}))if(typeof t==="string"&&!Ut.has(t))Ut.set(t,e);function ls(){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 Bn(){if(typeof document<"u"&&document.documentElement)document.documentElement.lang=bt}Bn();function Pt(e){return Vt.add(e),()=>{Vt.delete(e)}}function In(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!==bt;if(bt=n,Bn(),i)for(let s of Vt)s(bt);return i}function b(e,t,n){let s=(ht[bt]||ht.en||{})[e]??ht.en?.[e]??t??e;return Tn(s,n)}function xe(e){if(!e)return"";let t=Ut.get(e);if(!t)return e;return b(t,e)}function J(e,t="",n=""){let i=document.createElement(e);if(t)i.className=t;if(n)i.textContent=n;return i}function Fe(e,t="",n){let i=J("button",t,e);if(i.type="button",n)i.addEventListener("click",n);return i}function cs(e){let t=e.replace(/[\\/]+$/,"");if(!t)return e||"/";let n=t.split(/[\\/]/);return n[n.length-1]||t}function ds(e,t){let n=e.includes("\\")&&!e.includes("/")?"\\":"/";return e.endsWith(n)?e+t:e+n+t}class Wt{hub;actionLabel;action;root;pathInput;upBtn;listEl;errEl;actBtn;path="";parent=null;gen=0;busy=!1;constructor(e,t,n,i=[]){this.hub=e;this.actionLabel=t;this.action=n;this.root=J("div","bp-fb"),this.root.setAttribute("data-testid","folder-browser");let s=J("div","bp-fb-head");this.upBtn=Fe("↑","bp-btn-ghost bp-fb-up",()=>{if(this.parent)this.go(this.parent)}),this.upBtn.title=b("web.clone.up","Up"),this.upBtn.setAttribute("aria-label",b("web.clone.up","Up")),this.pathInput=J("input","bp-input bp-fb-path"),this.pathInput.spellcheck=!1,this.pathInput.setAttribute("data-testid","folder-path"),this.pathInput.addEventListener("keydown",(r)=>{if(r.key==="Enter"){r.preventDefault();let o=this.pathInput.value.trim();if(o)this.go(o)}}),s.append(this.upBtn,this.pathInput),this.listEl=J("div","bp-fb-list"),this.errEl=J("div","bp-ap-err bp-hidden");let a=J("div","bp-ap-foot");this.actBtn=Fe("","primary",()=>{this.run()}),this.actBtn.setAttribute("data-testid","folder-act"),a.append(...i,this.actBtn),this.root.append(s,this.listEl,this.errEl,a)}currentPath(){return this.path}async go(e){let t=++this.gen;this.setError(""),this.listEl.replaceChildren(J("div","bp-fb-empty",b("web.clone.loading","Loading…")));try{let n=await this.hub.rpc("dirs.list",{path:e});if(t!==this.gen)return;this.path=n.path,this.parent=n.parent??null,this.render(n.dirs??[])}catch(n){if(t!==this.gen)return;this.setError(xe(n instanceof Error?n.message:String(n))),this.render(null)}}refreshLocale(){this.upBtn.title=b("web.clone.up","Up"),this.updateAct()}render(e){if(this.pathInput.value=this.path,this.upBtn.disabled=!this.parent,this.updateAct(),e===null){this.listEl.replaceChildren();return}if(e.length===0){this.listEl.replaceChildren(J("div","bp-fb-empty",b("web.clone.no.folders","No folders here")));return}let t=document.createDocumentFragment();for(let n of e){let i=Fe("","bp-fb-row",()=>{this.go(ds(this.path,n))});i.append(J("span","bp-fb-icon","▸"),J("span","bp-fb-name",n)),t.appendChild(i)}this.listEl.replaceChildren(t),this.listEl.scrollTop=0}updateAct(){this.actBtn.textContent=this.path?this.actionLabel(cs(this.path)):this.actionLabel("…"),this.actBtn.disabled=!this.path||this.busy}async run(){if(!this.path||this.busy)return;this.busy=!0,this.updateAct(),this.setError("");try{await this.action(this.path)}catch(e){this.setError(xe(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 _t{container;host;backdrop=null;bodyEl=null;tabsEl=null;mode="folder";repoText="";repoValue="";firstText="";wantThread=!0;userParent="";nameText="";nameTouched=!1;dest=null;destGen=0;destPending=!1;destTimer=null;repos=null;reposGen=0;reposTimer=null;showSuggest=!1;suggestIdx=-1;startErr="";starting=!1;picking=!1;jobId="";job=null;specs=new Map;signin=null;copied=!1;repoInput=null;suggestEl=null;destEl=null;signinEl=null;cloneBtn=null;jobEl=null;constructor(e,t){this.container=e;this.host=t}isOpen(){return this.backdrop!==null}open(e={}){let t=this.host.hub.hasFeature("clone"),n=!e.repo&&Boolean(this.jobId)&&(!this.job||this.job.state==="running"||this.job.state==="done");if(!this.backdrop)this.build();if(!n)this.jobId="",this.job=null,this.resetForm();if(e.repo!==void 0||e.text!==void 0)this.repoText=(e.repo??"").trim(),this.repoValue="",this.firstText=(e.text??"").trim();if(this.mode=t&&(e.mode==="clone"||n)?"clone":"folder",this.render(),n){if(this.job)this.maybeGo(this.job);this.reconcile()}else if(this.mode==="clone"&&this.repoText)this.askDest()}reconcile(){let e=this.jobId;if(!e)return;this.host.hub.rpc("clone.status",{id:e}).then((t)=>this.apply(t)).catch(()=>{})}close(){if(this.reposTimer!==null)window.clearTimeout(this.reposTimer);if(this.destTimer!==null)window.clearTimeout(this.destTimer);this.reposTimer=null,this.destTimer=null,this.backdrop?.remove(),this.backdrop=null,this.bodyEl=null,this.tabsEl=null}escape(){if(this.picking){this.picking=!1,this.render();return}if(this.showSuggest){this.showSuggest=!1,this.renderSuggest();return}this.close()}refreshLocale(){if(this.backdrop)this.render()}handleFrame(e){if(e.k==="clone"){let t=e.clone;if(t)this.apply(t)}else if(e.k==="clone.repos"){if(this.isOpen()&&this.mode==="clone"&&!this.jobId)this.askRepos(0)}else if(e.k==="clone.signin"){if(!this.signin)return;let t=this.signin.state;if(this.signin=e.signin??null,this.signin?.state==="cancelled")this.signin=null;if(t!=="done"&&this.signin?.state==="done")this.askRepos(0);this.renderSignin()}}build(){let e=J("div","bp-modal-backdrop");e.setAttribute("data-testid","add-project");let t=J("div","bp-modal bp-ap"),n=J("div","bp-modal-head"),i=J("h2","",b("sidebar.add.project","Add project")),s=Fe("×","icon",()=>this.close());s.title=b("common.close","Close"),s.setAttribute("aria-label",b("common.close","Close")),n.append(i,s),this.tabsEl=J("div","bp-ap-tabs"),this.bodyEl=J("div","bp-modal-body bp-ap-body"),t.append(n,this.tabsEl,this.bodyEl),e.appendChild(t),e.addEventListener("mousedown",(a)=>{if(a.target===e)this.close()}),this.container.appendChild(e),this.backdrop=e}resetForm(){this.repoText="",this.repoValue="",this.firstText="",this.wantThread=!0,this.userParent="",this.nameText="",this.nameTouched=!1,this.dest=null,this.destPending=!1,this.repos=null,this.showSuggest=!1,this.suggestIdx=-1,this.startErr="",this.starting=!1,this.picking=!1,this.signin=null,this.copied=!1}render(){if(!this.bodyEl||!this.tabsEl||!this.backdrop)return;let e=this.backdrop.querySelector(".bp-modal-head h2");if(e)e.textContent=b("sidebar.add.project","Add project");if(this.renderTabs(),this.repoInput=null,this.suggestEl=null,this.destEl=null,this.signinEl=null,this.cloneBtn=null,this.jobEl=null,this.mode==="folder")this.renderFolder();else if(this.jobId&&this.job)this.renderJobView();else if(this.picking)this.renderPickParent();else this.renderCloneForm()}renderTabs(){if(!this.tabsEl)return;if(!this.host.hub.hasFeature("clone")){this.tabsEl.classList.add("bp-hidden");return}this.tabsEl.classList.remove("bp-hidden");let e=(t,n)=>{let i=Fe(n,"bp-ap-tab"+(this.mode===t?" on":""),()=>{if(this.mode===t)return;if(this.mode=t,this.render(),t==="clone"&&!this.jobId&&this.repos===null)this.askRepos(0)});return i.setAttribute("data-testid",`ap-tab-${t}`),i.setAttribute("aria-pressed",String(this.mode===t)),i};this.tabsEl.replaceChildren(e("folder",b("gpui.e.open.folder","Open folder")),e("clone",b("web.clone.tab","Clone from git")))}renderFolder(){let e=new Wt(this.host.hub,(t)=>b("web.clone.add.dir","Add {dir}",{dir:t}),async(t)=>{let n=await this.host.hub.rpc("project.add",{path:t},30000);if(this.close(),n.project)this.host.onProjectAdded(n.project)});this.bodyEl.replaceChildren(e.root),e.go("")}renderCloneForm(){let e=this.bodyEl,t=J("div","bp-ap-form"),n=J("div","bp-ap-repo"),i=J("input","bp-input");i.type="text",i.spellcheck=!1,i.autocomplete="off",i.placeholder=b("web.clone.repo.placeholder","https or ssh URL, or owner/repo"),i.setAttribute("aria-label",b("web.clone.repo.placeholder","https or ssh URL, or owner/repo")),i.setAttribute("data-testid","clone-repo"),i.value=this.repoText,i.addEventListener("input",()=>{if(this.repoText=i.value,this.repoValue="",this.showSuggest=!0,this.suggestIdx=-1,this.startErr="",!this.nameTouched)this.nameText="";this.askRepos(200),this.askDest(250)}),i.addEventListener("focus",()=>{if(this.showSuggest=!0,this.repos===null)this.askRepos(0);else this.renderSuggest()}),i.addEventListener("blur",()=>{window.setTimeout(()=>{if(document.activeElement!==i)this.showSuggest=!1,this.renderSuggest()},120)}),i.addEventListener("keydown",(u)=>this.repoKey(u)),this.repoInput=i,this.suggestEl=J("div","bp-ap-suggest bp-hidden"),this.suggestEl.setAttribute("data-testid","clone-suggest"),n.append(i,this.suggestEl),this.signinEl=J("div","bp-ap-signin bp-hidden"),this.signinEl.setAttribute("data-testid","clone-signin"),this.destEl=J("div","bp-ap-dest"),this.destEl.setAttribute("data-testid","clone-dest");let s=J("label","bp-ap-check"),a=J("input");a.type="checkbox",a.checked=this.wantThread,a.setAttribute("data-testid","clone-thread"),a.addEventListener("change",()=>{this.wantThread=a.checked}),s.append(a,J("span","",b("web.clone.start.thread","Start a thread")));let r=[n,this.signinEl,this.destEl,s];if(this.firstText)r.push(J("div","bp-ap-first bp-dim",b("web.clone.first","First message: {text}",{text:this.firstText})));let o=J("div","bp-ap-err"+(this.startErr?"":" bp-hidden"),this.startErr);o.setAttribute("data-testid","clone-start-error");let c=J("div","bp-ap-foot");this.cloneBtn=Fe(b("web.clone.go","Clone"),"primary",()=>{this.startClone()}),this.cloneBtn.setAttribute("data-testid","clone-go"),c.append(this.cloneBtn),r.push(o,c),t.append(...r),e.replaceChildren(t),this.renderSuggest(),this.renderSignin(),this.renderDest(),window.setTimeout(()=>{if(this.repoInput===i&&!this.repoText)i.focus()},0)}repoKey(e){let t=this.repos?.repos??[],n=this.showSuggest&&t.length>0;if(e.key==="ArrowDown"&&n)e.preventDefault(),this.suggestIdx=Math.min(t.length-1,this.suggestIdx+1),this.renderSuggest();else if(e.key==="ArrowUp"&&n)e.preventDefault(),this.suggestIdx=Math.max(-1,this.suggestIdx-1),this.renderSuggest();else if(e.key==="Enter"){e.preventDefault();let i=n&&this.suggestIdx>=0?t[this.suggestIdx]:void 0;if(i)this.pickRepo(i);else if(this.canStart())this.startClone()}}pickRepo(e){if(this.repoText=e.name,this.repoValue=e.value,this.showSuggest=!1,this.suggestIdx=-1,this.startErr="",!this.nameTouched)this.nameText="";if(this.repoInput)this.repoInput.value=e.name;this.renderSuggest(),this.askDest()}repoArg(){return this.repoValue||this.repoText.trim()}askRepos(e){if(this.reposTimer!==null)window.clearTimeout(this.reposTimer);this.reposTimer=window.setTimeout(()=>{this.reposTimer=null;let t=++this.reposGen,n=this.repoValue?"":this.repoText.trim();this.host.hub.rpc("clone.repos",{q:n,limit:12},30000).then((i)=>{if(t!==this.reposGen)return;this.repos=i,this.renderSuggest(),this.renderSignin()}).catch(()=>{if(t!==this.reposGen)return;this.repos={repos:[],state:"error",hint:"Couldn't list your GitHub repositories."},this.renderSuggest()})},e)}renderSuggest(){let e=this.suggestEl;if(!e)return;let t=this.repos,n=t?.repos??[],i=[];if(this.showSuggest&&!this.repoValue){if(n.forEach((s,a)=>{let r=Fe("","bp-ap-sug"+(a===this.suggestIdx?" active":""));r.setAttribute("data-testid","clone-suggestion"),r.addEventListener("mousedown",(c)=>c.preventDefault()),r.addEventListener("click",()=>this.pickRepo(s));let o=J("div","bp-ap-sug-top");if(o.append(J("span","bp-ap-sug-name",s.name)),s.private)o.append(J("span","bp-ap-tag",b("web.clone.private","private")));if(r.append(o),s.description)r.append(J("div","bp-ap-sug-desc",s.description));i.push(r)}),n.length===0&&t){if(t.loading)i.push(J("div","bp-ap-sug-note",b("web.clone.loading","Loading…")));else if(t.hint){let s=J("div","bp-ap-sug-note");if(s.append(J("span","",xe(t.hint))),t.state==="signedout"){let a=Fe(b("web.clone.signin","Sign in to GitHub"),"bp-btn-line",()=>{this.startSignin()});a.addEventListener("mousedown",(r)=>r.preventDefault()),a.setAttribute("data-testid","clone-signin-btn"),s.append(a)}i.push(s)}}}e.replaceChildren(...i),e.classList.toggle("bp-hidden",i.length===0)}askDest(e=0){if(this.destTimer!==null)window.clearTimeout(this.destTimer);this.destPending=!0,this.updateCloneBtn(),this.destTimer=window.setTimeout(()=>{this.destTimer=null;let t=++this.destGen,n=this.repoArg();if(!n){this.dest=null,this.destPending=!1,this.renderDest();return}let i={repo:n};if(this.userParent)i.parent=this.userParent;if(this.nameTouched&&this.nameText.trim())i.name=this.nameText.trim();else if(this.userParent)i.name="";this.host.hub.rpc("clone.dest",i).then((s)=>{if(t!==this.destGen)return;if(this.dest=s,this.destPending=!1,!this.nameTouched&&s.folder)this.nameText=s.folder;this.renderDest()}).catch((s)=>{if(t!==this.destGen)return;this.dest={ok:!1,error:s instanceof Error?s.message:String(s)},this.destPending=!1,this.renderDest()})},e)}renderDest(){let e=this.destEl;if(!e)return;let t=this.dest,n=[];if(t&&!t.repo){if(t.error&&this.repoText.trim())n.push(this.errLine(xe(t.error)))}else if(t){let r=J("div","bp-ap-where"),o=J("span","bp-ap-dest-path",t.destShown||t.dest||t.defaultParentShown||"");o.setAttribute("data-testid","clone-dest-shown");let c=Fe(b("web.clone.change.folder","Change folder"),"bp-btn-line",()=>{this.picking=!0,this.render()});c.setAttribute("data-testid","clone-change-folder"),r.append(o,c),n.push(r);let u=J("label","bp-ap-name");u.append(J("span","bp-ap-lbl",b("web.clone.folder.name","Folder name")));let l=J("input","bp-input");if(l.type="text",l.spellcheck=!1,l.value=this.nameText,l.setAttribute("data-testid","clone-name"),l.addEventListener("input",()=>{this.nameText=l.value,this.nameTouched=l.value.trim()!=="",this.startErr="",this.askDest(250)}),l.addEventListener("keydown",(p)=>{if(p.key==="Enter"&&this.canStart())p.preventDefault(),this.startClone()}),u.append(l),n.push(u),!t.ok&&t.error)n.push(this.errLine(xe(t.error)));else if(t.same)n.push(J("div","bp-ap-note bp-dim",b("web.clone.same","Already cloned there: it is added as it is.")))}let i=document.activeElement,s=i&&e.contains(i)&&i.getAttribute("data-testid")==="clone-name",a=s?i.selectionStart:null;if(e.replaceChildren(...n),e.classList.toggle("bp-hidden",n.length===0),s){let r=e.querySelector('[data-testid="clone-name"]');if(r){if(r.focus(),a!==null)r.setSelectionRange(a,a)}}this.updateCloneBtn()}errLine(e){let t=J("div","bp-ap-err",e);return t.setAttribute("data-testid","clone-dest-error"),t}canStart(){return Boolean(this.dest?.ok&&this.dest.repo&&!this.destPending&&!this.starting&&this.repoArg())}updateCloneBtn(){if(this.cloneBtn)this.cloneBtn.disabled=!this.canStart()}renderPickParent(){let e=this.dest?.parent||this.userParent||this.dest?.defaultParent||"",t=Fe(b("web.clone.back","Back"),"bp-btn-line",()=>{this.picking=!1,this.render()}),n=new Wt(this.host.hub,(i)=>b("web.clone.use.dir","Use {dir}",{dir:i}),async(i)=>{this.userParent=i,this.picking=!1,this.render(),this.askDest()},[t]);this.bodyEl.replaceChildren(n.root),n.go(e)}async startClone(){if(!this.canStart()||!this.dest)return;this.starting=!0,this.startErr="",this.updateCloneBtn();let e={repo:this.repoArg(),thread:this.wantThread,text:this.firstText},t=Ot();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=xe(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=Ot(),s=this.jobId;this.jobId=i,this.specs.set(i,n),t.disabled=!0;try{let a=await this.host.hub.rpc("clone.start",{id:i,repo:n.repo,dest:e.dest??"",thread:n.thread,text:n.text});this.apply(a)}catch(a){let r=xe(a instanceof Error?a.message:String(a));if(this.jobId!==i)return;if(!this.job||this.job.id!==i){let o=await this.host.hub.rpc("clone.status",{id:i}).catch(()=>null);if(o&&o.id===i){this.apply(o);return}}if(this.jobId===i&&(!this.job||this.job.id!==i))this.jobId=s,t.disabled=!1,this.showJobError(r)}}apply(e){if(!e||e.id!==this.jobId)return;if(!Nn(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&&Mn(e))this.goTo(e)}renderJobView(){this.jobEl=J("div","bp-ap-job"),this.jobEl.setAttribute("data-testid","clone-job"),this.signinEl=J("div","bp-ap-signin bp-hidden"),this.signinEl.setAttribute("data-testid","clone-signin"),this.bodyEl.replaceChildren(this.jobEl,this.signinEl),this.renderJob(),this.renderSignin()}renderJob(){let e=this.jobEl,t=this.job;if(!e||!t)return;let n=t.destShown||t.dest||"",i=t.repo||"",s=t.state==="done"?b("web.clone.cloned","Cloned {repo} into {dest}",{repo:i,dest:n}):t.state==="cancelled"?b("web.clone.stopped","Stopped cloning {repo}",{repo:i}):b("web.clone.cloning","Cloning {repo} into {dest}",{repo:i,dest:n}),a=[J("div","bp-ap-job-title",s)];if(t.state==="running"){let r=J("div","bp-ap-phase",xe(t.phase||""));r.setAttribute("data-testid","clone-phase");let o=J("div","bp-ap-bar"+(typeof t.pct==="number"?"":" indeterminate")),c=J("div","bp-ap-bar-fill");if(typeof t.pct==="number")c.style.width=`${Math.max(0,Math.min(100,t.pct))}%`;if(o.appendChild(c),o.setAttribute("role","progressbar"),typeof t.pct==="number")o.setAttribute("aria-valuenow",String(t.pct));if(a.push(r,o),t.detail)a.push(J("div","bp-ap-detail bp-dim",t.detail));let u=J("div","bp-ap-foot"),l=Fe(b("common.cancel","Cancel"),"bp-btn-line",()=>{this.host.hub.rpc("clone.cancel",{id:t.id}).then((p)=>this.apply(p)).catch(()=>{})});l.setAttribute("data-testid","clone-cancel"),u.append(l),a.push(u)}else if(t.state==="failed"||t.state==="cancelled"){if(t.state==="failed"&&t.error){let u=J("div","bp-ap-err",xe(t.error));u.setAttribute("data-testid","clone-error"),a.push(u)}let r=J("div","bp-ap-foot"),o=Fe(b("web.clone.back","Back"),"bp-btn-line",()=>{this.jobId="",this.job=null,this.signin=null,this.render(),this.askDest()});if(r.append(o),t.signin){let u=Fe(b("web.clone.signin","Sign in to GitHub"),"bp-btn-line",()=>{this.startSignin()});u.setAttribute("data-testid","clone-signin-btn"),r.append(u)}let c=Fe(b("web.clone.retry","Try again"),"primary",()=>{this.retry(t,c)});c.setAttribute("data-testid","clone-retry"),r.append(c),a.push(r)}else if(t.state==="done"){let r=t.notes??[];if(r.length>0){let l=J("ul","bp-ap-notes");l.setAttribute("data-testid","clone-notes");for(let p of r)l.appendChild(J("li","",xe(p)));a.push(l)}let o=J("div","bp-ap-foot"),c=t.thread?b("web.clone.open.thread","Open the thread"):b("web.clone.open.project","Open the project"),u=Fe(c,"primary",()=>this.goTo(t));u.setAttribute("data-testid","clone-open"),o.append(u),a.push(o)}e.replaceChildren(...a)}showJobError(e){if(!this.jobEl)return;this.jobEl.querySelector(".bp-ap-job-err")?.remove();let t=J("div","bp-ap-err bp-ap-job-err",e);this.jobEl.appendChild(t)}goTo(e){this.jobId="",this.job=null,this.close(),this.host.onCloneDone(e)}async startSignin(){this.signin={state:"starting"},this.copied=!1,this.renderSignin();try{let e=await this.host.hub.rpc("clone.signin",{restart:!0},30000);if(!this.signin||this.signin.state==="starting")this.signin=e}catch(e){this.signin={state:"failed",error:e instanceof Error?e.message:String(e)}}if(this.signin?.state==="done")this.askRepos(0);this.renderSignin()}renderSignin(){let e=this.signinEl;if(!e)return;let t=this.signin,n=[];if(t&&t.state){if(t.state==="starting"||t.state==="waiting"&&!t.code)n.push(J("div","bp-dim",b("web.clone.signin.wait","Starting GitHub sign-in…")));else if(t.state==="waiting"){n.push(J("div","",b("web.clone.signin.enter","Enter this code on GitHub:")));let i=J("div","bp-ap-code-row"),s=J("span","bp-ap-code",t.code||"");s.setAttribute("data-testid","clone-signin-code");let a=Fe(this.copied?b("web.clone.copied","Copied"):b("common.copy","Copy"),"bp-btn-line",()=>{navigator.clipboard?.writeText(t.code||"").then(()=>{this.copied=!0,this.renderSignin()}).catch(()=>{})});if(i.append(s,a),n.push(i),t.url){let r=J("a","bp-ap-link",t.url);r.href=t.url,r.target="_blank",r.rel="noopener noreferrer",r.setAttribute("data-testid","clone-signin-url"),n.push(r)}}else if(t.state==="done")n.push(J("div","bp-ok",b("web.clone.signin.done","Signed in to GitHub")));else if(t.state==="failed")n.push(J("div","bp-ap-err",xe(t.error||"")))}e.replaceChildren(...n),e.classList.toggle("bp-hidden",n.length===0)}}function ps(e){try{let t=new URL(e,window.location.origin);if(t.protocol==="https:"||t.protocol==="http:")return t.href}catch{}return null}function gt(e,t){let n=/(`[^`]+`|\*\*[^*]+\*\*|\*[^*]+\*|\[([^\]]+)\]\(([^)]+)\))/g,i=0,s;while((s=n.exec(t))!==null){if(s.index>i)e.appendChild(document.createTextNode(t.slice(i,s.index)));let a=s[0];if(a.startsWith("`")&&a.endsWith("`")){let r=document.createElement("code");r.className="bp-code-inline",r.textContent=a.slice(1,-1),e.appendChild(r)}else if(a.startsWith("**")&&a.endsWith("**")){let r=document.createElement("strong");r.textContent=a.slice(2,-2),e.appendChild(r)}else if(a.startsWith("*")&&a.endsWith("*")){let r=document.createElement("em");r.textContent=a.slice(1,-1),e.appendChild(r)}else if(a.startsWith("[")){let r=s[2]??"",o=ps(s[3]??"");if(o){let c=document.createElement("a");c.href=o,c.target="_blank",c.rel="noopener noreferrer",c.textContent=r,e.appendChild(c)}else e.appendChild(document.createTextNode(r))}i=n.lastIndex}if(i=(e.ended??0)}function jn(e){if(e.state!=="done")return!1;if(typeof e.hold==="boolean")return!e.hold;return(e.notes??[]).length===0}var gt={en:{"agy.signout":"Sign out","android.hub.machines.approve":"Approve","android.load.earlier":"load earlier","approval.dismiss":"Dismiss","approval.implement":"Implement","ask.plan":"Proposed plan","bots.rooms":"Rooms","bots.tab.browser":"Browser","common.cancel":"Cancel","common.close":"Close","common.copy":"Copy","common.delete":"Delete","common.refresh":"Refresh","common.remove":"Remove","common.save":"Save","composer.placeholder":"Ask anything: @bot, >thread, %project, #room, $skill, /btw","composer.send":"Send","composer.stop":"Stop","gpui.acct.connected":"Connected","gpui.acct.not.connected":"Not connected","gpui.acct.sign.in.expired":"Sign-in expired","gpui.ask.plan.ready":"Ready for review","gpui.ask.plan.revise":"Revise","gpui.ask.plan.reviseph":"What should change in the plan?","gpui.ask.plan.sendrev":"Send revision","gpui.b.in.reply.to":"↩ In reply to: {quote}","gpui.b.replying.to":"↩ Replying to: {line}","gpui.bots.recall.off":"Off","gpui.bots.recall.on":"On","gpui.c.term.collapse":"Collapse","gpui.c.term.expand":"Expand","gpui.commands":"Commands","gpui.e.open.folder":"Open folder","gpui.filter.projects.and.threads":"Filter projects and threads","gpui.fold.or.unfold.the.sidebar":"Fold or unfold the sidebar","gpui.follow.paused":"Following paused","gpui.follow.wait":"Following: waiting for the agent's next edit","gpui.gerbers":"Gerbers","gpui.improvements":"Improvements","gpui.jump.to.a.thread.run":"Jump to a thread, run a command or find what was said","gpui.mgmt.bom.dnp":"DNP","gpui.mgmt.bom.nompn":"no MPN","gpui.mgmt.checks.all":"All","gpui.mgmt.checks.fix":"Fix with agent","gpui.mgmt.checks.run":"Run","gpui.mgmt.close":"Close the panel","gpui.mgmt.fab.apply":"Apply","gpui.mgmt.fab.changed":"Changed since you last looked","gpui.mgmt.fab.derived":"* worked out from the fab's page (a mil in mm, a ring from a diameter). Dimmed: the rigid board's value, where this board's page says nothing else. A date opens the page it was read from.","gpui.mgmt.fab.extra":"Costs more","gpui.mgmt.fab.findings":"Findings","gpui.mgmt.fab.free":"Base price","gpui.mgmt.fab.judge":"Datasheets","gpui.mgmt.fab.limit":"Limit","gpui.mgmt.fab.readcol":"Read","gpui.mgmt.fab.refresh":"Refresh","gpui.mgmt.fab.reviewbtn":"Review","gpui.mgmt.fab.seen":"Seen","gpui.mgmt.fab.thefab":"The fab","gpui.mgmt.fab.use":"Use","gpui.mgmt.life.nopart":"No reading of this part yet.","gpui.mgmt.life.reading":"Reading its history…","gpui.mgmt.plan.addnote":"Add note","gpui.mgmt.plan.all":"Approve all","gpui.mgmt.plan.before":"Plan before routing","gpui.mgmt.plan.compact":"Compact","gpui.mgmt.plan.done":"done","gpui.mgmt.plan.drawn":"The plan's corridors and planes are drawn on the board while this panel is open. Close it to hide them.","gpui.mgmt.plan.edited":"Edited","gpui.mgmt.plan.elsewhere":"A routing plan for {board} awaits your approval","gpui.mgmt.plan.emptysub":"Layers, corridors, and planes appear here once a plan is proposed.","gpui.mgmt.plan.expand":"Expand","gpui.mgmt.plan.fit":"Fit","gpui.mgmt.plan.grid.all":"All layers","gpui.mgmt.plan.grid.pair":"Side by side","gpui.mgmt.plan.grid.single":"Single","gpui.mgmt.plan.hide":"Hide done","gpui.mgmt.plan.hint":"Drag waypoints to steer · Click + on edge to insert · Right-click vertex to remove","gpui.mgmt.plan.keysnote":"On this KiCad version, approve from this panel: in plan view KiCad's A, R and W keys aren't the plan's yet (A opens Add Footprint). Update KiCad.","gpui.mgmt.plan.layer":"Approve layer","gpui.mgmt.plan.layer.short":"Layer","gpui.mgmt.plan.lock":"Lock","gpui.mgmt.plan.locked":"Locked","gpui.mgmt.plan.noboard":"No routing plan for this board.","gpui.mgmt.plan.noitems":"No corridors or planes on this layer","gpui.mgmt.plan.note.placeholder":"Steering note for router…","gpui.mgmt.plan.nothing":"Nothing awaits your approval","gpui.mgmt.plan.offwords":"Agents route as you ask. Turn it on to have them propose a routing plan first and route only what you approve here.","gpui.mgmt.plan.onwords":"Before routing a board with 4 or more copper layers or more than 60 nets, the agent proposes corridors and plane regions here. It routes only what you approve.","gpui.mgmt.plan.reading":"Reading the routing plan…","gpui.mgmt.plan.reference":"over {layer}","gpui.mgmt.plan.refused":"KiCad refused","gpui.mgmt.plan.reject":"Reject","gpui.mgmt.plan.rejectlayer":"Reject layer","gpui.mgmt.plan.reqplain":"Approval requested","gpui.mgmt.plan.requested":"Approval requested: {what}","gpui.mgmt.plan.saved":"saved plan","gpui.mgmt.plan.show":"Show done","gpui.mgmt.plan.st.approved":"Approved","gpui.mgmt.plan.st.awaiting":"Awaiting review","gpui.mgmt.plan.st.blocked":"Blocked","gpui.mgmt.plan.st.empty":"Empty","gpui.mgmt.plan.st.partial":"Partial","gpui.mgmt.plan.st.rejected":"Rejected","gpui.mgmt.plan.st.routed":"Routed","gpui.mgmt.plan.st.routing":"Routing","gpui.mgmt.plan.st.verified":"Verified","gpui.mgmt.plan.stackup.short":"Stackup","gpui.mgmt.plan.stop":"Stop routing","gpui.mgmt.plan.sync":"Link zoom","gpui.mgmt.plan.tab":"Plan","gpui.mgmt.plan.unlock":"Unlock","gpui.mgmt.plan.verify":"Verify","gpui.mgmt.plan.view.canvas":"Canvas","gpui.mgmt.plan.view.list":"List","gpui.mgmt.plan.view.split":"Split","gpui.mgmt.plan.width":"Width","gpui.next.thread":"Next thread","gpui.nothing.matches":"Nothing matches","gpui.planmode.bar.always":"Plan mode — explores and proposes a plan before editing","gpui.planmode.bar.executing":"Building the approved plan","gpui.planmode.bar.once":"Plan mode (1 turn) — explores and proposes a plan before editing","gpui.planmode.bar.pending":"Proposed plan awaits review below","gpui.planmode.bar.planning":"Planning — drafting a plan before edits","gpui.planmode.chip.building":"Building","gpui.planmode.chip.once":"Plan · 1t","gpui.planmode.scope.always":"Always","gpui.planmode.scope.once":"1 turn","gpui.planmode.tip":"Plan before acting (1 turn, always, or off)","gpui.planmode.top.executing":"Building plan","gpui.planmode.top.once":"Plan (1 turn)","gpui.planmode.top.pending":"Review plan","gpui.planmode.top.planning":"Planning","gpui.previous.thread":"Previous thread","gpui.rail.no.board":"No board in this project","gpui.rail.no.mech":"No mechanical parts in this project","gpui.rail.no.schematic":"No schematic in this project","gpui.rail.split.needs.both":"Split needs a board and a schematic","home.away":"Home ({name}) is away","home.away.queued":"Home ({name}) is away · {n} queued","home.away.since":"Home ({name}) is away since {time}","home.away.since.queued":"Home ({name}) is away since {time} · {n} queued","home.machine":"Home machine","home.move.failed":"Home move failed","home.move.failed.note":"Home move failed: {note}","home.move.here":"Make this machine the home","home.moving":"Moving home to {to}…","home.moving.step":"Moving home to {to}: {step}","hub.back.crash":"Backplane is back after it stopped unexpectedly","hub.restarting":"Restarting Backplane…","hub.restarting.build":"Restarting Backplane… (new build {build})","hub.stopped":"Backplane stopped","ios.hub.address.field":"Hub address","menu.pin":"Pin","menu.settle":"Settle","menu.unpin":"Unpin","model.col.agent":"Agent","notify.settled":"Settled","palette.archive":"Archive thread","palette.command.placeholder":"Type a command or a thread","palette.diff":"Diff: what this thread changed","palette.newthread":"New thread","palette.settings":"Settings","palette.terminal":"Terminal","palette.unarchive":"Unarchive thread","phone.unsettle":"Unsettle","provider.notice.button":"Open Settings → Accounts","provider.notice.head":"No AI provider connected","provider.notice.senderr":"No AI provider connected yet. Open Settings → Accounts to connect Claude, Codex, Antigravity, or another provider.","provider.notice.text.none":"Connect Claude, Codex, Antigravity, or another provider to start chatting.","provider.notice.text.signedout":"Sign in to Claude, Codex, or another provider in Settings → Accounts to start chatting.","reply.action":"Reply","reply.cancel":"Cancel reply","reply.to":"In reply to:","secret.you":"You","settings.lang":"Language","sheet.rename":"Rename thread","sidebar.add.project":"Add project","sidebar.search.projects":"Search projects","thread.context.base":"Backplane","thread.context.copied":"Prompt copied.","thread.context.copy":"Copy prompt","thread.context.disable":"Disable","thread.context.enable":"Enable","thread.context.index":"Available skills index","thread.context.injected.label":"Injected project instructions","thread.context.instructions":"Instructions","thread.context.mcp":"Project MCPs","thread.context.native.note":"Backplane’s launch prompt. Native files are loaded by the provider.","thread.context.none.instructions":"No project instructions found.","thread.context.none.mcp":"No project MCP configurations found.","thread.context.reading":"Reading thread context…","thread.context.size":"{bytes} B · ≈{tokens} tokens","thread.context.skills":"Skills","thread.context.system":"System Prompt","thread.context.title":"Context & Prompt","thread.context.trust":"Trust and enable","thread.new":"New thread","tools.pinned":"Pinned","tools.retry":"Retry","tour.title.bots":"Bots","viewer.board":"Board","viewer.diff":"Diff","viewer.files":"Files","viewer.mech":"Mech","viewer.review":"Review","viewer.schematic":"Schematic","viewer.solid":"3D","web.chat.answer.btn":"Answer","web.chat.answer.placeholder":"Type answer…","web.chat.answered":"Answered: {answer}","web.chat.choose":"Choose a project thread on the left to begin.","web.chat.empty":"No messages yet. Type below to start a turn.","web.chat.finished":"Finished {time}","web.chat.finished.dur":"Finished {time} · {dur}","web.chat.loading":"Loading messages…","web.chat.review.mode":"Review mode","web.chat.streaming":"Streaming…","web.clone.add.dir":"Add {dir}","web.clone.back":"Back","web.clone.change.folder":"Change folder","web.clone.cloned":"Cloned {repo} into {dest}","web.clone.cloning":"Cloning {repo} into {dest}","web.clone.copied":"Copied","web.clone.first":"First message: {text}","web.clone.folder.name":"Folder name","web.clone.go":"Clone","web.clone.loading":"Loading…","web.clone.no.folders":"No folders here","web.clone.open.project":"Open the project","web.clone.open.thread":"Open the thread","web.clone.private":"private","web.clone.repo.placeholder":"https or ssh URL, or owner/repo","web.clone.retry":"Try again","web.clone.same":"Already cloned there: it is added as it is.","web.clone.signin":"Sign in to GitHub","web.clone.signin.done":"Signed in to GitHub","web.clone.signin.enter":"Enter this code on GitHub:","web.clone.signin.wait":"Starting GitHub sign-in…","web.clone.start.thread":"Start a thread","web.clone.stopped":"Stopped cloning {repo}","web.clone.tab":"Clone from git","web.clone.up":"Up","web.clone.use.dir":"Use {dir}","web.composer.attach":"Attach image","web.composer.maximages":"At most {max} images per message.","web.composer.unsupported":"Unsupported image type: {type}","web.composer.voice":"Voice dictation","web.logout.failed":"Could not confirm sign-out. Try again.","web.pair.approve.in":"Approve on desktop or paired phone · expires in {time}","web.pair.approved":"Approved. Opening Backplane…","web.pair.cancelled":"Cancelled.","web.pair.code":"Comparison code","web.pair.denied":"Pairing request was denied.","web.pair.expired":"Pairing code expired. Request a new code to try again.","web.pair.failed":"Pairing request failed ({status})","web.pair.name":"Browser name","web.pair.nocode":"Hub did not return a comparison code.","web.pair.ratelimited":"Too many pairing attempts. Wait a moment and try again.","web.pair.request":"Request pairing","web.pair.requesting":"Requesting pairing code…","web.pair.subtitle":"Pair this browser with your hub. Approve the 6-digit code in Backplane › Settings › Devices.","web.pair.unreachable":"Could not reach the hub. Check your tailnet connection.","web.plan.awaiting":"{n} awaiting approval","web.plan.net.one":"1 net","web.plan.nets":"{n} nets","web.settings.providers":"AI providers","web.settings.providers.browser":"Connect a provider in the Backplane desktop or mobile app under Settings → Accounts."},es:{"agy.signout":"Cerrar sesión","android.hub.machines.approve":"Aprobar","android.load.earlier":"cargar anteriores","approval.dismiss":"Descartar","approval.implement":"Implementar","ask.plan":"Plan propuesto","bots.rooms":"Salas","bots.tab.browser":"Navegador","common.cancel":"Cancelar","common.close":"Cerrar","common.copy":"Copiar","common.delete":"Eliminar","common.refresh":"Actualizar","common.remove":"Quitar","common.save":"Guardar","composer.placeholder":"Pregunta lo que sea: @bot, >hilo, %proyecto, #sala, $skill, /btw","composer.send":"Enviar","composer.stop":"Detener","gpui.acct.connected":"Conectado","gpui.acct.not.connected":"No conectado","gpui.acct.sign.in.expired":"Sesión caducada","gpui.ask.plan.ready":"Listo para revisar","gpui.ask.plan.revise":"Revisar","gpui.ask.plan.reviseph":"¿Qué debería cambiar en el plan?","gpui.ask.plan.sendrev":"Enviar revisión","gpui.b.in.reply.to":"↩ En respuesta a: {quote}","gpui.b.replying.to":"↩ Respondiendo a: {line}","gpui.bots.recall.off":"Desactivado","gpui.bots.recall.on":"Activado","gpui.c.term.collapse":"Contraer","gpui.c.term.expand":"Expandir","gpui.commands":"Comandos","gpui.e.open.folder":"Abrir carpeta","gpui.filter.projects.and.threads":"Filtrar proyectos e hilos","gpui.fold.or.unfold.the.sidebar":"Plegar o desplegar la barra lateral","gpui.follow.paused":"Seguimiento en pausa","gpui.follow.wait":"Siguiendo: esperando la próxima edición del agente","gpui.gerbers":"Gerbers","gpui.improvements":"Mejoras","gpui.jump.to.a.thread.run":"Saltar a un hilo, ejecutar un comando o buscar lo dicho","gpui.mgmt.bom.dnp":"DNP","gpui.mgmt.bom.nompn":"sin MPN","gpui.mgmt.checks.all":"Todas","gpui.mgmt.checks.fix":"Corregir con agente","gpui.mgmt.checks.run":"Ejecutar","gpui.mgmt.close":"Cerrar el panel","gpui.mgmt.fab.apply":"Aplicar","gpui.mgmt.fab.changed":"Cambió desde la última vez que miraste","gpui.mgmt.fab.derived":"* calculado desde la página del fabricante (un mil en mm, un anillo desde un diámetro). Atenuado: el valor de la placa rígida, cuando la página de esta placa no dice otra cosa. Una fecha abre la página de la que se leyó.","gpui.mgmt.fab.extra":"Cuesta más","gpui.mgmt.fab.findings":"Hallazgos","gpui.mgmt.fab.free":"Precio base","gpui.mgmt.fab.judge":"Hojas de datos","gpui.mgmt.fab.limit":"Límite","gpui.mgmt.fab.readcol":"Leído","gpui.mgmt.fab.refresh":"Actualizar","gpui.mgmt.fab.reviewbtn":"Revisar","gpui.mgmt.fab.seen":"Visto","gpui.mgmt.fab.thefab":"El fabricante","gpui.mgmt.fab.use":"Usar","gpui.mgmt.life.nopart":"Sin lectura de esta pieza aún.","gpui.mgmt.life.reading":"Leyendo su historial…","gpui.mgmt.plan.addnote":"Añadir nota","gpui.mgmt.plan.all":"Aprobar todo","gpui.mgmt.plan.before":"Planificar antes de rutear","gpui.mgmt.plan.compact":"Compacto","gpui.mgmt.plan.done":"hecho","gpui.mgmt.plan.drawn":"Los corredores y planos del plan se dibujan en la placa mientras este panel está abierto. Ciérralo para ocultarlos.","gpui.mgmt.plan.edited":"Editado","gpui.mgmt.plan.elsewhere":"Un plan de ruteo para {board} espera tu aprobación","gpui.mgmt.plan.emptysub":"Las capas, corredores y planos aparecerán aquí cuando se proponga un plan.","gpui.mgmt.plan.expand":"Expandir","gpui.mgmt.plan.fit":"Ajustar","gpui.mgmt.plan.grid.all":"Todas las capas","gpui.mgmt.plan.grid.pair":"Lado a lado","gpui.mgmt.plan.grid.single":"Única","gpui.mgmt.plan.hide":"Ocultar hechos","gpui.mgmt.plan.hint":"Arrastra vértices para guiar · Clic en + del borde para insertar · Clic derecho en vértice para quitar","gpui.mgmt.plan.keysnote":"En esta versión de KiCad, aprueba desde este panel: en la vista de plan las teclas A, R y W de KiCad aún no son del plan (A abre Añadir Huella). Actualiza KiCad.","gpui.mgmt.plan.layer":"Aprobar capa","gpui.mgmt.plan.layer.short":"Capa","gpui.mgmt.plan.lock":"Bloquear","gpui.mgmt.plan.locked":"Bloqueado","gpui.mgmt.plan.noboard":"No hay plan de ruteo para esta placa.","gpui.mgmt.plan.noitems":"Sin corredores ni planos en esta capa","gpui.mgmt.plan.note.placeholder":"Nota de guiado para el router…","gpui.mgmt.plan.nothing":"Nada espera tu aprobación","gpui.mgmt.plan.offwords":"Los agentes rutean como les pidas. Actívalo para que primero propongan un plan de ruteo y ruteen solo lo que apruebes aquí.","gpui.mgmt.plan.onwords":"Antes de rutear una placa con 4 o más capas de cobre o más de 60 redes, el agente propone aquí corredores y regiones de plano. Solo rutea lo que apruebes.","gpui.mgmt.plan.reading":"Leyendo el plan de ruteo…","gpui.mgmt.plan.reference":"sobre {layer}","gpui.mgmt.plan.refused":"KiCad lo rechazó","gpui.mgmt.plan.reject":"Rechazar","gpui.mgmt.plan.rejectlayer":"Rechazar capa","gpui.mgmt.plan.reqplain":"Aprobación solicitada","gpui.mgmt.plan.requested":"Aprobación solicitada: {what}","gpui.mgmt.plan.saved":"plan guardado","gpui.mgmt.plan.show":"Mostrar hechos","gpui.mgmt.plan.st.approved":"Aprobado","gpui.mgmt.plan.st.awaiting":"Esperando revisión","gpui.mgmt.plan.st.blocked":"Bloqueado","gpui.mgmt.plan.st.empty":"Vacío","gpui.mgmt.plan.st.partial":"Parcial","gpui.mgmt.plan.st.rejected":"Rechazado","gpui.mgmt.plan.st.routed":"Ruteado","gpui.mgmt.plan.st.routing":"Ruteando","gpui.mgmt.plan.st.verified":"Verificado","gpui.mgmt.plan.stackup.short":"Apilamiento","gpui.mgmt.plan.stop":"Detener ruteo","gpui.mgmt.plan.sync":"Vincular zoom","gpui.mgmt.plan.tab":"Plan","gpui.mgmt.plan.unlock":"Desbloquear","gpui.mgmt.plan.verify":"Verificar","gpui.mgmt.plan.view.canvas":"Lienzo","gpui.mgmt.plan.view.list":"Lista","gpui.mgmt.plan.view.split":"Dividido","gpui.mgmt.plan.width":"Ancho","gpui.next.thread":"Hilo siguiente","gpui.nothing.matches":"Nada coincide","gpui.planmode.bar.always":"Modo plan — explora y propone un plan antes de editar","gpui.planmode.bar.executing":"Ejecutando el plan aprobado","gpui.planmode.bar.once":"Modo plan (1 turno) — explora y propone un plan antes de editar","gpui.planmode.bar.pending":"El plan propuesto espera revisión abajo","gpui.planmode.bar.planning":"Planificando — redactando un plan antes de editar","gpui.planmode.chip.building":"Ejecutando","gpui.planmode.chip.once":"Plan · 1t","gpui.planmode.scope.always":"Siempre","gpui.planmode.scope.once":"1 turno","gpui.planmode.tip":"Planificar antes de actuar (1 turno, siempre u off)","gpui.planmode.top.executing":"Ejecutando plan","gpui.planmode.top.once":"Plan (1 turno)","gpui.planmode.top.pending":"Revisar plan","gpui.planmode.top.planning":"Planificando","gpui.previous.thread":"Hilo anterior","gpui.rail.no.board":"Este proyecto no tiene placa","gpui.rail.no.mech":"Este proyecto no tiene piezas mecánicas","gpui.rail.no.schematic":"Este proyecto no tiene esquema","gpui.rail.split.needs.both":"La vista dividida requiere una placa y un esquema","home.away":"El inicio ({name}) no está disponible","home.away.queued":"El inicio ({name}) no está disponible · {n} en cola","home.away.since":"El inicio ({name}) no está disponible desde las {time}","home.away.since.queued":"El inicio ({name}) no está disponible desde las {time} · {n} en cola","home.machine":"Máquina de inicio","home.move.failed":"No se pudo mover el inicio","home.move.failed.note":"No se pudo mover el inicio: {note}","home.move.here":"Hacer de esta máquina el inicio","home.moving":"Moviendo el inicio a {to}…","home.moving.step":"Moviendo el inicio a {to}: {step}","hub.back.crash":"Backplane volvió tras detenerse de forma inesperada","hub.restarting":"Reiniciando Backplane…","hub.restarting.build":"Reiniciando Backplane… (nueva compilación {build})","hub.stopped":"Backplane se detuvo","ios.hub.address.field":"Dirección del hub","menu.pin":"Fijar","menu.settle":"Cerrar","menu.unpin":"Desfijar","model.col.agent":"Agente","notify.settled":"Cerrado","palette.archive":"Archivar hilo","palette.command.placeholder":"Escribe un comando o un hilo","palette.diff":"Diff: qué cambió este hilo","palette.newthread":"Nuevo hilo","palette.settings":"Ajustes","palette.terminal":"Terminal","palette.unarchive":"Desarchivar hilo","phone.unsettle":"Reabrir","provider.notice.button":"Abrir Configuración → Cuentas","provider.notice.head":"No hay ningún proveedor de IA conectado","provider.notice.senderr":"Aún no hay ningún proveedor de IA conectado. Abre Configuración → Cuentas para conectar Claude, Codex, Antigravity u otro proveedor.","provider.notice.text.none":"Conecta Claude, Codex, Antigravity u otro proveedor para empezar a chatear.","provider.notice.text.signedout":"Inicia sesión en Claude, Codex u otro proveedor en Configuración → Cuentas para empezar a chatear.","reply.action":"Responder","reply.cancel":"Cancelar respuesta","reply.to":"En respuesta a:","secret.you":"Tú","settings.lang":"Idioma","sheet.rename":"Renombrar hilo","sidebar.add.project":"Añadir proyecto","sidebar.search.projects":"Buscar proyectos","thread.context.base":"Backplane","thread.context.copied":"Se copiaron las instrucciones.","thread.context.copy":"Copiar instrucciones","thread.context.disable":"Desactivar","thread.context.enable":"Activar","thread.context.index":"Índice de habilidades disponibles","thread.context.injected.label":"Instrucciones del proyecto añadidas","thread.context.instructions":"Instrucciones","thread.context.mcp":"MCP del proyecto","thread.context.native.note":"Instrucciones de inicio de Backplane. El proveedor carga los archivos nativos.","thread.context.none.instructions":"No se encontraron instrucciones del proyecto.","thread.context.none.mcp":"No se encontraron configuraciones MCP del proyecto.","thread.context.reading":"Leyendo el contexto del hilo…","thread.context.size":"{bytes} B · ≈{tokens} tokens","thread.context.skills":"Habilidades","thread.context.system":"Instrucciones del sistema","thread.context.title":"Contexto e instrucciones","thread.context.trust":"Confiar y activar","thread.new":"Nuevo hilo","tools.pinned":"Fijado","tools.retry":"Reintentar","tour.title.bots":"Bots","viewer.board":"Placa","viewer.diff":"Diff","viewer.files":"Archivos","viewer.mech":"Mech","viewer.review":"Revisión","viewer.schematic":"Esquemático","viewer.solid":"3D","web.chat.answer.btn":"Responder","web.chat.answer.placeholder":"Escribe una respuesta…","web.chat.answered":"Respondido: {answer}","web.chat.choose":"Elige un hilo de proyecto a la izquierda para empezar.","web.chat.empty":"Aún no hay mensajes. Escribe abajo para iniciar un turno.","web.chat.finished":"Terminado {time}","web.chat.finished.dur":"Terminado {time} · {dur}","web.chat.loading":"Cargando mensajes…","web.chat.review.mode":"Modo de revisión","web.chat.streaming":"Transmitiendo…","web.clone.add.dir":"Añadir {dir}","web.clone.back":"Atrás","web.clone.change.folder":"Cambiar carpeta","web.clone.cloned":"{repo} clonado en {dest}","web.clone.cloning":"Clonando {repo} en {dest}","web.clone.copied":"Copiado","web.clone.first":"Primer mensaje: {text}","web.clone.folder.name":"Nombre de la carpeta","web.clone.go":"Clonar","web.clone.loading":"Cargando…","web.clone.no.folders":"No hay carpetas aquí","web.clone.open.project":"Abrir el proyecto","web.clone.open.thread":"Abrir el hilo","web.clone.private":"privado","web.clone.repo.placeholder":"URL https o ssh, o propietario/repositorio","web.clone.retry":"Reintentar","web.clone.same":"Ya está clonado ahí: se añade tal cual.","web.clone.signin":"Iniciar sesión en GitHub","web.clone.signin.done":"Sesión iniciada en GitHub","web.clone.signin.enter":"Introduce este código en GitHub:","web.clone.signin.wait":"Iniciando sesión en GitHub…","web.clone.start.thread":"Empezar un hilo","web.clone.stopped":"Se detuvo la clonación de {repo}","web.clone.tab":"Clonar desde git","web.clone.up":"Subir","web.clone.use.dir":"Usar {dir}","web.composer.attach":"Adjuntar imagen","web.composer.maximages":"Como máximo {max} imágenes por mensaje.","web.composer.unsupported":"Tipo de imagen no compatible: {type}","web.composer.voice":"Dictado por voz","web.logout.failed":"No se pudo confirmar el cierre de sesión. Inténtalo de nuevo.","web.pair.approve.in":"Aprueba en el escritorio o en un teléfono vinculado · caduca en {time}","web.pair.approved":"Aprobado. Abriendo Backplane…","web.pair.cancelled":"Cancelado.","web.pair.code":"Código de comparación","web.pair.denied":"Se rechazó la solicitud de vinculación.","web.pair.expired":"El código de vinculación caducó. Solicita uno nuevo para intentarlo otra vez.","web.pair.failed":"Falló la solicitud de vinculación ({status})","web.pair.name":"Nombre del navegador","web.pair.nocode":"El hub no devolvió un código de comparación.","web.pair.ratelimited":"Demasiados intentos de vinculación. Espera un momento e inténtalo de nuevo.","web.pair.request":"Solicitar vinculación","web.pair.requesting":"Solicitando código de vinculación…","web.pair.subtitle":"Vincula este navegador con tu hub. Aprueba el código de 6 dígitos en Backplane › Ajustes › Dispositivos.","web.pair.unreachable":"No se pudo conectar con el hub. Comprueba tu conexión de tailnet.","web.plan.awaiting":"{n} esperando aprobación","web.plan.net.one":"1 red","web.plan.nets":"{n} redes","web.settings.providers":"Proveedores de IA","web.settings.providers.browser":"Conecta un proveedor en la aplicación de escritorio o móvil de Backplane en Configuración → Cuentas."},ja:{"agy.signout":"サインアウト","android.hub.machines.approve":"承認","android.load.earlier":"以前のメッセージを読み込む","approval.dismiss":"閉じる","approval.implement":"実装","ask.plan":"提案されたプラン","bots.rooms":"ルーム","bots.tab.browser":"ブラウザ","common.cancel":"キャンセル","common.close":"閉じる","common.copy":"コピー","common.delete":"削除","common.refresh":"更新","common.remove":"削除","common.save":"保存","composer.placeholder":"何でも質問:@bot、>thread、%project、#room、$skill、/btw","composer.send":"送信","composer.stop":"停止","gpui.acct.connected":"接続済み","gpui.acct.not.connected":"未接続","gpui.acct.sign.in.expired":"サインインの期限切れ","gpui.ask.plan.ready":"確認待ち","gpui.ask.plan.revise":"修正","gpui.ask.plan.reviseph":"計画のどこを変更しますか?","gpui.ask.plan.sendrev":"修正を送る","gpui.b.in.reply.to":"↩ 返信先:{quote}","gpui.b.replying.to":"↩ 返信中:{line}","gpui.bots.recall.off":"オフ","gpui.bots.recall.on":"オン","gpui.c.term.collapse":"折りたたむ","gpui.c.term.expand":"展開","gpui.commands":"コマンド","gpui.e.open.folder":"フォルダを開く","gpui.filter.projects.and.threads":"プロジェクトとスレッドを絞り込む","gpui.fold.or.unfold.the.sidebar":"サイドバーを折りたたむ/開く","gpui.follow.paused":"追従を一時停止中","gpui.follow.wait":"追従中: エージェントの次の編集を待っています","gpui.gerbers":"ガーバー","gpui.improvements":"改善","gpui.jump.to.a.thread.run":"スレッドへ移動、コマンドを実行、または発言を検索","gpui.mgmt.bom.dnp":"実装しない","gpui.mgmt.bom.nompn":"MPNなし","gpui.mgmt.checks.all":"すべて","gpui.mgmt.checks.fix":"エージェントに直してもらう","gpui.mgmt.checks.run":"実行","gpui.mgmt.close":"パネルを閉じる","gpui.mgmt.fab.apply":"適用","gpui.mgmt.fab.changed":"前回見てから変わったところ","gpui.mgmt.fab.derived":"* 製造元のページから計算した値です(milをmmに、径からランドを)。薄い色の項目はリジッド基板の値です(この基板のページに記載がないもの)。日付を押すと読んだページが開きます。","gpui.mgmt.fab.extra":"追加料金","gpui.mgmt.fab.findings":"指摘","gpui.mgmt.fab.free":"基本料金","gpui.mgmt.fab.judge":"データシート","gpui.mgmt.fab.limit":"項目","gpui.mgmt.fab.readcol":"読んだ日","gpui.mgmt.fab.refresh":"再読み込み","gpui.mgmt.fab.reviewbtn":"レビュー","gpui.mgmt.fab.seen":"確認済み","gpui.mgmt.fab.thefab":"製造元","gpui.mgmt.fab.use":"使う","gpui.mgmt.life.nopart":"この部品の記録はまだありません。","gpui.mgmt.life.reading":"履歴を読んでいます…","gpui.mgmt.plan.addnote":"メモを追加","gpui.mgmt.plan.all":"すべて承認","gpui.mgmt.plan.before":"配線前に計画する","gpui.mgmt.plan.compact":"標準","gpui.mgmt.plan.done":"完了","gpui.mgmt.plan.drawn":"計画の配線経路とプレーンは、このパネルを開いている間だけ基板上に表示されます。閉じると消えます。","gpui.mgmt.plan.edited":"編集済み","gpui.mgmt.plan.elsewhere":"{board}の配線計画が承認を待っています","gpui.mgmt.plan.emptysub":"計画が提案されると、レイヤー・コリドー・ベタ領域がここに表示されます。","gpui.mgmt.plan.expand":"拡大","gpui.mgmt.plan.fit":"全体表示","gpui.mgmt.plan.grid.all":"全レイヤー","gpui.mgmt.plan.grid.pair":"並べて表示","gpui.mgmt.plan.grid.single":"単一","gpui.mgmt.plan.hide":"完了を隠す","gpui.mgmt.plan.hint":"頂点をドラッグして誘導 · 辺の + をクリックで追加 · 頂点を右クリックで削除","gpui.mgmt.plan.keysnote":"このバージョンのKiCadでは、このパネルから承認してください。プランビューでのKiCadのA・R・Wキーはまだ計画のものではありません(Aはフットプリントの追加を開きます)。KiCadを更新してください。","gpui.mgmt.plan.layer":"層を承認","gpui.mgmt.plan.layer.short":"レイヤー","gpui.mgmt.plan.lock":"ロック","gpui.mgmt.plan.locked":"ロック中","gpui.mgmt.plan.noboard":"この基板の配線計画はありません。","gpui.mgmt.plan.noitems":"このレイヤーにコリドーまたはプレーンがありません","gpui.mgmt.plan.note.placeholder":"ルーターへの指示メモ…","gpui.mgmt.plan.nothing":"承認待ちはありません","gpui.mgmt.plan.offwords":"エージェントは指示どおりに配線します。オンにすると、まず配線計画を提案し、ここで承認したものだけを配線します。","gpui.mgmt.plan.onwords":"銅箔層が4層以上、またはネットが60本を超える基板では、配線の前にエージェントがここで配線経路とプレーン領域を提案します。承認したものだけを配線します。","gpui.mgmt.plan.reading":"配線計画を読んでいます…","gpui.mgmt.plan.reference":"基準 {layer}","gpui.mgmt.plan.refused":"KiCad が拒否しました","gpui.mgmt.plan.reject":"却下","gpui.mgmt.plan.rejectlayer":"レイヤーを却下","gpui.mgmt.plan.reqplain":"承認が求められています","gpui.mgmt.plan.requested":"承認が求められています: {what}","gpui.mgmt.plan.saved":"保存された計画","gpui.mgmt.plan.show":"完了を表示","gpui.mgmt.plan.st.approved":"承認済み","gpui.mgmt.plan.st.awaiting":"承認待ち","gpui.mgmt.plan.st.blocked":"ブロック","gpui.mgmt.plan.st.empty":"空","gpui.mgmt.plan.st.partial":"一部完了","gpui.mgmt.plan.st.rejected":"却下","gpui.mgmt.plan.st.routed":"配線済み","gpui.mgmt.plan.st.routing":"配線中","gpui.mgmt.plan.st.verified":"検証済み","gpui.mgmt.plan.stackup.short":"スタックアップ","gpui.mgmt.plan.stop":"配線を止める","gpui.mgmt.plan.sync":"ズーム連動","gpui.mgmt.plan.tab":"計画","gpui.mgmt.plan.unlock":"ロック解除","gpui.mgmt.plan.verify":"検証","gpui.mgmt.plan.view.canvas":"キャンバス","gpui.mgmt.plan.view.list":"リスト","gpui.mgmt.plan.view.split":"分割","gpui.mgmt.plan.width":"幅","gpui.next.thread":"次のスレッド","gpui.nothing.matches":"一致するものはありません","gpui.planmode.bar.always":"計画モード — 編集前に調査して計画を提案します","gpui.planmode.bar.executing":"承認された計画を実行しています","gpui.planmode.bar.once":"計画モード (1回) — 編集前に調査して計画を提案します","gpui.planmode.bar.pending":"提案された計画が下のレビューを待っています","gpui.planmode.bar.planning":"計画中 — 編集前の計画を作成しています","gpui.planmode.chip.building":"実行中","gpui.planmode.chip.once":"計画 · 1回","gpui.planmode.scope.always":"常時","gpui.planmode.scope.once":"1回","gpui.planmode.tip":"実行前に計画を作成 (1回・常時・オフ)","gpui.planmode.top.executing":"計画を実行中","gpui.planmode.top.once":"計画 (1回)","gpui.planmode.top.pending":"計画を確認","gpui.planmode.top.planning":"計画中","gpui.previous.thread":"前のスレッド","gpui.rail.no.board":"このプロジェクトには基板がありません","gpui.rail.no.mech":"このプロジェクトには機械部品がありません","gpui.rail.no.schematic":"このプロジェクトには回路図がありません","gpui.rail.split.needs.both":"分割表示には基板と回路図が必要です","home.away":"ホーム({name})はオフラインです","home.away.queued":"ホーム({name})はオフラインです · {n} 件待機中","home.away.since":"ホーム({name})は {time} からオフラインです","home.away.since.queued":"ホーム({name})は {time} からオフラインです · {n} 件待機中","home.machine":"ホームマシン","home.move.failed":"ホームの移動に失敗しました","home.move.failed.note":"ホームの移動に失敗しました: {note}","home.move.here":"このマシンをホームにする","home.moving":"ホームを {to} へ移動中…","home.moving.step":"ホームを {to} へ移動中: {step}","hub.back.crash":"予期せず停止したBackplaneが戻りました","hub.restarting":"Backplaneを再起動しています…","hub.restarting.build":"Backplaneを再起動しています…(新しいビルド {build})","hub.stopped":"Backplaneは停止しました","ios.hub.address.field":"ハブのアドレス","menu.pin":"ピン留め","menu.settle":"完了","menu.unpin":"ピン留めを解除","model.col.agent":"エージェント","notify.settled":"完了","palette.archive":"スレッドをアーカイブ","palette.command.placeholder":"コマンドまたはスレッドを入力","palette.diff":"差分:このスレッドの変更","palette.newthread":"新しいスレッド","palette.settings":"設定","palette.terminal":"ターミナル","palette.unarchive":"スレッドのアーカイブを解除","phone.unsettle":"未完了に戻す","provider.notice.button":"設定 → アカウントを開く","provider.notice.head":"AI プロバイダーが接続されていません","provider.notice.senderr":"AI プロバイダーがまだ接続されていません。設定 → アカウントを開いて、Claude、Codex、Antigravity などのプロバイダーを接続してください。","provider.notice.text.none":"チャットを始めるには、Claude、Codex、Antigravity などのプロバイダーを接続してください。","provider.notice.text.signedout":"チャットを始めるには、設定 → アカウントで Claude、Codex などのプロバイダーにサインインしてください。","reply.action":"返信","reply.cancel":"返信をやめる","reply.to":"返信先:","secret.you":"あなた","settings.lang":"言語","sheet.rename":"スレッド名を変更","sidebar.add.project":"プロジェクトを追加","sidebar.search.projects":"プロジェクトを検索","thread.context.base":"Backplane","thread.context.copied":"プロンプトをコピーしました。","thread.context.copy":"プロンプトをコピー","thread.context.disable":"無効にする","thread.context.enable":"有効にする","thread.context.index":"利用可能なスキルの一覧","thread.context.injected.label":"追加されたプロジェクトの指示","thread.context.instructions":"指示","thread.context.mcp":"プロジェクトの MCP","thread.context.native.note":"Backplane が起動時に渡すプロンプトです。ネイティブファイルはプロバイダーが読み込みます。","thread.context.none.instructions":"プロジェクトの指示が見つかりません。","thread.context.none.mcp":"プロジェクトの MCP 設定が見つかりません。","thread.context.reading":"スレッドのコンテキストを読み込み中…","thread.context.size":"{bytes} B・約{tokens}トークン","thread.context.skills":"スキル","thread.context.system":"システムプロンプト","thread.context.title":"コンテキストとプロンプト","thread.context.trust":"承認して有効にする","thread.new":"新しいスレッド","tools.pinned":"固定中","tools.retry":"再試行","tour.title.bots":"ボット","viewer.board":"基板","viewer.diff":"差分","viewer.files":"ファイル","viewer.mech":"Mech","viewer.review":"レビュー","viewer.schematic":"回路図","viewer.solid":"3D","web.chat.answer.btn":"回答","web.chat.answer.placeholder":"回答を入力…","web.chat.answered":"回答済み: {answer}","web.chat.choose":"左側からプロジェクトのスレッドを選んで開始してください。","web.chat.empty":"まだメッセージはありません。下に入力して開始してください。","web.chat.finished":"完了 {time}","web.chat.finished.dur":"完了 {time} · {dur}","web.chat.loading":"メッセージを読み込んでいます…","web.chat.review.mode":"レビューモード","web.chat.streaming":"受信中…","web.clone.add.dir":"{dir} を追加","web.clone.back":"戻る","web.clone.change.folder":"フォルダを変更","web.clone.cloned":"{repo} を {dest} にクローンしました","web.clone.cloning":"{repo} を {dest} にクローン中","web.clone.copied":"コピーしました","web.clone.first":"最初のメッセージ: {text}","web.clone.folder.name":"フォルダ名","web.clone.go":"クローン","web.clone.loading":"読み込み中…","web.clone.no.folders":"フォルダがありません","web.clone.open.project":"プロジェクトを開く","web.clone.open.thread":"スレッドを開く","web.clone.private":"非公開","web.clone.repo.placeholder":"https / ssh の URL、または owner/repo","web.clone.retry":"もう一度","web.clone.same":"すでにそこにクローンされています: そのまま追加します。","web.clone.signin":"GitHub にサインイン","web.clone.signin.done":"GitHub にサインインしました","web.clone.signin.enter":"このコードを GitHub に入力してください:","web.clone.signin.wait":"GitHub のサインインを開始しています…","web.clone.start.thread":"スレッドを開始","web.clone.stopped":"{repo} のクローンを中止しました","web.clone.tab":"git からクローン","web.clone.up":"上へ","web.clone.use.dir":"{dir} を使う","web.composer.attach":"画像を添付","web.composer.maximages":"1 件のメッセージに添付できる画像は最大 {max} 枚です。","web.composer.unsupported":"未対応の画像形式です: {type}","web.composer.voice":"音声入力","web.logout.failed":"サインアウトを確認できませんでした。もう一度お試しください。","web.pair.approve.in":"デスクトップまたはペアリング済みの端末で承認してください · 有効期限 {time}","web.pair.approved":"承認されました。Backplane を開いています…","web.pair.cancelled":"キャンセルしました。","web.pair.code":"確認コード","web.pair.denied":"ペアリングのリクエストが拒否されました。","web.pair.expired":"ペアリングコードの有効期限が切れました。新しいコードをリクエストしてください。","web.pair.failed":"ペアリングのリクエストに失敗しました ({status})","web.pair.name":"ブラウザー名","web.pair.nocode":"ハブから確認コードが返されませんでした。","web.pair.ratelimited":"ペアリングの試行回数が多すぎます。しばらく待ってからやり直してください。","web.pair.request":"ペアリングをリクエスト","web.pair.requesting":"ペアリングコードをリクエストしています…","web.pair.subtitle":"このブラウザーをハブとペアリングします。Backplane › 設定 › デバイス で 6 桁のコードを承認してください。","web.pair.unreachable":"ハブに接続できませんでした。tailnet の接続を確認してください。","web.plan.awaiting":"{n} 件が承認待ち","web.plan.net.one":"1 ネット","web.plan.nets":"{n} ネット","web.settings.providers":"AI プロバイダー","web.settings.providers.browser":"Backplane のデスクトップまたはモバイルアプリの設定 → アカウントからプロバイダーを接続してください。"}};function Hn(e,t){if(!t)return e;return e.replace(/\{([a-zA-Z0-9_.-]+)\}/g,(n,i)=>Object.prototype.hasOwnProperty.call(t,i)?String(t[i]):n)}var ft=hs(),_t=new Set,qt=new Map;for(let[e,t]of Object.entries(gt.en||{}))if(typeof t==="string"&&!qt.has(t))qt.set(t,e);function hs(){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 Dn(){if(typeof document<"u"&&document.documentElement)document.documentElement.lang=ft}Dn();function Tt(e){return _t.add(e),()=>{_t.delete(e)}}function Fn(e){if(!e)return!1;let t=e.toLowerCase(),n=t.startsWith("ja")?"ja":t.startsWith("es")?"es":t.startsWith("en")?"en":"";if(!n)return!1;let i=n!==ft;if(ft=n,Dn(),i)for(let s of _t)s(ft);return i}function b(e,t,n){let s=(gt[ft]||gt.en||{})[e]??gt.en?.[e]??t??e;return Hn(s,n)}function pe(e){if(!e)return"";let t=qt.get(e);if(!t)return e;return b(t,e)}function J(e,t="",n=""){let i=document.createElement(e);if(t)i.className=t;if(n)i.textContent=n;return i}function Fe(e,t="",n){let i=J("button",t,e);if(i.type="button",n)i.addEventListener("click",n);return i}function bs(e){let t=e.replace(/[\\/]+$/,"");if(!t)return e||"/";let n=t.split(/[\\/]/);return n[n.length-1]||t}function gs(e,t){let n=e.includes("\\")&&!e.includes("/")?"\\":"/";return e.endsWith(n)?e+t:e+n+t}class Kt{hub;actionLabel;action;root;pathInput;upBtn;listEl;errEl;actBtn;path="";parent=null;gen=0;busy=!1;constructor(e,t,n,i=[]){this.hub=e;this.actionLabel=t;this.action=n;this.root=J("div","bp-fb"),this.root.setAttribute("data-testid","folder-browser");let s=J("div","bp-fb-head");this.upBtn=Fe("↑","bp-btn-ghost bp-fb-up",()=>{if(this.parent)this.go(this.parent)}),this.upBtn.title=b("web.clone.up","Up"),this.upBtn.setAttribute("aria-label",b("web.clone.up","Up")),this.pathInput=J("input","bp-input bp-fb-path"),this.pathInput.spellcheck=!1,this.pathInput.setAttribute("data-testid","folder-path"),this.pathInput.addEventListener("keydown",(a)=>{if(a.key==="Enter"){a.preventDefault();let o=this.pathInput.value.trim();if(o)this.go(o)}}),s.append(this.upBtn,this.pathInput),this.listEl=J("div","bp-fb-list"),this.errEl=J("div","bp-ap-err bp-hidden");let r=J("div","bp-ap-foot");this.actBtn=Fe("","primary",()=>{this.run()}),this.actBtn.setAttribute("data-testid","folder-act"),r.append(...i,this.actBtn),this.root.append(s,this.listEl,this.errEl,r)}currentPath(){return this.path}async go(e){let t=++this.gen;this.setError(""),this.listEl.replaceChildren(J("div","bp-fb-empty",b("web.clone.loading","Loading…")));try{let n=await this.hub.rpc("dirs.list",{path:e});if(t!==this.gen)return;this.path=n.path,this.parent=n.parent??null,this.render(n.dirs??[])}catch(n){if(t!==this.gen)return;this.setError(pe(n instanceof Error?n.message:String(n))),this.render(null)}}refreshLocale(){this.upBtn.title=b("web.clone.up","Up"),this.updateAct()}render(e){if(this.pathInput.value=this.path,this.upBtn.disabled=!this.parent,this.updateAct(),e===null){this.listEl.replaceChildren();return}if(e.length===0){this.listEl.replaceChildren(J("div","bp-fb-empty",b("web.clone.no.folders","No folders here")));return}let t=document.createDocumentFragment();for(let n of e){let i=Fe("","bp-fb-row",()=>{this.go(gs(this.path,n))});i.append(J("span","bp-fb-icon","▸"),J("span","bp-fb-name",n)),t.appendChild(i)}this.listEl.replaceChildren(t),this.listEl.scrollTop=0}updateAct(){this.actBtn.textContent=this.path?this.actionLabel(bs(this.path)):this.actionLabel("…"),this.actBtn.disabled=!this.path||this.busy}async run(){if(!this.path||this.busy)return;this.busy=!0,this.updateAct(),this.setError("");try{await this.action(this.path)}catch(e){this.setError(pe(e instanceof Error?e.message:String(e)))}finally{this.busy=!1,this.updateAct()}}setError(e){this.errEl.textContent=e,this.errEl.classList.toggle("bp-hidden",!e)}}class zt{container;host;backdrop=null;bodyEl=null;tabsEl=null;mode="folder";repoText="";repoValue="";firstText="";wantThread=!0;userParent="";nameText="";nameTouched=!1;dest=null;destGen=0;destPending=!1;destTimer=null;repos=null;reposGen=0;reposTimer=null;showSuggest=!1;suggestIdx=-1;startErr="";starting=!1;picking=!1;jobId="";job=null;specs=new Map;signin=null;copied=!1;repoInput=null;suggestEl=null;destEl=null;signinEl=null;cloneBtn=null;jobEl=null;constructor(e,t){this.container=e;this.host=t}isOpen(){return this.backdrop!==null}open(e={}){let t=this.host.hub.hasFeature("clone"),n=!e.repo&&Boolean(this.jobId)&&(!this.job||this.job.state==="running"||this.job.state==="done");if(!this.backdrop)this.build();if(!n)this.jobId="",this.job=null,this.resetForm();if(e.repo!==void 0||e.text!==void 0)this.repoText=(e.repo??"").trim(),this.repoValue="",this.firstText=(e.text??"").trim();if(this.mode=t&&(e.mode==="clone"||n)?"clone":"folder",this.render(),n){if(this.job)this.maybeGo(this.job);this.reconcile()}else if(this.mode==="clone"&&this.repoText)this.askDest()}reconcile(){let e=this.jobId;if(!e)return;this.host.hub.rpc("clone.status",{id:e}).then((t)=>this.apply(t)).catch(()=>{})}close(){if(this.reposTimer!==null)window.clearTimeout(this.reposTimer);if(this.destTimer!==null)window.clearTimeout(this.destTimer);this.reposTimer=null,this.destTimer=null,this.backdrop?.remove(),this.backdrop=null,this.bodyEl=null,this.tabsEl=null}escape(){if(this.picking){this.picking=!1,this.render();return}if(this.showSuggest){this.showSuggest=!1,this.renderSuggest();return}this.close()}refreshLocale(){if(this.backdrop)this.render()}handleFrame(e){if(e.k==="clone"){let t=e.clone;if(t)this.apply(t)}else if(e.k==="clone.repos"){if(this.isOpen()&&this.mode==="clone"&&!this.jobId)this.askRepos(0)}else if(e.k==="clone.signin"){if(!this.signin)return;let t=this.signin.state;if(this.signin=e.signin??null,this.signin?.state==="cancelled")this.signin=null;if(t!=="done"&&this.signin?.state==="done")this.askRepos(0);this.renderSignin()}}build(){let e=J("div","bp-modal-backdrop");e.setAttribute("data-testid","add-project");let t=J("div","bp-modal bp-ap"),n=J("div","bp-modal-head"),i=J("h2","",b("sidebar.add.project","Add project")),s=Fe("×","icon",()=>this.close());s.title=b("common.close","Close"),s.setAttribute("aria-label",b("common.close","Close")),n.append(i,s),this.tabsEl=J("div","bp-ap-tabs"),this.bodyEl=J("div","bp-modal-body bp-ap-body"),t.append(n,this.tabsEl,this.bodyEl),e.appendChild(t),e.addEventListener("mousedown",(r)=>{if(r.target===e)this.close()}),this.container.appendChild(e),this.backdrop=e}resetForm(){this.repoText="",this.repoValue="",this.firstText="",this.wantThread=!0,this.userParent="",this.nameText="",this.nameTouched=!1,this.dest=null,this.destPending=!1,this.repos=null,this.showSuggest=!1,this.suggestIdx=-1,this.startErr="",this.starting=!1,this.picking=!1,this.signin=null,this.copied=!1}render(){if(!this.bodyEl||!this.tabsEl||!this.backdrop)return;let e=this.backdrop.querySelector(".bp-modal-head h2");if(e)e.textContent=b("sidebar.add.project","Add project");if(this.renderTabs(),this.repoInput=null,this.suggestEl=null,this.destEl=null,this.signinEl=null,this.cloneBtn=null,this.jobEl=null,this.mode==="folder")this.renderFolder();else if(this.jobId&&this.job)this.renderJobView();else if(this.picking)this.renderPickParent();else this.renderCloneForm()}renderTabs(){if(!this.tabsEl)return;if(!this.host.hub.hasFeature("clone")){this.tabsEl.classList.add("bp-hidden");return}this.tabsEl.classList.remove("bp-hidden");let e=(t,n)=>{let i=Fe(n,"bp-ap-tab"+(this.mode===t?" on":""),()=>{if(this.mode===t)return;if(this.mode=t,this.render(),t==="clone"&&!this.jobId&&this.repos===null)this.askRepos(0)});return i.setAttribute("data-testid",`ap-tab-${t}`),i.setAttribute("aria-pressed",String(this.mode===t)),i};this.tabsEl.replaceChildren(e("folder",b("gpui.e.open.folder","Open folder")),e("clone",b("web.clone.tab","Clone from git")))}renderFolder(){let e=new Kt(this.host.hub,(t)=>b("web.clone.add.dir","Add {dir}",{dir:t}),async(t)=>{let n=await this.host.hub.rpc("project.add",{path:t},30000);if(this.close(),n.project)this.host.onProjectAdded(n.project)});this.bodyEl.replaceChildren(e.root),e.go("")}renderCloneForm(){let e=this.bodyEl,t=J("div","bp-ap-form"),n=J("div","bp-ap-repo"),i=J("input","bp-input");i.type="text",i.spellcheck=!1,i.autocomplete="off",i.placeholder=b("web.clone.repo.placeholder","https or ssh URL, or owner/repo"),i.setAttribute("aria-label",b("web.clone.repo.placeholder","https or ssh URL, or owner/repo")),i.setAttribute("data-testid","clone-repo"),i.value=this.repoText,i.addEventListener("input",()=>{if(this.repoText=i.value,this.repoValue="",this.showSuggest=!0,this.suggestIdx=-1,this.startErr="",!this.nameTouched)this.nameText="";this.askRepos(200),this.askDest(250)}),i.addEventListener("focus",()=>{if(this.showSuggest=!0,this.repos===null)this.askRepos(0);else this.renderSuggest()}),i.addEventListener("blur",()=>{window.setTimeout(()=>{if(document.activeElement!==i)this.showSuggest=!1,this.renderSuggest()},120)}),i.addEventListener("keydown",(u)=>this.repoKey(u)),this.repoInput=i,this.suggestEl=J("div","bp-ap-suggest bp-hidden"),this.suggestEl.setAttribute("data-testid","clone-suggest"),n.append(i,this.suggestEl),this.signinEl=J("div","bp-ap-signin bp-hidden"),this.signinEl.setAttribute("data-testid","clone-signin"),this.destEl=J("div","bp-ap-dest"),this.destEl.setAttribute("data-testid","clone-dest");let s=J("label","bp-ap-check"),r=J("input");r.type="checkbox",r.checked=this.wantThread,r.setAttribute("data-testid","clone-thread"),r.addEventListener("change",()=>{this.wantThread=r.checked}),s.append(r,J("span","",b("web.clone.start.thread","Start a thread")));let a=[n,this.signinEl,this.destEl,s];if(this.firstText)a.push(J("div","bp-ap-first bp-dim",b("web.clone.first","First message: {text}",{text:this.firstText})));let o=J("div","bp-ap-err"+(this.startErr?"":" bp-hidden"),this.startErr);o.setAttribute("data-testid","clone-start-error");let c=J("div","bp-ap-foot");this.cloneBtn=Fe(b("web.clone.go","Clone"),"primary",()=>{this.startClone()}),this.cloneBtn.setAttribute("data-testid","clone-go"),c.append(this.cloneBtn),a.push(o,c),t.append(...a),e.replaceChildren(t),this.renderSuggest(),this.renderSignin(),this.renderDest(),window.setTimeout(()=>{if(this.repoInput===i&&!this.repoText)i.focus()},0)}repoKey(e){let t=this.repos?.repos??[],n=this.showSuggest&&t.length>0;if(e.key==="ArrowDown"&&n)e.preventDefault(),this.suggestIdx=Math.min(t.length-1,this.suggestIdx+1),this.renderSuggest();else if(e.key==="ArrowUp"&&n)e.preventDefault(),this.suggestIdx=Math.max(-1,this.suggestIdx-1),this.renderSuggest();else if(e.key==="Enter"){e.preventDefault();let i=n&&this.suggestIdx>=0?t[this.suggestIdx]:void 0;if(i)this.pickRepo(i);else if(this.canStart())this.startClone()}}pickRepo(e){if(this.repoText=e.name,this.repoValue=e.value,this.showSuggest=!1,this.suggestIdx=-1,this.startErr="",!this.nameTouched)this.nameText="";if(this.repoInput)this.repoInput.value=e.name;this.renderSuggest(),this.askDest()}repoArg(){return this.repoValue||this.repoText.trim()}askRepos(e){if(this.reposTimer!==null)window.clearTimeout(this.reposTimer);this.reposTimer=window.setTimeout(()=>{this.reposTimer=null;let t=++this.reposGen,n=this.repoValue?"":this.repoText.trim();this.host.hub.rpc("clone.repos",{q:n,limit:12},30000).then((i)=>{if(t!==this.reposGen)return;this.repos=i,this.renderSuggest(),this.renderSignin()}).catch(()=>{if(t!==this.reposGen)return;this.repos={repos:[],state:"error",hint:"Couldn't list your GitHub repositories."},this.renderSuggest()})},e)}renderSuggest(){let e=this.suggestEl;if(!e)return;let t=this.repos,n=t?.repos??[],i=[];if(this.showSuggest&&!this.repoValue){if(n.forEach((s,r)=>{let a=Fe("","bp-ap-sug"+(r===this.suggestIdx?" active":""));a.setAttribute("data-testid","clone-suggestion"),a.addEventListener("mousedown",(c)=>c.preventDefault()),a.addEventListener("click",()=>this.pickRepo(s));let o=J("div","bp-ap-sug-top");if(o.append(J("span","bp-ap-sug-name",s.name)),s.private)o.append(J("span","bp-ap-tag",b("web.clone.private","private")));if(a.append(o),s.description)a.append(J("div","bp-ap-sug-desc",s.description));i.push(a)}),n.length===0&&t){if(t.loading)i.push(J("div","bp-ap-sug-note",b("web.clone.loading","Loading…")));else if(t.hint){let s=J("div","bp-ap-sug-note");if(s.append(J("span","",pe(t.hint))),t.state==="signedout"){let r=Fe(b("web.clone.signin","Sign in to GitHub"),"bp-btn-line",()=>{this.startSignin()});r.addEventListener("mousedown",(a)=>a.preventDefault()),r.setAttribute("data-testid","clone-signin-btn"),s.append(r)}i.push(s)}}}e.replaceChildren(...i),e.classList.toggle("bp-hidden",i.length===0)}askDest(e=0){if(this.destTimer!==null)window.clearTimeout(this.destTimer);this.destPending=!0,this.updateCloneBtn(),this.destTimer=window.setTimeout(()=>{this.destTimer=null;let t=++this.destGen,n=this.repoArg();if(!n){this.dest=null,this.destPending=!1,this.renderDest();return}let i={repo:n};if(this.userParent)i.parent=this.userParent;if(this.nameTouched&&this.nameText.trim())i.name=this.nameText.trim();else if(this.userParent)i.name="";this.host.hub.rpc("clone.dest",i).then((s)=>{if(t!==this.destGen)return;if(this.dest=s,this.destPending=!1,!this.nameTouched&&s.folder)this.nameText=s.folder;this.renderDest()}).catch((s)=>{if(t!==this.destGen)return;this.dest={ok:!1,error:s instanceof Error?s.message:String(s)},this.destPending=!1,this.renderDest()})},e)}renderDest(){let e=this.destEl;if(!e)return;let t=this.dest,n=[];if(t&&!t.repo){if(t.error&&this.repoText.trim())n.push(this.errLine(pe(t.error)))}else if(t){let a=J("div","bp-ap-where"),o=J("span","bp-ap-dest-path",t.destShown||t.dest||t.defaultParentShown||"");o.setAttribute("data-testid","clone-dest-shown");let c=Fe(b("web.clone.change.folder","Change folder"),"bp-btn-line",()=>{this.picking=!0,this.render()});c.setAttribute("data-testid","clone-change-folder"),a.append(o,c),n.push(a);let u=J("label","bp-ap-name");u.append(J("span","bp-ap-lbl",b("web.clone.folder.name","Folder name")));let l=J("input","bp-input");if(l.type="text",l.spellcheck=!1,l.value=this.nameText,l.setAttribute("data-testid","clone-name"),l.addEventListener("input",()=>{this.nameText=l.value,this.nameTouched=l.value.trim()!=="",this.startErr="",this.askDest(250)}),l.addEventListener("keydown",(p)=>{if(p.key==="Enter"&&this.canStart())p.preventDefault(),this.startClone()}),u.append(l),n.push(u),!t.ok&&t.error)n.push(this.errLine(pe(t.error)));else if(t.same)n.push(J("div","bp-ap-note bp-dim",b("web.clone.same","Already cloned there: it is added as it is.")))}let i=document.activeElement,s=i&&e.contains(i)&&i.getAttribute("data-testid")==="clone-name",r=s?i.selectionStart:null;if(e.replaceChildren(...n),e.classList.toggle("bp-hidden",n.length===0),s){let a=e.querySelector('[data-testid="clone-name"]');if(a){if(a.focus(),r!==null)a.setSelectionRange(r,r)}}this.updateCloneBtn()}errLine(e){let t=J("div","bp-ap-err",e);return t.setAttribute("data-testid","clone-dest-error"),t}canStart(){return Boolean(this.dest?.ok&&this.dest.repo&&!this.destPending&&!this.starting&&this.repoArg())}updateCloneBtn(){if(this.cloneBtn)this.cloneBtn.disabled=!this.canStart()}renderPickParent(){let e=this.dest?.parent||this.userParent||this.dest?.defaultParent||"",t=Fe(b("web.clone.back","Back"),"bp-btn-line",()=>{this.picking=!1,this.render()}),n=new Kt(this.host.hub,(i)=>b("web.clone.use.dir","Use {dir}",{dir:i}),async(i)=>{this.userParent=i,this.picking=!1,this.render(),this.askDest()},[t]);this.bodyEl.replaceChildren(n.root),n.go(e)}async startClone(){if(!this.canStart()||!this.dest)return;this.starting=!0,this.startErr="",this.updateCloneBtn();let e={repo:this.repoArg(),thread:this.wantThread,text:this.firstText},t=Wt();this.jobId=t,this.job=null,this.specs.set(t,e);try{let n=await this.host.hub.rpc("clone.start",{id:t,repo:e.repo,parent:this.dest.parent??"",name:this.dest.folder??this.nameText.trim(),thread:e.thread,text:e.text});this.starting=!1,this.apply(n)}catch(n){this.starting=!1;let i=pe(n instanceof Error?n.message:String(n));if(this.jobId===t&&!this.job){let s=await this.host.hub.rpc("clone.status",{id:t}).catch(()=>null);if(s&&s.id===t){this.apply(s);return}}if(this.jobId===t&&!this.job){if(this.jobId="",this.startErr=i,this.mode==="clone")this.render()}}}async retry(e,t){let n=this.specs.get(e.id)??{repo:e.origin||e.repo||"",thread:!0,text:""},i=Wt(),s=this.jobId;this.jobId=i,this.specs.set(i,n),t.disabled=!0;try{let r=await this.host.hub.rpc("clone.start",{id:i,repo:n.repo,dest:e.dest??"",thread:n.thread,text:n.text});this.apply(r)}catch(r){let a=pe(r instanceof Error?r.message:String(r));if(this.jobId!==i)return;if(!this.job||this.job.id!==i){let o=await this.host.hub.rpc("clone.status",{id:i}).catch(()=>null);if(o&&o.id===i){this.apply(o);return}}if(this.jobId===i&&(!this.job||this.job.id!==i))this.jobId=s,t.disabled=!1,this.showJobError(a)}}apply(e){if(!e||e.id!==this.jobId)return;if(!Rn(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&&jn(e))this.goTo(e)}renderJobView(){this.jobEl=J("div","bp-ap-job"),this.jobEl.setAttribute("data-testid","clone-job"),this.signinEl=J("div","bp-ap-signin bp-hidden"),this.signinEl.setAttribute("data-testid","clone-signin"),this.bodyEl.replaceChildren(this.jobEl,this.signinEl),this.renderJob(),this.renderSignin()}renderJob(){let e=this.jobEl,t=this.job;if(!e||!t)return;let n=t.destShown||t.dest||"",i=t.repo||"",s=t.state==="done"?b("web.clone.cloned","Cloned {repo} into {dest}",{repo:i,dest:n}):t.state==="cancelled"?b("web.clone.stopped","Stopped cloning {repo}",{repo:i}):b("web.clone.cloning","Cloning {repo} into {dest}",{repo:i,dest:n}),r=[J("div","bp-ap-job-title",s)];if(t.state==="running"){let a=J("div","bp-ap-phase",pe(t.phase||""));a.setAttribute("data-testid","clone-phase");let o=J("div","bp-ap-bar"+(typeof t.pct==="number"?"":" indeterminate")),c=J("div","bp-ap-bar-fill");if(typeof t.pct==="number")c.style.width=`${Math.max(0,Math.min(100,t.pct))}%`;if(o.appendChild(c),o.setAttribute("role","progressbar"),typeof t.pct==="number")o.setAttribute("aria-valuenow",String(t.pct));if(r.push(a,o),t.detail)r.push(J("div","bp-ap-detail bp-dim",t.detail));let u=J("div","bp-ap-foot"),l=Fe(b("common.cancel","Cancel"),"bp-btn-line",()=>{this.host.hub.rpc("clone.cancel",{id:t.id}).then((p)=>this.apply(p)).catch(()=>{})});l.setAttribute("data-testid","clone-cancel"),u.append(l),r.push(u)}else if(t.state==="failed"||t.state==="cancelled"){if(t.state==="failed"&&t.error){let u=J("div","bp-ap-err",pe(t.error));u.setAttribute("data-testid","clone-error"),r.push(u)}let a=J("div","bp-ap-foot"),o=Fe(b("web.clone.back","Back"),"bp-btn-line",()=>{this.jobId="",this.job=null,this.signin=null,this.render(),this.askDest()});if(a.append(o),t.signin){let u=Fe(b("web.clone.signin","Sign in to GitHub"),"bp-btn-line",()=>{this.startSignin()});u.setAttribute("data-testid","clone-signin-btn"),a.append(u)}let c=Fe(b("web.clone.retry","Try again"),"primary",()=>{this.retry(t,c)});c.setAttribute("data-testid","clone-retry"),a.append(c),r.push(a)}else if(t.state==="done"){let a=t.notes??[];if(a.length>0){let l=J("ul","bp-ap-notes");l.setAttribute("data-testid","clone-notes");for(let p of a)l.appendChild(J("li","",pe(p)));r.push(l)}let o=J("div","bp-ap-foot"),c=t.thread?b("web.clone.open.thread","Open the thread"):b("web.clone.open.project","Open the project"),u=Fe(c,"primary",()=>this.goTo(t));u.setAttribute("data-testid","clone-open"),o.append(u),r.push(o)}e.replaceChildren(...r)}showJobError(e){if(!this.jobEl)return;this.jobEl.querySelector(".bp-ap-job-err")?.remove();let t=J("div","bp-ap-err bp-ap-job-err",e);this.jobEl.appendChild(t)}goTo(e){this.jobId="",this.job=null,this.close(),this.host.onCloneDone(e)}async startSignin(){this.signin={state:"starting"},this.copied=!1,this.renderSignin();try{let e=await this.host.hub.rpc("clone.signin",{restart:!0},30000);if(!this.signin||this.signin.state==="starting")this.signin=e}catch(e){this.signin={state:"failed",error:e instanceof Error?e.message:String(e)}}if(this.signin?.state==="done")this.askRepos(0);this.renderSignin()}renderSignin(){let e=this.signinEl;if(!e)return;let t=this.signin,n=[];if(t&&t.state){if(t.state==="starting"||t.state==="waiting"&&!t.code)n.push(J("div","bp-dim",b("web.clone.signin.wait","Starting GitHub sign-in…")));else if(t.state==="waiting"){n.push(J("div","",b("web.clone.signin.enter","Enter this code on GitHub:")));let i=J("div","bp-ap-code-row"),s=J("span","bp-ap-code",t.code||"");s.setAttribute("data-testid","clone-signin-code");let r=Fe(this.copied?b("web.clone.copied","Copied"):b("common.copy","Copy"),"bp-btn-line",()=>{navigator.clipboard?.writeText(t.code||"").then(()=>{this.copied=!0,this.renderSignin()}).catch(()=>{})});if(i.append(s,r),n.push(i),t.url){let a=J("a","bp-ap-link",t.url);a.href=t.url,a.target="_blank",a.rel="noopener noreferrer",a.setAttribute("data-testid","clone-signin-url"),n.push(a)}}else if(t.state==="done")n.push(J("div","bp-ok",b("web.clone.signin.done","Signed in to GitHub")));else if(t.state==="failed")n.push(J("div","bp-ap-err",pe(t.error||"")))}e.replaceChildren(...n),e.classList.toggle("bp-hidden",n.length===0)}}function fs(e){try{let t=new URL(e,window.location.origin);if(t.protocol==="https:"||t.protocol==="http:")return t.href}catch{}return null}function vt(e,t){let n=/(`[^`]+`|\*\*[^*]+\*\*|\*[^*]+\*|\[([^\]]+)\]\(([^)]+)\))/g,i=0,s;while((s=n.exec(t))!==null){if(s.index>i)e.appendChild(document.createTextNode(t.slice(i,s.index)));let r=s[0];if(r.startsWith("`")&&r.endsWith("`")){let a=document.createElement("code");a.className="bp-code-inline",a.textContent=r.slice(1,-1),e.appendChild(a)}else if(r.startsWith("**")&&r.endsWith("**")){let a=document.createElement("strong");a.textContent=r.slice(2,-2),e.appendChild(a)}else if(r.startsWith("*")&&r.endsWith("*")){let a=document.createElement("em");a.textContent=r.slice(1,-1),e.appendChild(a)}else if(r.startsWith("[")){let a=s[2]??"",o=fs(s[3]??"");if(o){let c=document.createElement("a");c.href=o,c.target="_blank",c.rel="noopener noreferrer",c.textContent=a,e.appendChild(c)}else e.appendChild(document.createTextNode(a))}i=n.lastIndex}if(i{navigator.clipboard?.writeText(l).then(()=>{y.textContent="✓",window.setTimeout(()=>{y.textContent=m},1200)}).catch(()=>{})}),d.append(g,y);let h=document.createElement("pre"),f=document.createElement("code");f.textContent=l,h.appendChild(f),p.append(d,h),t.appendChild(p);continue}if(!s.trim()){i++;continue}let a=/^(#{1,4})\s+(.+)$/.exec(s);if(a){let c=document.createElement(`h${Math.min(4,a[1].length+1)}`);c.className="bp-md-h",gt(c,a[2]),t.appendChild(c),i++;continue}if(s.startsWith("> ")){let c=document.createElement("blockquote");c.className="bp-md-quote";let u=[];while(i "))u.push(n[i].slice(2)),i++;gt(c,u.join(` -`)),t.appendChild(c);continue}if(/^\s*[-*]\s+/.test(s)){let c=document.createElement("ul");c.className="bp-md-list";while(i ")&&!/^\s*[-*]\s+/.test(n[i])&&!/^\s*\d+\.\s+/.test(n[i]))r.push(n[i]),i++;let o=document.createElement("p");o.className="bp-md-p";for(let c=0;c0)o.appendChild(document.createElement("br"));gt(o,r[c])}t.appendChild(o)}return t}var Rn="http://www.w3.org/2000/svg";function vt(e){let t=document.createElementNS(Rn,"svg");t.setAttribute("viewBox","0 0 24 24"),t.setAttribute("width","12"),t.setAttribute("height","12"),t.setAttribute("fill","none"),t.setAttribute("stroke","currentColor"),t.setAttribute("stroke-width","1.8"),t.setAttribute("aria-hidden","true");for(let n of e){let i=document.createElementNS(Rn,"path");i.setAttribute("d",n),t.appendChild(i)}return t}function Kt(e){return e<10000000000?e*1000:e}function ms(e){if(!e)return"";return new Date(Kt(e)).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",hour12:!1})}function us(e){if(!Number.isFinite(e)||e<=0||e>3600000)return"";let t=Math.max(1,Math.round(e/1000));if(t<60)return`${t}s`;let n=Math.floor(t/60),i=t%60;return i>0?`${n}m ${i}s`:`${n}m`}function qt(e){if(e.agentOnly)return!0;if(e.kind==="note"){let t=(e.text||"").trim();if(t.startsWith("Made this folder a git repository")||t.startsWith("Backplane: snapshot")||t.includes("snapshot of existing work before first use"))return!0}return!1}class zt{bannerEl;scrollEl;listEl;olderBtn;cb;thread=null;entries=[];hasMore=!1;loadingOlder=!1;review=null;unanswered=null;btwNote=null;liveNodes=new Map;imageCache=new Map;pinnedToBottom=!0;planExpanded=new Set;planRevisingId="";planReviseDrafts=new Map;constructor(e,t){if(this.cb=t,this.bannerEl=document.createElement("div"),this.bannerEl.className="bp-thread-banners",this.scrollEl=document.createElement("div"),this.scrollEl.className="bp-timeline-scroll",this.scrollEl.setAttribute("data-testid","timeline"),this.olderBtn=document.createElement("button"),this.olderBtn.type="button",this.olderBtn.className="bp-older-btn bp-hidden",this.olderBtn.textContent=b("android.load.earlier","Load earlier"),this.olderBtn.setAttribute("data-testid","load-older-btn"),this.olderBtn.addEventListener("click",()=>{if(!this.loadingOlder&&this.hasMore)this.loadingOlder=!0,this.cb.onLoadOlder()}),this.scrollEl.addEventListener("scroll",()=>{if(this.pinnedToBottom=this.isNearBottom(),this.hasMore&&!this.loadingOlder&&this.scrollEl.scrollTop<48)this.loadingOlder=!0,this.cb.onLoadOlder()}),typeof ResizeObserver<"u"){let n=0;new ResizeObserver(()=>{let s=this.scrollEl.clientHeight;if(n>0&&s!==n&&this.pinnedToBottom)this.scrollToBottom();n=s}).observe(this.scrollEl)}this.listEl=document.createElement("div"),this.listEl.className="bp-timeline-list",this.scrollEl.append(this.olderBtn,this.listEl),e.append(this.bannerEl,this.scrollEl)}setLoading(e){this.thread=e,this.entries=[],this.hasMore=!1,this.loadingOlder=!1,this.review=null,this.unanswered=null,this.btwNote=null,this.liveNodes.clear(),this.planExpanded.clear(),this.planRevisingId="",this.planReviseDrafts.clear(),this.renderBanners(),this.olderBtn.classList.add("bp-hidden");let t=document.createElement("div");t.className="bp-empty-state",t.textContent=b("web.chat.loading","Loading messages…"),this.listEl.replaceChildren(t)}setError(e,t,n){this.thread=e,this.entries=[],this.hasMore=!1,this.loadingOlder=!1,this.review=null,this.unanswered=null,this.btwNote=null,this.liveNodes.clear(),this.planExpanded.clear(),this.planRevisingId="",this.planReviseDrafts.clear(),this.renderBanners(),this.olderBtn.classList.add("bp-hidden");let i=document.createElement("div");i.className="bp-empty-state";let s=document.createElement("div");s.className="bp-bad",s.textContent=t;let a=document.createElement("button");a.type="button",a.textContent=b("tools.retry","Retry"),a.addEventListener("click",n),i.append(s,a),this.listEl.replaceChildren(i)}getEntries(){return this.entries.slice()}refreshLocale(){let e=this.scrollEl.scrollTop;if(this.olderBtn.textContent=b("android.load.earlier","Load earlier"),this.renderBanners(),this.thread&&this.entries.length>0)this.renderEntries(!1);this.scrollEl.scrollTop=e}setThread(e,t,n,i,s){if((this.thread?.id??"")!==(e?.id??""))this.planExpanded.clear(),this.planRevisingId="",this.planReviseDrafts.clear();this.thread=e,this.entries=t.filter((a)=>!qt(a)),this.hasMore=n,this.loadingOlder=!1,this.review=i,this.unanswered=s,this.btwNote=null,this.renderBanners(),this.renderEntries(!0)}updateThreadMeta(e){if(!this.thread||this.thread.id!==e.id)return;this.thread=e}setReview(e){this.review=e,this.renderBanners()}setUnanswered(e){this.unanswered=e,this.renderBanners()}showBtw(e,t){this.btwNote={q:e,a:t},this.renderBanners()}prependEntries(e,t){this.loadingOlder=!1;let n=this.scrollEl.scrollHeight,i=new Set(this.entries.map((a)=>a.id)),s=e.filter((a)=>!qt(a)&&!i.has(a.id));this.entries=[...s,...this.entries],this.hasMore=t,this.renderEntries(!1),this.scrollEl.scrollTop+=this.scrollEl.scrollHeight-n}clearLoadingOlder(){this.loadingOlder=!1}upsertEntry(e){if(qt(e))return;let t=this.isNearBottom()||e.kind==="user"&&Boolean(e.clientId),n=this.entries.findIndex((i)=>i.id===e.id);if(n<0&&e.clientId)n=this.entries.findIndex((i)=>i.clientId&&i.clientId===e.clientId);if(n>=0)this.entries[n]=e;else this.entries.push(e);this.renderEntries(t)}goTo(e){let t=this.scrollEl.querySelector(`[data-entry-id="${CSS.escape(e)}"]`);if(!t)return!1;return t.scrollIntoView({block:"center",behavior:"smooth"}),t.classList.remove("bp-entry-flash"),t.offsetWidth,t.classList.add("bp-entry-flash"),window.setTimeout(()=>t.classList.remove("bp-entry-flash"),1200),!0}removeEntry(e){let t=this.entries.filter((n)=>n.id!==e);if(t.length!==this.entries.length)this.entries=t,this.renderEntries(!1)}appendLiveText(e,t,n){let i=this.isNearBottom(),s=this.entries.find((r)=>r.id===e);if(!s){s={id:e,kind:"assistant",text:t,at:n,live:!0},this.entries.push(s),this.renderEntries(i);return}s.text+=t,s.live=!0;let a=this.liveNodes.get(e);if(a){if(a.replaceChildren(ft(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.review&&(this.review.text||this.review.button)){let t=document.createElement("div");t.className="bp-banner bp-review-bar",t.setAttribute("data-testid","review-bar");let n=document.createElement("span");if(n.textContent=this.review.text||b("web.chat.review.mode","Review mode"),t.appendChild(n),this.review.button){let i=document.createElement("button");i.type="button",i.textContent=this.review.button,i.addEventListener("click",()=>this.cb.onToggleReview(!(this.review?.on??!0))),t.appendChild(i)}e.appendChild(t)}if(this.unanswered&&(this.unanswered.head||this.unanswered.text)){let t=document.createElement("div");t.className="bp-banner bp-unanswered",t.setAttribute("data-testid","unanswered-notice");let n=document.createElement("div");if(n.className="bp-unanswered-body",this.unanswered.head){let i=document.createElement("strong");i.textContent=this.unanswered.head,n.appendChild(i)}if(this.unanswered.text){let i=document.createElement("span");i.textContent=this.unanswered.text,n.appendChild(i)}if(t.appendChild(n),this.unanswered.buttons?.length){let i=document.createElement("div");i.className="bp-banner-actions";for(let s of this.unanswered.buttons){let a=document.createElement("button");if(a.type="button",s.primary)a.className="primary";a.textContent=s.label,a.addEventListener("click",()=>this.cb.onUnansweredAction(s.action,s.value)),i.appendChild(a)}t.appendChild(i)}e.appendChild(t)}if(this.btwNote){let t=document.createElement("div");t.className="bp-banner bp-btw-banner";let n=document.createElement("div"),i=document.createElement("div");i.className="bp-dim",i.textContent=`/btw ${this.btwNote.q}`;let s=document.createElement("div");s.appendChild(ft(this.btwNote.a)),n.append(i,s);let a=document.createElement("button");a.type="button",a.className="icon",a.textContent="×",a.addEventListener("click",()=>{this.btwNote=null,this.renderBanners()}),t.append(n,a),e.appendChild(t)}this.bannerEl.replaceChildren(e)}makeEntryActions(e,t,n){let i=document.createElement("div");i.className="bp-entry-foot"+(t?" user":"");let s=document.createElement("button");s.type="button",s.className="bp-entry-act";let a=b("common.copy","Copy"),r=document.createElement("span");r.textContent=a,s.append(vt(["M9 9h11v11H9z","M5 15H4a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1h10a1 1 0 0 1 1 1v1"]),r),s.addEventListener("click",()=>{navigator.clipboard?.writeText(e.text||"").then(()=>{r.textContent="✓",window.setTimeout(()=>{r.textContent=a},1000)}).catch(()=>{})});let o=document.createElement("button");o.type="button",o.className="bp-entry-act";let c=document.createElement("span");c.textContent=b("reply.action","Reply"),o.append(vt(["M9 17l-5-5 5-5","M20 18v-2a4 4 0 0 0-4-4H4"]),c),o.addEventListener("click",()=>this.cb.onReplyEntry(e));let u=!e.live&&!e.id.startsWith("local-")&&!e.id.startsWith("live:"),l=document.createElement("span");l.className="bp-entry-time";let p=ms(e.at);if(t)l.textContent=p,i.append(s,...u?[o]:[],l);else{let d=n&&e.at?us(Kt(e.at)-Kt(n)):"",g=p?d?b("web.chat.finished.dur","Finished {time} · {dur}",{time:p,dur:d}):b("web.chat.finished","Finished {time}",{time:p}):"";l.textContent=e.live?b("web.chat.streaming","Streaming…"):g,i.append(l,s,...u?[o]:[])}return i}closePlanRevise(){let e=this.planRevisingId;if(!e)return!1;this.planRevisingId="";let t=this.scrollEl.scrollTop;return this.renderEntries(!1),this.scrollEl.scrollTop=t,this.listEl.querySelector(`[data-testid="ask-${CSS.escape(e)}"] [data-testid="plan-revise"]`)?.focus(),!0}renderEntries(e){let t=null,n=typeof document<"u"?document.activeElement:null;if(n instanceof HTMLTextAreaElement&&n.classList.contains("bp-plan-revise-input")&&this.listEl.contains(n)&&this.planRevisingId)this.planReviseDrafts.set(this.planRevisingId,n.value),t={askId:this.planRevisingId,start:n.selectionStart,end:n.selectionEnd,dir:n.selectionDirection};this.olderBtn.classList.toggle("bp-hidden",!this.hasMore),this.liveNodes.clear();let i=document.createDocumentFragment();if(!this.thread){let a=document.createElement("div");a.className="bp-empty-state",a.textContent=b("web.chat.choose","Choose a project thread on the left to begin."),i.appendChild(a),this.listEl.replaceChildren(i);return}if(this.entries.length===0){let a=document.createElement("div");a.className="bp-empty-state",a.textContent=b("web.chat.empty","No messages yet. Type below to start a turn."),i.appendChild(a),this.listEl.replaceChildren(i);return}let s=0;for(let a of this.entries){if(a.kind==="user"&&a.at)s=a.at;let r=document.createElement("article");if(r.className=`bp-entry bp-entry-${a.kind}`+(a.live?" is-live":""),r.setAttribute("data-entry-id",a.id),a.kind==="tool"&&a.tool){let l=document.createElement("div");l.className=`bp-tool-pill bp-tool-${a.tool.state||"done"}`;let p=document.createElement("span");if(p.className="bp-tool-name",p.textContent=a.tool.name,l.appendChild(p),a.tool.summary){let d=document.createElement("span");d.className="bp-tool-summary",d.textContent=a.tool.summary,l.appendChild(d)}r.appendChild(l),i.appendChild(r);continue}if(a.kind==="ask"&&a.ask){let l=a.ask;if(l.kind==="plan"){r.appendChild(this.renderPlanAsk(l)),i.appendChild(r);continue}let p=document.createElement("div");p.className="bp-ask-card",p.setAttribute("data-testid",`ask-${l.id}`);let d=document.createElement("div");if(d.className="bp-ask-q",d.textContent=l.question,p.appendChild(d),l.state==="open"){let g=document.createElement("div");if(g.className="bp-ask-opts",l.options&&l.options.length>0)for(let y of l.options){let m=document.createElement("button");m.type="button",m.textContent=y.label,m.addEventListener("click",()=>this.cb.onAnswerAsk(l.id,y.id)),g.appendChild(m)}else{let y=document.createElement("input");y.type="text",y.className="bp-input",y.placeholder=b("web.chat.answer.placeholder","Type answer…");let m=document.createElement("button");m.type="button",m.className="primary",m.textContent=b("web.chat.answer.btn","Answer"),m.addEventListener("click",()=>{if(y.value.trim())this.cb.onAnswerAsk(l.id,y.value.trim())}),g.append(y,m)}p.appendChild(g)}else{let g=document.createElement("div");g.className="bp-ask-answered",g.textContent=b("web.chat.answered","Answered: {answer}",{answer:l.answered??""}),p.appendChild(g)}r.appendChild(p),i.appendChild(r);continue}let o=Boolean(a.text&&a.text.trim().length>0),c=Boolean(a.images&&a.images.length>0),u=Boolean(a.attachments&&a.attachments.length>0);if(!o&&!c&&!u&&!a.live)continue;if(a.replyTo?.quote){let l=document.createElement("div");l.className="bp-reply-quote",l.textContent=b("gpui.b.in.reply.to","↩ In reply to: {quote}",{quote:a.replyTo.quote});let p=a.replyTo.id;l.setAttribute("role","button"),l.tabIndex=0,l.setAttribute("data-testid","entry-reply-quote");let d=()=>{if(this.cb.onGoToEntry)this.cb.onGoToEntry(p);else this.goTo(p)};l.addEventListener("click",d),l.addEventListener("keydown",(g)=>{if(g.key==="Enter"||g.key===" ")g.preventDefault(),d()}),r.appendChild(l)}if(o||a.live){let l=document.createElement("div");if(l.className="bp-entry-body",a.kind==="user")l.textContent=a.text;else l.appendChild(ft(a.text||""));if(a.live)this.liveNodes.set(a.id,l);r.appendChild(l)}if(u&&a.attachments){let l=document.createElement("div");l.className="bp-entry-images";for(let p of a.attachments)if(p.previewUrl){let d=document.createElement("img");d.className="bp-reply-img",d.src=p.previewUrl,d.alt=p.name||"attachment",l.appendChild(d)}else if(p.path||p.name){let d=document.createElement("span");d.className="bp-tool-pill",d.textContent=p.name||p.path||"image",l.appendChild(d)}if(l.childElementCount>0)r.appendChild(l)}if(a.images&&a.images.length>0){let l=document.createElement("div");l.className="bp-entry-images";for(let p of a.images){let d=document.createElement("img");d.className="bp-reply-img",d.alt=p;let g=`${a.id}|${p}`,y=this.imageCache.get(g);if(y)d.src=y;else this.cb.onLoadImage(a.id,p).then((m)=>{if(!m)return;let h=m.url??(m.mime&&m.data?`data:${m.mime};base64,${m.data}`:"");if(!h)return;this.imageCache.set(g,h),d.src=h});l.appendChild(d)}r.appendChild(l)}r.appendChild(this.makeEntryActions(a,a.kind==="user",a.kind==="assistant"?s:void 0)),i.appendChild(r)}if(this.listEl.replaceChildren(i),t&&this.planRevisingId===t.askId){let a=this.listEl.querySelector(`[data-testid="ask-${CSS.escape(t.askId)}"] .bp-plan-revise-input`);if(a){if(a.focus({preventScroll:!0}),t.start!==null&&t.end!==null)a.setSelectionRange(t.start,t.end,t.dir??void 0)}}if(e&&!t)this.scrollToBottom()}renderPlanAsk(e){let t=this.planExpanded.has(e.id),n=e.state==="open"&&this.planRevisingId===e.id,i=document.createElement("div");i.className="bp-ask-card bp-ask-plan",i.setAttribute("data-testid",`ask-${e.id}`);let s=document.createElement("div");s.className="bp-plan-head";let a=vt(["M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z","M14 2v6h6","M16 13H8","M16 17H8","M10 9H8"]);a.classList.add("bp-plan-head-ic");let r=document.createElement("span");if(r.className="bp-plan-title",r.textContent=!e.head||e.head==="Proposed plan"?b("ask.plan","Proposed plan"):xe(e.head),s.append(a,r),e.state==="open"){let l=document.createElement("span");l.className="bp-plan-badge",l.textContent=b("gpui.ask.plan.ready","Ready for review"),s.appendChild(l)}let o=document.createElement("span");if(o.className="bp-mgmt-flex1",s.appendChild(o),e.question){let l=document.createElement("button");l.type="button",l.className="bp-plan-head-btn";let p=b("common.copy","Copy"),d=document.createElement("span");d.textContent=p,l.append(vt(["M9 9h11v11H9z","M5 15H4a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1h10a1 1 0 0 1 1 1v1"]),d),l.addEventListener("click",()=>{navigator.clipboard?.writeText(e.question).then(()=>{l.classList.add("copied"),d.textContent=b("web.clone.copied","Copied"),window.setTimeout(()=>{l.classList.remove("copied"),d.textContent=p},1200)}).catch(()=>{})}),s.appendChild(l)}let c=document.createElement("button");c.type="button",c.className="bp-plan-head-btn",c.setAttribute("data-testid","plan-expand"),c.textContent=t?b("gpui.c.term.collapse","Collapse"):b("gpui.c.term.expand","Expand"),c.addEventListener("click",()=>{if(this.planExpanded.has(e.id))this.planExpanded.delete(e.id);else this.planExpanded.add(e.id);let l=this.scrollEl.scrollTop;this.renderEntries(!1),this.scrollEl.scrollTop=l}),s.appendChild(c),i.appendChild(s);let u=document.createElement("div");if(u.className="bp-plan-body"+(t?" is-expanded":""),u.setAttribute("data-testid","plan-body"),u.appendChild(ft(e.question||"")),i.appendChild(u),e.state==="open"){let l=document.createElement("div");l.className="bp-plan-actions";let p=e.options?.find((m)=>m.id==="implement"||m.id.endsWith("|implement")),d=document.createElement("button");if(d.type="button",d.className="primary",d.setAttribute("data-testid","plan-implement"),d.textContent=p?.label&&p.label!=="Implement"?xe(p.label):b("approval.implement","Implement"),d.addEventListener("click",()=>{this.planRevisingId="",this.planReviseDrafts.delete(e.id),this.cb.onAnswerAsk(e.id,p?.id??"implement")}),l.appendChild(d),e.revise!==!1){let m=document.createElement("button");m.type="button",m.className="bp-plan-revise-btn"+(n?" active":""),m.setAttribute("data-testid","plan-revise"),m.append(vt(["M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7","M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"]),document.createTextNode(b("gpui.ask.plan.revise","Revise"))),m.addEventListener("click",()=>{let h=this.planRevisingId!==e.id;this.planRevisingId=h?e.id:"";let f=this.scrollEl.scrollTop;if(this.renderEntries(!1),this.scrollEl.scrollTop=f,h)this.listEl.querySelector(`[data-testid="ask-${CSS.escape(e.id)}"] .bp-plan-revise-input`)?.focus()}),l.appendChild(m)}let g=e.options?.find((m)=>m.id==="dismiss"||m.id.endsWith("|dismiss")),y=document.createElement("button");if(y.type="button",y.className="bp-plan-dismiss-btn",y.setAttribute("data-testid","plan-dismiss"),y.textContent=g?.label&&g.label!=="Dismiss"?xe(g.label):b("approval.dismiss","Dismiss"),y.addEventListener("click",()=>{this.planRevisingId="",this.planReviseDrafts.delete(e.id),this.cb.onAnswerAsk(e.id,g?.id??"dismiss")}),l.appendChild(y),i.appendChild(l),n){let m=document.createElement("div");m.className="bp-plan-revise",m.setAttribute("data-testid","plan-revise-drawer");let h=document.createElement("textarea");h.rows=2,h.className="bp-input bp-plan-revise-input",h.placeholder=b("gpui.ask.plan.reviseph","What should change in the plan?"),h.value=this.planReviseDrafts.get(e.id)??"";let f=document.createElement("button");f.type="button",f.className="bp-plan-revise-send",f.setAttribute("data-testid","plan-revise-send"),f.textContent=b("gpui.ask.plan.sendrev","Send revision"),f.disabled=h.value.trim().length===0;let w=()=>{let M=h.value.trim();if(!M)return;this.planRevisingId="",this.planReviseDrafts.delete(e.id),this.cb.onAnswerAsk(e.id,`revise:${M}`)},C=()=>{this.closePlanRevise()};m.addEventListener("keydown",(M)=>{if(M.key==="Escape")M.preventDefault(),M.stopPropagation(),C()}),h.addEventListener("input",()=>{this.planReviseDrafts.set(e.id,h.value),f.disabled=h.value.trim().length===0}),h.addEventListener("keydown",(M)=>{if(M.key==="Enter"&&!M.shiftKey)M.preventDefault(),w()}),f.addEventListener("click",w);let L=document.createElement("button");L.type="button",L.className="bp-btn-ghost",L.textContent=b("common.cancel","Cancel"),L.addEventListener("click",C),m.append(h,f,L),i.appendChild(m)}}else{let l=document.createElement("div");l.className="bp-ask-answered",l.textContent=b("web.chat.answered","Answered: {answer}",{answer:e.answered??""}),i.appendChild(l)}return i}}var jn="http://www.w3.org/2000/svg",Hn=4,Dn=new Set(["image/png","image/jpeg","image/webp","image/gif"]);function Nt(e){let t=document.createElementNS(jn,"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(jn,"path");i.setAttribute("d",n),t.appendChild(i)}return t}function Jt(){return Nt(["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 Fn(){return Nt(["M6 4l14 8-14 8z"])}function hs(e){let t=(e||"").toLowerCase();if(t.includes("claude")||t.includes("anthropic"))return{glyph:"A",color:"#d97706",title:"Claude"};if(t.includes("codex")||t.includes("openai"))return{glyph:"O",color:"#10b981",title:"Codex"};if(t.includes("gemini")||t.includes("antigravity"))return{glyph:"G",color:"#3b82f6",title:"Gemini"};if(t.includes("grok"))return{glyph:"X",color:"#94a3b8",title:"Grok"};return{glyph:"●",color:"var(--accent)",title:e||"Model"}}class Yt{popupEl;attachStripEl;planBarEl;fileInput;textarea;memoryEl;memoryFill;memoryText;providerMarkEl;modelTextEl;ctxEl;planChipBtn;planChipIconHost;planChipLbl;attachBtn;voiceBtn;sendBtn;stopBtn;errorEl;replyEl;cb;commands=[];popupMode="none";filteredSlash=[];mentionItems=[];popupIdx=0;enabled=!1;attachments=[];planMode=null;constructor(e,t){this.cb=t;let n=document.createElement("div");n.className="bp-composer",n.setAttribute("data-testid","composer");let i=document.createElement("div");i.className="bp-composer-inner",this.popupEl=document.createElement("div"),this.popupEl.className="bp-composer-popup bp-hidden",this.popupEl.setAttribute("data-testid","slash-menu"),this.errorEl=document.createElement("div"),this.errorEl.className="bp-composer-err bp-hidden",this.replyEl=document.createElement("div"),this.replyEl.className="bp-reply-strip bp-hidden",this.replyEl.setAttribute("data-testid","composer-reply"),this.attachStripEl=document.createElement("div"),this.attachStripEl.className="bp-attach-strip bp-hidden",this.attachStripEl.setAttribute("data-testid","composer-attachments"),this.planBarEl=document.createElement("div"),this.planBarEl.className="bp-plan-bar bp-hidden",this.planBarEl.setAttribute("data-testid","composer-plan-bar"),this.fileInput=document.createElement("input"),this.fileInput.type="file",this.fileInput.accept="image/png,image/jpeg,image/webp,image/gif",this.fileInput.multiple=!0,this.fileInput.className="bp-hidden",this.fileInput.setAttribute("data-testid","composer-file-input"),this.fileInput.addEventListener("change",()=>{if(this.fileInput.files)this.addFiles(Array.from(this.fileInput.files));this.fileInput.value=""}),this.textarea=document.createElement("textarea"),this.textarea.className="bp-composer-input",this.textarea.rows=2,this.textarea.placeholder=b("composer.placeholder","Ask anything: @bot, >thread, %project, #room, $skill, /btw"),this.textarea.setAttribute("data-testid","composer-input");let s=document.createElement("div");s.className="bp-composer-bar";let a=document.createElement("div");a.className="bp-composer-model",this.providerMarkEl=document.createElement("span"),this.providerMarkEl.className="bp-provider-mark",this.providerMarkEl.textContent="●",this.modelTextEl=document.createElement("span"),this.modelTextEl.className="bp-model-text",this.modelTextEl.textContent="default",this.ctxEl=document.createElement("span"),this.ctxEl.className="bp-ctx-pct bp-hidden",this.ctxEl.setAttribute("data-testid","composer-ctx"),a.append(this.providerMarkEl,this.modelTextEl,this.ctxEl),this.planChipBtn=document.createElement("button"),this.planChipBtn.type="button",this.planChipBtn.className="bp-plan-chip bp-hidden",this.planChipBtn.setAttribute("data-testid","composer-plan-chip"),this.planChipBtn.setAttribute("aria-pressed","false"),this.planChipIconHost=document.createElement("span"),this.planChipIconHost.className="bp-plan-chip-ic",this.planChipIconHost.appendChild(Jt()),this.planChipLbl=document.createElement("span"),this.planChipLbl.textContent=b("gpui.mgmt.plan.tab","Plan"),this.planChipBtn.append(this.planChipIconHost,this.planChipLbl),this.planChipBtn.addEventListener("click",()=>this.cb.onCyclePlanMode?.()),this.memoryEl=document.createElement("div"),this.memoryEl.className="bp-composer-memory bp-hidden",this.memoryEl.setAttribute("data-testid","composer-memory");let r=document.createElement("div");r.className="bp-memory-meter",this.memoryFill=document.createElement("div"),this.memoryFill.className="bp-memory-fill",r.appendChild(this.memoryFill),this.memoryText=document.createElement("span"),this.memoryEl.append(r,this.memoryText);let o=document.createElement("div");o.className="bp-composer-btns",this.attachBtn=document.createElement("button"),this.attachBtn.type="button",this.attachBtn.className="icon bp-composer-tool",this.attachBtn.title=b("web.composer.attach","Attach image"),this.attachBtn.setAttribute("aria-label",b("web.composer.attach","Attach image")),this.attachBtn.setAttribute("data-testid","composer-attach"),this.attachBtn.appendChild(Nt(["M21.44 11.05l-9.19 9.19a6 6 0 0 1-8.49-8.49l9.19-9.19a4 4 0 0 1 5.66 5.66l-9.2 9.19a2 2 0 0 1-2.83-2.83l8.49-8.48"])),this.attachBtn.addEventListener("click",()=>this.fileInput.click()),this.voiceBtn=document.createElement("button"),this.voiceBtn.type="button",this.voiceBtn.className="icon bp-composer-tool",this.voiceBtn.title=b("web.composer.voice","Voice dictation"),this.voiceBtn.setAttribute("aria-label",b("web.composer.voice","Voice dictation")),this.voiceBtn.setAttribute("data-testid","composer-voice"),this.voiceBtn.appendChild(Nt(["M12 1a3 3 0 0 0-3 3v8a3 3 0 0 0 6 0V4a3 3 0 0 0-3-3z","M19 10v2a7 7 0 0 1-14 0v-2","M12 19v4","M8 23h8"])),this.voiceBtn.addEventListener("click",()=>this.cb.onToggleVoice?.()),this.stopBtn=document.createElement("button"),this.stopBtn.type="button",this.stopBtn.className="primary stop bp-hidden",this.stopBtn.textContent=b("composer.stop","Stop"),this.stopBtn.setAttribute("data-testid","composer-stop"),this.stopBtn.addEventListener("click",()=>this.cb.onInterrupt()),this.sendBtn=document.createElement("button"),this.sendBtn.type="button",this.sendBtn.className="primary bp-send-btn",this.sendBtn.textContent=b("composer.send","Send"),this.sendBtn.setAttribute("data-testid","composer-send"),this.sendBtn.addEventListener("click",()=>this.submit()),o.append(this.attachBtn,this.voiceBtn,this.stopBtn,this.sendBtn),s.append(a,this.planChipBtn,this.memoryEl,o),i.append(this.popupEl,this.errorEl,this.replyEl,this.attachStripEl,this.planBarEl,this.fileInput,this.textarea,s),n.appendChild(i),e.appendChild(n),this.textarea.addEventListener("paste",(c)=>{let u=c.clipboardData?.items;if(!u)return;let l=[];for(let p=0;p0)c.preventDefault(),this.addFiles(l)}),this.textarea.addEventListener("input",()=>{this.autoGrow(),this.clearError(),this.updatePopups()}),this.textarea.addEventListener("keydown",(c)=>{if(this.popupMode!=="none"){let u=this.popupMode==="slash"?this.filteredSlash.length:this.mentionItems.length;if(c.key==="ArrowDown"){c.preventDefault(),this.popupIdx=(this.popupIdx+1)%Math.max(1,u),this.renderPopup();return}if(c.key==="ArrowUp"){c.preventDefault(),this.popupIdx=(this.popupIdx-1+Math.max(1,u))%Math.max(1,u),this.renderPopup();return}if(c.key==="Tab"||c.key==="Enter"&&!c.shiftKey&&this.shouldCompleteOnEnter()){c.preventDefault(),this.applyPopupChoice(this.popupIdx);return}if(c.key==="Escape"){c.preventDefault(),this.closePopup();return}}if(c.key==="Tab"&&c.shiftKey&&this.planMode!==null){c.preventDefault(),this.cb.onCyclePlanMode?.();return}if(c.key==="Enter"&&!c.shiftKey)c.preventDefault(),this.submit()})}setCommands(e){this.commands=e.map((t)=>({...t,word:t.word.replace(/^\//,"")}))}setModelChip(e,t,n){let i=hs(t);if(this.providerMarkEl.textContent=i.glyph,this.providerMarkEl.style.color=i.color,this.providerMarkEl.title=i.title,this.modelTextEl.textContent=e||"default",typeof n==="number"&&Number.isFinite(n)&&n>=0)this.ctxEl.textContent=`ctx ${Math.round(n)}%`,this.ctxEl.classList.remove("bp-hidden");else this.ctxEl.textContent="",this.ctxEl.classList.add("bp-hidden")}setFeatures(e,t){this.attachBtn.classList.toggle("bp-hidden",!e),this.voiceBtn.classList.toggle("bp-hidden",!t)}setVoiceRecording(e){this.voiceBtn.classList.toggle("recording",e),this.voiceBtn.setAttribute("aria-pressed",e?"true":"false")}setVoiceLevel(e){this.voiceBtn.setAttribute("data-level",String(e))}getDraft(){return this.textarea.value}getCaret(){return this.textarea.selectionStart??this.textarea.value.length}setMemory(e){if(this.memoryEl.classList.toggle("bp-hidden",!e),!e)return;let t=e.total??0,n=t>0?Math.min(1,(e.done??0)/t):1;this.memoryFill.style.width=`${Math.round(n*100)}%`,this.memoryFill.dataset.state=e.state??"",this.memoryText.textContent=e.line??"",this.memoryEl.title=[e.status,e.lines,e.viewLine].filter(Boolean).join(` -`)}setPlanMode(e){if(this.planMode=e,this.textarea.classList.remove("is-plan","is-plan-exec"),this.sendBtn.classList.remove("is-plan","is-plan-exec"),this.planChipBtn.classList.remove("is-plan","is-exec"),this.planBarEl.classList.remove("is-exec"),!e){this.planChipBtn.classList.add("bp-hidden"),this.planChipBtn.setAttribute("aria-pressed","false"),this.planBarEl.classList.add("bp-hidden"),this.planBarEl.replaceChildren(),this.sendBtn.textContent=b("composer.send","Send");return}let t=e.phase,n=t!=="off",i=t==="armed"||t==="planning"||t==="pending",s=t==="executing";this.planChipBtn.classList.remove("bp-hidden"),this.planChipBtn.classList.toggle("is-plan",i),this.planChipBtn.classList.toggle("is-exec",s),this.planChipBtn.setAttribute("aria-pressed",n?"true":"false");let a=`${b("gpui.planmode.tip","Plan before acting (1 turn, always, or off)")} · Shift+Tab`;if(this.planChipBtn.title=a,this.planChipBtn.setAttribute("aria-label",a),this.planChipIconHost.replaceChildren(s?Fn():Jt()),this.planChipLbl.textContent=s?b("gpui.planmode.chip.building","Building"):t==="pending"?b("gpui.mgmt.fab.reviewbtn","Review"):i&&e.once?b("gpui.planmode.chip.once","Plan · 1t"):b("gpui.mgmt.plan.tab","Plan"),this.textarea.classList.toggle("is-plan",i),this.textarea.classList.toggle("is-plan-exec",s),this.sendBtn.classList.toggle("is-plan",i),this.sendBtn.classList.toggle("is-plan-exec",s),this.sendBtn.textContent=i?b("gpui.mgmt.plan.tab","Plan"):b("composer.send","Send"),!n){this.planBarEl.classList.add("bp-hidden"),this.planBarEl.replaceChildren();return}this.planBarEl.classList.remove("bp-hidden"),this.planBarEl.classList.toggle("is-exec",s);let r=document.createElement("span");r.className="bp-plan-bar-ic",r.appendChild(s?Fn():Jt());let o=document.createElement("span");o.className="bp-plan-bar-text",o.textContent=t==="armed"&&e.once?b("gpui.planmode.bar.once","Plan mode (1 turn) — explores and proposes a plan before editing"):t==="armed"?b("gpui.planmode.bar.always","Plan mode — explores and proposes a plan before editing"):t==="planning"?b("gpui.planmode.bar.planning","Planning — drafting a plan before edits"):t==="pending"?b("gpui.planmode.bar.pending","Proposed plan awaits review below"):b("gpui.planmode.bar.executing","Building the approved plan");let c=[r,o];if(t==="armed"||t==="planning"){let u=document.createElement("div");u.className="bp-plan-scopes";let l=(p,d,g,y)=>{let m=document.createElement("button");return m.type="button",m.className="bp-plan-scope-btn"+(d?" active":""),m.textContent=p,m.disabled=!this.enabled,m.setAttribute("data-testid",y),m.addEventListener("click",()=>this.cb.onSetPlanMode?.(g)),m};u.append(l(b("gpui.planmode.scope.once","1 turn"),e.once,"once","plan-scope-once"),l(b("gpui.planmode.scope.always","Always"),!e.once,"always","plan-scope-always"),l(b("gpui.bots.recall.off","Off"),!1,"off","plan-scope-off")),c.push(u)}this.planBarEl.replaceChildren(...c)}setState(e,t){this.enabled=e,this.textarea.disabled=!e,this.sendBtn.disabled=!e,this.attachBtn.disabled=!e,this.voiceBtn.disabled=!e,this.planChipBtn.disabled=!e,this.planBarEl.querySelectorAll(".bp-plan-scope-btn").forEach((n)=>{n.disabled=!e}),this.stopBtn.classList.toggle("bp-hidden",!t)}setDraft(e){this.textarea.value=e,this.autoGrow(),this.textarea.focus()}setReply(e,t,n){if(!e){this.replyEl.replaceChildren(),this.replyEl.classList.add("bp-hidden");return}let i=document.createElement("button");i.type="button",i.className="bp-reply-strip-body",i.setAttribute("data-testid","composer-reply-go");let s=document.createElement("span");s.className="bp-reply-strip-who",s.textContent=e.who;let a=document.createElement("span");if(a.className="bp-reply-strip-line",a.textContent=b("gpui.b.replying.to","↩ Replying to: {line}",{line:e.line}),i.append(s,a),t)i.addEventListener("click",t);let r=document.createElement("button");r.type="button",r.className="icon bp-reply-strip-drop",r.textContent="×";let o=b("reply.cancel","Cancel reply");if(r.title=o,r.setAttribute("aria-label",o),r.setAttribute("data-testid","composer-reply-drop"),n)r.addEventListener("click",n);this.replyEl.replaceChildren(i,r),this.replyEl.classList.remove("bp-hidden"),this.textarea.focus()}prependDraft(e){let t=this.textarea.value;this.textarea.value=t?`${e} -${t}`:e,this.autoGrow(),this.textarea.focus()}showError(e){this.errorEl.textContent=e,this.errorEl.classList.remove("bp-hidden")}clearError(){this.errorEl.textContent="",this.errorEl.classList.add("bp-hidden")}focus(){this.textarea.focus()}refreshLocale(){this.textarea.placeholder=b("composer.placeholder","Ask anything: @bot, >thread, %project, #room, $skill, /btw"),this.attachBtn.title=b("web.composer.attach","Attach image"),this.attachBtn.setAttribute("aria-label",b("web.composer.attach","Attach image")),this.voiceBtn.title=b("web.composer.voice","Voice dictation"),this.voiceBtn.setAttribute("aria-label",b("web.composer.voice","Voice dictation")),this.sendBtn.textContent=b("composer.send","Send"),this.stopBtn.textContent=b("composer.stop","Stop"),this.setPlanMode(this.planMode)}autoGrow(){this.textarea.style.height="auto",this.textarea.style.height=`${Math.min(180,Math.max(54,this.textarea.scrollHeight))}px`}shouldCompleteOnEnter(){if(this.popupMode==="mention")return!0;if(this.popupMode==="slash"){let e=this.textarea.value;return e.startsWith("/")&&!e.includes(" ")}return!1}updatePopups(){let e=this.textarea.value;if(e.startsWith("/")&&!e.includes(" ")&&!e.includes(` -`)){let n=e.slice(1).toLowerCase();if(this.filteredSlash=this.commands.filter((i)=>i.word.toLowerCase().startsWith(n)),this.filteredSlash.length>0){this.popupMode="slash",this.popupIdx=Math.min(this.popupIdx,this.filteredSlash.length-1),this.renderPopup();return}}let t=/(?:^|\s)([@>%#])([a-zA-Z0-9._-]{1,32})$/.exec(e.slice(0,this.textarea.selectionStart));if(t){let n=t[1],i=t[2];this.cb.onQueryMentions(i,n).then((s)=>{if(s.length>0)this.mentionItems=s,this.popupMode="mention",this.popupIdx=0,this.renderPopup();else if(this.popupMode==="mention")this.closePopup()});return}this.closePopup()}closePopup(){this.popupMode="none",this.popupEl.classList.add("bp-hidden"),this.popupEl.replaceChildren()}renderPopup(){let e=document.createDocumentFragment();if(this.popupMode==="slash")this.filteredSlash.forEach((t,n)=>{let i=document.createElement("button");i.type="button",i.className="bp-popup-row"+(n===this.popupIdx?" active":""),i.setAttribute("data-testid",`slash-item-${t.word}`);let s=document.createElement("span");s.className="bp-popup-name",s.textContent=`/${t.word}`;let a=document.createElement("span");a.className="bp-popup-desc",a.textContent=t.desc||t.label,i.append(s,a),i.addEventListener("mousedown",(r)=>{r.preventDefault(),this.applyPopupChoice(n)}),e.appendChild(i)});else if(this.popupMode==="mention")this.mentionItems.forEach((t,n)=>{let i=document.createElement("button");i.type="button",i.className="bp-popup-row"+(n===this.popupIdx?" active":"");let s=document.createElement("span");s.className="bp-popup-name",s.textContent=t.word||`${t.sigil}${t.label}`;let a=document.createElement("span");a.className="bp-popup-desc",a.textContent=t.detail||t.label,i.append(s,a),i.addEventListener("mousedown",(r)=>{r.preventDefault(),this.applyPopupChoice(n)}),e.appendChild(i)});this.popupEl.replaceChildren(e),this.popupEl.classList.remove("bp-hidden")}applyPopupChoice(e){if(this.popupMode==="slash"){let t=this.filteredSlash[e];if(t)this.textarea.value=`/${t.word} `,this.autoGrow(),this.textarea.focus();this.closePopup()}else if(this.popupMode==="mention"){let t=this.mentionItems[e];if(t){let n=this.textarea.selectionStart,i=this.textarea.value.slice(0,n),s=this.textarea.value.slice(n),a=i.replace(/([@>%#][a-zA-Z0-9._-]{1,32})$/,`${t.word} `);this.textarea.value=a+s,this.textarea.selectionStart=this.textarea.selectionEnd=a.length,this.textarea.focus()}this.closePopup()}}async addFiles(e){this.clearError();for(let t of e){if(!Dn.has(t.type)){this.showError(b("web.composer.unsupported","Unsupported image type: {type}",{type:t.type||t.name}));continue}if(this.attachments.length>=Hn){this.showError(b("web.composer.maximages","At most {max} images per message.",{max:Hn}));break}let n=await new Promise((s,a)=>{let r=new FileReader;r.onload=()=>s(String(r.result||"")),r.onerror=()=>a(Error("read failed")),r.readAsDataURL(t)}).catch(()=>""),i=n.indexOf(",");if(i<0)continue;this.attachments.push({name:t.name||`image-${this.attachments.length+1}.png`,mime:t.type,data:n.slice(i+1),previewUrl:n})}this.renderAttachments()}renderAttachments(){if(this.attachments.length===0){this.attachStripEl.classList.add("bp-hidden"),this.attachStripEl.replaceChildren();return}let e=document.createDocumentFragment();this.attachments.forEach((t,n)=>{let i=document.createElement("div");i.className="bp-attach-chip";let s=document.createElement("img");s.src=t.previewUrl,s.alt=t.name,s.className="bp-attach-thumb";let a=document.createElement("button");a.type="button",a.className="icon bp-attach-rm",a.textContent="×",a.title=b("common.remove","Remove"),a.addEventListener("click",()=>{this.attachments.splice(n,1),this.renderAttachments()}),i.append(s,a),e.appendChild(i)}),this.attachStripEl.replaceChildren(e),this.attachStripEl.classList.remove("bp-hidden")}submit(){if(!this.enabled)return;let e=this.textarea.value.trim();if(!e&&this.attachments.length===0)return;if(this.closePopup(),this.clearError(),e.startsWith("/")&&this.attachments.length===0){let n=e.slice(1).split(/\s+/)[0]?.toLowerCase()??"";if(this.commands.some((i)=>i.word.toLowerCase()===n)){this.textarea.value="",this.autoGrow(),this.cb.onRunCommand(e);return}}let t=this.attachments.map(({name:n,mime:i,data:s})=>({name:n,mime:i,data:s}));this.attachments=[],this.renderAttachments(),this.textarea.value="",this.autoGrow(),this.cb.onSend(e,t)}}async function $n(e,t=fetch){let n=await t("/auth/web/logout",{method:"POST",credentials:"same-origin",redirect:"error",headers:{"Content-Type":"application/json"},body:"{}"});if(n.status!==200||(await n.json()).state!=="revoked")throw Error("Logout was not confirmed");e()}var bs=new Set(["bom","checks","life","plan","fab"]);function Mt(e){if(!e||!Array.isArray(e.panels))return[];return e.panels.filter((t)=>t&&typeof t.id==="string"&&bs.has(t.id))}function _n(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 Tt(e,t=22){let n=e.join(", ");if(n.length<=t)return n;let i="";for(let s=0;s0?` +${o}`.length:0)>t)return i?`${i} +${e.length-s}`:`${e[0]} +${e.length-1}`;i=r}return i}function rt(e){if(!Number.isFinite(e)||e<0)return"?";if(e<1000)return String(Math.round(e));if(e<1e6){let n=e/1000;return n<10?`${n.toFixed(1).replace(/\.0$/,"")}k`:`${Math.round(n)}k`}let t=e/1e6;return t<10?`${t.toFixed(1).replace(/\.0$/,"")}M`:`${Math.round(t)}M`}function ot(e){if(!Number.isFinite(e))return"";if(e>=1)return`$${e.toFixed(2)}`;let t=e.toFixed(4).replace(/0+$/,"");return(t.split(".")[1]??"").length<2?`$${e.toFixed(2)}`:`$${t}`}var gs=new Set(["0201","0402","0603","0805","1206","1210","1812","2010","2512"]),fs=new Set(["QFN","DFN","SOT","SOIC","SOP","SSOP","TSSOP","MSOP","QFP","LQFP","TQFP","BGA","WLCSP","SOD","TO","SON","LGA"]);function qn(e){if(!e)return"";let t=e.indexOf(":"),i=(t>=0?e.slice(t+1):e).split("_");for(let r of i)if(gs.has(r))return r;let s=i[0]??"",a=s.replace(/[^a-zA-Z].*$/,"").toUpperCase();if(fs.has(a)){let r=s.split("-");if(r.length>=2&&/^\d+$/.test(r[1]))return`${r[0]}-${r[1]}`;return r[0]}return i.slice(0,2).join("_")}function Kn(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 ${rt(Math.max(n,0))}`,tone:"bad"};if(t==="low")return{text:`low ${rt(n)}`,tone:"warn"};return{text:rt(n),tone:"ok"}}function zn(e,t){let n=t.trim().toLowerCase().split(/\s+/).filter(Boolean);if(n.length===0)return e;return e.filter((i)=>{let s=[(i.refs??[]).join(" "),i.value??"",i.footprint??"",i.mpn??"",i.fab??""].join(" ").toLowerCase();return n.every((a)=>a==="dnp"&&Boolean(i.dnp)||s.includes(a))})}function Jn(e,t){if(!t)return e;return e.filter((n)=>n.source===t)}function Zt(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 Bt(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 Yn(e){return e.state==="routed"||e.state==="verified"}function Xn(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 Zn(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 Qn(e){let t=e.done??0,n=e.approved??0,i=e.awaiting??0,s=e.blocked??0,a=0;if(typeof e.total!=="number"){for(let r of e.layers??[])for(let o of r.items??[])if(o.state==="routed"||o.state==="verified")t+=1;else if(o.state==="routing")a+=1;else if(o.state==="approved")n+=1}else if(e.routing)a=Math.max(0,e.total-(t+n+i+s));return[{count:t,tone:"ok"},{count:a,tone:"accent"},{count:n,tone:"input"},{count:i,tone:"warn"},{count:s,tone:"bad"}]}function ei(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 ti(e){return e==="extra"?"costs-more limits":"base-price limits"}function Qt(e,t){return e.watchGen===t.watchGen&&e.editGen===t.editGen&&e.project!==""&&e.project===t.project&&e.editId!==""&&e.editId===t.editId}function ni(e){return{project:e.project,refs:e.refs.slice(),field:e.field,value:e.was}}function en(e,t){return e.watchGen===t.watchGen&&e.project!==""&&e.project===t.project&&e.threadId!==""&&e.threadId===t.threadId&&e.threadGen===t.threadGen}var Gn=["#f59e0b","#38bdf8","#c084fc","#2dd4bf","#ef4444","#a3e635","#f97316","#ec4899"],On=["#14b8a6","#f59e0b","#c084fc","#22c55e","#38bdf8","#ef4444","#e879f9","#84cc16"];function ii(e){let t=2166136261;for(let n=0;n>>0;return t}function yt(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 Gn[ii(i)%Gn.length]}function lt(e,t=""){let n=t.trim().toLowerCase();if(n&&n!=="#8a8a8a")return t;return On[ii(e)%On.length]}function si(e,t,n,i=14){let s=Math.max(1,Math.abs(e[2]-e[0])),a=Math.max(1,Math.abs(e[3]-e[1])),r=Math.max(20,t-i*2),o=Math.max(20,n-i*2),c=Math.max(0.05,Math.min(200,Math.min(r/s,o/a)));return{cx:(e[0]+e[2])*0.5,cy:(e[1]+e[3])*0.5,scale:c,fitted:c,touched:!1}}function Oe(e,t,n,i,s){return[i*0.5+(t-e.cx)*e.scale,s*0.5+(n-e.cy)*e.scale]}function It(e,t,n,i,s){let a=Math.max(0.0001,e.scale);return[e.cx+(t-i*0.5)/a,e.cy+(n-s*0.5)/a]}function ai(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 ri(e,t,n,i,s,a){let r=Math.max(0.02,e.fitted*0.35),o=Math.max(40,e.fitted*24),c=Math.max(r,Math.min(o,e.scale*t)),[u,l]=It(e,n,i,s,a);return{...e,cx:u-(n-s*0.5)/c,cy:l-(i-a*0.5)/c,scale:c,touched:!0}}function oi(e,t,n,i){let s=e.map((r)=>[r[0],r[1]]);if(s.length===0)return[n];let a=i&&t+1>=s.length?s.length:Math.min(t+1,s.length);return s.splice(a,0,[n[0],n[1]]),s}function tn(e,t,n){let i=n?3:2;if(e.length<=i||t<0||t>=e.length)return null;let s=e.map((a)=>[a[0],a[1]]);return s.splice(t,1),s}function vs(e,t,n,i,s,a){let r=s-n,o=a-i,c=r*r+o*o;if(c<0.000001)return(e-n)*(e-n)+(t-i)*(t-i);let u=Math.max(0,Math.min(1,((e-n)*r+(t-i)*o)/c)),l=n+u*r,p=i+u*o;return(e-l)*(e-l)+(t-p)*(t-p)}function Vn(e,t,n){if(n.length<3)return!1;let i=!1;for(let s=0,a=n.length-1;st!==u>t&&e<(c-r)*(t-o)/(u-o+0.000000000001)+r)i=!i}return i}function nn(e,t){return Math.max(5,Math.min(32,e*t))}function Rt(e,t,n,i,s,a,r,o,c){if(i){for(let d of e){if(d.layer!==n||d.id!==i||d.locked)continue;let g=d.path??[];for(let y=0;y=3)for(let y=0;y=0;d--){let g=t[d];if(g.layer!==n)continue;let y=g.outline??[];if(!Vn(l,p,y))continue;if(!(g.holes??[]).some((h)=>Vn(l,p,h)))return{kind:"region",id:g.id}}return null}function ct(e){let t=null,n=null,i=[];for(let a of e){if(!a.layer)continue;i.push(a.layer);let r=a.items??[],o=r.filter((u)=>u.kind==="corridor").length,c=r.filter((u)=>u.kind==="plane").length;if((o>0||a.role==="signal")&&(!t||o>t.count))t={count:o,layer:a.layer};if((c>0||a.role==="power"||a.role==="plane")&&(!n||c>n.count))n={count:c,layer:a.layer}}let s=[];if(t)s.push(t.layer);if(n&&!s.includes(n.layer))s.push(n.layer);for(let a of i){if(s.length>=2)break;if(!s.includes(a))s.push(a)}return s}function Un(e,t){if(!e||e.length===0)return null;if(e.length===1)return e[0];let n=Math.max(0,Math.min(1,t)),i=0;for(let r=1;r=s&&o>0.000000001){let c=(s-a)/o;return[e[r-1][0]+(e[r][0]-e[r-1][0])*c,e[r-1][1]+(e[r][1]-e[r-1][1])*c]}a+=o}return e[e.length-1]}function st(e,t,n){for(let i of t??[])if(i.layer===e&&i.title)return i.title;for(let i of n??[])if(i.layer===e&&i.title)return i.title;return e}function li(e,t,n){if(e==="split"&&n.length>0)return t.filter((i)=>n.includes(i.layer));return t}function Xt(e,t){return!(e[2]<=t[0]||e[0]>=t[2]||e[3]<=t[1]||e[1]>=t[3])}function Wn(e,t,n){if(n.length<3)return!1;let i=!1;for(let s=0,a=n.length-1;st!==u>t&&e<(c-r)*(t-o)/(u-o+0.000000000001)+r)i=!i}return i}function ci(e,t){if(e.length<3)return null;let n=1/0,i=1/0,s=-1/0,a=-1/0,r=0,o=0;for(let u of e)n=Math.min(n,u[0]),i=Math.min(i,u[1]),s=Math.max(s,u[0]),a=Math.max(a,u[1]),r+=u[0],o+=u[1];let c=[[(n+s)*0.5,(i+a)*0.5],[r/e.length,o/e.length]];for(let u of[0.5,0.25,0.75,0.125,0.875])for(let l of[0.5,0.25,0.75,0.125,0.875])c.push([n+(s-n)*l,i+(a-i)*u]);for(let u of c)if(Wn(u[0],u[1],e)&&!t.some((l)=>Wn(u[0],u[1],l)))return u;return null}function di(e,t,n,i,s,a){let r=[];for(let l of e){let p=l.nets??0,d=l.path??[];if(p<=0||d.length<2)continue;let g=0;for(let y=1;y{let d=l.sel||l.hov?1:0,g=p.sel||p.hov?1:0;if(g!==d)return g-d;if(p.nets!==l.nets)return p.nets-l.nets;return l.b.id.localeCompare(p.b.id)});let o=[],c=[],u=(l,p,d,g,y)=>[l-d*0.5-y,p-g*0.5-y,l+d*0.5+y,p+g*0.5+y];for(let l of r){let p=l.b.name||"",d=String(l.nets),g=p?`${p} · ${l.nets}`:d,y=(l.sel||l.hov||l.pxLen>=95)&&p?[g,d]:[d],m=null,h=(w,C)=>Math.max(C*0.5+3,Math.min(Math.max(C*0.5+3,n-C*0.5-3),w)),f=(w,C)=>Math.max(C*0.5+3,Math.min(Math.max(C*0.5+3,i-C*0.5-3),w));e:for(let w of y){let C=Math.max(16,w.length*5.9+10),L=15;for(let M of[0.5,0.35,0.65,0.22,0.78]){let S=Un(l.pts,M);if(!S)continue;let[T,B]=Oe(t,S[0],S[1],n,i),R=h(T,C),G=f(B,15),D=u(R,G,C,15,2);if(!o.some((re)=>Xt(D,re))){m={id:l.b.id,text:w,cx:R,cy:G,pw:C,ph:15,col:l.col,sel:l.sel};break e}}}if(!m){let w=Un(l.pts,0.5);if(w){let[C,L]=Oe(t,w[0],w[1],n,i),M=Math.max(16,d.length*6.5+8),S=15,T=h(C,M);for(let B of[-18,18]){let R=f(L+B,15);if(!o.some((G)=>Xt(u(T,R,M,15,2),G))){m={id:l.b.id,text:d,cx:T,cy:R,pw:M,ph:15,col:l.col,sel:l.sel};break}}}}if(m)o.push(u(m.cx,m.cy,m.pw,m.ph,2)),c.push(m)}return c}function pi(e,t,n,i,s,a=[]){let r=new Set(s),o=[];for(let l of e){if(!l.r||!l.b||l.b.length!==4)continue;let[p,d]=Oe(t,l.b[0],l.b[1],n,i),[g,y]=Oe(t,l.b[2],l.b[3],n,i),m=Math.abs(g-p),h=Math.abs(y-d);if(m<13||h<9)continue;let f=(p+g)*0.5,w=(d+y)*0.5;if(f<8||f>n-8||w<8||w>i-8)continue;o.push({text:l.r,cx:f,cy:w,bw:l.r.length*5.8+4,bh:11,score:m*h+(r.has(l.r)?1e4:0)})}o.sort((l,p)=>p.score-l.score);let c=[...a],u=[];for(let l of o){let p=[l.cx-l.bw*0.5,l.cy-l.bh*0.5,l.cx+l.bw*0.5,l.cy+l.bh*0.5];if(!c.some((g)=>Xt(p,g)))c.push(p),u.push({text:l.text,cx:l.cx,cy:l.cy})}return u}function mi(e){if(!e||typeof e!=="object")return null;let t=e;if(t.panel&&typeof t.panel==="object")return t.panel;if(t.result&&typeof t.result==="object"){let n=t.result.panel;if(n&&typeof n==="object")return n}return null}function jt(e,t){if(!t||t.length===0)return e;let n=new Map;for(let a of e)if(a.layer)n.set(a.layer,a);let i=[],s=new Set;for(let a of t){if(!a.layer)continue;s.add(a.layer);let r=n.get(a.layer);if(r)i.push(r);else i.push({layer:a.layer,index:a.index,title:a.title||`L${a.index} · ${a.layer}`,subtitle:a.subtitle||"",role:a.role,status:"proposed",done:0,approved:0,total:0,items:[]})}for(let a of e)if(a.layer&&!s.has(a.layer))i.push(a);return i}function ui(e,t,n,i,s,a,r,o){return e===t&&n===i&&s===a&&(o===void 0||r>=o)}var hi="#111917",ys="#16201d",ws="rgba(212, 224, 219, 0.92)",Es="rgba(61, 80, 73, 0.72)",xs="rgba(82, 107, 97, 0.85)";var bi="#f59e0b",Cs="#eef5f2",gi="#ef4444";function at(e,t){let n=e.trim().replace(/^#/,"");if(n.length===6){let i=parseInt(n.slice(0,2),16),s=parseInt(n.slice(2,4),16),a=parseInt(n.slice(4,6),16);if(!Number.isNaN(i)&&!Number.isNaN(s)&&!Number.isNaN(a))return`rgba(${i}, ${s}, ${a}, ${t})`}return`rgba(20, 184, 166, ${t})`}function ks(e,t,n){let i=0.14,s=0.45,a=0.85,r=!1;switch(e){case"approved":case"routing":i=0.16,s=0.51,a=0.91;break;case"edited":i=0.2,s=0.56,a=0.95;break;case"routed":case"verified":i=0.08,s=0.26,a=0.59;break;case"rejected":case"failed":i=0.05,s=0.13,a=0.27;break;case"blocked":i=0.18,s=0.48,a=0.88,r=!0;break}if(t)i=Math.min(0.35,i+0.1),s=Math.min(0.71,s+0.12),a=1;else if(n)i=Math.min(0.28,i+0.06),s=Math.min(0.63,s+0.07);return{glow:i,body:s,core:a,bad:r}}function Ls(e,t,n){let i=0.27,s=0.83,a=!1;switch(e){case"approved":case"routing":i=0.36,s=0.91;break;case"edited":i=0.38,s=0.95;break;case"routed":case"verified":i=0.16,s=0.54;break;case"rejected":case"failed":i=0.08,s=0.27;break;case"blocked":i=0.31,s=0.94,a=!0;break}if(t)i=Math.min(0.53,i+0.12),s=1;else if(n)i=Math.min(0.45,i+0.06),s=Math.min(1,s+0.1);return{fill:i,edge:s,bad:a}}function Ss(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 sn{root;cb;state=null;cards=new Map;renderedLayerKey="";sharedCam=null;layerCams=new Map;hover=null;selectedVertex=null;drag=null;downPos=null;rafPending=0;constructor(e){this.cb=e,this.root=document.createElement("div"),this.root.className="bp-plan-canvas-grid",this.root.tabIndex=0,this.root.setAttribute("data-testid","mgmt-plan-canvas-grid"),this.root.addEventListener("keydown",(t)=>this.onKeyDown(t))}isDragging(){return this.drag!==null}fitAll(){this.sharedCam=null,this.layerCams.clear(),this.scheduleDraw()}destroy(){if(this.rafPending)cancelAnimationFrame(this.rafPending),this.rafPending=0;for(let e of this.cards.values())e.ro.disconnect();this.cards.clear(),this.root.replaceChildren()}visibleLayers(e){let t=jt(e.layers,e.copperLayers);if(t.length===0)return[];if(e.gridMode==="all")return t;if(e.gridMode==="single"){let s=e.shownLayers.find((r)=>t.some((o)=>o.layer===r))??ct(t)[0]??t[0]?.layer,a=t.find((r)=>r.layer===s);return a?[a]:[]}let n=e.shownLayers.length>0&&e.shownLayers.every((s)=>t.some((a)=>a.layer===s))?e.shownLayers.slice(0,2):ct(t),i=[];for(let s of n){let a=t.find((r)=>r.layer===s);if(a)i.push(a)}return i.length>0?i:t.slice(0,2)}update(e,t){this.state=e;let n=this.visibleLayers(e);this.root.classList.toggle("two-cols",t&&n.length>1);let i=n.map((s)=>s.layer).join("|");if(i!==this.renderedLayerKey){this.renderedLayerKey=i;for(let s of this.cards.values())s.ro.disconnect();this.cards.clear(),this.root.replaceChildren();for(let s of n){let a=this.buildCard(s);this.cards.set(s.layer,a),this.root.appendChild(a.el)}}else for(let s of n){let a=this.cards.get(s.layer);if(a)this.syncCardHeaderAndLegend(a,s)}this.scheduleDraw()}effectiveBbox(e){let t=e.bbox;if(!t||t.length!==4||Math.abs(t[2]-t[0])<0.5||Math.abs(t[3]-t[1])<0.5)return[0,0,100,70];return t}getCam(e,t,n){let i=this.state,s=i?.syncZoom?this.sharedCam:this.layerCams.get(e)??null;if(s&&s.touched)return s;return si(i?this.effectiveBbox(i.board):[0,0,100,70],t,n,14)}setCam(e,t){if(this.state?.syncZoom)this.sharedCam=t;else this.layerCams.set(e,t)}buildCard(e){let t=document.createElement("section");t.className="bp-plan-card",t.setAttribute("data-testid",`mgmt-plan-card-${e.layer}`);let n=document.createElement("div");n.className="bp-plan-card-head";let i=document.createElement("div");i.className="bp-plan-card-head-top";let s=document.createElement("span"),a=e.role==="power"||(e.items?.length??0)>0&&(e.items??[]).every((w)=>w.kind==="plane");s.className="bp-plan-card-bar "+(a?"pwr":"sig");let r=document.createElement("span");r.className="bp-plan-card-title";let o=document.createElement("span");o.className="bp-plan-status-badge";let c=document.createElement("button");c.type="button",c.className="bp-mgmt-btn bp-plan-mini-btn",c.textContent="✓",c.title=b("gpui.mgmt.plan.layer","Approve layer"),c.addEventListener("click",(w)=>{w.stopPropagation(),this.cb.onApproveLayer(e.layer,!0)});let u=document.createElement("button");u.type="button",u.className="bp-mgmt-btn bp-plan-mini-btn",u.textContent="✗",u.title=b("gpui.mgmt.plan.rejectlayer","Reject layer"),u.addEventListener("click",(w)=>{w.stopPropagation(),this.cb.onApproveLayer(e.layer,!1)}),i.append(s,r,o,c,u);let l=document.createElement("div");l.className="bp-plan-card-sub",n.append(i,l);let p=document.createElement("div");p.className="bp-plan-card-canvas-wrap";let d=document.createElement("canvas");d.className="bp-plan-card-canvas",d.setAttribute("data-testid",`mgmt-plan-canvas-${e.layer}`);let g=document.createElement("div");g.className="bp-plan-hover-hud bp-hidden",p.append(d,g);let y=document.createElement("div");y.className="bp-plan-legend bp-hidden",t.append(n,p,y);let m=d.getContext("2d"),h=new ResizeObserver(()=>this.scheduleDraw());h.observe(p),this.attachPointerListeners(d,e.layer);let f={layer:e.layer,el:t,canvas:d,ctx:m,legendEl:y,okBtn:c,noBtn:u,statusEl:o,titleEl:r,subtitleEl:l,hoverHudEl:g,ro:h};return this.syncCardHeaderAndLegend(f,e),f}syncCardHeaderAndLegend(e,t){e.titleEl.textContent=st(t.layer,this.state?.copperLayers,this.state?.layers)||t.title||t.layer;let n=t.subtitle||t.stackup||"";e.subtitleEl.textContent=n,e.subtitleEl.classList.toggle("bp-hidden",!n);let i=t.items??[],s=Ss(t);e.statusEl.className=`bp-plan-card-status tone-${s.tone==="warn"?"dim":s.tone}`,e.statusEl.textContent=i.length>0?b(s.key,s.label):"",e.statusEl.classList.toggle("bp-hidden",i.length===0);let a=i.some((o)=>o.state==="proposed"||o.state==="edited");if(e.okBtn)e.okBtn.classList.toggle("bp-hidden",!a);if(e.noBtn)e.noBtn.classList.toggle("bp-hidden",!a);let r=(this.state?.regions??[]).filter((o)=>o.layer===t.layer);if(r.length===0)e.legendEl.classList.add("bp-hidden"),e.legendEl.replaceChildren();else{e.legendEl.classList.remove("bp-hidden");let o=document.createDocumentFragment();for(let c of r){let u=document.createElement("button");u.type="button";let l=this.state?.selectedId===c.id;u.className="bp-plan-legend-chip"+(l?" active":"");let p=document.createElement("span");p.className="bp-plan-legend-sw",p.style.background=yt(c.net||c.id,c.color||"");let d=document.createElement("span");d.textContent=c.net||c.id,u.append(p,d),u.addEventListener("click",()=>{this.cb.onSelect(c.id),this.cb.onFocusItem(c.id)}),o.appendChild(u)}e.legendEl.replaceChildren(o)}}attachPointerListeners(e,t){e.addEventListener("contextmenu",(i)=>i.preventDefault()),e.addEventListener("dblclick",()=>this.fitAll()),e.addEventListener("pointerdown",(i)=>{let s=this.state;if(!s)return;this.root.focus({preventScroll:!0});let a=e.getBoundingClientRect(),r=i.clientX-a.left,o=i.clientY-a.top,c=Math.max(1,a.width),u=Math.max(1,a.height),l=this.getCam(t,c,u),p=Rt(s.bands,s.regions,t,s.selectedId,l,c,u,r,o);if(i.button===2){if(p?.kind==="vertex"){let d=this.getItemPts(p.id,p.isPlane),g=tn(d,p.idx,p.isPlane);if(g)this.selectedVertex=null,this.cb.onCommitFields(p.id,{[p.isPlane?"outline":"path"]:g})}return}if(i.button!==0)return;if(e.setPointerCapture(i.pointerId),this.downPos={x:i.clientX,y:i.clientY},p?.kind==="vertex"){let d=this.getItemPts(p.id,p.isPlane),g=d.map((y)=>[y[0],y[1]]);this.selectedVertex={id:p.id,idx:p.idx},this.drag={layer:t,kind:"vertex",id:p.id,isPlane:p.isPlane,idx:p.idx,pts:d.map((y)=>[y[0],y[1]]),origPts:g,moved:!1},this.scheduleDraw()}else if(p?.kind==="midpoint"){let d=this.getItemPts(p.id,p.isPlane),g=d.map((h)=>[h[0],h[1]]),y=oi(d,p.segIdx,p.pos,p.isPlane),m=p.isPlane&&p.segIdx+1>=d.length?y.length-1:Math.min(p.segIdx+1,y.length-1);this.selectedVertex={id:p.id,idx:m},this.patchLocalItem(p.id,p.isPlane,y),this.drag={layer:t,kind:"vertex",id:p.id,isPlane:p.isPlane,idx:m,pts:y,origPts:g,moved:!0},this.scheduleDraw()}else this.selectedVertex=null,this.drag={layer:t,kind:"pan",lastX:r,lastY:o}}),e.addEventListener("pointermove",(i)=>{let s=this.state;if(!s)return;let a=e.getBoundingClientRect(),r=i.clientX-a.left,o=i.clientY-a.top,c=Math.max(1,a.width),u=Math.max(1,a.height);if(this.drag&&this.drag.layer===t){if(this.drag.kind==="pan"){let L=this.getCam(t,c,u);this.setCam(t,ai(L,r-this.drag.lastX,o-this.drag.lastY)),this.drag.lastX=r,this.drag.lastY=o,this.scheduleDraw();return}if(this.downPos&&Math.hypot(i.clientX-this.downPos.x,i.clientY-this.downPos.y)<1.5&&!this.drag.moved)return;let m=this.getCam(t,c,u),[h,f]=It(m,r,o,c,u),w=[Math.round(h*1000)/1000,Math.round(f*1000)/1000];this.drag.moved=!0,this.drag.pts[this.drag.idx]=w;let C=this.drag.pts.map((L)=>[L[0],L[1]]);this.patchLocalItem(this.drag.id,this.drag.isPlane,C),this.scheduleDraw();return}let l=this.getCam(t,c,u),p=Rt(s.bands,s.regions,t,s.selectedId,l,c,u,r,o),d=this.hover?.hit?"id"in this.hover.hit?this.hover.hit.id:"":"",g=this.hover?.hit.kind??"",y=p?p.id:"";if(this.hover=p?{layer:t,hit:p}:null,e.style.cursor=p?"pointer":"crosshair",d!==y||(p?.kind??"")!==g)this.syncHoverHud(t),this.scheduleDraw()}),e.addEventListener("pointerleave",()=>{if(this.hover?.layer===t)this.hover=null,this.syncHoverHud(t),this.scheduleDraw()});let n=()=>{let i=this.drag;if(!i||i.layer!==t)return;if(this.drag=null,this.downPos=null,i.kind==="vertex"&&i.moved){let s=i.origPts.map((a)=>[a[0],a[1]]);this.patchLocalItem(i.id,i.isPlane,s)}this.cb.onDragEnd?.(),this.scheduleDraw()};e.addEventListener("pointercancel",n),e.addEventListener("lostpointercapture",n),e.addEventListener("pointerup",(i)=>{let s=this.state,a=this.drag,r=this.downPos;if(this.drag=null,this.downPos=null,e.hasPointerCapture(i.pointerId))e.releasePointerCapture(i.pointerId);if(a&&a.kind==="vertex"&&a.layer===t){if(a.moved)this.cb.onCommitFields(a.id,{[a.isPlane?"outline":"path"]:a.pts});else this.cb.onDragEnd?.(),this.scheduleDraw();return}if(s&&r&&Math.hypot(i.clientX-r.x,i.clientY-r.y)<4.5){let o=e.getBoundingClientRect(),c=i.clientX-o.left,u=i.clientY-o.top,l=Math.max(1,o.width),p=Math.max(1,o.height),d=this.getCam(t,l,p),g=Rt(s.bands,s.regions,t,s.selectedId,d,l,p,c,u);if(g&&(g.kind==="band"||g.kind==="region")){this.cb.onSelect(g.id),this.cb.onFocusItem(g.id);return}if(!g&&s.selectedId){this.cb.onSelect("");return}}this.cb.onDragEnd?.()}),e.addEventListener("wheel",(i)=>{i.preventDefault();let s=e.getBoundingClientRect(),a=i.clientX-s.left,r=i.clientY-s.top,o=Math.max(1,s.width),c=Math.max(1,s.height),u=this.getCam(t,o,c),l=Math.max(0.65,Math.min(1.55,1-i.deltaY*0.002));this.setCam(t,ri(u,l,a,r,o,c)),this.scheduleDraw()},{passive:!1})}patchLocalItem(e,t,n){let i=this.state;if(!i)return;if(t){let s=i.regions.find((a)=>a.id===e);if(s){if(s.outline=n,s.edited=!0,s.state==="proposed")s.state="edited"}}else{let s=i.bands.find((a)=>a.id===e);if(s){if(s.path=n,s.edited=!0,s.state==="proposed")s.state="edited"}}}getItemPts(e,t){let n=this.state;if(!n)return[];if(t)return(n.regions.find((i)=>i.id===e)?.outline??[]).map((i)=>[i[0],i[1]]);return(n.bands.find((i)=>i.id===e)?.path??[]).map((i)=>[i[0],i[1]])}syncHoverHud(e){let t=this.cards.get(e),n=this.state;if(!t||!n)return;if(!this.hover||this.hover.layer!==e){t.hoverHudEl.classList.add("bp-hidden"),t.hoverHudEl.textContent="";return}let i=this.hover.hit.id,s=n.bands.find((o)=>o.id===i),a=n.regions.find((o)=>o.id===i),r="";if(s)r=`${s.name||i} · ${s.nets??0}n · ${(s.width??1.5).toFixed(2)}mm`;else if(a)r=a.reference?`${a.net||i} · ${a.reference}`:a.net||i;if(!r)t.hoverHudEl.classList.add("bp-hidden");else t.hoverHudEl.classList.remove("bp-hidden"),t.hoverHudEl.textContent=r}onKeyDown(e){let t=this.state;if(!t)return;if(e.key==="0"||e.key==="Home"){e.preventDefault(),this.fitAll();return}if(e.key==="Escape"){this.selectedVertex=null,this.cb.onSelect("");return}if(!t.selectedId)return;let n=t.bands.find((r)=>r.id===t.selectedId),i=t.regions.find((r)=>r.id===t.selectedId),s=Boolean(n?.locked??i?.locked),a=e.key.toLowerCase();if(a==="a")e.preventDefault(),this.cb.onQuickApprove([t.selectedId],!0);else if(a==="r")e.preventDefault(),this.cb.onQuickApprove([t.selectedId],!1);else if(a==="l")e.preventDefault(),this.cb.onCommitFields(t.selectedId,{locked:!s});else if(a==="w"&&n&&!s){e.preventDefault();let r=e.shiftKey?-0.25:0.25,o=Math.round(Math.max(0.15,Math.min(25,(n.width??1.5)+r))*100)/100;this.cb.onCommitFields(t.selectedId,{width:o})}else if((e.key==="Delete"||e.key==="Backspace")&&!s&&this.selectedVertex?.id===t.selectedId){e.preventDefault();let r=Boolean(i),o=this.getItemPts(t.selectedId,r),c=tn(o,this.selectedVertex.idx,r);if(c)this.selectedVertex=null,this.cb.onCommitFields(t.selectedId,{[r?"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)),a=Math.max(165,Math.min(250,Math.round(s*t)));n.canvas.style.height=`${a}px`;let r=Math.max(1,window.devicePixelRatio||1),o=Math.round(s*r),c=Math.round(a*r);if(n.canvas.width!==o||n.canvas.height!==c)n.canvas.width=o,n.canvas.height=c;n.ctx.setTransform(r,0,0,r,0,0),this.drawLayer(n.ctx,n.layer,s,a,e)}}drawLayer(e,t,n,i,s){let a=this.getCam(t,n,i),r=(m,h)=>Oe(a,m,h,n,i);e.fillStyle=hi,e.fillRect(0,0,n,i);let o=(s.board.outline??[]).filter((m)=>m.length>=3);if(e.fillStyle=ys,o.length>0){e.beginPath();for(let m of o){for(let h=0;hm.layer===t),u=this.hover?.layer===t?this.hover.hit:null;for(let m of c){let h=m.outline??[];if(h.length<3)continue;let f=s.selectedId===m.id,w=u?.id===m.id,C=Ls(m.state||"proposed",f,w),L=yt(m.net||m.id,m.color||"");e.beginPath();for(let S=0;SB)B=D;if(re>R)R=re}if(Math.abs(B-S)>=38&&Math.abs(R-T)>=18){let G=ci(h,m.holes??[]);if(G){let[D,re]=r(G[0],G[1]);e.fillStyle=at(L,f?0.91:0.67),e.font="bold 10px ui-monospace, 'SFMono-Regular', Menlo, monospace",e.textAlign="center",e.textBaseline="middle",e.fillText(M,D,re)}}}}if(e.strokeStyle=ws,e.lineWidth=1.25,e.lineCap="round",e.lineJoin="round",o.length>0){e.beginPath();for(let m of o){for(let h=0;hm.layer===t),d=di(p,a,n,i,s.selectedId,u?.id??""),g=d.map((m)=>[m.cx-m.pw*0.5-1,m.cy-m.ph*0.5-1,m.cx+m.pw*0.5+1,m.cy+m.ph*0.5+1]),y=[];for(let m of p){for(let h of m.from??[])y.push(h);for(let h of m.to??[])y.push(h)}e.fillStyle="rgba(143, 163, 155, 0.72)",e.font="9.5px ui-monospace, 'SFMono-Regular', Menlo, monospace",e.textAlign="center",e.textBaseline="middle";for(let m of pi(l,a,n,i,y,g))e.fillText(m.text,m.cx,m.cy);for(let m of p){let h=m.guides??[];if(h.length===0)continue;let f=s.selectedId===m.id||u?.id===m.id,w=lt(m.name||m.id,m.color||"");e.strokeStyle=at(w,f?0.38:0.17),e.lineWidth=f?1:0.7,e.beginPath();for(let C of h){let[L,M]=r(C[0],C[1]),[S,T]=r(C[2],C[3]);e.moveTo(L,M),e.lineTo(S,T)}e.stroke()}for(let m of p){let h=m.path??[];if(h.length<2)continue;let f=s.selectedId===m.id,w=u?.id===m.id,C=ks(m.state||"proposed",f,w),L=lt(m.name||m.id,m.color||""),M=nn(m.width??1.5,a.scale),S=()=>{e.beginPath();for(let T=0;T{let w=f?h.length:Math.max(0,h.length-1);for(let C=0;Cn.id===e))return;if(this.openPanel!==e)this.togglePanel(e)}getTabs(){return Mt(this.getStateInfo())}isOpen(){return this.openPanel!==""}closePanel(){if(!this.openPanel)return;if(this.openPanel="",this.project)this.cb.hub.rpc("mgmt.panel",{project:this.project,open:""}).catch(()=>{});this.render()}clear(){this.watchGen++,this.bomEditGen++,this.askedProject="",this.digest="",this.project="",this.openPanel="",this.errorMsg="",this.bomEditingId="",this.bomLastUndo=null,this.bomEditStatus="",this.checksStatus="",this.planStatus="",this.planSelectedId="",this.planStackupOpen=!1,this.planShownLayers=[],this.planOptimistic.clear(),this.planOptimisticRev=void 0,this.planHydratedKey="",this.planHydrateAskedKey="",this.planHydrateGen++,this.planHydratedRev=void 0,this.planRenderDeferred=!1,this.planHydratedBoard=null,this.planHydratedDraw=null,this.planNoteOpen=!1,this.planMoveLayerOpen=!1,this.planCanvas?.destroy(),this.planCanvas=null,this.planCommitFields=null,this.fabStatus="",this.render()}async watchProject(e){if(!e||!this.cb.hub.hasFeature("mgmt")){this.clear();return}if(e===this.askedProject&&this.digest){this.render();return}let t=++this.watchGen;if(this.askedProject=e,this.project!==e)this.bomEditGen++,this.digest="",this.project="",this.openPanel="",this.errorMsg="",this.bomSelectedId="",this.bomEditingId="",this.bomEditStatus="",this.bomLastUndo=null,this.checksSelectedId="",this.checksStatus="",this.planStatus="",this.planSelectedId="",this.planStackupOpen=!1,this.planShownLayers=[],this.planOptimistic.clear(),this.planOptimisticRev=void 0,this.planHydratedKey="",this.planHydrateAskedKey="",this.planHydrateGen++,this.planHydratedRev=void 0,this.planRenderDeferred=!1,this.planHydratedBoard=null,this.planHydratedDraw=null,this.planNoteOpen=!1,this.planMoveLayerOpen=!1,this.planCanvas?.destroy(),this.planCanvas=null,this.planCommitFields=null,this.fabStatus="",this.lifeSelectedKey="",this.lifePartSamples=null,this.render();try{let n=await this.cb.hub.rpc("mgmt.watch",{project:e});if(t!==this.watchGen)return;let i=typeof n.digest==="string"?n.digest:"";if(!i){this.render();return}if(this.digest=i,this.project=typeof n.project==="string"&&n.project?n.project:e,n.state&&typeof n.state==="object")this.infos.set(`mgmt.state.${i}`,n.state);if(n.data&&typeof n.data==="object"){for(let[s,a]of Object.entries(n.data))if(a&&typeof a==="object")this.infos.set(`mgmt.${s}.${i}`,a)}this.errorMsg="",this.render()}catch{if(t===this.watchGen)this.render()}}handleInfo(e){let t=!1;for(let[n,i]of Object.entries(e)){if(!n.startsWith("mgmt.")&&!n.startsWith("kicad.checks."))continue;if(i===""||i===null||i===void 0){if(this.infos.delete(n))t=!0;continue}if(typeof i==="string")try{let s=JSON.parse(i);if(s&&typeof s==="object")this.infos.set(n,s),t=!0}catch{}else if(typeof i==="object")this.infos.set(n,i),t=!0}if(t)this.render()}getStateInfo(){if(!this.digest)return null;return this.infos.get(`mgmt.state.${this.digest}`)??null}getPanelData(e){if(!this.digest)return null;return this.infos.get(`mgmt.${e}.${this.digest}`)??null}togglePanel(e){let t=this.openPanel===e?"":e;if(this.openPanel=t,this.errorMsg="",this.render(),this.project)this.cb.hub.rpc("mgmt.panel",{project:this.project,open:t}).catch((n)=>{this.errorMsg=n instanceof Error?n.message:"Could not update panel",this.render()})}render(){if(this.openPanel==="plan"&&this.planCanvas?.isDragging()){this.planRenderDeferred=!0;return}this.planRenderDeferred=!1;let e=this.getStateInfo(),t=Mt(e);if(!this.digest||t.length===0){this.planCanvas?.destroy(),this.planCanvas=null,this.panelEl.classList.remove("bp-plan-expanded"),this.stripEl.classList.add("bp-hidden"),this.panelEl.classList.add("bp-hidden"),this.panelEl.removeAttribute("data-testid"),this.panelEl.replaceChildren(),this.stripEl.replaceChildren(),this.cb.onOpenChange?.(!1);return}this.stripEl.classList.remove("bp-hidden");let n=document.createDocumentFragment(),i=document.createElement("div");i.className="bp-mgmt-tabs";for(let r of t){let o=document.createElement("button");o.type="button";let c=this.openPanel===r.id;o.className="bp-mgmt-tab"+(c?" active":""),o.setAttribute("data-testid",`mgmt-tab-${r.id}`),o.setAttribute("aria-pressed",c?"true":"false");let u=document.createElement("span");u.textContent=xe(r.label),o.appendChild(u);let l=this.getPanelData(r.id),p=_n(l);if(p){let d=document.createElement("span");d.className=`bp-mgmt-badge bp-tone-${p.tone}`,d.textContent=p.text,o.appendChild(d)}o.addEventListener("click",()=>this.togglePanel(r.id)),i.appendChild(o)}if(n.appendChild(i),this.openPanel){let r=document.createElement("button");r.type="button",r.className="icon bp-mgmt-close",r.textContent="×",r.title=b("gpui.mgmt.close","Close the panel"),r.setAttribute("aria-label",b("gpui.mgmt.close","Close the panel")),r.setAttribute("data-testid","mgmt-close"),r.addEventListener("click",()=>this.closePanel()),n.appendChild(r)}if(this.stripEl.replaceChildren(n),!this.openPanel){this.planCanvas?.destroy(),this.planCanvas=null,this.panelEl.classList.remove("bp-plan-expanded"),this.panelEl.classList.add("bp-hidden"),this.panelEl.removeAttribute("data-testid"),this.panelEl.replaceChildren(),this.cb.onOpenChange?.(!1);return}if(this.openPanel!=="plan")this.planCanvas?.destroy(),this.planCanvas=null,this.panelEl.classList.remove("bp-plan-expanded");else this.panelEl.classList.toggle("bp-plan-expanded",this.planExpanded);this.panelEl.classList.remove("bp-hidden"),this.panelEl.setAttribute("data-testid",`mgmt-panel-${this.openPanel}`),this.cb.onOpenChange?.(!0);let s=this.openPanel==="plan"&&this.planCanvas!==null&&document.activeElement instanceof HTMLElement&&this.panelEl.contains(document.activeElement)&&(document.activeElement===this.planCanvas.root||this.planCanvas.root.contains(document.activeElement)),a=document.createDocumentFragment();if(this.errorMsg){let r=document.createElement("div");r.className="bp-mgmt-note bp-tone-bad",r.textContent=this.errorMsg,a.appendChild(r)}switch(this.openPanel){case"bom":a.appendChild(this.renderBom());break;case"checks":a.appendChild(this.renderChecks());break;case"life":a.appendChild(this.renderLife());break;case"plan":a.appendChild(this.renderPlan());break;case"fab":a.appendChild(this.renderFab());break}if(this.panelEl.replaceChildren(a),s)this.planCanvas?.root.focus({preventScroll:!0})}renderBom(){let e=document.createElement("div");e.className="bp-mgmt-body";let t=this.getPanelData("bom");if(!t)return e.appendChild(this.makeEmpty("Reading the schematic…")),e;let n=Array.isArray(t.lines)?t.lines:[],i=document.createElement("div");i.className="bp-mgmt-head";let s=document.createElement("span");s.className="bp-dim",s.textContent=`${t.parts??0} parts · ${n.length} lines`;let a=document.createElement("span"),r=t.source==="kicad";if(a.className="bp-mgmt-pill"+(r?" accent":""),a.textContent=r?"live":"saved",i.append(s,a),(t.priced??0)>0&&(t.checking??0)===0&&typeof t.cost==="number"){let u=document.createElement("span");u.className="bp-dim",u.textContent=(t.priced??0)<(t.lookups??0)?`≥ ${ot(t.cost)}/board`:`${ot(t.cost)}/board`,i.appendChild(u)}if(t.paused){let u=document.createElement("span");u.className="bp-mgmt-faint",u.textContent="Stock check paused",i.appendChild(u)}if(e.appendChild(i),t.stock_note){let u=document.createElement("div");u.className="bp-mgmt-note bp-mgmt-faint",u.textContent=xe(t.stock_note),e.appendChild(u)}let o=this.bomEditingId?n.find((u)=>u.id===this.bomEditingId)??null:null;if(o)e.appendChild(this.renderBomEditor(o));else{let u=document.createElement("div");u.className="bp-mgmt-filter-row";let l=document.createElement("input");l.type="text",l.className="bp-mgmt-filter",l.placeholder="Filter BOM (ref, value, footprint, MPN, dnp)…",l.value=this.bomFilter,l.setAttribute("data-testid","mgmt-bom-filter"),l.addEventListener("input",()=>{this.bomFilter=l.value,this.renderBomRows(c,n)}),u.appendChild(l),e.appendChild(u)}let c=document.createElement("div");return c.className="bp-mgmt-rows",c.setAttribute("data-testid","mgmt-bom-rows"),this.renderBomRows(c,n),e.appendChild(c),e}renderBomRows(e,t){let n=zn(t,this.bomFilter);if(n.length===0){e.replaceChildren(this.makeEmpty(t.length===0?"No parts found.":"No matching lines."));return}let i=t.some((a)=>Boolean(a.mpn)||Boolean(a.fab)),s=document.createDocumentFragment();for(let a of n){let r=Array.isArray(a.refs)?a.refs:[],o=document.createElement("div");o.className="bp-mgmt-row"+(this.bomSelectedId===a.id?" active":"")+(a.dnp?" faint":""),o.setAttribute("data-testid",`mgmt-bom-row-${a.id}`);let c=document.createElement("div");c.className="bp-mgmt-row-line";let u=document.createElement("span");if(u.className="bp-mgmt-strong bp-mgmt-flex1",u.textContent=Tt(r,24),c.appendChild(u),a.dnp){let m=document.createElement("span");m.className="bp-mgmt-pill",m.textContent=b("gpui.mgmt.bom.dnp","DNP"),c.appendChild(m)}else{let m=Kn(a.stock);if(m){let h=document.createElement("span");h.className=`bp-tone-${m.tone}`,h.textContent=m.text,c.appendChild(h)}}let l=document.createElement("button");l.type="button",l.className="bp-mgmt-btn",l.textContent="Edit",l.addEventListener("click",(m)=>{m.stopPropagation(),this.bomEditGen++,this.bomEditingId=a.id,this.bomEditDraft=a.mpn??"",this.bomEditStatus="",this.bomLastUndo=null,this.render()}),c.appendChild(l);let p=document.createElement("div");p.className="bp-mgmt-row-sub";let d=[`${a.qty??r.length}×`,a.value??"",qn(a.footprint??"")].filter(Boolean).join(" · "),g=document.createElement("span");g.className="bp-dim",g.textContent=d;let y=document.createElement("span");if(y.className="bp-mgmt-flex1",a.mpn)y.textContent=a.mpn;else if(i&&!a.dnp)y.className+=" bp-tone-warn",y.textContent=b("gpui.mgmt.bom.nompn","no MPN");if(p.append(g,y),!a.dnp&&typeof a.stock?.price==="number"){let m=document.createElement("span");m.className="bp-dim",m.textContent=ot(a.stock.price),p.appendChild(m)}if(!a.dnp&&a.stock?.class){let m=document.createElement("span");m.className="bp-mgmt-faint",m.textContent=xe(a.stock.class),p.appendChild(m)}o.append(c,p),o.addEventListener("click",()=>{this.bomSelectedId=a.id,this.renderBomRows(e,t)}),s.appendChild(o)}e.replaceChildren(s)}renderBomEditor(e){let t=document.createElement("div");t.className="bp-mgmt-editor",t.setAttribute("data-testid","mgmt-bom-edit");let n=Array.isArray(e.refs)?e.refs:[],i=document.createElement("div");i.className="bp-mgmt-row-line";let s=document.createElement("span");s.className="bp-mgmt-strong",s.textContent=Tt(n,30);let a=document.createElement("button");a.type="button",a.className="icon",a.textContent="×",a.addEventListener("click",()=>{this.bomEditGen++,this.bomEditingId="",this.bomLastUndo=null,this.bomEditStatus="",this.render()}),i.append(s,a);let r=document.createElement("input");r.type="text",r.className="bp-mgmt-filter",r.placeholder="MPN",r.value=this.bomEditDraft,r.addEventListener("input",()=>{this.bomEditDraft=r.value});let o=()=>({watchGen:this.watchGen,editGen:this.bomEditGen,project:this.project,editId:this.bomEditingId}),c=async(d,g=!1)=>{let y=o();this.bomEditStatus="Writing…",this.render();try{let m=await this.cb.hub.rpc("mgmt.bom.edit",d);if(!Qt(y,o()))return;this.bomLastUndo=!g&&(m.changed??0)>0?{project:d.project,editId:y.editId,refs:d.refs.slice(),field:d.field,was:typeof m.was==="string"?m.was:d.field==="mpn"?e.mpn??"":e.dnp?"yes":"no"}:null,this.bomEditStatus=g?"Restored":(m.changed??0)===0?"No change":m.via==="kicad"?"Updated in KiCad":"Saved to schematic"}catch(m){if(!Qt(y,o()))return;this.bomEditStatus=m instanceof Error?m.message:"Could not save edit"}this.render()},u=document.createElement("div");u.className="bp-mgmt-btn-row";let l=document.createElement("button");l.type="button",l.className="primary bp-mgmt-btn",l.textContent="Save MPN",l.addEventListener("click",()=>{c({project:this.project,refs:n.slice(),field:"mpn",value:this.bomEditDraft.trim()})});let p=document.createElement("button");if(p.type="button",p.className="bp-mgmt-btn",p.textContent=e.dnp?"Clear DNP":"Mark DNP",p.addEventListener("click",()=>{c({project:this.project,refs:n.slice(),field:"dnp",value:e.dnp?"no":"yes"})}),u.append(l,p),this.bomLastUndo&&this.bomLastUndo.project===this.project&&this.bomLastUndo.editId===this.bomEditingId){let d=this.bomLastUndo,g=document.createElement("button");g.type="button",g.className="bp-mgmt-btn",g.textContent="Undo",g.addEventListener("click",()=>{c(ni(d),!0)}),u.appendChild(g)}if(t.append(i,r,u),this.bomEditStatus){let d=document.createElement("div");d.className="bp-mgmt-faint",d.textContent=this.bomEditStatus,t.appendChild(d)}return t}renderChecks(){let e=document.createElement("div");e.className="bp-mgmt-body";let t=this.getPanelData("checks");if(!t)return e.appendChild(this.makeEmpty("Reading checks…")),e;let n=Array.isArray(t.groups)?t.groups:[],i=Array.from(new Set(n.map((d)=>d.source).filter(Boolean))),s=(d)=>t.sources?.[d]?.label||d.toUpperCase(),a=(d)=>t.sources?.[d]?.judged===!0,r=document.createElement("div");r.className="bp-mgmt-head bp-mgmt-scroll-x";let o=document.createElement("button");o.type="button",o.className="bp-mgmt-btn"+(this.checksSource===""?" active":""),o.textContent=b("gpui.mgmt.checks.all","All"),o.addEventListener("click",()=>{this.checksSource="",this.render()}),r.appendChild(o);for(let d of i){let g=document.createElement("button");g.type="button",g.className="bp-mgmt-btn"+(this.checksSource===d?" active":""),g.textContent=s(d)+(a(d)?" · judged":""),g.addEventListener("click",()=>{this.checksSource=this.checksSource===d?"":d,this.render()}),r.appendChild(g)}let c=document.createElement("span");c.className="bp-mgmt-flex1";let u=document.createElement("button");if(u.type="button",u.className="bp-mgmt-btn",u.textContent=b("gpui.mgmt.checks.run","Run"),u.addEventListener("click",()=>{let d=this.watchGen,g=this.project;this.checksStatus="Running checks…",this.render(),this.cb.hub.rpc("kicad.checks.run",{project:g}).then(()=>{if(d!==this.watchGen||g!==this.project)return;this.checksStatus="",this.render()}).catch((y)=>{if(d!==this.watchGen||g!==this.project)return;this.checksStatus=y instanceof Error?y.message:"Could not run checks",this.render()})}),r.append(c,u),e.appendChild(r),this.checksStatus){let d=document.createElement("div");d.className="bp-mgmt-note bp-dim",d.textContent=this.checksStatus,e.appendChild(d)}let l=document.createElement("div");l.className="bp-mgmt-rows",l.setAttribute("data-testid","mgmt-checks-rows");let p=Jn(n,this.checksSource);if(p.length===0)l.appendChild(this.makeEmpty("No check findings."));else for(let d of p){let g=d.severity==="error"?"bad":d.severity==="warning"?"warn":"faint",y=document.createElement("div");y.className="bp-mgmt-group-head";let m=document.createElement("span");m.className=`bp-mgmt-dot bp-tone-bg-${g}`;let h=document.createElement("span");h.className="bp-mgmt-flex1",h.textContent=`${s(d.source)} · ${d.rule}`;let f=document.createElement("span");f.className=`bp-tone-${g}`,f.textContent=String(d.n),y.append(m,h,f),l.appendChild(y);for(let w of d.rows??[]){let C=document.createElement("div");C.className="bp-mgmt-row"+(this.checksSelectedId===w.id?" active":"");let L=document.createElement("div");if(L.textContent=xe(w.title??""),C.appendChild(L),w.names||this.checksSelectedId===w.id){let M=document.createElement("div");M.className="bp-mgmt-row-sub";let S=document.createElement("span");if(S.className="bp-dim bp-mgmt-flex1",S.textContent=w.names??"",M.appendChild(S),this.checksSelectedId===w.id){let T=document.createElement("button");T.type="button",T.className="bp-mgmt-btn accent",T.textContent=b("gpui.mgmt.checks.fix","Fix with agent"),T.addEventListener("click",(B)=>{B.stopPropagation();let R={watchGen:this.watchGen,project:this.project,threadId:this.cb.getThreadId(),threadGen:this.cb.getThreadGen()};this.cb.hub.rpc("kicad.checks.fix",{project:R.project,id:w.id}).then((G)=>{let D={watchGen:this.watchGen,project:this.project,threadId:this.cb.getThreadId(),threadGen:this.cb.getThreadGen()};if(!en(R,D))return;if(G.text)this.cb.onSendText(G.text),this.checksStatus="Sent to agent",this.render()}).catch((G)=>{let D={watchGen:this.watchGen,project:this.project,threadId:this.cb.getThreadId(),threadGen:this.cb.getThreadGen()};if(!en(R,D))return;this.checksStatus=G instanceof Error?G.message:"Could not send finding",this.render()})}),M.appendChild(T)}C.appendChild(M)}C.addEventListener("click",()=>{this.checksSelectedId=w.id,this.cb.hub.rpc("kicad.checks.focus",{project:this.project,id:w.id}).catch(()=>{}),this.render()}),l.appendChild(C)}}return e.appendChild(l),e}renderLife(){let e=document.createElement("div");e.className="bp-mgmt-body";let t=this.getPanelData("life");if(!t)return e.appendChild(this.makeEmpty("Reading lifecycle…")),e;let n=document.createElement("div");n.className="bp-mgmt-head";let i=t.counts??{};for(let c of["active","nrnd","eol"]){let u=i[c]??0,l=Zt(c),p=document.createElement("span");p.className=u>0?`bp-tone-${l.tone}`:"bp-mgmt-faint",p.textContent=`${l.label} ${u}`,n.appendChild(p)}if((i.unknown??0)>0){let c=document.createElement("span");c.className="bp-mgmt-faint",c.textContent=`${i.unknown} unknown`,n.appendChild(c)}if(t.since){let c=document.createElement("span");c.className="bp-mgmt-flex1";let u=document.createElement("span");u.className="bp-mgmt-faint",u.textContent=`since ${Bt(t.since)} (${t.samples??0})`,n.append(c,u)}e.appendChild(n);let s=document.createElement("div");s.className="bp-mgmt-rows",s.setAttribute("data-testid","mgmt-life-rows");let a=t.bom?.cost??[],r=t.bom?.instock??[],o=t.bom?.lines??0;if(a.length===0)s.appendChild(this.makeEmpty(o===0?"No line has an MPN or fab part number to follow yet.":"No reading of the fab's stock yet: the BOM panel's lookups start it."));else{let c=a[a.length-1],u=r[r.length-1],l=document.createElement("div");l.className="bp-mgmt-note bp-dim",l.textContent=`Parts/board: ${ot(c[1])} · ${Math.round(u?.[1]??0)}/${o} lines in stock (${Bt(c[0])})`,s.appendChild(l)}for(let c of t.parts??[]){let u=this.lifeSelectedKey===c.key,l=Zt(c.lifecycle??"unknown"),p=document.createElement("div");p.className="bp-mgmt-row"+(u?" active":"");let d=document.createElement("div");d.className="bp-mgmt-row-line";let g=document.createElement("span");g.className="bp-mgmt-strong",g.textContent=Tt(c.refs??[],14);let y=document.createElement("span");y.className="bp-mgmt-flex1 bp-dim",y.textContent=c.mpn||c.key;let m=document.createElement("span");if(m.className=`bp-tone-${l.tone}`,m.textContent=l.label,d.append(g,y,m),typeof c.stock==="number"){let h=document.createElement("span");h.className="bp-dim",h.textContent=rt(c.stock),d.appendChild(h)}if(p.appendChild(d),u){let h=document.createElement("div");if(h.className="bp-mgmt-row-sub bp-mgmt-faint",this.lifePartLoading)h.textContent=b("gpui.mgmt.life.reading","Reading its history…");else if(this.lifePartSamples&&this.lifePartSamples.length>0){let f=this.lifePartSamples[this.lifePartSamples.length-1];h.textContent=`${this.lifePartSamples.length} samples · latest ${f.at?Bt(f.at):""}`+(typeof f.stock==="number"?` · stock ${rt(f.stock)}`:"")+(typeof f.price==="number"?` · ${ot(f.price)}`:"")}else h.textContent=b("gpui.mgmt.life.nopart","No reading of this part yet.");p.appendChild(h)}p.addEventListener("click",()=>{if(this.lifeSelectedKey===c.key){this.lifeSelectedKey="",this.lifePartSamples=null,this.render();return}this.lifeSelectedKey=c.key,this.lifePartSamples=null,this.lifePartLoading=!0,this.render(),this.cb.hub.rpc("mgmt.life.part",{project:this.project,key:c.key}).then((h)=>{if(this.lifeSelectedKey!==c.key)return;this.lifePartLoading=!1,this.lifePartSamples=Array.isArray(h.samples)?h.samples:[],this.render()}).catch(()=>{if(this.lifeSelectedKey!==c.key)return;this.lifePartLoading=!1,this.lifePartSamples=[],this.render()})}),s.appendChild(p)}return e.appendChild(s),e}renderPlan(){let e=document.createElement("div");e.className="bp-mgmt-body";let t=this.getPanelData("plan");if(!t)return e.appendChild(this.makeEmpty(b("gpui.mgmt.plan.reading","Reading the routing plan…"))),e;let n=(E,k)=>{let j=this.watchGen,A=this.project;this.planStatus="",this.cb.hub.rpc(E,{pro:A,...k}).catch((K)=>{if(j!==this.watchGen||A!==this.project)return;this.planOptimistic.clear(),this.planStatus=K instanceof Error?K.message:b("gpui.mgmt.plan.refused","KiCad refused"),this.render()})};if(t.revision!==this.planOptimisticRev)this.planOptimisticRev=t.revision,this.planOptimistic.clear();let i=`${this.project}:${t.revision??0}`;if(t.board_trimmed&&this.planHydrateAskedKey!==i&&this.project){this.planHydrateAskedKey=i;let E=this.watchGen,k=++this.planHydrateGen,j=this.project,A=t.revision??0;this.cb.hub.rpc("plan.get",{pro:j,board:!0}).then((K)=>{let ee=mi(K);if(!ee)return;let F=typeof ee.revision==="number"?ee.revision:A;if(!ui(E,this.watchGen,k,this.planHydrateGen,j,this.project,F,this.planHydratedRev))return;this.planHydratedRev=F,this.planHydratedKey=`${j}:${F}`,this.planHydratedBoard=ee.board??null,this.planHydratedDraw=ee.draw??null,this.render()}).catch(()=>{})}let s=t.on===!0,a=document.createElement("div");a.className="bp-plan-header";let r=document.createElement("div");r.className="bp-plan-toggle";let o=document.createElement("span");o.className="bp-mgmt-strong",o.textContent=b("gpui.mgmt.plan.before","Plan before routing"),o.title=s?b("gpui.mgmt.plan.onwords","Before routing a board with 4 or more copper layers or more than 60 nets, the agent proposes corridors and plane regions here. It routes only what you approve."):b("gpui.mgmt.plan.offwords","Agents route as you ask. Turn it on to have them propose a routing plan first and route only what you approve here."),r.appendChild(o);let c=t.awaiting??0,u=t.blocked??0,l=t.done??0,p=t.total??0,d=t.revision??0,g=t.empty?[]:Qn(t),y=g.reduce((E,k)=>E+k.count,0);if(!t.empty){let E=Zn(t),k=document.createElement("span");if(k.className=`bp-plan-status-badge tone-${E.tone}`,k.textContent=b(E.key,E.label),r.appendChild(k),d>0){let A=document.createElement("span");A.className="bp-dim",A.textContent=`v${d}`,r.appendChild(A)}let j=document.createElement("span");if(j.className="bp-plan-header-counts bp-mgmt-flex1 "+(c>0?"bp-tone-warn":u>0?"bp-tone-bad":"bp-dim"),j.textContent=p>0?`${l}/${p} ${b("gpui.mgmt.plan.done","done")}`:c>0?b("web.plan.awaiting","{n} awaiting approval",{n:c}):b("gpui.mgmt.plan.nothing","Nothing awaits your approval"),r.appendChild(j),!t.live){let A=document.createElement("span");A.className="bp-mgmt-pill",A.textContent=b("gpui.mgmt.plan.saved","saved plan"),r.appendChild(A)}}else{let E=document.createElement("span");E.className="bp-mgmt-flex1",r.appendChild(E)}let m=document.createElement("button");m.type="button",m.className="bp-mgmt-btn bp-plan-chip-btn"+(s?" active":""),m.setAttribute("data-testid","mgmt-plan-on"),m.setAttribute("aria-pressed",s?"true":"false"),m.textContent=b("gpui.bots.recall.on","On"),m.addEventListener("click",()=>n("plan.enable",{on:!0}));let h=document.createElement("button");if(h.type="button",h.className="bp-mgmt-btn bp-plan-chip-btn"+(!s?" active":""),h.setAttribute("data-testid","mgmt-plan-off"),h.setAttribute("aria-pressed",!s?"true":"false"),h.textContent=b("gpui.bots.recall.off","Off"),h.addEventListener("click",()=>n("plan.enable",{on:!1})),r.append(m,h),a.appendChild(r),y>0){let E=document.createElement("div");E.className="bp-plan-segbar";for(let k of g){if(k.count<=0)continue;let j=document.createElement("div");j.className=`bp-plan-seg bp-tone-bg-${k.tone}`,j.style.flexGrow=String(k.count),E.appendChild(j)}a.appendChild(E)}e.appendChild(a);for(let E of t.elsewhere??[]){let k=document.createElement("div");k.className="bp-plan-elsewhere";let j=document.createElement("span");j.className="bp-tone-warn bp-mgmt-flex1",j.textContent=b("gpui.mgmt.plan.elsewhere","A routing plan for {board} awaits your approval",{board:E.name||E.rel||""}),k.appendChild(j),e.appendChild(k)}if(t.empty){let E=document.createElement("div");E.className="bp-mgmt-note";let k=document.createElement("div");k.className="bp-dim",k.textContent=b("gpui.mgmt.plan.noboard","No routing plan for this board.");let j=document.createElement("div");return j.className="bp-mgmt-faint",j.textContent=b("gpui.mgmt.plan.emptysub","Layers, corridors, and planes appear here once a plan is proposed."),E.append(k,j),e.appendChild(E),e}let f=t.stackup_summary??"",w=Array.isArray(t.impedances)?t.impedances:[],C=Boolean(f)||w.length>0,L=document.createElement("div");if(L.className="bp-mgmt-head",c>0){let E=document.createElement("button");E.type="button",E.className="primary bp-mgmt-btn",E.setAttribute("data-testid","mgmt-plan-approve-all"),E.textContent=b("gpui.mgmt.plan.all","Approve all"),E.addEventListener("click",()=>n("plan.approve",{layer:"",ids:[],approve:!0})),L.appendChild(E)}if(t.routing){let E=document.createElement("button");E.type="button",E.className="bp-mgmt-btn",E.setAttribute("data-testid","mgmt-plan-stop"),E.textContent=b("gpui.mgmt.plan.stop","Stop routing"),E.addEventListener("click",()=>n("plan.stop",{})),L.appendChild(E)}if(t.live&&l>0){let E=document.createElement("button");E.type="button",E.className="bp-mgmt-btn",E.setAttribute("data-testid","mgmt-plan-verify"),E.textContent=b("gpui.mgmt.plan.verify","Verify"),E.addEventListener("click",()=>n("plan.verify",{})),L.appendChild(E)}let M=document.createElement("span");if(M.className="bp-mgmt-flex1",L.appendChild(M),C){let E=document.createElement("button");E.type="button",E.className="bp-mgmt-btn bp-plan-chip-btn"+(this.planStackupOpen?" active":""),E.setAttribute("data-testid","mgmt-plan-stackup-toggle"),E.setAttribute("aria-expanded",this.planStackupOpen?"true":"false"),E.textContent=`${b("gpui.mgmt.plan.stackup.short","Stackup")} ${this.planStackupOpen?"▾":"▸"}`,E.addEventListener("click",()=>{this.planStackupOpen=!this.planStackupOpen,this.render()}),L.appendChild(E)}let S=document.createElement("button");S.type="button",S.className="bp-mgmt-btn",S.setAttribute("data-testid","mgmt-plan-hide"),S.textContent=this.planHideDone?b("gpui.mgmt.plan.show","Show done"):b("gpui.mgmt.plan.hide","Hide done"),S.addEventListener("click",()=>{this.planHideDone=!this.planHideDone,this.render()}),L.appendChild(S),e.appendChild(L);let T=Array.isArray(t.asks)?t.asks:[];if(T.length>0){let E=T.map((ee)=>ee.what||"").filter(Boolean).join(", "),k=T[0]?.note||"",j=document.createElement("div");j.className="bp-plan-elsewhere";let A=document.createElement("div");A.className="bp-plan-ask-col";let K=document.createElement("div");if(K.className="bp-tone-warn",K.textContent=E?b("gpui.mgmt.plan.requested","Approval requested: {what}",{what:E}):b("gpui.mgmt.plan.reqplain","Approval requested"),A.appendChild(K),k){let ee=document.createElement("div");ee.className="bp-dim",ee.textContent=k,A.appendChild(ee)}j.appendChild(A),e.appendChild(j)}if(this.planStatus){let E=document.createElement("div");E.className="bp-mgmt-note bp-plan-err bp-tone-bad";let k=document.createElement("span");k.className="bp-mgmt-flex1",k.textContent=this.planStatus==="KiCad refused"?b("gpui.mgmt.plan.refused","KiCad refused"):xe(this.planStatus);let j=document.createElement("button");j.type="button",j.className="icon",j.textContent="×",j.title=b("common.close","Close"),j.addEventListener("click",()=>{this.planStatus="",this.render()}),E.append(k,j),e.appendChild(E)}if(t.keys_note){let E=document.createElement("div");E.className="bp-mgmt-note bp-dim";let k="On this KiCad version, approve from this panel: in plan view KiCad's A, R and W keys aren't the plan's yet (A opens Add Footprint). Update KiCad.";E.textContent=t.keys_note===k?b("gpui.mgmt.plan.keysnote",k):xe(t.keys_note),e.appendChild(E)}if(C&&this.planStackupOpen){let E=document.createElement("div");if(E.className="bp-plan-stackup-body",E.setAttribute("data-testid","mgmt-plan-stackup-body"),f){let k=document.createElement("div");k.className="bp-dim",k.textContent=f,E.appendChild(k)}for(let k of w){let j=document.createElement("div");j.className="bp-mgmt-faint",j.textContent=`· ${k}`,E.appendChild(j)}e.appendChild(E)}let B=(E,k,j,A)=>{let K=document.createElement("button");return K.type="button",K.className="bp-mgmt-btn bp-plan-chip-btn"+(k?" active":""),K.setAttribute("data-testid",j),K.setAttribute("aria-pressed",k?"true":"false"),K.textContent=E,K.addEventListener("click",A),K},R=document.createElement("div");if(R.className="bp-plan-viewbar",R.append(B(b("gpui.mgmt.plan.view.canvas","Canvas"),this.planViewMode==="canvas","mgmt-plan-view-canvas",()=>{this.planViewMode="canvas",this.render()}),B(b("gpui.mgmt.plan.view.split","Split"),this.planViewMode==="split","mgmt-plan-view-split",()=>{this.planViewMode="split",this.render()}),B(b("gpui.mgmt.plan.view.list","List"),this.planViewMode==="list","mgmt-plan-view-list",()=>{this.planViewMode="list",this.render()})),this.planViewMode!=="list"){let E=document.createElement("span");E.className="bp-plan-sep";let k=document.createElement("span");k.className="bp-plan-sep";let j=document.createElement("button");j.type="button",j.className="bp-mgmt-btn bp-plan-mini-btn",j.setAttribute("data-testid","mgmt-plan-fit"),j.textContent=b("gpui.mgmt.plan.fit","Fit"),j.addEventListener("click",()=>this.planCanvas?.fitAll()),R.append(E,B(b("gpui.mgmt.plan.grid.pair","Side by side"),this.planGridMode==="pair","mgmt-plan-grid-pair",()=>{this.planGridMode="pair",this.render()}),B(b("gpui.mgmt.plan.grid.all","All layers"),this.planGridMode==="all","mgmt-plan-grid-all",()=>{this.planGridMode="all",this.render()}),B(b("gpui.mgmt.plan.grid.single","Single"),this.planGridMode==="single","mgmt-plan-grid-single",()=>{this.planGridMode="single",this.render()}),k,B(b("gpui.mgmt.plan.sync","Link zoom"),this.planSyncZoom,"mgmt-plan-sync",()=>{this.planSyncZoom=!this.planSyncZoom,this.render()}),j)}let G=document.createElement("span");G.className="bp-mgmt-flex1";let D=document.createElement("button");D.type="button",D.className="bp-mgmt-btn bp-plan-mini-btn",D.setAttribute("data-testid","mgmt-plan-expand"),D.textContent=this.planExpanded?b("gpui.mgmt.plan.compact","Compact"):b("gpui.mgmt.plan.expand","Expand"),D.addEventListener("click",()=>{this.planExpanded=!this.planExpanded,this.render()}),R.append(G,D),e.appendChild(R);let re=Boolean(this.planHydratedBoard)&&this.planHydratedKey.startsWith(`${this.project}:`)&&(this.planHydratedKey===i||this.planHydratedRev!==void 0&&this.planHydratedRev>=(t.revision??0)),me=re&&this.planHydratedBoard?this.planHydratedBoard:t.board??{bbox:[0,0,100,70],outline:[],parts:[]},le=re&&this.planHydratedDraw?this.planHydratedDraw:t.draw??{bands:[],regions:[]},we=(le.bands??[]).map((E)=>{let k=this.planOptimistic.get(E.id);if(!k)return{...E};return{...E,...k,edited:!0,state:E.state==="proposed"?"edited":E.state}}),Se=(le.regions??[]).map((E)=>{let k=this.planOptimistic.get(E.id);if(!k)return{...E};return{...E,...k,edited:!0,state:E.state==="proposed"?"edited":E.state}}),Pe=[],he=(t.layers??[]).map((E)=>{let k=[];for(let j of E.items??[]){let A=this.planOptimistic.get(j.id);if(!A){k.push(j);continue}let K={...j,width:typeof A.width==="number"?A.width:j.width,locked:typeof A.locked==="boolean"?A.locked:j.locked,edited:!0,state:j.state==="proposed"?"edited":j.state};if(typeof A.layer==="string"&&A.layer!==E.layer)Pe.push({target:A.layer,item:K});else k.push(K)}return{...E,items:k}});for(let E of Pe){let k=he.find((j)=>j.layer===E.target);if(k)k.items=[...k.items??[],E.item]}let be=jt(he,t.copper_layers),I=this.planGridMode==="all"?be.map((E)=>E.layer):this.planGridMode==="single"?[this.planShownLayers.find((E)=>be.some((k)=>k.layer===E))??ct(be)[0]??be[0]?.layer??""].filter(Boolean):this.planShownLayers.length>0&&this.planShownLayers.every((E)=>be.some((k)=>k.layer===E))?this.planShownLayers.slice(0,2):ct(be);if(this.planViewMode!=="list"&&this.planGridMode!=="all"&&be.length>1){let E=document.createElement("div");E.className="bp-plan-layerbar";for(let k of be){let j=I.includes(k.layer),A=(k.items??[]).length,K=st(k.layer,t.copper_layers,be)||k.title||k.layer,ee=A>0?`${K} · ${A}`:K,F=B(ee,j,`mgmt-plan-layerpill-${k.layer}`,()=>{if(this.planGridMode==="single")this.planShownLayers=[k.layer];else if(this.planGridMode==="pair"){if(!I.includes(k.layer))this.planShownLayers=I.length>=2?[I[0],k.layer]:[...I,k.layer]}else this.planGridMode="single",this.planShownLayers=[k.layer];this.render()});if(A===0&&!j)F.classList.add("empty-layer");E.appendChild(F)}e.appendChild(E)}let ce=(E,k)=>{let j=this.planOptimistic.get(E)??{};if(this.planOptimistic.set(E,{...j,...k}),typeof k.layer==="string"){if(this.planGridMode==="single")this.planShownLayers=[k.layer];else if(this.planGridMode==="pair"&&!I.includes(k.layer))this.planShownLayers=I.length>=2?[I[0],k.layer]:[...I,k.layer]}let A=typeof t.revision==="number"?t.revision:void 0;this.render(),n("plan.update",{ops:[{op:"set",id:E,fields:k}],...A!==void 0?{base:A}:{}})};if(this.planCommitFields=ce,this.planSelectedId){let E="",k=null;for(let j of he){let A=(j.items??[]).find((K)=>K.id===this.planSelectedId);if(A){E=j.layer,k=A;break}}if(k){let j=st(E,t.copper_layers,be),A=document.createElement("div");A.className="bp-plan-inspector",A.setAttribute("data-testid","mgmt-plan-inspector");let K=document.createElement("div");K.className="bp-plan-ins-row";let ee=document.createElement("span");ee.className="bp-plan-ins-sw",ee.style.background=k.kind==="corridor"?lt(k.name||k.id,k.color||""):yt(k.name||k.id,k.color||"");let F=document.createElement("span");F.className="bp-mgmt-strong",F.textContent=k.name||k.id;let z=document.createElement("span");if(z.className="bp-dim",z.textContent=j,K.append(ee,F,z),k.edited||k.state==="edited"){let Y=document.createElement("span");Y.className="bp-plan-ins-pill warn",Y.textContent=b("gpui.mgmt.plan.edited","Edited"),K.appendChild(Y)}if(k.locked){let Y=document.createElement("span");Y.className="bp-plan-ins-pill",Y.textContent=b("gpui.mgmt.plan.locked","Locked"),K.appendChild(Y)}let Re=document.createElement("span");Re.className="bp-mgmt-flex1",K.appendChild(Re);let Ae=document.createElement("button");if(Ae.type="button",Ae.className="bp-mgmt-btn bp-plan-mini-btn",Ae.setAttribute("data-testid","mgmt-plan-lock"),Ae.textContent=k.locked?b("gpui.mgmt.plan.unlock","Unlock"):b("gpui.mgmt.plan.lock","Lock"),Ae.addEventListener("click",()=>ce(k.id,{locked:!k.locked})),K.appendChild(Ae),k.state==="proposed"||k.state==="edited"){let Y=document.createElement("button");Y.type="button",Y.className="primary bp-mgmt-btn bp-plan-mini-btn",Y.textContent=b("android.hub.machines.approve","Approve"),Y.addEventListener("click",()=>n("plan.approve",{layer:"",ids:[k.id],approve:!0}));let ge=document.createElement("button");ge.type="button",ge.className="bp-mgmt-btn bp-plan-mini-btn",ge.textContent=b("gpui.mgmt.plan.reject","Reject"),ge.addEventListener("click",()=>n("plan.approve",{layer:"",ids:[k.id],approve:!1})),K.append(Y,ge)}let pe=document.createElement("button");pe.type="button",pe.className="bp-mgmt-btn bp-plan-mini-btn",pe.setAttribute("data-testid","mgmt-plan-note-toggle"),pe.textContent=b("gpui.mgmt.plan.addnote","Add note"),pe.addEventListener("click",()=>{this.planNoteOpen=!this.planNoteOpen,this.render()});let Ne=document.createElement("button");if(Ne.type="button",Ne.className="icon",Ne.textContent="×",Ne.addEventListener("click",()=>{this.planSelectedId="",this.planNoteOpen=!1,this.planMoveLayerOpen=!1,this.render()}),K.append(pe,Ne),A.appendChild(K),!k.locked){let Y=document.createElement("div");if(Y.className="bp-plan-ins-row",k.kind==="corridor"){let ie=typeof k.width==="number"?k.width:1.5,ke=document.createElement("span");ke.className="bp-dim",ke.textContent=b("gpui.mgmt.plan.width","Width");let je=document.createElement("button");je.type="button",je.className="bp-mgmt-btn bp-plan-mini-btn",je.setAttribute("data-testid","mgmt-plan-w-down"),je.textContent="-",je.addEventListener("click",()=>{let Ve=Math.round(Math.max(0.15,ie-0.25)*100)/100;ce(k.id,{width:Ve})});let ae=document.createElement("span");ae.className="bp-plan-ins-val",ae.textContent=`${ie.toFixed(2)}mm`;let fe=document.createElement("button");fe.type="button",fe.className="bp-mgmt-btn bp-plan-mini-btn",fe.setAttribute("data-testid","mgmt-plan-w-up"),fe.textContent="+",fe.addEventListener("click",()=>{let Ve=Math.round(Math.min(25,ie+0.25)*100)/100;ce(k.id,{width:Ve})});let _e=document.createElement("span");_e.className="bp-plan-sep",Y.append(ke,je,ae,fe,_e)}let ge=(t.copper_layers??[]).length>0?(t.copper_layers??[]).map((ie)=>ie.layer):he.map((ie)=>ie.layer);if(ge.length>0){let ie=document.createElement("span");ie.className="bp-dim",ie.textContent=b("gpui.mgmt.plan.layer.short","Layer"),Y.appendChild(ie),Y.appendChild(B(`${j} ${this.planMoveLayerOpen?"▴":"▾"}`,this.planMoveLayerOpen,"mgmt-plan-move-toggle",()=>{this.planMoveLayerOpen=!this.planMoveLayerOpen,this.render()}))}if(A.appendChild(Y),this.planMoveLayerOpen&&ge.length>0){let ie=document.createElement("div");ie.className="bp-plan-ins-row";for(let ke of ge){let je=st(ke,t.copper_layers,be);ie.appendChild(B(je,ke===E,`mgmt-plan-move-${ke}`,()=>{if(this.planMoveLayerOpen=!1,ke!==E)ce(k.id,{layer:ke});else this.render()}))}A.appendChild(ie)}}if(this.planNoteOpen){let Y=document.createElement("form");Y.className="bp-plan-note-form";let ge=document.createElement("input");ge.type="text",ge.className="bp-plan-note-input",ge.setAttribute("data-testid","mgmt-plan-note-input"),ge.placeholder=b("gpui.mgmt.plan.note.placeholder","Steering note for router…");let ie=document.createElement("button");ie.type="submit",ie.className="primary bp-mgmt-btn bp-plan-mini-btn",ie.setAttribute("data-testid","mgmt-plan-note-submit"),ie.textContent=b("gpui.mgmt.plan.addnote","Add note"),Y.append(ge,ie),Y.addEventListener("submit",(ke)=>{ke.preventDefault();let je=ge.value.trim();if(!je)return;ge.value="",this.planNoteOpen=!1;let ae=typeof t.revision==="number"?t.revision:void 0;this.render(),n("plan.update",{ops:[{op:"note",target:k.id,text:je}],...ae!==void 0?{base:ae}:{}})}),A.appendChild(Y)}if(this.planViewMode!=="list"&&!k.locked){let Y=document.createElement("div");Y.className="bp-plan-hint",Y.textContent=b("gpui.mgmt.plan.hint","Drag waypoints to steer · Click + on edge to insert · Right-click vertex to remove"),A.appendChild(Y)}e.appendChild(A)}}let ne=document.createElement("div");ne.className="bp-mgmt-rows"+(this.planViewMode==="split"?" bp-plan-split-list":""),ne.setAttribute("data-testid","mgmt-plan-rows");let X=b("gpui.mgmt.plan.done","done"),de=li(this.planViewMode,he,I);if(this.planViewMode==="split"&&de.length===0){let E=document.createElement("div");E.className="bp-dim",E.style.padding="6px 8px",E.style.fontSize="11px",E.textContent=b("gpui.mgmt.plan.noitems","No corridors or planes on this layer"),ne.appendChild(E)}for(let E of de){let k=E.items??[],j=st(E.layer,t.copper_layers,be)||E.layer;if(this.planViewMode==="split"){if(de.length>1){let A=document.createElement("div");A.className="bp-plan-split-divider";let K=E.role==="power"||E.role==="plane",ee=document.createElement("span");ee.className="bp-plan-card-bar "+(K?"pwr":"sig");let F=document.createElement("span");F.className="bp-mgmt-strong",F.textContent=j;let z=document.createElement("span");z.className="bp-dim",z.textContent=`${E.done??0}/${k.length} ${X}`,A.append(ee,F,z),ne.appendChild(A)}}else{let A=document.createElement("div");A.className="bp-mgmt-group-head bp-plan-layer-head";let K=document.createElement("div");K.className="bp-mgmt-row-line";let ee=document.createElement("span");ee.className="bp-mgmt-strong",ee.textContent=j;let F=document.createElement("span");if(F.className="bp-dim bp-mgmt-flex1",F.textContent=`${E.role?`${E.role} · `:""}${E.done??0}/${k.length} ${X}`,K.append(ee,F),E.status!=="approved"&&k.length>0){let z=document.createElement("button");z.type="button",z.className="bp-mgmt-btn",z.textContent=b("gpui.mgmt.plan.layer","Approve layer"),z.addEventListener("click",()=>n("plan.approve",{layer:E.layer,ids:[],approve:!0}));let Re=document.createElement("button");Re.type="button",Re.className="bp-mgmt-btn",Re.textContent=b("gpui.mgmt.plan.reject","Reject"),Re.addEventListener("click",()=>n("plan.approve",{layer:E.layer,ids:[],approve:!1})),K.append(z,Re)}if(A.appendChild(K),E.stackup){let z=document.createElement("div");z.className="bp-plan-layer-stackup",z.textContent=E.stackup,A.appendChild(z)}ne.appendChild(A)}for(let A of k){if(this.planHideDone&&Yn(A))continue;let K=this.planSelectedId===A.id,ee=document.createElement("div");ee.className="bp-mgmt-row bp-plan-row"+(K?" active":""),ee.setAttribute("data-testid",`mgmt-plan-row-${A.id}`);let F=document.createElement("div");F.className="bp-mgmt-row-line";let z=document.createElement("span");z.className=`bp-plan-swatch bp-plan-st-${A.state||"proposed"}`,z.style.setProperty("--swatch-color",A.color||"#8a8a8a");let Re=document.createElement("span");Re.className="bp-mgmt-flex1"+(A.state==="blocked"||A.state==="failed"?" bp-tone-bad":A.state==="edited"?" bp-tone-warn":A.state==="rejected"||A.state==="routed"||A.state==="verified"?" bp-dim":""),Re.textContent=`${A.name||A.id}${A.locked?" \uD83D\uDD12":""}`;let Ae=[];if(A.kind==="plane"){if(A.reference)Ae.push(b("gpui.mgmt.plan.reference","over {layer}",{layer:A.reference}))}else{let Y=A.nets??0;Ae.push(Y===1?b("web.plan.net.one","1 net"):b("web.plan.nets","{n} nets",{n:Y}))}if(typeof A.width==="number"&&Number.isFinite(A.width))Ae.push(`${A.width.toFixed(2)}mm`);if(A.impedance)Ae.push(A.impedance);let pe=Ae.join(" · "),Ne=document.createElement("span");if(Ne.className="bp-plan-mark "+(A.state==="blocked"||A.state==="failed"?"bp-tone-bad":A.state==="verified"||A.state==="routed"?"bp-tone-ok":A.state==="approved"?"bp-tone-accent":"bp-dim"),Ne.textContent=Xn(A),F.append(z,Re,Ne),A.state==="proposed"||A.state==="edited"){let Y=document.createElement("button");Y.type="button",Y.className="bp-mgmt-btn",Y.textContent="✓",Y.title=b("gpui.mgmt.plan.layer","Approve layer"),Y.addEventListener("click",(ie)=>{ie.stopPropagation(),n("plan.approve",{layer:"",ids:[A.id],approve:!0})});let ge=document.createElement("button");ge.type="button",ge.className="bp-mgmt-btn",ge.textContent="✗",ge.title=b("gpui.mgmt.plan.reject","Reject"),ge.addEventListener("click",(ie)=>{ie.stopPropagation(),n("plan.approve",{layer:"",ids:[A.id],approve:!1})}),F.append(Y,ge)}if(ee.appendChild(F),pe){let Y=document.createElement("div");Y.className="bp-mgmt-row-sub bp-plan-detail bp-dim",Y.textContent=pe,ee.appendChild(Y)}if(A.state==="routing"&&typeof A.total==="number"&&A.total>0){let Y=document.createElement("div");Y.className="bp-plan-microbar";let ge=document.createElement("div");ge.className="bp-plan-microbar-fill";let ie=Math.max(0,Math.min(100,Math.round((A.routed??0)/A.total*100)));ge.style.width=`${ie}%`,Y.appendChild(ge),ee.appendChild(Y)}if(A.problem_text){let Y=document.createElement("div");Y.className="bp-plan-problem",Y.textContent=A.problem_text,ee.appendChild(Y)}ee.addEventListener("click",()=>{this.planSelectedId=A.id,n("plan.focus",{id:A.id}),this.render()}),ne.appendChild(ee)}}if(this.planViewMode!=="list"){if(!this.planCanvas)this.planCanvas=new sn({onSelect:(A)=>{if(this.planSelectedId=A,!A)this.planNoteOpen=!1;this.render()},onFocusItem:(A)=>{n("plan.focus",{id:A})},onDragEnd:()=>{if(this.planRenderDeferred)this.planRenderDeferred=!1,this.render()},onCommitFields:(A,K)=>{(this.planCommitFields??ce)(A,K)},onApproveLayer:(A,K)=>{n("plan.approve",{layer:A,ids:[],approve:K})},onQuickApprove:(A,K)=>{n("plan.approve",{layer:"",ids:A,approve:K})}});let E=this.panelEl.parentElement?.classList.contains("bp-has-viewer")===!1,k=this.planExpanded||this.panelEl.clientWidth>=540||E;this.planCanvas.update({gridMode:this.planGridMode,syncZoom:this.planSyncZoom,shownLayers:I,selectedId:this.planSelectedId,board:me,bands:we,regions:Se,layers:be,copperLayers:t.copper_layers},k);let j=document.createElement("div");j.className="bp-plan-canvas-scroll",j.appendChild(this.planCanvas.root),e.appendChild(j)}if(this.planViewMode!=="canvas")e.appendChild(ne);if((t.draw?.bands?.length??0)>0||(t.draw?.regions?.length??0)>0){let E=document.createElement("div");E.className="bp-plan-footer",E.textContent=b("gpui.mgmt.plan.drawn","The plan's corridors and planes are drawn on the board while this panel is open. Close it to hide them."),e.appendChild(E)}return e}renderFab(){let e=document.createElement("div");e.className="bp-mgmt-body";let t=this.getPanelData("fab");if(!t)return e.appendChild(this.makeEmpty("Reading the fab's profile…")),e;if(t.error){let w=document.createElement("div");return w.className="bp-mgmt-note bp-tone-warn",w.textContent=t.error,e.appendChild(w),e}let n=(w,C={})=>{let L=this.watchGen,M=this.project;this.fabStatus="",this.cb.hub.rpc("fab.profile",{pro:M,action:w,...C}).catch((S)=>{if(L!==this.watchGen||M!==this.project)return;this.fabStatus=S instanceof Error?S.message:"Fab action failed",this.render()})},i=document.createElement("div");i.className="bp-mgmt-head";let s=document.createElement("span");s.className="bp-mgmt-strong",s.textContent=b("gpui.mgmt.fab.thefab","The fab");let a=document.createElement("span");a.className="bp-dim bp-mgmt-flex1",a.textContent=`rev ${t.rev??0}${t.updated?` · ${t.updated}`:""}${t.board?` · ${t.board}`:""} · ${ti(t.tier??"")}`;let r=document.createElement("button");if(r.type="button",r.className="bp-mgmt-btn",r.textContent=b("gpui.mgmt.fab.refresh","Refresh"),r.addEventListener("click",()=>n("refresh")),i.append(s,a,r),e.appendChild(i),this.fabStatus){let w=document.createElement("div");w.className="bp-mgmt-note bp-tone-bad",w.textContent=this.fabStatus,e.appendChild(w)}let o=document.createElement("div");o.className="bp-mgmt-rows",o.setAttribute("data-testid","mgmt-fab-rows");let c=t.review,u=document.createElement("div");u.className="bp-mgmt-row";let l=document.createElement("div");l.className="bp-mgmt-row-line";let p=document.createElement("span"),d=(c?.counts?.error??0)>0;if(p.className="bp-mgmt-flex1 "+(d?"bp-tone-bad":"bp-dim"),p.textContent=c?.running?"Reviewing the design…":c?.at==null?"No design review yet":`${c.counts?.error??0} must-fix · ${c.counts?.warning??0} should-fix · ${c.counts?.info??0} notes${c.scope?` (${c.scope})`:""}`,l.appendChild(p),c?.at!=null){let w=document.createElement("button");w.type="button",w.className="bp-mgmt-btn",w.textContent=b("gpui.mgmt.fab.findings","Findings"),w.addEventListener("click",()=>this.togglePanel("checks")),l.appendChild(w)}if(!c?.running){let w=document.createElement("button");w.type="button",w.className="bp-mgmt-btn",w.textContent=b("gpui.mgmt.fab.reviewbtn","Review"),w.addEventListener("click",()=>n("review")),l.appendChild(w)}if(c?.judge){let w=document.createElement("button");w.type="button",w.className="bp-mgmt-btn",w.textContent=b("gpui.mgmt.fab.judge","Datasheets"),w.addEventListener("click",()=>{if(c.judge)this.cb.onSendText(c.judge)}),l.appendChild(w)}u.appendChild(l),o.appendChild(u);let g=ei(t.drc?.state??""),y=document.createElement("div");y.className="bp-mgmt-row";let m=document.createElement("div");m.className="bp-mgmt-row-line";let h=document.createElement("span");if(h.className="bp-mgmt-flex1 "+(g.button?"bp-tone-warn":"bp-dim"),h.textContent=g.text,m.appendChild(h),g.button){let w=document.createElement("button");w.type="button",w.className="bp-mgmt-btn",w.textContent=g.button,w.addEventListener("click",()=>n("drc")),m.appendChild(w)}y.appendChild(m),o.appendChild(y);for(let w of t.conflicts??[]){let C=document.createElement("div");C.className="bp-mgmt-row bp-tone-bad",C.textContent=w,o.appendChild(C)}for(let w of t.suggestions??[]){let C=document.createElement("div");C.className="bp-mgmt-row";let 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=`${w.label||w.key}: board ${w.project??"?"} mm, fab ${w.fab??"?"} mm`;let S=document.createElement("button");S.type="button",S.className="bp-mgmt-btn",S.textContent=b("gpui.mgmt.fab.apply","Apply"),S.addEventListener("click",()=>n("apply",{key:w.key})),L.append(M,S),C.appendChild(L),o.appendChild(C)}if(t.stackup?.chosen){let w=document.createElement("div");w.className="bp-mgmt-row";let C=document.createElement("div");C.className="bp-mgmt-row-line";let 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)`:""}`,C.appendChild(M),L){let S=t.stackup.chosen,T=document.createElement("button");T.type="button",T.className="bp-mgmt-btn",T.textContent=b("gpui.mgmt.fab.use","Use"),T.addEventListener("click",()=>n("stackup",{id:S})),C.appendChild(T)}w.appendChild(C),o.appendChild(w)}if(Array.isArray(t.changed)&&t.changed.length>0){let w=document.createElement("div");w.className="bp-mgmt-row";let C=document.createElement("div");C.className="bp-mgmt-row-line";let L=document.createElement("span");L.className="bp-mgmt-flex1 bp-tone-warn",L.textContent=b("gpui.mgmt.fab.changed","Changed since you last looked");let M=document.createElement("button");M.type="button",M.className="bp-mgmt-btn",M.textContent=b("gpui.mgmt.fab.seen","Seen"),M.addEventListener("click",()=>n("seen")),C.append(L,M),w.appendChild(C);for(let S of t.changed.slice(0,12)){let T=document.createElement("div");T.className="bp-mgmt-faint",T.textContent=S,w.appendChild(T)}o.appendChild(w)}let f=Array.isArray(t.limits)?t.limits:[];if(f.length>0){let w=document.createElement("div");w.className="bp-mgmt-group-head";let C=document.createElement("span");C.className="bp-mgmt-flex1",C.textContent=b("gpui.mgmt.fab.limit","Limit");let L=document.createElement("span");L.className="bp-mgmt-col",L.textContent=b("gpui.mgmt.fab.free","Base price");let M=document.createElement("span");M.className="bp-mgmt-col",M.textContent=b("gpui.mgmt.fab.extra","Costs more");let S=document.createElement("span");S.className="bp-mgmt-col bp-mgmt-col-read",S.textContent=b("gpui.mgmt.fab.readcol","Read"),w.append(C,L,M,S),o.appendChild(w);for(let B of f){let R=document.createElement("div");R.className="bp-mgmt-row";let G=document.createElement("div");G.className="bp-mgmt-row-line";let D=document.createElement("span");D.className="bp-mgmt-flex1"+(B.changed?" bp-tone-warn":B.inherited?" bp-dim":""),D.textContent=`${B.changed?"• ":""}${B.label??""}`;let re=document.createElement("span");re.className="bp-mgmt-col",re.textContent=B.free?.text||"—";let me=document.createElement("span");me.className="bp-mgmt-col bp-dim",me.textContent=B.extra?.text||"—";let le=B.free&&typeof B.free==="object"?B.free:B.extra,we=le?.fetched??"",Se=Boolean(we)&&le?.confidence!=="published",Pe=we?Se?`${we}*`:we:"—",he=le?.source??"",be;if(he.startsWith("https://")&&we){let I=document.createElement("a");I.className="bp-mgmt-col bp-mgmt-col-read bp-mgmt-read-link",I.href=he,I.target="_blank",I.rel="noopener noreferrer",I.textContent=Pe,be=I}else{let I=document.createElement("span");I.className="bp-mgmt-col bp-mgmt-col-read bp-mgmt-faint",I.textContent=Pe,be=I}G.append(D,re,me,be),R.appendChild(G),o.appendChild(R)}let T=document.createElement("div");T.className="bp-mgmt-note bp-mgmt-faint",T.textContent=b("gpui.mgmt.fab.derived","* worked out from the fab's page. Dimmed: the rigid board's value. A date opens the source page."),o.appendChild(T)}return e.appendChild(o),e}makeEmpty(e){let t=document.createElement("div");return t.className="bp-mgmt-note bp-mgmt-faint",t.textContent=e,t}}var As={trs:(e)=>e,t:(e,t)=>t},Ps=new Set(["/settle"]);function fi(e,t){let n=t.trim().toLowerCase();if(!n)return 1;let i=e.toLowerCase();if(i.startsWith(n))return 3;if(i.split(/[^a-z0-9]+/i).some((r)=>r.startsWith(n)))return 2;let a=0;for(let r=0;r0||e.status==="waiting")return{urgency:3,want:"waiting"};if(e.status==="asking")return{urgency:2,want:"question"};if(e.status==="failed"||e.state==="failed")return{urgency:1,want:"failed"};return{urgency:0,want:""}}function yi(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 wi(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 Ei(e,t=As){let{t:n,trs:i}=t,s=[],a=new Map;for(let o of e.projects)a.set(o.id,o.title||o.id);let r=e.threads.find((o)=>o.id===e.selectedThreadId)??null;for(let o of e.railItems){if(o.state==="disabled"||o.id==="commands")continue;if(!r&&o.id!=="terminal")continue;s.push({label:i(o.label),place:o.id==="terminal"?"":"viewer",kind:"action",shortcut:o.key?o.key.toUpperCase():void 0,action:{type:"rail",id:o.id}})}if(r)s.push({label:r.pinned?n("menu.unpin","Unpin"):n("menu.pin","Pin"),place:"",kind:"action",action:{type:"thread-act",action:r.pinned?"unpin":"pin"}}),s.push({label:r.settled?n("phone.unsettle","Unsettle"):n("menu.settle","Settle"),place:"",kind:"action",action:{type:"thread-act",action:r.settled?"unsettle":"settle"}}),s.push({label:r.archived?n("palette.unarchive","Unarchive"):n("palette.archive","Archive"),place:"",kind:"action",action:{type:"thread-act",action:r.archived?"unarchive":"archive"}}),s.push({label:n("sheet.rename","Rename thread"),place:"",kind:"action",action:{type:"rename"}}),s.push({label:n("gpui.previous.thread","Previous thread"),place:"",kind:"action",action:{type:"prev-thread"}}),s.push({label:n("gpui.next.thread","Next thread"),place:"",kind:"action",action:{type:"next-thread"}});if(r)for(let o of e.commands){if(!o.word)continue;let c=Ps.has(o.word.toLowerCase());s.push({label:o.label?`${o.word} — ${o.label}`:o.word,place:o.desc||"command",kind:"command",action:{type:"command",word:o.word,runDirectly:c}})}s.push({label:n("gpui.improvements","Improvements"),place:"",kind:"action",action:{type:"improvements"}}),s.push({label:n("palette.settings","Settings"),place:"",kind:"action",action:{type:"settings"}}),s.push({label:n("gpui.fold.or.unfold.the.sidebar","Fold or unfold the sidebar"),place:"",kind:"action",action:{type:"sidebar"}});for(let o of e.projects)s.push({label:`New thread in ${o.title||o.id}`,place:"",kind:"action",action:{type:"new-thread",projectId:o.id}});for(let o of e.threads){let{urgency:c,want:u}=vi(o);s.push({label:o.title||"Untitled thread",place:o.project?a.get(o.project)??"":"",kind:"thread",urgency:c,want:u,dotClass:yi(o),action:{type:"thread",id:o.id}})}for(let o of e.bots){if(!o.name||!o.thread)continue;s.push({label:o.name,place:"",kind:"bot",action:{type:"thread",id:o.thread}})}return s}function xi(e,t,n,i=[],s=10,a=14){let r=t.trim(),o=r.length===0,c=e.slice();if(n?.threads&&n.threads.length>0){let d=new Map;for(let y of i)d.set(y.id,y.title||y.id);let g=new Set;for(let y of c)if(y.action.type==="thread")g.add(y.action.id);for(let y of n.threads){if(!y.id||g.has(y.id))continue;g.add(y.id);let{urgency:m,want:h}=vi(y);c.push({label:y.title||"Untitled thread",place:y.project?d.get(y.project)??"":"",kind:"thread",urgency:m,want:h,dotClass:yi(y),action:{type:"thread",id:y.id}})}}let u=[];for(let d=0;d0)u.push({score:h,index:d,item:g})}u.sort((d,g)=>{if(o){let h=(g.item.urgency??0)-(d.item.urgency??0);if(h!==0)return h}if(g.score!==d.score)return g.score-d.score;let y=d.item.kind==="thread"?0:1,m=g.item.kind==="thread"?0:1;if(y!==m)return y-m;return d.index-g.index});let l=new Set,p=[];for(let d of u){let g=`${d.item.label}\x00${d.item.place}\x00${d.item.kind}`;if(l.has(g))continue;if(l.add(g),p.push(d.item),p.length>=s)break}if(n?.messages&&n.messages.length>0&&p.length{if(r.target===t)this.close()}),s.addEventListener("input",()=>{this.query=s.value,this.activeIdx=0,this.renderList(),this.scheduleSearch()}),s.addEventListener("keydown",(r)=>{if(r.key==="Escape")r.preventDefault(),r.stopPropagation(),this.close();else if(r.key==="ArrowDown"){if(r.preventDefault(),this.listed.length>0)this.activeIdx=(this.activeIdx+1)%this.listed.length,this.renderList(!0)}else if(r.key==="ArrowUp"){if(r.preventDefault(),this.listed.length>0)this.activeIdx=(this.activeIdx-1+this.listed.length)%this.listed.length,this.renderList(!0)}else if(r.key==="Enter")r.preventDefault(),this.runAt(this.activeIdx)}),this.backdrop=t,this.inputEl=s,this.listEl=a,this.root.appendChild(t),this.renderList(),this.query.trim().length>=2)this.scheduleSearch();s.focus()}close(){if(this.searchTimer!==null)window.clearTimeout(this.searchTimer),this.searchTimer=null;if(this.searchGen++,this.backdrop)this.backdrop.remove(),this.backdrop=null,this.inputEl=null,this.listEl=null;this.prevFocus?.focus(),this.prevFocus=null}scheduleSearch(){if(this.searchTimer!==null)window.clearTimeout(this.searchTimer),this.searchTimer=null;let e=this.query.trim();if(e.length<2){this.searchHits=null,this.searchHitsQuery="";return}if(e===this.searchHitsQuery)return;let t=++this.searchGen;this.searchTimer=window.setTimeout(()=>{this.searchTimer=null,this.cb.onSearch(e).then((n)=>{if(t!==this.searchGen||!this.backdrop)return;if(this.query.trim()!==e)return;this.searchHits=n,this.searchHitsQuery=e,this.renderList()}).catch(()=>{})},180)}runAt(e){let t=this.listed[e];if(!t)return;this.close(),this.cb.onExecute(t.action)}renderList(e=!1){if(!this.listEl)return;let t=this.cb.getState(),n=Ei(t,{t:b,trs:xe}),i=this.query.trim()===this.searchHitsQuery?this.searchHits:null;if(this.listed=xi(n,this.query,i,t.projects),this.activeIdx>=this.listed.length)this.activeIdx=Math.max(0,this.listed.length-1);if(this.listed.length===0){let r=document.createElement("div");r.className="bp-palette-empty",r.textContent=b("gpui.nothing.matches","Nothing matches"),this.listEl.replaceChildren(r);return}let s=document.createDocumentFragment(),a=null;for(let r=0;r0)u.appendChild(document.createTextNode(o.label.slice(0,d)));let y=document.createElement("strong");if(y.className="bp-palette-mark",y.textContent=o.label.slice(d,g),u.appendChild(y),g{if(this.activeIdx!==r)this.activeIdx=r,this.updateActiveClass()}),c.addEventListener("click",()=>this.runAt(r)),r===this.activeIdx)a=c;s.appendChild(c)}if(this.listEl.replaceChildren(s),e&&a)a.scrollIntoView({block:"nearest"})}updateActiveClass(){if(!this.listEl)return;let e=this.listEl.children;for(let t=0;tthis.onPress(e.id));return a}render(){let e=this.items.filter((r)=>r.group!=="tools"),t=this.items.filter((r)=>r.group==="tools"),n=document.createElement("div");n.className="bp-rail-pages";let i;for(let r of e){if(i!==void 0&&r.group!==i){let o=document.createElement("div");o.className="bp-rail-rule",n.appendChild(o)}i=r.group,n.appendChild(this.renderButton(r))}let s=()=>{let r=n.scrollLeft>2,o=n.scrollLeft+n.clientWidth0){let r=document.createElement("div");r.className="bp-rail-tools";for(let o of t)r.appendChild(this.renderButton(o));a.appendChild(r)}this.el.replaceChildren(a)}}var Ms=new Set(["resume","raise","retry","move","signin"]);function Li(e){if(!e||typeof e!=="object")return null;let t=e,n=(a)=>typeof a==="string"?a:"",i=(Array.isArray(t.actions)?t.actions:[]).filter((a)=>Boolean(a)&&typeof a==="object").map((a)=>({label:n(a.label),act:n(a.act),room:n(a.room),thread:n(a.thread)})),s={line:n(t.line),why:n(t.why),actions:i};return s.line||i.length?s:null}function Ht(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(Ms.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 Si(e){let t=e&&typeof e==="object"?e.open:void 0;if(typeof t!=="string")return null;let n=t.indexOf(":"),i=n<0?"":t.slice(n+1);if(!i)return null;if(t.startsWith("account:"))return{kind:"account",id:i};if(t.startsWith("thread:"))return{kind:"thread",id:i};return null}class ln{backdrop;titleEl;closeBtn;bodyEl;cb;openState=!1;constructor(e,t){this.cb=t,this.backdrop=document.createElement("div"),this.backdrop.className="bp-modal-backdrop bp-hidden",this.backdrop.setAttribute("data-testid","settings-modal");let n=document.createElement("div");n.className="bp-modal";let i=document.createElement("div");i.className="bp-modal-head",this.titleEl=document.createElement("h2"),this.titleEl.textContent=`${b("palette.settings","Settings")} · Devices`,this.closeBtn=document.createElement("button"),this.closeBtn.type="button",this.closeBtn.className="icon",this.closeBtn.textContent="×",this.closeBtn.setAttribute("aria-label",b("common.close","Close")),this.closeBtn.addEventListener("click",()=>this.close()),i.append(this.titleEl,this.closeBtn),this.bodyEl=document.createElement("div"),this.bodyEl.className="bp-modal-body",n.append(i,this.bodyEl),this.backdrop.appendChild(n),this.backdrop.addEventListener("click",(s)=>{if(s.target===this.backdrop)this.close()}),e.appendChild(this.backdrop)}isOpen(){return this.openState}async open(){this.openState=!0,this.backdrop.classList.remove("bp-hidden"),await this.refresh()}close(){this.openState=!1,this.backdrop.classList.add("bp-hidden")}refreshLocale(){if(this.titleEl.textContent=`${b("palette.settings","Settings")} · Devices`,this.closeBtn.setAttribute("aria-label",b("common.close","Close")),this.openState)this.refresh()}async refresh(){let e=document.createDocumentFragment(),t=this.cb.onGetHome?.()??null;if(t){let u=document.createElement("section");u.className="bp-set-section",u.setAttribute("data-testid","settings-home");let l=document.createElement("div");l.className="bp-set-head",l.textContent=b("home.machine","Home machine");let p=document.createElement("div");p.className="bp-set-row";let d=document.createElement("div");d.className="bp-set-info";let g=document.createElement("div"),y=t.kind==="local"?`${t.name||"This machine"} (this machine)`:t.kind==="boat"?`${t.name||"Boat"} (Boat)`:t.name||"Linked machine";g.textContent=y,d.appendChild(g);let m=document.createElement("div");if(m.className="bp-dim",t.moving?.state==="moving")m.textContent=t.moving.step?b("home.moving.step","Moving home to {to}: {step}").replace("{to}",t.moving.to).replace("{step}",t.moving.step):b("home.moving","Moving home to {to}…").replace("{to}",t.moving.to);else if(t.moving?.state==="failed")m.textContent=t.moving.note?b("home.move.failed.note","Home move failed: {note}").replace("{note}",t.moving.note):b("home.move.failed","Home move failed");else if(!t.online)m.textContent=t.queuedCount>0?b("home.away.queued","Home ({name}) is away · {n} queued").replace("{name}",t.name||"home").replace("{n}",String(t.queuedCount)):b("home.away","Home ({name}) is away").replace("{name}",t.name||"home");else m.textContent="Online";if(d.appendChild(m),p.appendChild(d),t.canMoveHere&&this.cb.onMoveHomeHere){let h=document.createElement("button");h.type="button",h.className="primary",h.textContent=b("home.move.here","Make this machine the home"),h.setAttribute("data-testid","home-move-here-btn"),h.addEventListener("click",()=>{h.disabled=!0,this.cb.onMoveHomeHere?.().finally(()=>{this.refresh()})}),p.appendChild(h)}u.append(l,p),e.appendChild(u)}let n=document.createElement("section");n.className="bp-set-section";let i=document.createElement("div");i.className="bp-set-head",i.textContent="This browser";let s=document.createElement("div");s.className="bp-set-row";let a=document.createElement("span");a.className="bp-dim",a.textContent="Sign out and revoke this browser's session cookie.";let r=document.createElement("button");r.type="button",r.className="primary stop",r.textContent=b("agy.signout","Sign out"),r.setAttribute("data-testid","logout-btn"),r.addEventListener("click",()=>{r.disabled=!0,this.cb.onLogout().catch(()=>{a.setAttribute("role","alert"),a.textContent=b("web.logout.failed","Could not confirm sign-out. Try again."),r.disabled=!1})}),s.append(a,r),n.append(i,s),e.appendChild(n);let o=document.createElement("section");o.className="bp-set-section";let c=document.createElement("div");c.className="bp-set-head",c.textContent="Paired devices",o.appendChild(c);try{let u=await this.cb.onLoadDevices();if(u.length===0){let l=document.createElement("div");l.className="bp-dim",l.textContent="No devices listed.",o.appendChild(l)}else for(let l of u){let p=document.createElement("div");p.className="bp-set-row";let d=document.createElement("div");d.className="bp-set-info";let g=document.createElement("div");if(g.textContent=l.title||l.head||"",d.appendChild(g),l.text||l.detail){let y=document.createElement("div");y.className="bp-dim",y.textContent=l.text||l.detail||"",d.appendChild(y)}if(p.appendChild(d),l.buttons?.length){let y=document.createElement("div");y.className="bp-set-btns";for(let m of l.buttons){let h=document.createElement("button");if(h.type="button",m.primary)h.className="primary";if(m.danger)h.className="primary stop";h.textContent=m.label||b("common.remove","Remove"),h.addEventListener("click",()=>{h.disabled=!0,this.cb.onDevicesAct(m.action,m.value).finally(()=>{this.refresh()})}),y.appendChild(h)}p.appendChild(y)}o.appendChild(p)}}catch(u){let l=document.createElement("div");l.className="bp-dim";let p=u instanceof Error&&u.message?u.message:"Not available from a browser";l.textContent=`${p} — manage paired devices in Backplane › Settings › Devices on desktop or a paired phone.`,o.appendChild(l)}e.appendChild(o),this.bodyEl.replaceChildren(e)}}function Ce(e,t,n){let i=document.createElement(e);if(t)i.className=t;if(n)i.textContent=n;return i}function wt(e,t,n=!1){let i=Ce("button",n?"primary":"bp-btn-ghost",e);return i.type="button",i.addEventListener("click",t),i}function cn(e){return Ce("pre","bp-context-code",e)}function Ts(e){return Ce("span",`bp-context-badge ${e==="Native"||e==="Enabled"?"active":e==="Untrusted"||e==="Invalid"?"warn":""}`,xe(e))}function Dt(e,t){let n=Ce("div","bp-context-row");return n.append(Ce("strong",void 0,e),Ts(t)),n}class dn{fetchContext;dialog=Ce("dialog","bp-context");title=Ce("h2");cwd=Ce("div","bp-context-path");tabs=Ce("div","bp-context-tabs");body=Ce("div","bp-context-body");notice=Ce("p","bp-context-notice");current;thread="";requestId=0;tab=0;busy=!1;constructor(e,t){this.fetchContext=t;let n=Ce("div","bp-context-head"),i=Ce("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,wt(b("common.refresh","Refresh"),()=>{this.load()}),wt(b("common.close","Close"),()=>this.dialog.close())),this.dialog.append(n,this.tabs,this.notice,this.body),this.dialog.addEventListener("close",()=>{this.requestId++}),e.append(this.dialog)}open(e){if(this.thread=e,this.tab=0,this.current=void 0,this.busy=!1,this.title.textContent=b("thread.context.title","Context & Prompt"),this.cwd.textContent="",!this.dialog.open)this.dialog.showModal();this.render(),this.load()}async load(e){if(this.busy)return;let t=++this.requestId;this.busy=!0,this.notice.textContent=b("thread.context.reading","Reading thread context…"),this.render();try{let n=await this.fetchContext(this.thread,e);if(t!==this.requestId)return;this.current=n,this.cwd.textContent=n.cwd,this.notice.textContent=""}catch(n){if(t===this.requestId)this.notice.textContent=String(n)}finally{if(t===this.requestId)this.busy=!1,this.render()}}render(){let e=[b("thread.context.instructions","Instructions"),b("thread.context.system","System Prompt"),b("thread.context.skills","Skills"),b("thread.context.mcp","Project MCPs")];this.tabs.replaceChildren(...e.map((n,i)=>{let s=wt(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(Ce("p","bp-dim",b("thread.context.none.instructions","No project instructions found.")));for(let t of e){let n=Ce("details","bp-context-card"),i=Ce("summary");if(i.append(Dt(t.path,t.status),Ce("small","bp-dim",b("thread.context.size","{bytes} B · ≈{tokens} tokens",{bytes:t.bytes,tokens:t.estimated_tokens}))),n.append(i,cn(t.preview)),t.note)n.append(Ce("small","bp-dim",t.note));this.body.append(n)}}prompt(e){let t=Ce("div","bp-context-row"),n=wt(b("thread.context.copy","Copy prompt"),()=>{navigator.clipboard.writeText(e.prompt).then(()=>{this.notice.textContent=b("thread.context.copied","Prompt copied.")}).catch((i)=>{this.notice.textContent=String(i)})});t.append(Ce("p","bp-dim",b("thread.context.native.note","Backplane’s launch prompt. Native files are loaded by the provider.")),n),this.body.append(t);for(let[i,s]of[[b("thread.context.base","Backplane"),e.sections.base],[b("thread.context.injected.label","Injected project instructions"),e.sections.instructions],[b("thread.context.index","Available skills index"),e.sections.skills]])if(s)this.body.append(Ce("h3",void 0,i),cn(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(Ce("h3",void 0,xe(t)));for(let i of n){let s=Ce("article","bp-context-card");s.append(Dt(i.name,i.status),Ce("p",void 0,i.description),Ce("small","bp-context-path",[i.source,i.provider,i.model].filter(Boolean).join(" · ")),Ce("small","bp-context-path",i.path)),this.body.append(s)}}}mcps(e){if(!e.length)this.body.append(Ce("p","bp-dim",b("thread.context.none.mcp","No project MCP configurations found.")));for(let t of e){let n=Ce("article","bp-context-card");n.append(Dt(t.path,t.state));for(let s of t.servers){let a=s.url||[s.command,...s.args].map((r)=>JSON.stringify(r)).join(" ");if(n.append(Dt(s.name,s.status),cn(a)),s.cwd)n.append(Ce("small","bp-context-path",s.cwd))}if(t.error)n.append(Ce("p","bp-warn",t.error));let i=t.state==="Untrusted"?"trust":t.state==="Enabled"?"disable":t.state==="Disabled"?"enable":"";if(i){let s=i==="trust"?b("thread.context.trust","Trust and enable"):i==="disable"?b("thread.context.disable","Disable"):b("thread.context.enable","Enable"),a=wt(s,()=>{this.load({action:i,path:t.path,sha256:t.sha256})},i==="trust");a.disabled=this.busy;let r=Ce("div","bp-context-actions");r.append(a),n.append(r)}this.body.append(n)}}}var Ai="http://www.w3.org/2000/svg";function Pi(){let e=document.createElementNS(Ai,"svg");e.setAttribute("viewBox","0 0 24 24"),e.setAttribute("width","14"),e.setAttribute("height","14"),e.setAttribute("fill","none"),e.setAttribute("stroke","currentColor"),e.setAttribute("stroke-width","1.75"),e.setAttribute("aria-hidden","true"),e.classList.add("bp-folder-icon");let t=document.createElementNS(Ai,"path");return t.setAttribute("d","M3 6h6l2 2h10v11H3z"),e.appendChild(t),e}function Bs(e,t,n,i){let s=e||t||n||"";if(s==="active"||s==="working"||s==="running"||s==="run")return"bp-dot-work";if(s==="finished"||s==="done")return"bp-dot-done";if(s==="waiting"||s==="asking"||s==="blocked"||s==="needs"||s==="failed"||s==="fail"||s==="cut"||s==="interrupted"||s==="limit"||s==="monitoring"||(i??0)>0)return"bp-dot-need";return"bp-dot-idle"}function Ni(e){if(!e)return"";let t=e<10000000000?e*1000:e,n=Math.max(0,Math.floor((Date.now()-t)/1000));if(n<60)return"now";if(n<3600)return`${Math.floor(n/60)}m`;if(n<86400)return`${Math.floor(n/3600)}h`;return`${Math.floor(n/86400)}d`}class pn{el;hostLabel;homeBanner;filterInput;listEl;connEl;filterText="";showSettled=new Set;collapsedProjects=new Set;addShown=!1;sections=null;projects=[];threads=[];bots=[];rooms=[];selectedThreadId="";cb;needErr=new Map;needBusy=new Set;constructor(e,t){this.el=e,this.cb=t;let n=document.createElement("div");n.className="bp-side-host";let i=document.createElement("div");i.className="bp-side-host-left",this.hostLabel=document.createElement("span"),this.hostLabel.textContent="This computer";let s=document.createElement("span");s.className="bp-dim",s.textContent="›",i.append(this.hostLabel,s);let a=document.createElement("button");a.type="button",a.className="icon bp-side-collapse",a.textContent="‹",a.title="Collapse sidebar",a.setAttribute("aria-label","Collapse sidebar"),a.setAttribute("data-testid","sidebar-collapse"),a.addEventListener("click",()=>this.cb.onCollapseSidebar?.()),n.append(i,a);let r=document.createElement("div");r.className="bp-side-head",this.filterInput=document.createElement("input"),this.filterInput.type="search",this.filterInput.className="bp-input bp-side-search";let o=b("sidebar.search.projects","Search projects");this.filterInput.placeholder=o,this.filterInput.setAttribute("aria-label",o),this.filterInput.setAttribute("data-testid","sidebar-filter"),this.filterInput.addEventListener("input",()=>{this.filterText=this.filterInput.value.trim().toLowerCase(),this.render()});let c=document.createElement("button");c.type="button",c.className="icon bp-side-add",c.textContent="+",c.title=b("thread.new","New thread"),c.setAttribute("aria-label",b("thread.new","New thread")),c.setAttribute("data-testid","sidebar-new-thread"),c.addEventListener("click",()=>{let l=this.firstProjectId();if(l)this.cb.onNewThread(l)}),r.append(this.filterInput,c),this.homeBanner=document.createElement("div"),this.homeBanner.className="bp-side-home bp-hidden",this.homeBanner.setAttribute("data-testid","home-away-banner"),this.homeBanner.style.padding="6px 10px",this.homeBanner.style.fontSize="11px",this.homeBanner.style.borderBottom="1px solid var(--line, #2a2a2a)",this.listEl=document.createElement("div"),this.listEl.className="bp-side-list",this.listEl.setAttribute("data-testid","sidebar-list");let u=document.createElement("div");u.className="bp-side-footer",this.connEl=document.createElement("span"),this.connEl.className="bp-conn-status",this.connEl.textContent="Connecting…",this.connEl.setAttribute("data-testid","conn-status"),u.appendChild(this.connEl),this.el.append(n,r,this.homeBanner,this.listEl,u)}setHome(e){if(!e){this.homeBanner.classList.add("bp-hidden"),this.homeBanner.textContent="";return}let t="",n=!1;if(e.moving?.state==="moving")t=e.moving.step?b("home.moving.step","Moving home to {to}: {step}").replace("{to}",e.moving.to).replace("{step}",e.moving.step):b("home.moving","Moving home to {to}…").replace("{to}",e.moving.to);else if(e.moving?.state==="failed")t=e.moving.note?b("home.move.failed.note","Home move failed: {note}").replace("{note}",e.moving.note):b("home.move.failed","Home move failed"),n=!0;else if(!e.online){let i=e.name||"home",s="";if(e.awaySince&&e.awaySince>0){let a=new Date(e.awaySince);s=`${String(a.getHours()).padStart(2,"0")}:${String(a.getMinutes()).padStart(2,"0")}`}if(s&&e.queuedCount>0)t=b("home.away.since.queued","Home ({name}) is away since {time} · {n} queued").replace("{name}",i).replace("{time}",s).replace("{n}",String(e.queuedCount));else if(s)t=b("home.away.since","Home ({name}) is away since {time}").replace("{name}",i).replace("{time}",s);else if(e.queuedCount>0)t=b("home.away.queued","Home ({name}) is away · {n} queued").replace("{name}",i).replace("{n}",String(e.queuedCount));else t=b("home.away","Home ({name}) is away").replace("{name}",i)}if(!t)this.homeBanner.classList.add("bp-hidden"),this.homeBanner.textContent="";else this.homeBanner.textContent=t,this.homeBanner.className=n?"bp-side-home bp-bad":"bp-side-home bp-dim",this.homeBanner.classList.remove("bp-hidden")}setHostName(e){this.hostLabel.textContent=e||"This computer"}setConnStatus(e,t){this.connEl.textContent=e,this.connEl.className=`bp-conn-status ${t}`.trim()}setData(e,t,n,i){this.projects=e,this.threads=t,this.bots=n,this.rooms=i,this.render()}setSections(e,t,n){this.sections=e,this.bots=t,this.rooms=n,this.render()}setSelected(e){this.selectedThreadId=e,this.render()}focusFilter(){this.filterInput.focus()}firstProjectId(){if(this.sections){for(let e of this.sections)if(e.kind==="projects"&&e.rows.length>0){let t=e.rows[0];if(t.id&&!t.off)return t.id}}return this.projects[0]?.id??""}refreshLocale(){let e=b("sidebar.search.projects","Search projects");this.filterInput.placeholder=e,this.filterInput.setAttribute("aria-label",e),this.render()}projectsHead(e){let t=document.createElement("div");if(t.className="bp-side-section-head",!this.cb.onAddProject||this.addShown)return t.textContent=e,t;this.addShown=!0,t.classList.add("bp-side-section-row");let n=document.createElement("span");n.textContent=e;let i=document.createElement("button");i.type="button",i.className="bp-side-sec-plus bp-side-sec-btn",i.textContent="+";let s=b("sidebar.add.project","Add project");return i.title=s,i.setAttribute("aria-label",s),i.setAttribute("data-testid","sidebar-add-project"),i.addEventListener("click",(a)=>{a.stopPropagation(),this.cb.onAddProject?.()}),t.append(n,i),t}renderSectionThreadRow(e,t){let n=document.createElement("div");if(n.className="bp-thread-row"+(e.id===this.selectedThreadId?" active":"")+(e.off?" bp-dim":""),n.setAttribute("data-thread-id",e.id),n.setAttribute("data-testid",`thread-row-${e.id}`),t){let p=document.createElement("span");p.className="bp-tree-branch",p.setAttribute("aria-hidden","true"),n.appendChild(p)}let i=document.createElement("span");i.className=`bp-dot ${Bs(e.status,e.word,e.state)}`;let s=document.createElement("div");if(s.className="bp-thread-title",s.textContent=e.title||"Untitled thread",n.append(i,s),e.word==="needs"){let p=document.createElement("span");if(p.className="bp-badge-need",p.textContent=e.want==="approval"?"!":"•",e.say)p.title=e.say;n.appendChild(p)}else if(e.ago){let p=document.createElement("span");if(p.className="bp-thread-age",p.textContent=e.ago,e.pinned)p.title=b("tools.pinned","Pinned");n.appendChild(p)}let a=e.nav||e.id;if(!e.off&&a&&!a.startsWith("@room:"))n.addEventListener("click",()=>this.cb.onSelectThread(a));let r=e.kind==="swarm"?Li(e.need):null;if(!r)return n;let o=document.createElement("div");o.className="bp-need-wrap";let c=document.createElement("div");c.className="bp-need"+(t?" nested":"")+(e.off?" bp-dim":""),c.setAttribute("data-testid",`need-${e.id}`);let u=document.createElement("span");u.className="bp-need-line",u.textContent=r.line,u.title=r.line,c.appendChild(u);for(let p of r.actions){if(!Ht(p,Boolean(this.cb.hasRoomView)))continue;let d=document.createElement("button");d.type="button",d.className="bp-need-btn",d.textContent=p.label,d.setAttribute("data-testid",`need-${p.act}-${e.id}`),d.disabled=Boolean(e.off)||this.needBusy.has(e.id)||!this.cb.onNeedAct,d.addEventListener("click",(g)=>{g.stopPropagation();let y=this.cb.onNeedAct;if(!y)return;this.needErr.delete(e.id),this.needBusy.add(e.id),this.render(),y(p).catch((m)=>{this.needErr.set(e.id,m instanceof Error?m.message:String(m))}).finally(()=>{this.needBusy.delete(e.id),this.render()})}),c.appendChild(d)}o.append(n,c);let l=this.needErr.get(e.id);if(l){let p=document.createElement("div");p.className="bp-need-err"+(t?" nested":""),p.textContent=l,o.appendChild(p)}return o}renderHubSections(e,t){let n=this.sections??[],i=new Set;for(let r of n)if(r.kind==="threads")for(let o of r.rows)i.add(o.id);else if(r.kind==="projects")for(let o of r.rows)for(let c of o.threads??[])i.add(c.id);let s=this.selectedThreadId?this.threads.find((r)=>r.id===this.selectedThreadId)??null:null,a=!1;for(let r of n)if(r.kind==="projects"&&r.rows.length>0)a=!0;for(let r of n){if(r.kind==="bub")continue;if(r.kind==="threads"){let o=r.rows.filter((l)=>{if(!t)return!0;return`${l.title} ${l.project??""}`.toLowerCase().includes(t)});if(o.length===0)continue;let c=document.createElement("section");c.className="bp-side-section",c.setAttribute("data-section-id",r.id);let u=document.createElement("div");u.className="bp-side-section-head",u.textContent=r.title.toUpperCase(),c.appendChild(u);for(let l of o)c.appendChild(this.renderSectionThreadRow(l,!1));e.appendChild(c);continue}if(r.kind==="projects"){let o=r.rows.filter((l)=>{if(!t)return!0;if((l.title||l.id).toLowerCase().includes(t))return!0;if((l.threads??[]).some((p)=>p.title.toLowerCase().includes(t)))return!0;if((l.swarms??[]).some((p)=>p.title.toLowerCase().includes(t)))return!0;return!1}),c=Boolean(r.fold&&r.toggle);if(t&&o.length===0)continue;if(!c&&r.id!=="active"&&o.length===0)continue;let u=document.createElement("section");if(u.className="bp-side-section",u.setAttribute("data-section-id",r.id),c){let l=document.createElement("button");l.type="button",l.className="bp-side-section-head bp-side-section-toggle";let p=r.count??o.length,d=r.open?"▾":"▸";if(l.textContent=`${r.title.toUpperCase()} (${p}) ${d}`,r.hint)l.title=r.hint;l.addEventListener("click",()=>{if(r.toggle)this.cb.onToggleSection?.(r.toggle)}),u.appendChild(l)}else u.appendChild(this.projectsHead(r.title.toUpperCase()));if(!c||r.open||Boolean(t)){if(r.id==="active"&&!a&&!t){let l=document.createElement("div");l.className="bp-side-empty",l.textContent="No projects yet.",u.appendChild(l)}for(let l of o){let p=document.createElement("div");if(p.className="bp-proj-group"+(l.off?" bp-dim":""),p.setAttribute("data-project-id",l.id),l.nav||l.key)p.setAttribute("data-project-key",l.nav||l.key||"");let d=document.createElement("div");d.className="bp-proj-head";let g=document.createElement("button");g.type="button",g.className="bp-proj-toggle";let y=Pi();if(l.css)y.style.color=l.css;let m=document.createElement("span");if(m.className="bp-proj-name",m.textContent=l.title||l.id,g.append(y,m),l.fold==="project-fold"&&l.nav)g.addEventListener("click",()=>this.cb.onToggleProjectFold?.(l.nav));let h=document.createElement("button");if(h.type="button",h.className="icon bp-proj-add",h.title=b("thread.new","New thread"),h.textContent="+",h.setAttribute("data-testid",`new-thread-${l.id}`),l.off)h.disabled=!0;if(h.addEventListener("click",(f)=>{f.stopPropagation(),this.cb.onNewThread(l.id)}),d.append(g,h),p.appendChild(d),!l.folded||Boolean(t)){let f=Boolean(t)&&(l.title||l.id).toLowerCase().includes(t);for(let w of l.swarms??[]){if(t&&!f&&!w.title.toLowerCase().includes(t))continue;p.appendChild(this.renderSectionThreadRow(w,!0))}for(let w of l.threads??[]){if(t&&!f&&!w.title.toLowerCase().includes(t))continue;p.appendChild(this.renderSectionThreadRow(w,!0))}if(s&&s.project===l.id&&!i.has(s.id)&&(!t||f||s.title.toLowerCase().includes(t)))p.appendChild(this.renderSectionThreadRow({id:s.id,title:s.title,status:s.status,state:s.state,ago:Ni(s.updatedAt),pinned:s.pinned,nav:s.id},!0))}u.appendChild(p)}}e.appendChild(u)}}}render(){this.addShown=!1;let e=document.createDocumentFragment(),t=this.filterText;if(this.sections!==null)this.renderHubSections(e,t);else{let n=new Map;for(let i of this.threads){if(i.archived||i.swarm)continue;if(t){if(!`${i.title} ${i.preview??""}`.toLowerCase().includes(t))continue}let s=n.get(i.project)??[];s.push(i),n.set(i.project,s)}if(e.appendChild(this.projectsHead("ACTIVE")),this.projects.length===0&&this.threads.length===0){let i=document.createElement("div");i.className="bp-side-empty",i.textContent="No projects yet.",e.appendChild(i)}for(let i of this.projects){let s=n.get(i.id)??[];if(t&&s.length===0&&!i.title.toLowerCase().includes(t))continue;let a=document.createElement("section");a.className="bp-proj-group",a.setAttribute("data-project-id",i.id);let r=document.createElement("div");r.className="bp-proj-head";let o=document.createElement("button");o.type="button",o.className="bp-proj-toggle";let c=this.collapsedProjects.has(i.id)&&!t,u=Pi();if(i.css)u.style.color=i.css;let l=document.createElement("span");l.className="bp-proj-name",l.textContent=i.title||i.id,o.append(u,l),o.addEventListener("click",()=>{if(this.collapsedProjects.has(i.id))this.collapsedProjects.delete(i.id);else this.collapsedProjects.add(i.id);this.render()});let p=document.createElement("button");if(p.type="button",p.className="icon bp-proj-add",p.title=b("thread.new","New thread"),p.textContent="+",p.setAttribute("data-testid",`new-thread-${i.id}`),p.addEventListener("click",(d)=>{d.stopPropagation(),this.cb.onNewThread(i.id)}),r.append(o,p),a.appendChild(r),!c)for(let d of s)a.appendChild(this.renderSectionThreadRow({id:d.id,title:d.title,status:d.status,state:d.state,ago:Ni(d.updatedAt),pinned:d.pinned,nav:d.id},!0));e.appendChild(a)}}if(!t){let n=document.createElement("section");n.className="bp-proj-group bp-bots-group";let i=document.createElement("div");i.className="bp-side-section-head bp-side-section-row";let s=document.createElement("span");s.textContent=b("tour.title.bots","Bots").toUpperCase();let a=document.createElement("span");a.className="bp-side-sec-plus",a.textContent="+",a.setAttribute("aria-hidden","true"),i.append(s,a),n.appendChild(i);for(let l of this.bots){let p=document.createElement("div");p.className="bp-thread-row"+(l.thread===this.selectedThreadId?" active":"");let d=document.createElement("span");if(d.className="bp-dot bp-dot-idle",l.color)d.style.backgroundColor=l.color;let g=document.createElement("div");g.className="bp-thread-title",g.textContent=`@${l.name}`,p.append(d,g),p.addEventListener("click",()=>this.cb.onSelectBot(l)),n.appendChild(p)}e.appendChild(n);let r=document.createElement("section");r.className="bp-proj-group";let o=document.createElement("div");o.className="bp-side-section-head bp-side-section-row";let c=document.createElement("span");c.textContent=b("bots.rooms","Rooms").toUpperCase();let u=document.createElement("span");u.className="bp-side-sec-plus",u.textContent="+",u.setAttribute("aria-hidden","true"),o.append(c,u),r.appendChild(o);for(let l of this.rooms){let p=document.createElement("div");p.className="bp-thread-row";let d=document.createElement("div");d.className="bp-thread-title",d.textContent=`#${l.name}`,p.appendChild(d),r.appendChild(p)}e.appendChild(r)}this.listEl.replaceChildren(e)}}function Is(e){try{return new URL(e,window.location.origin).searchParams.get("s")||""}catch{return""}}function Et(e){if(!e)return;for(let t of e.getTracks())try{t.stop()}catch{}}function Rs(e,t){if(t===16000){let a=new Int16Array(e.length);for(let r=0;r0?c/u:0));s[a]=l<0?l*32768:l*32767}return s}class mn{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){Et(n);return}if(this.stream=n,await this.stopDrain,t!==this.sessionGen||this.cb.getThreadId()!==e){if(Et(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(Et(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?Is(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(Et(n),this.stream===n)this.stream=null}}async stop(){if(!this.active&&!this.starting)return;let e=this.activeGen,t=this.active,n=this.threadId,i=this.sessionKey;this.sessionGen++,this.starting=!1,this.active=!1,this.sessionKey="",this.cb.setRecording(!1),this.cb.setLevel(0),this.cleanupAudio();let a=this.stopDrain.then(async()=>{if(t&&i){let r=new Int16Array(this.pendingPcm);this.pendingPcm=[],this.enqueuePost(i,new Uint8Array(r.buffer),!0,e),await this.postChain}else this.pendingPcm=[];if(t&&n)await this.hub.rpc("voice.stop",{thread:n}).catch(()=>{})});this.stopDrain=a,await a}cancel(){if(!this.active&&!this.starting)return;let e=this.active,t=this.threadId;if(this.abortedGen=Math.max(this.abortedGen,this.sessionGen),this.sessionGen++,this.starting=!1,this.active=!1,this.sessionKey="",this.pendingPcm=[],this.cb.setRecording(!1),this.cb.setLevel(0),this.cleanupAudio(),e&&t&&this.hub.getState()==="connected")this.hub.rpc("voice.stop",{thread:t}).catch(()=>{})}handleFrame(e){let t=String(e.ev??""),n=String(e.thread??"");if(n&&this.cb.getThreadId()&&n!==this.cb.getThreadId())return;if(t==="draft"&&typeof e.text==="string")this.cb.setDraft(e.text),this.mark=e.text.length;else if(t==="edit"){let i=this.cb.getDraft(),s=Number(e.del??0),a=String(e.ins??""),r=Math.max(0,Math.min(i.length,this.mark)),o=Math.max(0,r-s),c=i.slice(0,o)+a+i.slice(r);this.mark=o+a.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),a=i.createScriptProcessor(4096,1,1);a.onaudioprocess=(r)=>{if(!this.active||t!==this.sessionGen||!this.sessionKey)return;let o=Rs(r.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(a),a.connect(i.destination),this.audioCtx=i,this.processor=a}enqueuePost(e,t,n,i){this.postChain=this.postChain.then(async()=>{if(i<=this.abortedGen)return;try{let s={"Content-Type":"application/octet-stream","X-Voice-Session":e};if(n)s["X-Voice-End"]="1";let a=await fetch("/voice/in",{method:"POST",credentials:"same-origin",headers:s,body:t});if(!a.ok&&!n&&i===this.sessionGen&&this.active)this.failUpload(`Voice upload failed (${a.status}).`)}catch{if(!n&&i===this.sessionGen&&this.active)this.failUpload("Voice upload failed.")}})}failUpload(e){this.abortedGen=Math.max(this.abortedGen,this.sessionGen),this.sessionGen++,this.active=!1,this.starting=!1,this.sessionKey="",this.pendingPcm=[],this.cleanupAudio(),this.cb.setRecording(!1),this.cb.setLevel(0),this.cb.showError(e)}cleanupAudio(){if(this.processor)this.processor.disconnect(),this.processor.onaudioprocess=null,this.processor=null;if(this.audioCtx)this.audioCtx.close().catch(()=>{}),this.audioCtx=null;Et(this.stream),this.stream=null}}var Mi=[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],Ti=[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],Bi=[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],Ii=[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],js=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];function xt(e,t){let n=new Int32Array(16),i=0;for(let o=0;o0){if(n[c]++,c>i)i=c}}let s=new Int32Array(16),a=0;for(let o=1;o<=15;o++)s[o]=a,a+=n[o];let r=new Int32Array(a);for(let o=0;o0)r[s[c]++]=o}return{counts:n,symbols:r,maxBits:i}}var Hs=(()=>{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),xt(e,288)})(),Ds=(()=>{let e=new Uint8Array(32);return e.fill(5),xt(e,32)})();class un{win=new Uint8Array(32768);winPos=0;feed(e,t=16777216){let n=0,i=0,s=0,a=(p)=>{while(s=e.length)throw Error("truncated deflate frame");i|=e[n++]<>>=p,s-=p,d},r=(p)=>{let d=0,g=0,y=0;for(let m=1;m<=p.maxBits;m++){d|=a(1);let h=p.counts[m];if(d-h{let d=c+p;if(d>t)throw Error("inflated frame exceeds limit");if(d<=o.length)return;let g=o.length;while(g{u(1),o[c++]=p,this.win[this.winPos]=p,this.winPos=this.winPos+1&32767};while(n0){if(n>=e.length&&s<3)break;let p=a(1),d=a(2);if(d===0){if(i=0,s=0,n+4>e.length)throw Error("truncated stored block");let g=e[n]|e[n+1]<<8,y=e[n+2]|e[n+3]<<8;if(n+=4,(g^65535)!==y)throw Error("invalid stored block length");if(n+g>e.length)throw Error("truncated stored payload");u(g);for(let m=0;m=e.length)break}else if(d===1||d===2){let g=Hs,y=Ds;if(d===2){let m=a(5)+257,h=a(5)+1,f=a(4)+4,w=new Uint8Array(19);for(let T=0;TL)throw Error("code length overflow");for(let G=0;GL)throw Error("code length overflow");S+=B}else if(T===18){let B=a(7)+11;if(S+B>L)throw Error("code length overflow");S+=B}else throw Error("invalid code length symbol")}g=xt(M,m),y=xt(M.subarray(m),h)}while(!0){let m=r(g);if(m<256)l(m);else if(m===256)break;else{let h=m-257;if(h>=Mi.length)throw Error("invalid length symbol");let f=Mi[h]+(Ti[h]?a(Ti[h]):0),w=r(y);if(w>=Bi.length)throw Error("invalid distance symbol");let C=Bi[w]+(Ii[w]?a(Ii[w]):0);u(f);let L=this.winPos-C&32767;for(let M=0;M{this.stateListeners.delete(e)}}onFrame(e){return this.frameListeners.add(e),()=>{this.frameListeners.delete(e)}}onBinary(e){return this.binaryListeners.add(e),()=>{this.binaryListeners.delete(e)}}rpc(e,t={},n=20000){return new Promise((i,s)=>{if(!this.ws||this.ws.readyState!==WebSocket.OPEN){s(Error("Not connected to hub"));return}let a=this.nextId++,r=window.setTimeout(()=>{this.pending.delete(a),s(Error(`RPC timeout: ${e}`))},n);this.pending.set(a,{resolve:i,reject:s,timer:r}),this.ws.send(JSON.stringify({id:a,m:e,p:t}))})}setState(e){this.state=e;for(let t of this.stateListeners)t(e,this.hello)}rejectAllPending(e){for(let[,t]of this.pending)window.clearTimeout(t.timer),t.reject(Error(e));this.pending.clear()}openSocket(){if(this.closed)return;this.inflater=null;let t=`${window.location.protocol==="https:"?"wss:":"ws:"}//${window.location.host}/ws?data=1&enc=json&z=deflate`,n=new WebSocket(t);n.binaryType="arraybuffer",this.ws=n;let i=(s)=>{let a;try{a=JSON.parse(s)}catch{return}if(a.t==="hub.restarting")this.restarting={reason:String(a.reason??""),build:String(a.build??""),text:String(a.text??""),at:Date.now()};if(a.t==="hello")this.restarting=null,this.hello=a,this.features=new Set(this.hello.features??[]),this.inflater=this.hello.z==="deflate"?new un:null,this.reconnectDelay=500,this.setState("connected");else if(a.t==="reply"&&typeof a.id==="number"){let r=this.pending.get(a.id);if(r)if(this.pending.delete(a.id),window.clearTimeout(r.timer),a.ok)r.resolve(a.result??{});else{let o=a.error,c=typeof o==="string"?o:o&&typeof o==="object"&&("message"in o)?String(o.message):"Request failed";r.reject(Error(c))}return}for(let r of this.frameListeners)r(a)};n.addEventListener("message",(s)=>{if(s.data instanceof ArrayBuffer){if(this.inflater){let a;try{a=this.inflater.feed(new Uint8Array(s.data))}catch{n.close();return}if(a.length>0&&a[0]===123)i(this.textDecoder.decode(a));else{let r=a.buffer.slice(a.byteOffset,a.byteOffset+a.byteLength);for(let o of this.binaryListeners)o(r)}return}for(let a of this.binaryListeners)a(s.data);return}if(typeof s.data!=="string")return;i(s.data)}),n.addEventListener("close",(s)=>{if(this.ws===n)this.ws=null;if(this.rejectAllPending("Connection closed"),this.closed)return;if(s.code===4001||s.code===4401||s.code===1008){this.handleRevoked();return}this.probeSessionOrReconnect()}),n.addEventListener("error",()=>{})}async probeSessionOrReconnect(){try{let t=await fetch("/",{method:"GET",credentials:"same-origin",cache:"no-store"});if(t.status===401||t.status===403){this.handleRevoked();return}if(t.ok){if((await t.text()).includes('id="pair-root"')){this.handleRevoked();return}}}catch{}this.setState("reconnecting");let e=this.reconnectDelay;this.reconnectDelay=Math.min(8000,Math.round(this.reconnectDelay*1.6)),this.reconnectTimer=window.setTimeout(()=>{this.reconnectTimer=null,this.openSocket()},e)}handleRevoked(){this.closed=!0,this.setState("revoked"),window.location.replace("/")}}var Fs=new TextDecoder;function Ri(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 ji(e){let t=0,n=0;function i(r){if(r<=23)return r;if(r===24){if(t>=e.length)return null;return e[t++]}if(r===25){if(t+2>e.length)return null;let o=e[t]<<8|e[t+1];return t+=2,o}if(r===26){if(t+4>e.length)return null;let o=(e[t]<<24|e[t+1]<<16|e[t+2]<<8|e[t+3])>>>0;return t+=4,o}return null}function s(r){if(n++,r>32||n>400000||t>=e.length)return null;let o=e[t++],c=o>>5,u=i(o&31);if(u===null)return null;switch(c){case 0:return u;case 1:return-1-u;case 2:{if(t+u>e.length)return null;let l=e.subarray(t,t+u);return t+=u,l}case 3:{if(t+u>e.length)return null;let l=Fs.decode(e.subarray(t,t+u));return t+=u,l}case 4:{if(u>e.length)return null;let l=Array(u);for(let p=0;p=this.b.length)return this.ok=!1,0;let n=this.b[this.i++],i=7*t;if(i>=28&&(n&240)!==0)return this.ok=!1,0;if(e=(e|(n&127)<>>0,n<128)return e}return this.ok=!1,0}nextI32(){let e=this.nextU32();return e>>>1^-(e&1)}}function Di(e){let t=0xcbf29ce484222325n,n=0x100000001b3n,i=0xffffffffffffffffn;for(let s=0;stypeof e[m]==="number"?e[m]:h,n=t("l",0),i=t("c",0),s=t("a",255)/255,a=t("m",1),r=t("w",0),o=r/2,c=a===0&&r!==0,u=e.d instanceof Uint8Array?e.d:new Uint8Array(0),l=new Hi(u),p=[],d=[],g=0,y=0;while(l.more()){let m=l.nextU32(),h=p.length,f=1/0,w=1/0,C=-1/0,L=-1/0;if(a===2)g=g+l.nextI32()|0,y=y+l.nextI32()|0,p.push(g,y),f=C=g,w=L=y;else{let S=Math.min(l.nextU32(),1048576);for(let T=0;TC)C=g;if(yL)L=y}}let M=(p.length-h)/2;if(M>0){let S=a===2||M===1?2:a===0?0:1,T=a===0?0:o;d.push({info:m,x0:f-T,y0:w-T,x1:C+T,y1:L+T,at:h,n:M,kind:S})}}return{layer:n,color:i,alpha:s,mode:a,r:o,own:c,pts:new Float32Array(p),pieces:d}}function Fi(e,t,n){let i=(r)=>Array.isArray(r)&&r.length>=4?[Number(r[0])||0,Number(r[1])||0,Number(r[2])||0,Number(r[3])||0]:[0,0,0,0],s=Array.isArray(e.cs)?e.cs:[],a=[];for(let r=0;r=0&&o0){n.delete(o.h),n.set(o.h,c);while(n.size>1024){let u=n.keys().next().value;if(u!==void 0)n.delete(u);else break}}}}return{key:typeof e.key==="string"?e.key:"",fam:typeof e.fam==="string"?e.fam:"",base:typeof e.base==="string"?e.base:"",box:i(e.box),edge:i(e.edge),thick:typeof e.thick==="number"?e.thick:1600,note:typeof e.note==="string"?e.note:"",warn:typeof e.warn==="number"?e.warn!==0:!1,chunks:a}}function $i(e,t,n,i=!0){if(n.width<=0||n.height<=0||n.naturalWidth<=0||n.naturalHeight<=0)return null;let s=Math.min(n.width/n.naturalWidth,n.height/n.naturalHeight),a=n.naturalWidth*s,r=n.naturalHeight*s,o=n.left+(n.width-a)/2,c=i?n.top:n.top+(n.height-r)/2,u=(e-o)/a,l=(t-c)/r;if(u<0||u>1||l<0||l>1)return null;return{x:Math.max(0,Math.min(1000,Math.round(u*1000))),y:Math.max(0,Math.min(1000,Math.round(l*1000)))}}var Gi=[["Enter","Enter"],["Tab","Tab"],["Bksp","Backspace"],["Esc","Escape"],["↑","ArrowUp"],["↓","ArrowDown"],["←","ArrowLeft"],["→","ArrowRight"]];function Oi(e){let t=e.trim();if(!t)return"";if(/^[a-zA-Z][a-zA-Z0-9+.-]*:/.test(t))return t;return`https://${t}`}class bn{tail=Promise.resolve();enqueue(e){let t=this.tail.then(e,e);return this.tail=t.catch(()=>{}),t}}function Vi(e,t,n){let i=!0,s=!1,a=!1,r="",o=!1,c=!1,u=-1,l=null,p=new bn,d=document.createElement("div");d.className="bp-pane bp-browser-pane",d.setAttribute("data-testid","pane-browser");let g=document.createElement("div");g.className="bp-pane-bar bp-browser-nav";function y(X,de,E){let k=document.createElement("button");if(k.type="button",k.className="bp-v-btn",k.textContent=X,k.setAttribute("data-testid",de),E)k.title=E;return k}let m=y("←","browser-back","Back"),h=y("→","browser-forward","Forward"),f=y("↻","browser-reload","Reload"),w=document.createElement("form");w.className="bp-browser-url-form";let C=document.createElement("input");C.type="text",C.className="bp-browser-input",C.placeholder="https://…",C.autocomplete="off",C.spellcheck=!1,C.setAttribute("data-testid","browser-url");let L=y("Go","browser-go","Navigate");L.type="submit",w.append(C,L);let M=y("Take over","browser-takeover");M.classList.add("is-primary"),g.append(m,h,f,w,M);let S=document.createElement("div");S.className="bp-browser-drive-bar",S.hidden=!0;let T=document.createElement("div");T.className="bp-browser-keys-row";let B=document.createElement("input");B.type="text",B.className="bp-browser-input",B.placeholder="Type text or press Enter/Tab/Arrows…",B.autocomplete="off",B.spellcheck=!1,B.setAttribute("data-testid","browser-keys");let R=y("Send","browser-type-send");T.append(B,R);let G=document.createElement("div");G.className="bp-browser-quick-keys";for(let[X,de]of Gi){let E=y(X,`browser-key-${de}`);E.addEventListener("click",()=>he("press",{key:de})),G.append(E)}S.append(T,G);let D=document.createElement("div");D.className="bp-browser-err",D.setAttribute("data-testid","browser-error"),D.hidden=!0;let re=document.createElement("div");re.className="bp-browser-stage",re.setAttribute("data-testid","browser-stage");let me=document.createElement("img");me.className="bp-browser-img",me.alt="Hub browser screen",me.draggable=!1,me.hidden=!0,me.setAttribute("data-testid","browser-frame");let le=document.createElement("div");le.className="bp-pane-empty",le.setAttribute("data-testid","browser-empty"),le.textContent="Loading browser screen…",re.append(me,le);let we=document.createElement("div");we.className="bp-browser-hint",we.textContent="You have the page: click to tap, scroll to wheel, type in the key box. Hand it back when done.",we.hidden=!0,d.append(g,S,D,re,we),e.replaceChildren(d);function Se(X){D.textContent=X,D.hidden=!X}function Pe(){S.hidden=!s,we.hidden=!s,M.textContent=s?"Hand back":"Take over",M.setAttribute("data-testid",s?"browser-handback":"browser-takeover"),M.classList.toggle("is-on",s),me.classList.toggle("is-driving",s)}function he(X,de={},E){p.enqueue(async()=>{if(!i)return;Se("");try{if(await t.hub.rpc("browser",{thread:n,op:X,...de}),!i)return;E?.(),ce()}catch(k){if(!i)return;Se(k instanceof Error?k.message:String(k))}})}function be(X){he("toolbar",{command:X},()=>{s=!0,Pe()})}m.addEventListener("click",()=>be("back")),h.addEventListener("click",()=>be("forward")),f.addEventListener("click",()=>be("reload")),w.addEventListener("submit",(X)=>{X.preventDefault();let de=Oi(C.value);if(!de)return;if(C.value=de,!s)he("takeover",{},()=>{s=!0,Pe()});he("navigate",{url:de},()=>{s=!0,Pe()})}),M.addEventListener("click",()=>{if(s)he("handback",{},()=>{s=!1,Pe()});else he("takeover",{},()=>{s=!0,Pe(),B.focus()})});function I(){let X=B.value;if(!X)return;B.value="",he("type",{text:X})}R.addEventListener("click",I),B.addEventListener("keydown",(X)=>{if(!s)return;if(X.key==="Enter"){if(X.preventDefault(),B.value)I();he("press",{key:"Enter"});return}if(X.key==="Tab"||X.key==="Escape"||X.key==="ArrowUp"||X.key==="ArrowDown"||X.key==="ArrowLeft"||X.key==="ArrowRight"||X.key==="Backspace"&&B.value==="")X.preventDefault(),he("press",{key:X.key})}),me.addEventListener("click",(X)=>{if(!s||!a)return;let de=me.getBoundingClientRect(),E=$i(X.clientX,X.clientY,{left:de.left,top:de.top,width:de.width,height:de.height,naturalWidth:me.naturalWidth,naturalHeight:me.naturalHeight});if(!E)return;he("click",E)}),me.addEventListener("wheel",(X)=>{if(!s||!a)return;X.preventDefault();let de=Math.round(X.deltaX),E=Math.round(X.deltaY);if(de===0&&E===0)return;he("scroll",{dx:de,dy:E})},{passive:!1});async function ce(){if(!i)return;if(o){c=!0;return}o=!0;try{do{c=!1,l=new AbortController;let X=await fetch(`/bots/${encodeURIComponent(n)}/screen.jpg`,{credentials:"same-origin",cache:"no-store",signal:l.signal});if(!i)return;if(X.ok){let de=await X.blob();if(!i)return;let E=URL.createObjectURL(de),k=r;if(r=E,me.src=E,me.hidden=!1,le.hidden=!0,a=!0,k)URL.revokeObjectURL(k)}else if(!a)me.hidden=!0,le.hidden=!1,le.textContent="No browser page yet. An agent opens one when it needs the web."}while(i&&c)}catch{if(!i)return;if(!a)me.hidden=!0,le.hidden=!1,le.textContent="No browser page yet. An agent opens one when it needs the web."}finally{l=null,o=!1}}let ne=t.hub.onFrame((X)=>{if(!i)return;if(X.t==="shot"&&X.bot===n){if(typeof X.n==="number"){if(X.n===u)return;u=X.n}ce()}});return ce(),{destroy(){if(i=!1,ne(),l?.abort(),r)URL.revokeObjectURL(r),r=""}}}function W(e,t,n){let i=document.createElement(e);if(t)i.className=t;if(n!==void 0)i.textContent=n;return i}function Ft(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 Wi(e){let t=e.lastIndexOf(".");return t>=0?e.slice(t+1).toLowerCase():""}function Gs(e){return["png","jpg","jpeg","gif","webp","svg","bmp","ico"].includes(e)}function Ui(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 Os(e){let t=Wi(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 _i(e,t,n,i){let s=!0,a="",r="",o=W("div","bp-pane bp-files-pane");o.setAttribute("data-testid","pane-files");let c=W("div","bp-pane-bar"),u=W("div","bp-files-crumbs"),l=W("button","bp-v-btn","Refresh");l.type="button",l.addEventListener("click",()=>void h(a)),c.append(u,l);let p=W("div","bp-files-split"),d=W("div","bp-files-list");d.setAttribute("data-testid","files-list");let g=W("div","bp-files-preview");g.setAttribute("data-testid","files-preview"),g.append(W("div","bp-pane-empty","Select a file to preview")),p.append(d,g),o.append(c,p),e.replaceChildren(o);function y(){u.replaceChildren();let f=W("button","bp-crumb-btn","project");if(f.type="button",f.addEventListener("click",()=>void h("")),u.append(f),!a)return;let w=a.split("/").filter(Boolean),C="";for(let L of w){C=C?`${C}/${L}`:L;let M=C;u.append(W("span","bp-vh-sep","/"));let S=W("button","bp-crumb-btn",L);S.type="button",S.addEventListener("click",()=>void h(M)),u.append(S)}}async function m(f,w,C){r=f,g.replaceChildren();let L=W("div","bp-files-prev-head");L.append(W("span","bp-files-prev-name",f));let M=W("div","bp-files-prev-acts"),S=Os(w);if(S){let G=W("button","bp-v-btn is-primary",`Open in ${S}`);G.type="button",G.setAttribute("data-testid","files-open-viewer"),G.addEventListener("click",()=>i(S,f)),M.append(G)}let T=`/files/get?thread=${encodeURIComponent(n)}&path=${encodeURIComponent(f)}`,B=W("a","bp-v-btn","Download");B.href=T,B.download=w,M.append(B),L.append(M),g.append(L);let R=Wi(w);if(Gs(R)){let G=W("div","bp-files-img-wrap"),D=document.createElement("img");D.className="bp-files-img",D.alt=w,D.src=T,G.append(D),g.append(G);return}if(C>524288&&!Ui(R)){g.append(W("div","bp-pane-empty",`Binary file (${Ft(C)}). Use Download to save.`));return}if(Ui(R)||C<=65536){let G=W("div","bp-pane-empty","Loading…");g.append(G);try{let D=await fetch(T,{credentials:"same-origin"});if(!s||r!==f)return;if(!D.ok){G.textContent=`Could not load file (${D.status})`;return}if((D.headers.get("content-type")||"").startsWith("image/")){G.remove();let ne=document.createElement("img");ne.className="bp-files-img",ne.alt=w,ne.src=T,g.append(ne);return}let me=262144,le=[],we=0,Se=!1;if(D.body){let ne=D.body.getReader();try{while(!0){let{done:X,value:de}=await ne.read();if(X||!de)break;if(we+de.byteLength>me){let E=me-we;if(E>0)le.push(de.subarray(0,E)),we+=E;Se=!0,await ne.cancel();break}le.push(de),we+=de.byteLength}}finally{ne.releaseLock()}}if(!s||r!==f)return;let Pe=new Uint8Array(we),he=0;for(let ne of le)Pe.set(ne,he),he+=ne.byteLength;let be=!1;for(let ne=0;neL.dir===M.dir?L.name.localeCompare(M.name):L.dir?-1:1),d.replaceChildren(),f){let L=W("button","bp-file-row is-dir");L.type="button",L.append(W("span","bp-file-icon","↰"),W("span","bp-file-name",".."));let M=f.includes("/")?f.slice(0,f.lastIndexOf("/")):"";L.addEventListener("click",()=>void h(M)),d.append(L)}if(C.length===0){d.append(W("div","bp-pane-empty","Empty folder"));return}for(let L of C){let M=f?`${f}/${L.name}`:L.name,S=W("button","bp-file-row"+(L.dir?" is-dir":"")+(M===r?" is-sel":""));S.type="button",S.setAttribute("data-testid",`file-row-${L.name}`),S.append(W("span","bp-file-icon",L.dir?"▸":"·"),W("span","bp-file-name",L.name),W("span","bp-file-size",L.dir?"":Ft(L.size))),S.addEventListener("click",()=>{if(L.dir)h(M);else d.querySelectorAll(".bp-file-row.is-sel").forEach((T)=>T.classList.remove("is-sel")),S.classList.add("is-sel"),m(M,L.name,L.size)}),d.append(S)}}catch(w){if(!s)return;d.replaceChildren(W("div","bp-pane-empty",w instanceof Error?w.message:String(w)))}}return h(""),{destroy(){s=!1}}}function qi(e,t,n){let i=!0,s=W("div","bp-pane bp-diff-pane");s.setAttribute("data-testid","pane-diff");let a=W("div","bp-pane-bar"),r=W("span","bp-diff-summary","Loading diff…"),o=W("button","bp-v-btn","Refresh");o.type="button",o.addEventListener("click",()=>void u()),a.append(r,o);let c=W("div","bp-diff-body");c.setAttribute("data-testid","diff-body"),s.append(a,c),e.replaceChildren(s);async function u(){r.textContent="Loading diff…",c.replaceChildren();try{let l=await t.hub.rpc("viewer.diff",{thread:n});if(!i)return;if(l?.nogit){r.textContent="Not a git repository",c.append(W("div","bp-pane-empty","This project is not a git repository."));return}let p=typeof l?.diff==="string"?l.diff:"";if(!p.trim()){r.textContent="Clean working tree",c.append(W("div","bp-pane-empty","No uncommitted changes."));return}let d=p.split(` -`),g=0,y=0,m=0,h=document.createDocumentFragment(),f=W("div","bp-diff-file");for(let w of d){if(w.startsWith("diff --git ")){if(f.childNodes.length>0)h.append(f);f=W("div","bp-diff-file"),g++;let C=w.match(/ b\/(.+)$/);f.append(W("div","bp-diff-file-head",C?C[1]:w));continue}if(w.startsWith("index ")||w.startsWith("--- ")||w.startsWith("+++ "))f.append(W("div","bp-diff-line is-meta",w));else if(w.startsWith("@@"))f.append(W("div","bp-diff-line is-hunk",w));else if(w.startsWith("+"))y++,f.append(W("div","bp-diff-line is-add",w));else if(w.startsWith("-"))m++,f.append(W("div","bp-diff-line is-del",w));else f.append(W("div","bp-diff-line",w))}if(f.childNodes.length>0)h.append(f);r.textContent=`${g||1} file${g===1?"":"s"} · +${y} -${m}`,c.append(h)}catch(l){if(!i)return;r.textContent="Diff unavailable",c.append(W("div","bp-pane-empty",l instanceof Error?l.message:String(l)))}}return u(),{destroy(){i=!1}}}function Ki(e,t,n){let i=!0,s="checks",a=W("div","bp-pane bp-review-pane");a.setAttribute("data-testid","pane-review");let r=W("div","bp-pane-bar"),o=W("div","bp-review-tabs"),c=W("button","bp-v-btn is-on","Checks"),u=W("button","bp-v-btn","BOM"),l=W("button","bp-v-btn","Comments");c.type=u.type=l.type="button",o.append(c,u,l);let p=W("button","bp-v-btn","Refresh");p.type="button",p.addEventListener("click",()=>void m()),r.append(o,p);let d=W("div","bp-review-body");d.setAttribute("data-testid","review-body"),a.append(r,d),e.replaceChildren(a);function g(h){s=h,c.classList.toggle("is-on",s==="checks"),u.classList.toggle("is-on",s==="bom"),l.classList.toggle("is-on",s==="comments"),m()}c.addEventListener("click",()=>g("checks")),u.addEventListener("click",()=>g("bom")),l.addEventListener("click",()=>g("comments"));function y(h){let f=W("div","bp-review-md"),w=h.split(` -`),C=0;while(C{T.preventDefault();let B=M.value.trim();if(!B)return;S.disabled=!0,t.hub.rpc("review.comment",{thread:n,text:B}).then(()=>{M.value="",S.disabled=!1,m()},()=>{S.disabled=!1})}),d.append(L),C.length===0){d.append(W("div","bp-pane-empty","No review comments yet."));return}for(let T of C){let B=W("div","bp-review-comment"+(T.resolved?" is-resolved":"")),R=[T.by||"review",T.file,T.layer,T.item].filter(Boolean).join(" · ");B.append(W("div","bp-review-comment-meta",R),W("div","bp-review-comment-text",T.text)),d.append(B)}return}let h=await t.hub.rpc("review.page",{thread:n,page:s});if(!i)return;let f=h?.report||{};if(d.replaceChildren(),f.line||f.gate){let w=W("div","bp-review-gate",[f.gate,f.line].filter(Boolean).join(" · "));d.append(w)}if(f.err)d.append(W("div","bp-review-err",f.err));if(Array.isArray(f.tasks)&&f.tasks.length>0){let w=W("div","bp-review-tasks");f.tasks.forEach((C,L)=>{let M=W("label","bp-review-task"),S=document.createElement("input");S.type="checkbox",S.checked=!!(C.done??C.checked);let T=typeof C.index==="number"?C.index:L;S.addEventListener("change",()=>{t.hub.rpc("review.tick",{thread:n,index:T}).then(()=>void m(),()=>{})}),M.append(S,W("span",void 0,C.text||C.label||`Item ${L+1}`)),w.append(M)}),d.append(w)}if(f.md&&f.md.trim())d.append(y(f.md));else if(!f.err&&(!f.tasks||f.tasks.length===0))d.append(W("div","bp-pane-empty",`No ${s==="bom"?"BOM":"design checks"} report available.`))}catch(h){if(!i)return;d.replaceChildren(W("div","bp-pane-empty",h instanceof Error?h.message:String(h)))}}return m(),{destroy(){i=!1}}}function zi(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 gn{canvas;ctx;frame=null;masks={off:0,dim:0,lift:255};highlights=new Set;lightTheme=!1;cx=0;cy=0;scale=0.0001;fittedKey="";fitW=0;fitH=0;userMoved=!1;dirty=!1;rafId=0;pointers=new Map;dragStart=null;pinchStart=null;resizeObs;cbs;constructor(e,t={}){this.cbs=t,this.canvas=document.createElement("canvas"),this.canvas.className="bp-viewer-canvas",this.canvas.style.width="100%",this.canvas.style.height="100%",this.canvas.style.display="block",this.canvas.style.touchAction="none",e.appendChild(this.canvas);let n=this.canvas.getContext("2d");if(!n)throw Error("Canvas2D unavailable");this.ctx=n,this.resizeObs=new ResizeObserver(()=>this.scheduleDraw()),this.resizeObs.observe(this.canvas),this.canvas.addEventListener("pointerdown",this.onPointerDown),this.canvas.addEventListener("pointermove",this.onPointerMove),this.canvas.addEventListener("pointerup",this.onPointerUp),this.canvas.addEventListener("pointercancel",this.onPointerUp),this.canvas.addEventListener("wheel",this.onWheel,{passive:!1}),this.canvas.addEventListener("dblclick",this.onDblClick)}setTheme(e){if(this.lightTheme!==e)this.lightTheme=e,this.scheduleDraw()}setFrame(e){if(this.frame=e,e&&e.key!==this.fittedKey)this.fittedKey=e.key,this.fit();else this.scheduleDraw()}setLayers(e){this.masks=e,this.scheduleDraw()}setHighlights(e){this.highlights.clear();for(let[t,n]of e)this.highlights.add(`${t}:${n}`);this.scheduleDraw()}presentMask(){if(!this.frame)return 0;let e=0;for(let t of this.frame.chunks)if(t.layer<32)e=(e|1<>>0;return e>>>0}presentColors(){let e=new Map;if(!this.frame)return e;for(let t of this.frame.chunks)if(!e.has(t.layer))e.set(t.layer,t.color);return e}applyFit(e,t){if(!this.frame||e<10||t<10)return;let n=this.frame.box,i=Math.max(n[2]-n[0],1000),s=Math.max(n[3]-n[1],1000);this.cx=(n[0]+n[2])*0.5,this.cy=(n[1]+n[3])*0.5,this.scale=Math.min(e/i,t/s)*0.92,this.fitW=e,this.fitH=t,this.userMoved=!1}fit(){if(!this.frame)return;this.userMoved=!1,this.fitW=0,this.fitH=0;let e=this.canvas.getBoundingClientRect();if(e.width>=10&&e.height>=10)this.applyFit(e.width,e.height);this.scheduleDraw()}zoomToBoxMm(e){let t=e[0]*1000,n=e[1]*1000,i=e[2]*1000,s=e[3]*1000,a=Math.max(i-t,1000),r=Math.max(s-n,1000),o=this.canvas.getBoundingClientRect(),c=Math.max(o.width,200),u=Math.max(o.height,200);this.cx=(t+i)*0.5,this.cy=(n+s)*0.5,this.scale=Math.min(c/a,u/r)*0.85,this.userMoved=!0,this.scheduleDraw()}scheduleDraw(){if(this.dirty)return;this.dirty=!0,this.rafId=requestAnimationFrame(()=>{this.dirty=!1,this.rafId=0,this.draw()})}draw(){let e=this.canvas.getBoundingClientRect(),t=Math.max(1,Math.round(e.width)),n=Math.max(1,Math.round(e.height)),i=Math.min(window.devicePixelRatio||1,2),s=Math.round(t*i),a=Math.round(n*i);if(this.canvas.width!==s||this.canvas.height!==a)this.canvas.width=s,this.canvas.height=a;let r=this.ctx;r.setTransform(i,0,0,i,0,0),r.fillStyle=this.lightTheme?"#f5f4ef":"#08090b",r.fillRect(0,0,t,n);let o=this.frame;if(!o)return;if(!this.userMoved&&t>=10&&n>=10&&(Math.abs(this.fitW-t)>2||Math.abs(this.fitH-n)>2))this.applyFit(t,n);let c=t*0.5,u=n*0.5,l=this.scale,p=this.cx,d=this.cy,g=p-c/l,y=p+c/l,m=d-u/l,h=d+u/l,{off:f,dim:w,lift:C}=this.masks,L=[],M=[];for(let T=0;T>>B&1)===1)continue;if(B===C)M.push(T);else L.push(T)}let S=L.concat(M);r.lineCap="round",r.lineJoin="round";for(let T=0;T>>R.layer&1)===1,D=R.alpha*(G?0.25:1);if(D<=0.01)continue;this.drawChunk(r,R,D,g,m,y,h,p,d,l,c,u)}if(this.highlights.size>0){r.fillStyle=this.lightTheme?"rgba(245,244,239,0.72)":"rgba(8,9,11,0.72)",r.fillRect(0,0,t,n);let T=this.lightTheme?"rgba(27,29,33,0.77)":"rgba(217,221,228,0.77)";for(let B=0;Ba||h.y1r)continue;if(h.n<3)continue;let f=(d[h.at]-o)*u+l,w=(d[h.at+1]-c)*u+p;e.moveTo(f,w);for(let C=1;C0)e.fill()}else if(t.mode===2){let y=Math.max(0.75,t.r*u);e.fillStyle=g,e.beginPath();let m=0;for(let h=0;ha||f.y1r)continue;let w=(d[f.at]-o)*u+l,C=(d[f.at+1]-c)*u+p;e.moveTo(w+y,C),e.arc(w,C,y,0,Math.PI*2),m++}if(m>0)e.fill()}else{e.strokeStyle=g,e.lineWidth=Math.max(1,t.r*2*u),e.beginPath();let y=0;for(let m=0;ma||h.y1r)continue;let f=(d[h.at]-o)*u+l,w=(d[h.at+1]-c)*u+p;if(h.n===1)e.moveTo(f,w),e.lineTo(f+0.01,w);else{e.moveTo(f,w);for(let C=1;C0)e.stroke()}}drawLitPieces(e,t,n,i,s,a,r,o,c,u,l,p,d){let g=t.pts,y=zi(t.color,t.alpha);for(let m=0;mr||h.y1o)continue;let f=(g[h.at]-c)*l+p,w=(g[h.at+1]-u)*l+d;if(h.kind===2){let C=Math.max(1.5,t.r*l);e.fillStyle=y,e.beginPath(),e.arc(f,w,C,0,Math.PI*2),e.fill(),e.strokeStyle=i,e.lineWidth=1.5,e.stroke()}else if(h.kind===0&&h.n>=3){e.fillStyle=y,e.beginPath(),e.moveTo(f,w);for(let C=1;C=0;l--){let p=n.chunks[l];if(p.layer<32&&(u>>>p.layer&1)===1)continue;for(let d=0;dg.x1+r||ag.y1+r)continue;let y=(g.x1-g.x0+1)*(g.y1-g.y0+1);if(y{if(this.canvas.setPointerCapture(e.pointerId),this.pointers.set(e.pointerId,{x:e.clientX,y:e.clientY}),this.pointers.size===1)this.dragStart={x:e.clientX,y:e.clientY,cx:this.cx,cy:this.cy,moved:!1},this.pinchStart=null;else if(this.pointers.size===2){let[t,n]=Array.from(this.pointers.values());this.pinchStart={dist:Math.hypot(n.x-t.x,n.y-t.y)||1,midX:(t.x+n.x)*0.5,midY:(t.y+n.y)*0.5,scale:this.scale,cx:this.cx,cy:this.cy},this.dragStart=null}};onPointerMove=(e)=>{if(!this.pointers.has(e.pointerId))return;if(this.pointers.set(e.pointerId,{x:e.clientX,y:e.clientY}),this.pointers.size===2&&this.pinchStart){let[t,n]=Array.from(this.pointers.values()),i=Math.hypot(n.x-t.x,n.y-t.y)||1,s=(t.x+n.x)*0.5,a=(t.y+n.y)*0.5,r=i/this.pinchStart.dist,o=Math.max(0.0000001,Math.min(2,this.pinchStart.scale*r)),c=this.canvas.getBoundingClientRect(),u=this.pinchStart.midX-c.left-c.width*0.5,l=this.pinchStart.midY-c.top-c.height*0.5,p=s-c.left-c.width*0.5,d=a-c.top-c.height*0.5;this.scale=o,this.cx=this.pinchStart.cx+u/this.pinchStart.scale-p/o,this.cy=this.pinchStart.cy+l/this.pinchStart.scale-d/o,this.userMoved=!0,this.cbs.onUserMove?.(),this.scheduleDraw();return}if(this.dragStart&&this.pointers.size===1){let t=e.clientX-this.dragStart.x,n=e.clientY-this.dragStart.y;if(Math.hypot(t,n)>3)this.dragStart.moved=!0;if(this.dragStart.moved)this.cx=this.dragStart.cx-t/this.scale,this.cy=this.dragStart.cy-n/this.scale,this.userMoved=!0,this.cbs.onUserMove?.(),this.scheduleDraw()}};onPointerUp=(e)=>{let t=this.dragStart&&!this.dragStart.moved&&this.pointers.size===1;if(this.pointers.delete(e.pointerId),this.pointers.size<2)this.pinchStart=null;if(this.pointers.size===0)this.dragStart=null;if(t&&this.cbs.onPick){let n=this.canvas.getBoundingClientRect(),i=this.hitTest(e.clientX-n.left,e.clientY-n.top);this.cbs.onPick(i)}};onWheel=(e)=>{e.preventDefault();let t=this.canvas.getBoundingClientRect(),n=e.clientX-t.left-t.width*0.5,i=e.clientY-t.top-t.height*0.5,s=e.deltaY<0?1.16:0.8620689655172414,a=Math.max(0.0000001,Math.min(2,this.scale*s));this.cx+=n/this.scale-n/a,this.cy+=i/this.scale-i/a,this.scale=a,this.userMoved=!0,this.cbs.onUserMove?.(),this.scheduleDraw()};onDblClick=()=>{this.fit()};destroy(){if(this.rafId)cancelAnimationFrame(this.rafId);this.resizeObs.disconnect(),this.canvas.removeEventListener("pointerdown",this.onPointerDown),this.canvas.removeEventListener("pointermove",this.onPointerMove),this.canvas.removeEventListener("pointerup",this.onPointerUp),this.canvas.removeEventListener("pointercancel",this.onPointerUp),this.canvas.removeEventListener("wheel",this.onWheel),this.canvas.removeEventListener("dblclick",this.onDblClick),this.canvas.remove()}}var Ji=[{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 Yi(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 fn(e,t,n,i){if(!e||!t||!n||!i)return!1;if(!e.startsWith(t))return!1;let s=e.slice(t.length).split(` -`),a=(s[0]||"").split("\t");if(a[0]!=="git"||a[2]!==n)return!1;let r=s[1]||a.slice(4).join("\t");if(!r)return!1;let o=r.replace(/\\/g,"/"),c=i.replace(/\\/g,"/");if(c.startsWith("/")||/^[A-Za-z]:\//.test(c))return o===c;return o===c||o.endsWith(`/${c}`)}class vn{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 Vs=`#version 300 es +`),p=document.createElement("div");p.className="bp-code-block";let d=document.createElement("div");d.className="bp-code-head";let g=document.createElement("span");g.className="bp-code-lang",g.textContent=c||"code";let y=document.createElement("button");y.type="button",y.className="bp-btn-ghost bp-code-copy";let m=b("common.copy","Copy");y.textContent=m,y.addEventListener("click",()=>{navigator.clipboard?.writeText(l).then(()=>{y.textContent="✓",window.setTimeout(()=>{y.textContent=m},1200)}).catch(()=>{})}),d.append(g,y);let h=document.createElement("pre"),f=document.createElement("code");f.textContent=l,h.appendChild(f),p.append(d,h),t.appendChild(p);continue}if(!s.trim()){i++;continue}let r=/^(#{1,4})\s+(.+)$/.exec(s);if(r){let c=document.createElement(`h${Math.min(4,r[1].length+1)}`);c.className="bp-md-h",vt(c,r[2]),t.appendChild(c),i++;continue}if(s.startsWith("> ")){let c=document.createElement("blockquote");c.className="bp-md-quote";let u=[];while(i "))u.push(n[i].slice(2)),i++;vt(c,u.join(` +`)),t.appendChild(c);continue}if(/^\s*[-*]\s+/.test(s)){let c=document.createElement("ul");c.className="bp-md-list";while(i ")&&!/^\s*[-*]\s+/.test(n[i])&&!/^\s*\d+\.\s+/.test(n[i]))a.push(n[i]),i++;let o=document.createElement("p");o.className="bp-md-p";for(let c=0;c0)o.appendChild(document.createElement("br"));vt(o,a[c])}t.appendChild(o)}return t}var $n="http://www.w3.org/2000/svg";function wt(e){let t=document.createElementNS($n,"svg");t.setAttribute("viewBox","0 0 24 24"),t.setAttribute("width","12"),t.setAttribute("height","12"),t.setAttribute("fill","none"),t.setAttribute("stroke","currentColor"),t.setAttribute("stroke-width","1.8"),t.setAttribute("aria-hidden","true");for(let n of e){let i=document.createElementNS($n,"path");i.setAttribute("d",n),t.appendChild(i)}return t}function Yt(e){return e<10000000000?e*1000:e}function vs(e){if(!e)return"";return new Date(Yt(e)).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",hour12:!1})}function ys(e){if(!Number.isFinite(e)||e<=0||e>3600000)return"";let t=Math.max(1,Math.round(e/1000));if(t<60)return`${t}s`;let n=Math.floor(t/60),i=t%60;return i>0?`${n}m ${i}s`:`${n}m`}function Jt(e){if(e.agentOnly)return!0;if(e.kind==="note"){let t=(e.text||"").trim();if(t.startsWith("Made this folder a git repository")||t.startsWith("Backplane: snapshot")||t.includes("snapshot of existing work before first use"))return!0}return!1}class Xt{bannerEl;scrollEl;listEl;olderBtn;cb;thread=null;entries=[];hasMore=!1;loadingOlder=!1;review=null;unanswered=null;noProvider=null;btwNote=null;liveNodes=new Map;imageCache=new Map;pinnedToBottom=!0;planExpanded=new Set;planRevisingId="";planReviseDrafts=new Map;constructor(e,t){if(this.cb=t,this.bannerEl=document.createElement("div"),this.bannerEl.className="bp-thread-banners",this.scrollEl=document.createElement("div"),this.scrollEl.className="bp-timeline-scroll",this.scrollEl.setAttribute("data-testid","timeline"),this.olderBtn=document.createElement("button"),this.olderBtn.type="button",this.olderBtn.className="bp-older-btn bp-hidden",this.olderBtn.textContent=b("android.load.earlier","Load earlier"),this.olderBtn.setAttribute("data-testid","load-older-btn"),this.olderBtn.addEventListener("click",()=>{if(!this.loadingOlder&&this.hasMore)this.loadingOlder=!0,this.cb.onLoadOlder()}),this.scrollEl.addEventListener("scroll",()=>{if(this.pinnedToBottom=this.isNearBottom(),this.hasMore&&!this.loadingOlder&&this.scrollEl.scrollTop<48)this.loadingOlder=!0,this.cb.onLoadOlder()}),typeof ResizeObserver<"u"){let n=0;new ResizeObserver(()=>{let s=this.scrollEl.clientHeight;if(n>0&&s!==n&&this.pinnedToBottom)this.scrollToBottom();n=s}).observe(this.scrollEl)}this.listEl=document.createElement("div"),this.listEl.className="bp-timeline-list",this.scrollEl.append(this.olderBtn,this.listEl),e.append(this.bannerEl,this.scrollEl)}setLoading(e){this.thread=e,this.entries=[],this.hasMore=!1,this.loadingOlder=!1,this.review=null,this.unanswered=null,this.btwNote=null,this.liveNodes.clear(),this.planExpanded.clear(),this.planRevisingId="",this.planReviseDrafts.clear(),this.renderBanners(),this.olderBtn.classList.add("bp-hidden");let t=document.createElement("div");t.className="bp-empty-state",t.textContent=b("web.chat.loading","Loading messages…"),this.listEl.replaceChildren(t)}setError(e,t,n){this.thread=e,this.entries=[],this.hasMore=!1,this.loadingOlder=!1,this.review=null,this.unanswered=null,this.btwNote=null,this.liveNodes.clear(),this.planExpanded.clear(),this.planRevisingId="",this.planReviseDrafts.clear(),this.renderBanners(),this.olderBtn.classList.add("bp-hidden");let i=document.createElement("div");i.className="bp-empty-state";let s=document.createElement("div");s.className="bp-bad",s.textContent=t;let r=document.createElement("button");r.type="button",r.textContent=b("tools.retry","Retry"),r.addEventListener("click",n),i.append(s,r),this.listEl.replaceChildren(i)}getEntries(){return this.entries.slice()}refreshLocale(){let e=this.scrollEl.scrollTop;if(this.olderBtn.textContent=b("android.load.earlier","Load earlier"),this.renderBanners(),this.thread&&this.entries.length>0)this.renderEntries(!1);this.scrollEl.scrollTop=e}setThread(e,t,n,i,s){if((this.thread?.id??"")!==(e?.id??""))this.planExpanded.clear(),this.planRevisingId="",this.planReviseDrafts.clear();this.thread=e,this.entries=t.filter((r)=>!Jt(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)=>!Jt(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(Jt(e))return;let t=this.isNearBottom()||e.kind==="user"&&Boolean(e.clientId),n=this.entries.findIndex((i)=>i.id===e.id);if(n<0&&e.clientId)n=this.entries.findIndex((i)=>i.clientId&&i.clientId===e.clientId);if(n>=0)this.entries[n]=e;else this.entries.push(e);this.renderEntries(t)}goTo(e){let t=this.scrollEl.querySelector(`[data-entry-id="${CSS.escape(e)}"]`);if(!t)return!1;return t.scrollIntoView({block:"center",behavior:"smooth"}),t.classList.remove("bp-entry-flash"),t.offsetWidth,t.classList.add("bp-entry-flash"),window.setTimeout(()=>t.classList.remove("bp-entry-flash"),1200),!0}removeEntry(e){let t=this.entries.filter((n)=>n.id!==e);if(t.length!==this.entries.length)this.entries=t,this.renderEntries(!1)}appendLiveText(e,t,n){let i=this.isNearBottom(),s=this.entries.find((a)=>a.id===e);if(!s){s={id:e,kind:"assistant",text:t,at:n,live:!0},this.entries.push(s),this.renderEntries(i);return}s.text+=t,s.live=!0;let r=this.liveNodes.get(e);if(r){if(r.replaceChildren(yt(s.text)),i)this.scrollToBottom()}else this.renderEntries(i)}isNearBottom(){let e=this.scrollEl;return e.scrollHeight-e.scrollTop-e.clientHeight<80}scrollToBottom(){this.pinnedToBottom=!0,this.scrollEl.scrollTop=this.scrollEl.scrollHeight}renderBanners(){let e=document.createDocumentFragment();if(this.noProvider&&!this.thread?.id.includes("~")){let t=document.createElement("div");t.className="bp-banner bp-no-provider",t.setAttribute("data-testid","no-provider-banner");let n=document.createElement("div");n.className="bp-no-provider-body";let i=document.createElement("strong");if(i.textContent=pe(this.noProvider.head),n.appendChild(i),this.noProvider.text){let a=document.createElement("span");a.className="bp-dim",a.textContent=pe(this.noProvider.text),n.appendChild(a)}let s=document.createElement("div");s.className="bp-banner-actions";let r=document.createElement("button");r.type="button",r.className="primary",r.setAttribute("data-testid","no-provider-accounts-btn"),r.textContent=pe(this.noProvider.button),r.addEventListener("click",()=>this.cb.onOpenAccounts?.()),s.appendChild(r),t.append(n,s),e.appendChild(t)}if(this.review&&(this.review.text||this.review.button)){let t=document.createElement("div");t.className="bp-banner bp-review-bar",t.setAttribute("data-testid","review-bar");let n=document.createElement("span");if(n.textContent=this.review.text||b("web.chat.review.mode","Review mode"),t.appendChild(n),this.review.button){let i=document.createElement("button");i.type="button",i.textContent=this.review.button,i.addEventListener("click",()=>this.cb.onToggleReview(!(this.review?.on??!0))),t.appendChild(i)}e.appendChild(t)}if(this.unanswered&&(this.unanswered.head||this.unanswered.text)){let t=document.createElement("div");t.className="bp-banner bp-unanswered",t.setAttribute("data-testid","unanswered-notice");let n=document.createElement("div");if(n.className="bp-unanswered-body",this.unanswered.head){let i=document.createElement("strong");i.textContent=this.unanswered.head,n.appendChild(i)}if(this.unanswered.text){let i=document.createElement("span");i.textContent=this.unanswered.text,n.appendChild(i)}if(t.appendChild(n),this.unanswered.buttons?.length){let i=document.createElement("div");i.className="bp-banner-actions";for(let s of this.unanswered.buttons){let r=document.createElement("button");if(r.type="button",s.primary)r.className="primary";r.textContent=s.label,r.addEventListener("click",()=>this.cb.onUnansweredAction(s.action,s.value)),i.appendChild(r)}t.appendChild(i)}e.appendChild(t)}if(this.btwNote){let t=document.createElement("div");t.className="bp-banner bp-btw-banner";let n=document.createElement("div"),i=document.createElement("div");i.className="bp-dim",i.textContent=`/btw ${this.btwNote.q}`;let s=document.createElement("div");s.appendChild(yt(this.btwNote.a)),n.append(i,s);let r=document.createElement("button");r.type="button",r.className="icon",r.textContent="×",r.addEventListener("click",()=>{this.btwNote=null,this.renderBanners()}),t.append(n,r),e.appendChild(t)}this.bannerEl.replaceChildren(e)}makeEntryActions(e,t,n){let i=document.createElement("div");i.className="bp-entry-foot"+(t?" user":"");let s=document.createElement("button");s.type="button",s.className="bp-entry-act";let r=b("common.copy","Copy"),a=document.createElement("span");a.textContent=r,s.append(wt(["M9 9h11v11H9z","M5 15H4a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1h10a1 1 0 0 1 1 1v1"]),a),s.addEventListener("click",()=>{navigator.clipboard?.writeText(e.text||"").then(()=>{a.textContent="✓",window.setTimeout(()=>{a.textContent=r},1000)}).catch(()=>{})});let o=document.createElement("button");o.type="button",o.className="bp-entry-act";let c=document.createElement("span");c.textContent=b("reply.action","Reply"),o.append(wt(["M9 17l-5-5 5-5","M20 18v-2a4 4 0 0 0-4-4H4"]),c),o.addEventListener("click",()=>this.cb.onReplyEntry(e));let u=!e.live&&!e.id.startsWith("local-")&&!e.id.startsWith("live:"),l=document.createElement("span");l.className="bp-entry-time";let p=vs(e.at);if(t)l.textContent=p,i.append(s,...u?[o]:[],l);else{let d=n&&e.at?ys(Yt(e.at)-Yt(n)):"",g=p?d?b("web.chat.finished.dur","Finished {time} · {dur}",{time:p,dur:d}):b("web.chat.finished","Finished {time}",{time:p}):"";l.textContent=e.live?b("web.chat.streaming","Streaming…"):g,i.append(l,s,...u?[o]:[])}return i}closePlanRevise(){let e=this.planRevisingId;if(!e)return!1;this.planRevisingId="";let t=this.scrollEl.scrollTop;return this.renderEntries(!1),this.scrollEl.scrollTop=t,this.listEl.querySelector(`[data-testid="ask-${CSS.escape(e)}"] [data-testid="plan-revise"]`)?.focus(),!0}renderEntries(e){let t=null,n=typeof document<"u"?document.activeElement:null;if(n instanceof HTMLTextAreaElement&&n.classList.contains("bp-plan-revise-input")&&this.listEl.contains(n)&&this.planRevisingId)this.planReviseDrafts.set(this.planRevisingId,n.value),t={askId:this.planRevisingId,start:n.selectionStart,end:n.selectionEnd,dir:n.selectionDirection};this.olderBtn.classList.toggle("bp-hidden",!this.hasMore),this.liveNodes.clear();let i=document.createDocumentFragment();if(!this.thread){let r=document.createElement("div");r.className="bp-empty-state",r.textContent=b("web.chat.choose","Choose a project thread on the left to begin."),i.appendChild(r),this.listEl.replaceChildren(i);return}if(this.entries.length===0){let r=document.createElement("div");r.className="bp-empty-state",r.textContent=b("web.chat.empty","No messages yet. Type below to start a turn."),i.appendChild(r),this.listEl.replaceChildren(i);return}let s=0;for(let r of this.entries){if(r.kind==="user"&&r.at)s=r.at;let a=document.createElement("article");if(a.className=`bp-entry bp-entry-${r.kind}`+(r.live?" is-live":""),a.setAttribute("data-entry-id",r.id),r.kind==="tool"&&r.tool){let l=document.createElement("div");l.className=`bp-tool-pill bp-tool-${r.tool.state||"done"}`;let p=document.createElement("span");if(p.className="bp-tool-name",p.textContent=r.tool.name,l.appendChild(p),r.tool.summary){let d=document.createElement("span");d.className="bp-tool-summary",d.textContent=r.tool.summary,l.appendChild(d)}a.appendChild(l),i.appendChild(a);continue}if(r.kind==="ask"&&r.ask){let l=r.ask;if(l.kind==="plan"){a.appendChild(this.renderPlanAsk(l)),i.appendChild(a);continue}let p=document.createElement("div");p.className="bp-ask-card",p.setAttribute("data-testid",`ask-${l.id}`);let d=document.createElement("div");if(d.className="bp-ask-q",d.textContent=l.question,p.appendChild(d),l.state==="open"){let g=document.createElement("div");if(g.className="bp-ask-opts",l.options&&l.options.length>0)for(let y of l.options){let m=document.createElement("button");m.type="button",m.textContent=y.label,m.addEventListener("click",()=>this.cb.onAnswerAsk(l.id,y.id)),g.appendChild(m)}else{let y=document.createElement("input");y.type="text",y.className="bp-input",y.placeholder=b("web.chat.answer.placeholder","Type answer…");let m=document.createElement("button");m.type="button",m.className="primary",m.textContent=b("web.chat.answer.btn","Answer"),m.addEventListener("click",()=>{if(y.value.trim())this.cb.onAnswerAsk(l.id,y.value.trim())}),g.append(y,m)}p.appendChild(g)}else{let g=document.createElement("div");g.className="bp-ask-answered",g.textContent=b("web.chat.answered","Answered: {answer}",{answer:l.answered??""}),p.appendChild(g)}a.appendChild(p),i.appendChild(a);continue}let o=Boolean(r.text&&r.text.trim().length>0),c=Boolean(r.images&&r.images.length>0),u=Boolean(r.attachments&&r.attachments.length>0);if(!o&&!c&&!u&&!r.live)continue;if(r.replyTo?.quote){let l=document.createElement("div");l.className="bp-reply-quote",l.textContent=b("gpui.b.in.reply.to","↩ In reply to: {quote}",{quote:r.replyTo.quote});let p=r.replyTo.id;l.setAttribute("role","button"),l.tabIndex=0,l.setAttribute("data-testid","entry-reply-quote");let d=()=>{if(this.cb.onGoToEntry)this.cb.onGoToEntry(p);else this.goTo(p)};l.addEventListener("click",d),l.addEventListener("keydown",(g)=>{if(g.key==="Enter"||g.key===" ")g.preventDefault(),d()}),a.appendChild(l)}if(o||r.live){let l=document.createElement("div");if(l.className="bp-entry-body",r.kind==="user")l.textContent=r.text;else l.appendChild(yt(r.text||""));if(r.live)this.liveNodes.set(r.id,l);a.appendChild(l)}if(u&&r.attachments){let l=document.createElement("div");l.className="bp-entry-images";for(let p of r.attachments)if(p.previewUrl){let d=document.createElement("img");d.className="bp-reply-img",d.src=p.previewUrl,d.alt=p.name||"attachment",l.appendChild(d)}else if(p.path||p.name){let d=document.createElement("span");d.className="bp-tool-pill",d.textContent=p.name||p.path||"image",l.appendChild(d)}if(l.childElementCount>0)a.appendChild(l)}if(r.images&&r.images.length>0){let l=document.createElement("div");l.className="bp-entry-images";for(let p of r.images){let d=document.createElement("img");d.className="bp-reply-img",d.alt=p;let g=`${r.id}|${p}`,y=this.imageCache.get(g);if(y)d.src=y;else this.cb.onLoadImage(r.id,p).then((m)=>{if(!m)return;let h=m.url??(m.mime&&m.data?`data:${m.mime};base64,${m.data}`:"");if(!h)return;this.imageCache.set(g,h),d.src=h});l.appendChild(d)}a.appendChild(l)}a.appendChild(this.makeEntryActions(r,r.kind==="user",r.kind==="assistant"?s:void 0)),i.appendChild(a)}if(this.listEl.replaceChildren(i),t&&this.planRevisingId===t.askId){let r=this.listEl.querySelector(`[data-testid="ask-${CSS.escape(t.askId)}"] .bp-plan-revise-input`);if(r){if(r.focus({preventScroll:!0}),t.start!==null&&t.end!==null)r.setSelectionRange(t.start,t.end,t.dir??void 0)}}if(e&&!t)this.scrollToBottom()}renderPlanAsk(e){let t=this.planExpanded.has(e.id),n=e.state==="open"&&this.planRevisingId===e.id,i=document.createElement("div");i.className="bp-ask-card bp-ask-plan",i.setAttribute("data-testid",`ask-${e.id}`);let s=document.createElement("div");s.className="bp-plan-head";let r=wt(["M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z","M14 2v6h6","M16 13H8","M16 17H8","M10 9H8"]);r.classList.add("bp-plan-head-ic");let a=document.createElement("span");if(a.className="bp-plan-title",a.textContent=!e.head||e.head==="Proposed plan"?b("ask.plan","Proposed plan"):pe(e.head),s.append(r,a),e.state==="open"){let l=document.createElement("span");l.className="bp-plan-badge",l.textContent=b("gpui.ask.plan.ready","Ready for review"),s.appendChild(l)}let o=document.createElement("span");if(o.className="bp-mgmt-flex1",s.appendChild(o),e.question){let l=document.createElement("button");l.type="button",l.className="bp-plan-head-btn";let p=b("common.copy","Copy"),d=document.createElement("span");d.textContent=p,l.append(wt(["M9 9h11v11H9z","M5 15H4a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1h10a1 1 0 0 1 1 1v1"]),d),l.addEventListener("click",()=>{navigator.clipboard?.writeText(e.question).then(()=>{l.classList.add("copied"),d.textContent=b("web.clone.copied","Copied"),window.setTimeout(()=>{l.classList.remove("copied"),d.textContent=p},1200)}).catch(()=>{})}),s.appendChild(l)}let c=document.createElement("button");c.type="button",c.className="bp-plan-head-btn",c.setAttribute("data-testid","plan-expand"),c.textContent=t?b("gpui.c.term.collapse","Collapse"):b("gpui.c.term.expand","Expand"),c.addEventListener("click",()=>{if(this.planExpanded.has(e.id))this.planExpanded.delete(e.id);else this.planExpanded.add(e.id);let l=this.scrollEl.scrollTop;this.renderEntries(!1),this.scrollEl.scrollTop=l}),s.appendChild(c),i.appendChild(s);let u=document.createElement("div");if(u.className="bp-plan-body"+(t?" is-expanded":""),u.setAttribute("data-testid","plan-body"),u.appendChild(yt(e.question||"")),i.appendChild(u),e.state==="open"){let l=document.createElement("div");l.className="bp-plan-actions";let p=e.options?.find((m)=>m.id==="implement"||m.id.endsWith("|implement")),d=document.createElement("button");if(d.type="button",d.className="primary",d.setAttribute("data-testid","plan-implement"),d.textContent=p?.label&&p.label!=="Implement"?pe(p.label):b("approval.implement","Implement"),d.addEventListener("click",()=>{this.planRevisingId="",this.planReviseDrafts.delete(e.id),this.cb.onAnswerAsk(e.id,p?.id??"implement")}),l.appendChild(d),e.revise!==!1){let m=document.createElement("button");m.type="button",m.className="bp-plan-revise-btn"+(n?" active":""),m.setAttribute("data-testid","plan-revise"),m.append(wt(["M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7","M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"]),document.createTextNode(b("gpui.ask.plan.revise","Revise"))),m.addEventListener("click",()=>{let h=this.planRevisingId!==e.id;this.planRevisingId=h?e.id:"";let f=this.scrollEl.scrollTop;if(this.renderEntries(!1),this.scrollEl.scrollTop=f,h)this.listEl.querySelector(`[data-testid="ask-${CSS.escape(e.id)}"] .bp-plan-revise-input`)?.focus()}),l.appendChild(m)}let g=e.options?.find((m)=>m.id==="dismiss"||m.id.endsWith("|dismiss")),y=document.createElement("button");if(y.type="button",y.className="bp-plan-dismiss-btn",y.setAttribute("data-testid","plan-dismiss"),y.textContent=g?.label&&g.label!=="Dismiss"?pe(g.label):b("approval.dismiss","Dismiss"),y.addEventListener("click",()=>{this.planRevisingId="",this.planReviseDrafts.delete(e.id),this.cb.onAnswerAsk(e.id,g?.id??"dismiss")}),l.appendChild(y),i.appendChild(l),n){let m=document.createElement("div");m.className="bp-plan-revise",m.setAttribute("data-testid","plan-revise-drawer");let h=document.createElement("textarea");h.rows=2,h.className="bp-input bp-plan-revise-input",h.placeholder=b("gpui.ask.plan.reviseph","What should change in the plan?"),h.value=this.planReviseDrafts.get(e.id)??"";let f=document.createElement("button");f.type="button",f.className="bp-plan-revise-send",f.setAttribute("data-testid","plan-revise-send"),f.textContent=b("gpui.ask.plan.sendrev","Send revision"),f.disabled=h.value.trim().length===0;let w=()=>{let M=h.value.trim();if(!M)return;this.planRevisingId="",this.planReviseDrafts.delete(e.id),this.cb.onAnswerAsk(e.id,`revise:${M}`)},C=()=>{this.closePlanRevise()};m.addEventListener("keydown",(M)=>{if(M.key==="Escape")M.preventDefault(),M.stopPropagation(),C()}),h.addEventListener("input",()=>{this.planReviseDrafts.set(e.id,h.value),f.disabled=h.value.trim().length===0}),h.addEventListener("keydown",(M)=>{if(M.key==="Enter"&&!M.shiftKey)M.preventDefault(),w()}),f.addEventListener("click",w);let A=document.createElement("button");A.type="button",A.className="bp-btn-ghost",A.textContent=b("common.cancel","Cancel"),A.addEventListener("click",C),m.append(h,f,A),i.appendChild(m)}}else{let l=document.createElement("div");l.className="bp-ask-answered",l.textContent=b("web.chat.answered","Answered: {answer}",{answer:e.answered??""}),i.appendChild(l)}return i}}var Gn="http://www.w3.org/2000/svg",On=4,Vn=new Set(["image/png","image/jpeg","image/webp","image/gif"]);function Bt(e){let t=document.createElementNS(Gn,"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(Gn,"path");i.setAttribute("d",n),t.appendChild(i)}return t}function Zt(){return Bt(["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 Un(){return Bt(["M6 4l14 8-14 8z"])}function ws(e){let t=(e||"").toLowerCase();if(t.includes("claude")||t.includes("anthropic"))return{glyph:"A",color:"#d97706",title:"Claude"};if(t.includes("codex")||t.includes("openai"))return{glyph:"O",color:"#10b981",title:"Codex"};if(t.includes("gemini")||t.includes("antigravity"))return{glyph:"G",color:"#3b82f6",title:"Gemini"};if(t.includes("grok"))return{glyph:"X",color:"#94a3b8",title:"Grok"};return{glyph:"●",color:"var(--accent)",title:e||"Model"}}class Qt{popupEl;attachStripEl;planBarEl;fileInput;textarea;memoryEl;memoryFill;memoryText;providerMarkEl;modelTextEl;ctxEl;planChipBtn;planChipIconHost;planChipLbl;attachBtn;voiceBtn;sendBtn;stopBtn;errorEl;replyEl;cb;commands=[];popupMode="none";filteredSlash=[];mentionItems=[];popupIdx=0;enabled=!1;attachments=[];planMode=null;constructor(e,t){this.cb=t;let n=document.createElement("div");n.className="bp-composer",n.setAttribute("data-testid","composer");let i=document.createElement("div");i.className="bp-composer-inner",this.popupEl=document.createElement("div"),this.popupEl.className="bp-composer-popup bp-hidden",this.popupEl.setAttribute("data-testid","slash-menu"),this.errorEl=document.createElement("div"),this.errorEl.className="bp-composer-err bp-hidden",this.replyEl=document.createElement("div"),this.replyEl.className="bp-reply-strip bp-hidden",this.replyEl.setAttribute("data-testid","composer-reply"),this.attachStripEl=document.createElement("div"),this.attachStripEl.className="bp-attach-strip bp-hidden",this.attachStripEl.setAttribute("data-testid","composer-attachments"),this.planBarEl=document.createElement("div"),this.planBarEl.className="bp-plan-bar bp-hidden",this.planBarEl.setAttribute("data-testid","composer-plan-bar"),this.fileInput=document.createElement("input"),this.fileInput.type="file",this.fileInput.accept="image/png,image/jpeg,image/webp,image/gif",this.fileInput.multiple=!0,this.fileInput.className="bp-hidden",this.fileInput.setAttribute("data-testid","composer-file-input"),this.fileInput.addEventListener("change",()=>{if(this.fileInput.files)this.addFiles(Array.from(this.fileInput.files));this.fileInput.value=""}),this.textarea=document.createElement("textarea"),this.textarea.className="bp-composer-input",this.textarea.rows=2,this.textarea.placeholder=b("composer.placeholder","Ask anything: @bot, >thread, %project, #room, $skill, /btw"),this.textarea.setAttribute("data-testid","composer-input");let s=document.createElement("div");s.className="bp-composer-bar";let r=document.createElement("div");r.className="bp-composer-model",this.providerMarkEl=document.createElement("span"),this.providerMarkEl.className="bp-provider-mark",this.providerMarkEl.textContent="●",this.modelTextEl=document.createElement("span"),this.modelTextEl.className="bp-model-text",this.modelTextEl.textContent="default",this.ctxEl=document.createElement("span"),this.ctxEl.className="bp-ctx-pct bp-hidden",this.ctxEl.setAttribute("data-testid","composer-ctx"),r.append(this.providerMarkEl,this.modelTextEl,this.ctxEl),this.planChipBtn=document.createElement("button"),this.planChipBtn.type="button",this.planChipBtn.className="bp-plan-chip bp-hidden",this.planChipBtn.setAttribute("data-testid","composer-plan-chip"),this.planChipBtn.setAttribute("aria-pressed","false"),this.planChipIconHost=document.createElement("span"),this.planChipIconHost.className="bp-plan-chip-ic",this.planChipIconHost.appendChild(Zt()),this.planChipLbl=document.createElement("span"),this.planChipLbl.textContent=b("gpui.mgmt.plan.tab","Plan"),this.planChipBtn.append(this.planChipIconHost,this.planChipLbl),this.planChipBtn.addEventListener("click",()=>this.cb.onCyclePlanMode?.()),this.memoryEl=document.createElement("div"),this.memoryEl.className="bp-composer-memory bp-hidden",this.memoryEl.setAttribute("data-testid","composer-memory");let a=document.createElement("div");a.className="bp-memory-meter",this.memoryFill=document.createElement("div"),this.memoryFill.className="bp-memory-fill",a.appendChild(this.memoryFill),this.memoryText=document.createElement("span"),this.memoryEl.append(a,this.memoryText);let o=document.createElement("div");o.className="bp-composer-btns",this.attachBtn=document.createElement("button"),this.attachBtn.type="button",this.attachBtn.className="icon bp-composer-tool",this.attachBtn.title=b("web.composer.attach","Attach image"),this.attachBtn.setAttribute("aria-label",b("web.composer.attach","Attach image")),this.attachBtn.setAttribute("data-testid","composer-attach"),this.attachBtn.appendChild(Bt(["M21.44 11.05l-9.19 9.19a6 6 0 0 1-8.49-8.49l9.19-9.19a4 4 0 0 1 5.66 5.66l-9.2 9.19a2 2 0 0 1-2.83-2.83l8.49-8.48"])),this.attachBtn.addEventListener("click",()=>this.fileInput.click()),this.voiceBtn=document.createElement("button"),this.voiceBtn.type="button",this.voiceBtn.className="icon bp-composer-tool",this.voiceBtn.title=b("web.composer.voice","Voice dictation"),this.voiceBtn.setAttribute("aria-label",b("web.composer.voice","Voice dictation")),this.voiceBtn.setAttribute("data-testid","composer-voice"),this.voiceBtn.appendChild(Bt(["M12 1a3 3 0 0 0-3 3v8a3 3 0 0 0 6 0V4a3 3 0 0 0-3-3z","M19 10v2a7 7 0 0 1-14 0v-2","M12 19v4","M8 23h8"])),this.voiceBtn.addEventListener("click",()=>this.cb.onToggleVoice?.()),this.stopBtn=document.createElement("button"),this.stopBtn.type="button",this.stopBtn.className="primary stop bp-hidden",this.stopBtn.textContent=b("composer.stop","Stop"),this.stopBtn.setAttribute("data-testid","composer-stop"),this.stopBtn.addEventListener("click",()=>this.cb.onInterrupt()),this.sendBtn=document.createElement("button"),this.sendBtn.type="button",this.sendBtn.className="primary bp-send-btn",this.sendBtn.textContent=b("composer.send","Send"),this.sendBtn.setAttribute("data-testid","composer-send"),this.sendBtn.addEventListener("click",()=>this.submit()),o.append(this.attachBtn,this.voiceBtn,this.stopBtn,this.sendBtn),s.append(r,this.planChipBtn,this.memoryEl,o),i.append(this.popupEl,this.errorEl,this.replyEl,this.attachStripEl,this.planBarEl,this.fileInput,this.textarea,s),n.appendChild(i),e.appendChild(n),this.textarea.addEventListener("paste",(c)=>{let u=c.clipboardData?.items;if(!u)return;let l=[];for(let p=0;p0)c.preventDefault(),this.addFiles(l)}),this.textarea.addEventListener("input",()=>{this.autoGrow(),this.clearError(),this.updatePopups()}),this.textarea.addEventListener("keydown",(c)=>{if(this.popupMode!=="none"){let u=this.popupMode==="slash"?this.filteredSlash.length:this.mentionItems.length;if(c.key==="ArrowDown"){c.preventDefault(),this.popupIdx=(this.popupIdx+1)%Math.max(1,u),this.renderPopup();return}if(c.key==="ArrowUp"){c.preventDefault(),this.popupIdx=(this.popupIdx-1+Math.max(1,u))%Math.max(1,u),this.renderPopup();return}if(c.key==="Tab"||c.key==="Enter"&&!c.shiftKey&&this.shouldCompleteOnEnter()){c.preventDefault(),this.applyPopupChoice(this.popupIdx);return}if(c.key==="Escape"){c.preventDefault(),this.closePopup();return}}if(c.key==="Tab"&&c.shiftKey&&this.planMode!==null){c.preventDefault(),this.cb.onCyclePlanMode?.();return}if(c.key==="Enter"&&!c.shiftKey)c.preventDefault(),this.submit()})}setCommands(e){this.commands=e.map((t)=>({...t,word:t.word.replace(/^\//,"")}))}setModelChip(e,t,n){let i=ws(t);if(this.providerMarkEl.textContent=i.glyph,this.providerMarkEl.style.color=i.color,this.providerMarkEl.title=i.title,this.modelTextEl.textContent=e||"default",typeof n==="number"&&Number.isFinite(n)&&n>=0)this.ctxEl.textContent=`ctx ${Math.round(n)}%`,this.ctxEl.classList.remove("bp-hidden");else this.ctxEl.textContent="",this.ctxEl.classList.add("bp-hidden")}setFeatures(e,t){this.attachBtn.classList.toggle("bp-hidden",!e),this.voiceBtn.classList.toggle("bp-hidden",!t)}setVoiceRecording(e){this.voiceBtn.classList.toggle("recording",e),this.voiceBtn.setAttribute("aria-pressed",e?"true":"false")}setVoiceLevel(e){this.voiceBtn.setAttribute("data-level",String(e))}getDraft(){return this.textarea.value}getCaret(){return this.textarea.selectionStart??this.textarea.value.length}setMemory(e){if(this.memoryEl.classList.toggle("bp-hidden",!e),!e)return;let t=e.total??0,n=t>0?Math.min(1,(e.done??0)/t):1;this.memoryFill.style.width=`${Math.round(n*100)}%`,this.memoryFill.dataset.state=e.state??"",this.memoryText.textContent=e.line??"",this.memoryEl.title=[e.status,e.lines,e.viewLine].filter(Boolean).join(` +`)}setPlanMode(e){if(this.planMode=e,this.textarea.classList.remove("is-plan","is-plan-exec"),this.sendBtn.classList.remove("is-plan","is-plan-exec"),this.planChipBtn.classList.remove("is-plan","is-exec"),this.planBarEl.classList.remove("is-exec"),!e){this.planChipBtn.classList.add("bp-hidden"),this.planChipBtn.setAttribute("aria-pressed","false"),this.planBarEl.classList.add("bp-hidden"),this.planBarEl.replaceChildren(),this.sendBtn.textContent=b("composer.send","Send");return}let t=e.phase,n=t!=="off",i=t==="armed"||t==="planning"||t==="pending",s=t==="executing";this.planChipBtn.classList.remove("bp-hidden"),this.planChipBtn.classList.toggle("is-plan",i),this.planChipBtn.classList.toggle("is-exec",s),this.planChipBtn.setAttribute("aria-pressed",n?"true":"false");let r=`${b("gpui.planmode.tip","Plan before acting (1 turn, always, or off)")} · Shift+Tab`;if(this.planChipBtn.title=r,this.planChipBtn.setAttribute("aria-label",r),this.planChipIconHost.replaceChildren(s?Un():Zt()),this.planChipLbl.textContent=s?b("gpui.planmode.chip.building","Building"):t==="pending"?b("gpui.mgmt.fab.reviewbtn","Review"):i&&e.once?b("gpui.planmode.chip.once","Plan · 1t"):b("gpui.mgmt.plan.tab","Plan"),this.textarea.classList.toggle("is-plan",i),this.textarea.classList.toggle("is-plan-exec",s),this.sendBtn.classList.toggle("is-plan",i),this.sendBtn.classList.toggle("is-plan-exec",s),this.sendBtn.textContent=i?b("gpui.mgmt.plan.tab","Plan"):b("composer.send","Send"),!n){this.planBarEl.classList.add("bp-hidden"),this.planBarEl.replaceChildren();return}this.planBarEl.classList.remove("bp-hidden"),this.planBarEl.classList.toggle("is-exec",s);let a=document.createElement("span");a.className="bp-plan-bar-ic",a.appendChild(s?Un():Zt());let o=document.createElement("span");o.className="bp-plan-bar-text",o.textContent=t==="armed"&&e.once?b("gpui.planmode.bar.once","Plan mode (1 turn) — explores and proposes a plan before editing"):t==="armed"?b("gpui.planmode.bar.always","Plan mode — explores and proposes a plan before editing"):t==="planning"?b("gpui.planmode.bar.planning","Planning — drafting a plan before edits"):t==="pending"?b("gpui.planmode.bar.pending","Proposed plan awaits review below"):b("gpui.planmode.bar.executing","Building the approved plan");let c=[a,o];if(t==="armed"||t==="planning"){let u=document.createElement("div");u.className="bp-plan-scopes";let l=(p,d,g,y)=>{let m=document.createElement("button");return m.type="button",m.className="bp-plan-scope-btn"+(d?" active":""),m.textContent=p,m.disabled=!this.enabled,m.setAttribute("data-testid",y),m.addEventListener("click",()=>this.cb.onSetPlanMode?.(g)),m};u.append(l(b("gpui.planmode.scope.once","1 turn"),e.once,"once","plan-scope-once"),l(b("gpui.planmode.scope.always","Always"),!e.once,"always","plan-scope-always"),l(b("gpui.bots.recall.off","Off"),!1,"off","plan-scope-off")),c.push(u)}this.planBarEl.replaceChildren(...c)}setState(e,t){this.enabled=e,this.textarea.disabled=!e,this.sendBtn.disabled=!e,this.attachBtn.disabled=!e,this.voiceBtn.disabled=!e,this.planChipBtn.disabled=!e,this.planBarEl.querySelectorAll(".bp-plan-scope-btn").forEach((n)=>{n.disabled=!e}),this.stopBtn.classList.toggle("bp-hidden",!t)}setDraft(e){this.textarea.value=e,this.autoGrow(),this.textarea.focus()}setReply(e,t,n){if(!e){this.replyEl.replaceChildren(),this.replyEl.classList.add("bp-hidden");return}let i=document.createElement("button");i.type="button",i.className="bp-reply-strip-body",i.setAttribute("data-testid","composer-reply-go");let s=document.createElement("span");s.className="bp-reply-strip-who",s.textContent=e.who;let r=document.createElement("span");if(r.className="bp-reply-strip-line",r.textContent=b("gpui.b.replying.to","↩ Replying to: {line}",{line:e.line}),i.append(s,r),t)i.addEventListener("click",t);let a=document.createElement("button");a.type="button",a.className="icon bp-reply-strip-drop",a.textContent="×";let o=b("reply.cancel","Cancel reply");if(a.title=o,a.setAttribute("aria-label",o),a.setAttribute("data-testid","composer-reply-drop"),n)a.addEventListener("click",n);this.replyEl.replaceChildren(i,a),this.replyEl.classList.remove("bp-hidden"),this.textarea.focus()}prependDraft(e){let t=this.textarea.value;this.textarea.value=t?`${e} +${t}`:e,this.autoGrow(),this.textarea.focus()}showError(e,t){let n=document.createElement("span");if(n.textContent=pe(e),t){let i=document.createElement("button");i.type="button",i.className="bp-composer-err-act",i.setAttribute("data-testid","composer-err-accounts"),i.textContent=t.label,i.addEventListener("click",t.onClick),this.errorEl.replaceChildren(n,i)}else this.errorEl.replaceChildren(n);this.errorEl.classList.remove("bp-hidden")}clearError(){this.errorEl.replaceChildren(),this.errorEl.classList.add("bp-hidden")}focus(){this.textarea.focus()}refreshLocale(){this.textarea.placeholder=b("composer.placeholder","Ask anything: @bot, >thread, %project, #room, $skill, /btw"),this.attachBtn.title=b("web.composer.attach","Attach image"),this.attachBtn.setAttribute("aria-label",b("web.composer.attach","Attach image")),this.voiceBtn.title=b("web.composer.voice","Voice dictation"),this.voiceBtn.setAttribute("aria-label",b("web.composer.voice","Voice dictation")),this.sendBtn.textContent=b("composer.send","Send"),this.stopBtn.textContent=b("composer.stop","Stop"),this.setPlanMode(this.planMode)}autoGrow(){this.textarea.style.height="auto",this.textarea.style.height=`${Math.min(180,Math.max(54,this.textarea.scrollHeight))}px`}shouldCompleteOnEnter(){if(this.popupMode==="mention")return!0;if(this.popupMode==="slash"){let e=this.textarea.value;return e.startsWith("/")&&!e.includes(" ")}return!1}updatePopups(){let e=this.textarea.value;if(e.startsWith("/")&&!e.includes(" ")&&!e.includes(` +`)){let n=e.slice(1).toLowerCase();if(this.filteredSlash=this.commands.filter((i)=>i.word.toLowerCase().startsWith(n)),this.filteredSlash.length>0){this.popupMode="slash",this.popupIdx=Math.min(this.popupIdx,this.filteredSlash.length-1),this.renderPopup();return}}let t=/(?:^|\s)([@>%#])([a-zA-Z0-9._-]{1,32})$/.exec(e.slice(0,this.textarea.selectionStart));if(t){let n=t[1],i=t[2];this.cb.onQueryMentions(i,n).then((s)=>{if(s.length>0)this.mentionItems=s,this.popupMode="mention",this.popupIdx=0,this.renderPopup();else if(this.popupMode==="mention")this.closePopup()});return}this.closePopup()}closePopup(){this.popupMode="none",this.popupEl.classList.add("bp-hidden"),this.popupEl.replaceChildren()}renderPopup(){let e=document.createDocumentFragment();if(this.popupMode==="slash")this.filteredSlash.forEach((t,n)=>{let i=document.createElement("button");i.type="button",i.className="bp-popup-row"+(n===this.popupIdx?" active":""),i.setAttribute("data-testid",`slash-item-${t.word}`);let s=document.createElement("span");s.className="bp-popup-name",s.textContent=`/${t.word}`;let r=document.createElement("span");r.className="bp-popup-desc",r.textContent=t.desc||t.label,i.append(s,r),i.addEventListener("mousedown",(a)=>{a.preventDefault(),this.applyPopupChoice(n)}),e.appendChild(i)});else if(this.popupMode==="mention")this.mentionItems.forEach((t,n)=>{let i=document.createElement("button");i.type="button",i.className="bp-popup-row"+(n===this.popupIdx?" active":"");let s=document.createElement("span");s.className="bp-popup-name",s.textContent=t.word||`${t.sigil}${t.label}`;let r=document.createElement("span");r.className="bp-popup-desc",r.textContent=t.detail||t.label,i.append(s,r),i.addEventListener("mousedown",(a)=>{a.preventDefault(),this.applyPopupChoice(n)}),e.appendChild(i)});this.popupEl.replaceChildren(e),this.popupEl.classList.remove("bp-hidden")}applyPopupChoice(e){if(this.popupMode==="slash"){let t=this.filteredSlash[e];if(t)this.textarea.value=`/${t.word} `,this.autoGrow(),this.textarea.focus();this.closePopup()}else if(this.popupMode==="mention"){let t=this.mentionItems[e];if(t){let n=this.textarea.selectionStart,i=this.textarea.value.slice(0,n),s=this.textarea.value.slice(n),r=i.replace(/([@>%#][a-zA-Z0-9._-]{1,32})$/,`${t.word} `);this.textarea.value=r+s,this.textarea.selectionStart=this.textarea.selectionEnd=r.length,this.textarea.focus()}this.closePopup()}}async addFiles(e){this.clearError();for(let t of e){if(!Vn.has(t.type)){this.showError(b("web.composer.unsupported","Unsupported image type: {type}",{type:t.type||t.name}));continue}if(this.attachments.length>=On){this.showError(b("web.composer.maximages","At most {max} images per message.",{max:On}));break}let n=await new Promise((s,r)=>{let a=new FileReader;a.onload=()=>s(String(a.result||"")),a.onerror=()=>r(Error("read failed")),a.readAsDataURL(t)}).catch(()=>""),i=n.indexOf(",");if(i<0)continue;this.attachments.push({name:t.name||`image-${this.attachments.length+1}.png`,mime:t.type,data:n.slice(i+1),previewUrl:n})}this.renderAttachments()}renderAttachments(){if(this.attachments.length===0){this.attachStripEl.classList.add("bp-hidden"),this.attachStripEl.replaceChildren();return}let e=document.createDocumentFragment();this.attachments.forEach((t,n)=>{let i=document.createElement("div");i.className="bp-attach-chip";let s=document.createElement("img");s.src=t.previewUrl,s.alt=t.name,s.className="bp-attach-thumb";let r=document.createElement("button");r.type="button",r.className="icon bp-attach-rm",r.textContent="×",r.title=b("common.remove","Remove"),r.addEventListener("click",()=>{this.attachments.splice(n,1),this.renderAttachments()}),i.append(s,r),e.appendChild(i)}),this.attachStripEl.replaceChildren(e),this.attachStripEl.classList.remove("bp-hidden")}submit(){if(!this.enabled)return;let e=this.textarea.value.trim();if(!e&&this.attachments.length===0)return;if(this.closePopup(),this.clearError(),e.startsWith("/")&&this.attachments.length===0){let n=e.slice(1).split(/\s+/)[0]?.toLowerCase()??"";if(this.commands.some((i)=>i.word.toLowerCase()===n)){this.textarea.value="",this.autoGrow(),this.cb.onRunCommand(e);return}}let t=this.attachments.map(({name:n,mime:i,data:s})=>({name:n,mime:i,data:s}));this.attachments=[],this.renderAttachments(),this.textarea.value="",this.autoGrow(),this.cb.onSend(e,t)}}async function Wn(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 Es=new Set(["bom","checks","life","plan","fab"]);function It(e){if(!e||!Array.isArray(e.panels))return[];return e.panels.filter((t)=>t&&typeof t.id==="string"&&Es.has(t.id))}function Yn(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 Rt(e,t=22){let n=e.join(", ");if(n.length<=t)return n;let i="";for(let s=0;s0?` +${o}`.length:0)>t)return i?`${i} +${e.length-s}`:`${e[0]} +${e.length-1}`;i=a}return i}function at(e){if(!Number.isFinite(e)||e<0)return"?";if(e<1000)return String(Math.round(e));if(e<1e6){let n=e/1000;return n<10?`${n.toFixed(1).replace(/\.0$/,"")}k`:`${Math.round(n)}k`}let t=e/1e6;return t<10?`${t.toFixed(1).replace(/\.0$/,"")}M`:`${Math.round(t)}M`}function ot(e){if(!Number.isFinite(e))return"";if(e>=1)return`$${e.toFixed(2)}`;let t=e.toFixed(4).replace(/0+$/,"");return(t.split(".")[1]??"").length<2?`$${e.toFixed(2)}`:`$${t}`}var xs=new Set(["0201","0402","0603","0805","1206","1210","1812","2010","2512"]),Cs=new Set(["QFN","DFN","SOT","SOIC","SOP","SSOP","TSSOP","MSOP","QFP","LQFP","TQFP","BGA","WLCSP","SOD","TO","SON","LGA"]);function Xn(e){if(!e)return"";let t=e.indexOf(":"),i=(t>=0?e.slice(t+1):e).split("_");for(let a of i)if(xs.has(a))return a;let s=i[0]??"",r=s.replace(/[^a-zA-Z].*$/,"").toUpperCase();if(Cs.has(r)){let a=s.split("-");if(a.length>=2&&/^\d+$/.test(a[1]))return`${a[0]}-${a[1]}`;return a[0]}return i.slice(0,2).join("_")}function Zn(e){let t=e?.status??"";if(!t)return null;let n=typeof e?.stock==="number"?e.stock:-1;if(t==="checking")return{text:"…",tone:"faint"};if(t==="unknown")return{text:"?",tone:"faint"};if(t==="out")return{text:`out ${at(Math.max(n,0))}`,tone:"bad"};if(t==="low")return{text:`low ${at(n)}`,tone:"warn"};return{text:at(n),tone:"ok"}}function Qn(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 ei(e,t){if(!t)return e;return e.filter((n)=>n.source===t)}function tn(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 jt(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 ti(e){return e.state==="routed"||e.state==="verified"}function ni(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 ii(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 si(e){let t=e.done??0,n=e.approved??0,i=e.awaiting??0,s=e.blocked??0,r=0;if(typeof e.total!=="number"){for(let a of e.layers??[])for(let o of a.items??[])if(o.state==="routed"||o.state==="verified")t+=1;else if(o.state==="routing")r+=1;else if(o.state==="approved")n+=1}else if(e.routing)r=Math.max(0,e.total-(t+n+i+s));return[{count:t,tone:"ok"},{count:r,tone:"accent"},{count:n,tone:"input"},{count:i,tone:"warn"},{count:s,tone:"bad"}]}function ri(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 ai(e){return e==="extra"?"costs-more limits":"base-price limits"}function nn(e,t){return e.watchGen===t.watchGen&&e.editGen===t.editGen&&e.project!==""&&e.project===t.project&&e.editId!==""&&e.editId===t.editId}function oi(e){return{project:e.project,refs:e.refs.slice(),field:e.field,value:e.was}}function sn(e,t){return e.watchGen===t.watchGen&&e.project!==""&&e.project===t.project&&e.threadId!==""&&e.threadId===t.threadId&&e.threadGen===t.threadGen}var _n=["#f59e0b","#38bdf8","#c084fc","#2dd4bf","#ef4444","#a3e635","#f97316","#ec4899"],qn=["#14b8a6","#f59e0b","#c084fc","#22c55e","#38bdf8","#ef4444","#e879f9","#84cc16"];function li(e){let t=2166136261;for(let n=0;n>>0;return t}function Et(e,t=""){let n=t.trim().toLowerCase();if(n&&n!=="#5a7a9a"&&n!=="#8a8a8a")return t;let i=e.toUpperCase();if(i.includes("3V3A")||i.includes("AVDD")||i.includes("VDDA"))return"#38bdf8";if(i.includes("1V8")||i.includes("1.8V"))return"#c084fc";if(i.includes("2V5")||i.includes("2.5V"))return"#a3e635";if(i.includes("3V3")||i.includes("3.3V")||i.includes("VCC"))return"#f59e0b";if(i.includes("5V")||i.startsWith("+5"))return"#ef4444";if(i.includes("12V")||i.includes("24V"))return"#f97316";if(i.includes("VBAT")||i.includes("VIN"))return"#ec4899";if(i.includes("GND"))return"#2dd4bf";return _n[li(i)%_n.length]}function lt(e,t=""){let n=t.trim().toLowerCase();if(n&&n!=="#8a8a8a")return t;return qn[li(e)%qn.length]}function ci(e,t,n,i=14){let s=Math.max(1,Math.abs(e[2]-e[0])),r=Math.max(1,Math.abs(e[3]-e[1])),a=Math.max(20,t-i*2),o=Math.max(20,n-i*2),c=Math.max(0.05,Math.min(200,Math.min(a/s,o/r)));return{cx:(e[0]+e[2])*0.5,cy:(e[1]+e[3])*0.5,scale:c,fitted:c,touched:!1}}function Ve(e,t,n,i,s){return[i*0.5+(t-e.cx)*e.scale,s*0.5+(n-e.cy)*e.scale]}function Ht(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 di(e,t,n){let i=Math.max(0.0001,e.scale);return{...e,cx:e.cx-t/i,cy:e.cy-n/i,touched:!0}}function pi(e,t,n,i,s,r){let a=Math.max(0.02,e.fitted*0.35),o=Math.max(40,e.fitted*24),c=Math.max(a,Math.min(o,e.scale*t)),[u,l]=Ht(e,n,i,s,r);return{...e,cx:u-(n-s*0.5)/c,cy:l-(i-r*0.5)/c,scale:c,touched:!0}}function mi(e,t,n,i){let s=e.map((a)=>[a[0],a[1]]);if(s.length===0)return[n];let r=i&&t+1>=s.length?s.length:Math.min(t+1,s.length);return s.splice(r,0,[n[0],n[1]]),s}function rn(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 ks(e,t,n,i,s,r){let a=s-n,o=r-i,c=a*a+o*o;if(c<0.000001)return(e-n)*(e-n)+(t-i)*(t-i);let u=Math.max(0,Math.min(1,((e-n)*a+(t-i)*o)/c)),l=n+u*a,p=i+u*o;return(e-l)*(e-l)+(t-p)*(t-p)}function Kn(e,t,n){if(n.length<3)return!1;let i=!1;for(let s=0,r=n.length-1;st!==u>t&&e<(c-a)*(t-o)/(u-o+0.000000000001)+a)i=!i}return i}function an(e,t){return Math.max(5,Math.min(32,e*t))}function Dt(e,t,n,i,s,r,a,o,c){if(i){for(let d of e){if(d.layer!==n||d.id!==i||d.locked)continue;let g=d.path??[];for(let y=0;y=3)for(let y=0;y=0;d--){let g=t[d];if(g.layer!==n)continue;let y=g.outline??[];if(!Kn(l,p,y))continue;if(!(g.holes??[]).some((h)=>Kn(l,p,h)))return{kind:"region",id:g.id}}return null}function ct(e){let t=null,n=null,i=[];for(let r of e){if(!r.layer)continue;i.push(r.layer);let a=r.items??[],o=a.filter((u)=>u.kind==="corridor").length,c=a.filter((u)=>u.kind==="plane").length;if((o>0||r.role==="signal")&&(!t||o>t.count))t={count:o,layer:r.layer};if((c>0||r.role==="power"||r.role==="plane")&&(!n||c>n.count))n={count:c,layer:r.layer}}let s=[];if(t)s.push(t.layer);if(n&&!s.includes(n.layer))s.push(n.layer);for(let r of i){if(s.length>=2)break;if(!s.includes(r))s.push(r)}return s}function zn(e,t){if(!e||e.length===0)return null;if(e.length===1)return e[0];let n=Math.max(0,Math.min(1,t)),i=0;for(let a=1;a=s&&o>0.000000001){let c=(s-r)/o;return[e[a-1][0]+(e[a][0]-e[a-1][0])*c,e[a-1][1]+(e[a][1]-e[a-1][1])*c]}r+=o}return e[e.length-1]}function it(e,t,n){for(let i of t??[])if(i.layer===e&&i.title)return i.title;for(let i of n??[])if(i.layer===e&&i.title)return i.title;return e}function ui(e,t,n){if(e==="split"&&n.length>0)return t.filter((i)=>n.includes(i.layer));return t}function en(e,t){return!(e[2]<=t[0]||e[0]>=t[2]||e[3]<=t[1]||e[1]>=t[3])}function Jn(e,t,n){if(n.length<3)return!1;let i=!1;for(let s=0,r=n.length-1;st!==u>t&&e<(c-a)*(t-o)/(u-o+0.000000000001)+a)i=!i}return i}function hi(e,t){if(e.length<3)return null;let n=1/0,i=1/0,s=-1/0,r=-1/0,a=0,o=0;for(let u of e)n=Math.min(n,u[0]),i=Math.min(i,u[1]),s=Math.max(s,u[0]),r=Math.max(r,u[1]),a+=u[0],o+=u[1];let c=[[(n+s)*0.5,(i+r)*0.5],[a/e.length,o/e.length]];for(let u of[0.5,0.25,0.75,0.125,0.875])for(let l of[0.5,0.25,0.75,0.125,0.875])c.push([n+(s-n)*l,i+(r-i)*u]);for(let u of c)if(Jn(u[0],u[1],e)&&!t.some((l)=>Jn(u[0],u[1],l)))return u;return null}function bi(e,t,n,i,s,r){let a=[];for(let l of e){let p=l.nets??0,d=l.path??[];if(p<=0||d.length<2)continue;let g=0;for(let y=1;y{let d=l.sel||l.hov?1:0,g=p.sel||p.hov?1:0;if(g!==d)return g-d;if(p.nets!==l.nets)return p.nets-l.nets;return l.b.id.localeCompare(p.b.id)});let o=[],c=[],u=(l,p,d,g,y)=>[l-d*0.5-y,p-g*0.5-y,l+d*0.5+y,p+g*0.5+y];for(let l of a){let p=l.b.name||"",d=String(l.nets),g=p?`${p} · ${l.nets}`:d,y=(l.sel||l.hov||l.pxLen>=95)&&p?[g,d]:[d],m=null,h=(w,C)=>Math.max(C*0.5+3,Math.min(Math.max(C*0.5+3,n-C*0.5-3),w)),f=(w,C)=>Math.max(C*0.5+3,Math.min(Math.max(C*0.5+3,i-C*0.5-3),w));e:for(let w of y){let C=Math.max(16,w.length*5.9+10),A=15;for(let M of[0.5,0.35,0.65,0.22,0.78]){let S=zn(l.pts,M);if(!S)continue;let[T,B]=Ve(t,S[0],S[1],n,i),R=h(T,C),O=f(B,15),H=u(R,O,C,15,2);if(!o.some((ae)=>en(H,ae))){m={id:l.b.id,text:w,cx:R,cy:O,pw:C,ph:15,col:l.col,sel:l.sel};break e}}}if(!m){let w=zn(l.pts,0.5);if(w){let[C,A]=Ve(t,w[0],w[1],n,i),M=Math.max(16,d.length*6.5+8),S=15,T=h(C,M);for(let B of[-18,18]){let R=f(A+B,15);if(!o.some((O)=>en(u(T,R,M,15,2),O))){m={id:l.b.id,text:d,cx:T,cy:R,pw:M,ph:15,col:l.col,sel:l.sel};break}}}}if(m)o.push(u(m.cx,m.cy,m.pw,m.ph,2)),c.push(m)}return c}function gi(e,t,n,i,s,r=[]){let a=new Set(s),o=[];for(let l of e){if(!l.r||!l.b||l.b.length!==4)continue;let[p,d]=Ve(t,l.b[0],l.b[1],n,i),[g,y]=Ve(t,l.b[2],l.b[3],n,i),m=Math.abs(g-p),h=Math.abs(y-d);if(m<13||h<9)continue;let f=(p+g)*0.5,w=(d+y)*0.5;if(f<8||f>n-8||w<8||w>i-8)continue;o.push({text:l.r,cx:f,cy:w,bw:l.r.length*5.8+4,bh:11,score:m*h+(a.has(l.r)?1e4:0)})}o.sort((l,p)=>p.score-l.score);let c=[...r],u=[];for(let l of o){let p=[l.cx-l.bw*0.5,l.cy-l.bh*0.5,l.cx+l.bw*0.5,l.cy+l.bh*0.5];if(!c.some((g)=>en(p,g)))c.push(p),u.push({text:l.text,cx:l.cx,cy:l.cy})}return u}function fi(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 Ft(e,t){if(!t||t.length===0)return e;let n=new Map;for(let r of e)if(r.layer)n.set(r.layer,r);let i=[],s=new Set;for(let r of t){if(!r.layer)continue;s.add(r.layer);let a=n.get(r.layer);if(a)i.push(a);else i.push({layer:r.layer,index:r.index,title:r.title||`L${r.index} · ${r.layer}`,subtitle:r.subtitle||"",role:r.role,status:"proposed",done:0,approved:0,total:0,items:[]})}for(let r of e)if(r.layer&&!s.has(r.layer))i.push(r);return i}function vi(e,t,n,i,s,r,a,o){return e===t&&n===i&&s===r&&(o===void 0||a>=o)}var yi="#111917",As="#16201d",Ls="rgba(212, 224, 219, 0.92)",Ss="rgba(61, 80, 73, 0.72)",Ps="rgba(82, 107, 97, 0.85)";var wi="#f59e0b",Ns="#eef5f2",Ei="#ef4444";function st(e,t){let n=e.trim().replace(/^#/,"");if(n.length===6){let i=parseInt(n.slice(0,2),16),s=parseInt(n.slice(2,4),16),r=parseInt(n.slice(4,6),16);if(!Number.isNaN(i)&&!Number.isNaN(s)&&!Number.isNaN(r))return`rgba(${i}, ${s}, ${r}, ${t})`}return`rgba(20, 184, 166, ${t})`}function Ms(e,t,n){let i=0.14,s=0.45,r=0.85,a=!1;switch(e){case"approved":case"routing":i=0.16,s=0.51,r=0.91;break;case"edited":i=0.2,s=0.56,r=0.95;break;case"routed":case"verified":i=0.08,s=0.26,r=0.59;break;case"rejected":case"failed":i=0.05,s=0.13,r=0.27;break;case"blocked":i=0.18,s=0.48,r=0.88,a=!0;break}if(t)i=Math.min(0.35,i+0.1),s=Math.min(0.71,s+0.12),r=1;else if(n)i=Math.min(0.28,i+0.06),s=Math.min(0.63,s+0.07);return{glow:i,body:s,core:r,bad:a}}function Ts(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 Bs(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 on{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=Ft(e.layers,e.copperLayers);if(t.length===0)return[];if(e.gridMode==="all")return t;if(e.gridMode==="single"){let s=e.shownLayers.find((a)=>t.some((o)=>o.layer===a))??ct(t)[0]??t[0]?.layer,r=t.find((a)=>a.layer===s);return r?[r]:[]}let n=e.shownLayers.length>0&&e.shownLayers.every((s)=>t.some((r)=>r.layer===s))?e.shownLayers.slice(0,2):ct(t),i=[];for(let s of n){let r=t.find((a)=>a.layer===s);if(r)i.push(r)}return i.length>0?i:t.slice(0,2)}update(e,t){this.state=e;let n=this.visibleLayers(e);this.root.classList.toggle("two-cols",t&&n.length>1);let i=n.map((s)=>s.layer).join("|");if(i!==this.renderedLayerKey){this.renderedLayerKey=i;for(let s of this.cards.values())s.ro.disconnect();this.cards.clear(),this.root.replaceChildren();for(let s of n){let r=this.buildCard(s);this.cards.set(s.layer,r),this.root.appendChild(r.el)}}else for(let s of n){let r=this.cards.get(s.layer);if(r)this.syncCardHeaderAndLegend(r,s)}this.scheduleDraw()}effectiveBbox(e){let t=e.bbox;if(!t||t.length!==4||Math.abs(t[2]-t[0])<0.5||Math.abs(t[3]-t[1])<0.5)return[0,0,100,70];return t}getCam(e,t,n){let i=this.state,s=i?.syncZoom?this.sharedCam:this.layerCams.get(e)??null;if(s&&s.touched)return s;return ci(i?this.effectiveBbox(i.board):[0,0,100,70],t,n,14)}setCam(e,t){if(this.state?.syncZoom)this.sharedCam=t;else this.layerCams.set(e,t)}buildCard(e){let t=document.createElement("section");t.className="bp-plan-card",t.setAttribute("data-testid",`mgmt-plan-card-${e.layer}`);let n=document.createElement("div");n.className="bp-plan-card-head";let i=document.createElement("div");i.className="bp-plan-card-head-top";let s=document.createElement("span"),r=e.role==="power"||(e.items?.length??0)>0&&(e.items??[]).every((w)=>w.kind==="plane");s.className="bp-plan-card-bar "+(r?"pwr":"sig");let a=document.createElement("span");a.className="bp-plan-card-title";let o=document.createElement("span");o.className="bp-plan-status-badge";let c=document.createElement("button");c.type="button",c.className="bp-mgmt-btn bp-plan-mini-btn",c.textContent="✓",c.title=b("gpui.mgmt.plan.layer","Approve layer"),c.addEventListener("click",(w)=>{w.stopPropagation(),this.cb.onApproveLayer(e.layer,!0)});let u=document.createElement("button");u.type="button",u.className="bp-mgmt-btn bp-plan-mini-btn",u.textContent="✗",u.title=b("gpui.mgmt.plan.rejectlayer","Reject layer"),u.addEventListener("click",(w)=>{w.stopPropagation(),this.cb.onApproveLayer(e.layer,!1)}),i.append(s,a,o,c,u);let l=document.createElement("div");l.className="bp-plan-card-sub",n.append(i,l);let p=document.createElement("div");p.className="bp-plan-card-canvas-wrap";let d=document.createElement("canvas");d.className="bp-plan-card-canvas",d.setAttribute("data-testid",`mgmt-plan-canvas-${e.layer}`);let g=document.createElement("div");g.className="bp-plan-hover-hud bp-hidden",p.append(d,g);let y=document.createElement("div");y.className="bp-plan-legend bp-hidden",t.append(n,p,y);let m=d.getContext("2d"),h=new ResizeObserver(()=>this.scheduleDraw());h.observe(p),this.attachPointerListeners(d,e.layer);let f={layer:e.layer,el:t,canvas:d,ctx:m,legendEl:y,okBtn:c,noBtn:u,statusEl:o,titleEl:a,subtitleEl:l,hoverHudEl:g,ro:h};return this.syncCardHeaderAndLegend(f,e),f}syncCardHeaderAndLegend(e,t){e.titleEl.textContent=it(t.layer,this.state?.copperLayers,this.state?.layers)||t.title||t.layer;let n=t.subtitle||t.stackup||"";e.subtitleEl.textContent=n,e.subtitleEl.classList.toggle("bp-hidden",!n);let i=t.items??[],s=Bs(t);e.statusEl.className=`bp-plan-card-status tone-${s.tone==="warn"?"dim":s.tone}`,e.statusEl.textContent=i.length>0?b(s.key,s.label):"",e.statusEl.classList.toggle("bp-hidden",i.length===0);let r=i.some((o)=>o.state==="proposed"||o.state==="edited");if(e.okBtn)e.okBtn.classList.toggle("bp-hidden",!r);if(e.noBtn)e.noBtn.classList.toggle("bp-hidden",!r);let a=(this.state?.regions??[]).filter((o)=>o.layer===t.layer);if(a.length===0)e.legendEl.classList.add("bp-hidden"),e.legendEl.replaceChildren();else{e.legendEl.classList.remove("bp-hidden");let o=document.createDocumentFragment();for(let c of a){let u=document.createElement("button");u.type="button";let l=this.state?.selectedId===c.id;u.className="bp-plan-legend-chip"+(l?" active":"");let p=document.createElement("span");p.className="bp-plan-legend-sw",p.style.background=Et(c.net||c.id,c.color||"");let d=document.createElement("span");d.textContent=c.net||c.id,u.append(p,d),u.addEventListener("click",()=>{this.cb.onSelect(c.id),this.cb.onFocusItem(c.id)}),o.appendChild(u)}e.legendEl.replaceChildren(o)}}attachPointerListeners(e,t){e.addEventListener("contextmenu",(i)=>i.preventDefault()),e.addEventListener("dblclick",()=>this.fitAll()),e.addEventListener("pointerdown",(i)=>{let s=this.state;if(!s)return;this.root.focus({preventScroll:!0});let r=e.getBoundingClientRect(),a=i.clientX-r.left,o=i.clientY-r.top,c=Math.max(1,r.width),u=Math.max(1,r.height),l=this.getCam(t,c,u),p=Dt(s.bands,s.regions,t,s.selectedId,l,c,u,a,o);if(i.button===2){if(p?.kind==="vertex"){let d=this.getItemPts(p.id,p.isPlane),g=rn(d,p.idx,p.isPlane);if(g)this.selectedVertex=null,this.cb.onCommitFields(p.id,{[p.isPlane?"outline":"path"]:g})}return}if(i.button!==0)return;if(e.setPointerCapture(i.pointerId),this.downPos={x:i.clientX,y:i.clientY},p?.kind==="vertex"){let d=this.getItemPts(p.id,p.isPlane),g=d.map((y)=>[y[0],y[1]]);this.selectedVertex={id:p.id,idx:p.idx},this.drag={layer:t,kind:"vertex",id:p.id,isPlane:p.isPlane,idx:p.idx,pts:d.map((y)=>[y[0],y[1]]),origPts:g,moved:!1},this.scheduleDraw()}else if(p?.kind==="midpoint"){let d=this.getItemPts(p.id,p.isPlane),g=d.map((h)=>[h[0],h[1]]),y=mi(d,p.segIdx,p.pos,p.isPlane),m=p.isPlane&&p.segIdx+1>=d.length?y.length-1:Math.min(p.segIdx+1,y.length-1);this.selectedVertex={id:p.id,idx:m},this.patchLocalItem(p.id,p.isPlane,y),this.drag={layer:t,kind:"vertex",id:p.id,isPlane:p.isPlane,idx:m,pts:y,origPts:g,moved:!0},this.scheduleDraw()}else this.selectedVertex=null,this.drag={layer:t,kind:"pan",lastX:a,lastY:o}}),e.addEventListener("pointermove",(i)=>{let s=this.state;if(!s)return;let r=e.getBoundingClientRect(),a=i.clientX-r.left,o=i.clientY-r.top,c=Math.max(1,r.width),u=Math.max(1,r.height);if(this.drag&&this.drag.layer===t){if(this.drag.kind==="pan"){let A=this.getCam(t,c,u);this.setCam(t,di(A,a-this.drag.lastX,o-this.drag.lastY)),this.drag.lastX=a,this.drag.lastY=o,this.scheduleDraw();return}if(this.downPos&&Math.hypot(i.clientX-this.downPos.x,i.clientY-this.downPos.y)<1.5&&!this.drag.moved)return;let m=this.getCam(t,c,u),[h,f]=Ht(m,a,o,c,u),w=[Math.round(h*1000)/1000,Math.round(f*1000)/1000];this.drag.moved=!0,this.drag.pts[this.drag.idx]=w;let C=this.drag.pts.map((A)=>[A[0],A[1]]);this.patchLocalItem(this.drag.id,this.drag.isPlane,C),this.scheduleDraw();return}let l=this.getCam(t,c,u),p=Dt(s.bands,s.regions,t,s.selectedId,l,c,u,a,o),d=this.hover?.hit?"id"in this.hover.hit?this.hover.hit.id:"":"",g=this.hover?.hit.kind??"",y=p?p.id:"";if(this.hover=p?{layer:t,hit:p}:null,e.style.cursor=p?"pointer":"crosshair",d!==y||(p?.kind??"")!==g)this.syncHoverHud(t),this.scheduleDraw()}),e.addEventListener("pointerleave",()=>{if(this.hover?.layer===t)this.hover=null,this.syncHoverHud(t),this.scheduleDraw()});let n=()=>{let i=this.drag;if(!i||i.layer!==t)return;if(this.drag=null,this.downPos=null,i.kind==="vertex"&&i.moved){let s=i.origPts.map((r)=>[r[0],r[1]]);this.patchLocalItem(i.id,i.isPlane,s)}this.cb.onDragEnd?.(),this.scheduleDraw()};e.addEventListener("pointercancel",n),e.addEventListener("lostpointercapture",n),e.addEventListener("pointerup",(i)=>{let s=this.state,r=this.drag,a=this.downPos;if(this.drag=null,this.downPos=null,e.hasPointerCapture(i.pointerId))e.releasePointerCapture(i.pointerId);if(r&&r.kind==="vertex"&&r.layer===t){if(r.moved)this.cb.onCommitFields(r.id,{[r.isPlane?"outline":"path"]:r.pts});else this.cb.onDragEnd?.(),this.scheduleDraw();return}if(s&&a&&Math.hypot(i.clientX-a.x,i.clientY-a.y)<4.5){let o=e.getBoundingClientRect(),c=i.clientX-o.left,u=i.clientY-o.top,l=Math.max(1,o.width),p=Math.max(1,o.height),d=this.getCam(t,l,p),g=Dt(s.bands,s.regions,t,s.selectedId,d,l,p,c,u);if(g&&(g.kind==="band"||g.kind==="region")){this.cb.onSelect(g.id),this.cb.onFocusItem(g.id);return}if(!g&&s.selectedId){this.cb.onSelect("");return}}this.cb.onDragEnd?.()}),e.addEventListener("wheel",(i)=>{i.preventDefault();let s=e.getBoundingClientRect(),r=i.clientX-s.left,a=i.clientY-s.top,o=Math.max(1,s.width),c=Math.max(1,s.height),u=this.getCam(t,o,c),l=Math.max(0.65,Math.min(1.55,1-i.deltaY*0.002));this.setCam(t,pi(u,l,r,a,o,c)),this.scheduleDraw()},{passive:!1})}patchLocalItem(e,t,n){let i=this.state;if(!i)return;if(t){let s=i.regions.find((r)=>r.id===e);if(s){if(s.outline=n,s.edited=!0,s.state==="proposed")s.state="edited"}}else{let s=i.bands.find((r)=>r.id===e);if(s){if(s.path=n,s.edited=!0,s.state==="proposed")s.state="edited"}}}getItemPts(e,t){let n=this.state;if(!n)return[];if(t)return(n.regions.find((i)=>i.id===e)?.outline??[]).map((i)=>[i[0],i[1]]);return(n.bands.find((i)=>i.id===e)?.path??[]).map((i)=>[i[0],i[1]])}syncHoverHud(e){let t=this.cards.get(e),n=this.state;if(!t||!n)return;if(!this.hover||this.hover.layer!==e){t.hoverHudEl.classList.add("bp-hidden"),t.hoverHudEl.textContent="";return}let i=this.hover.hit.id,s=n.bands.find((o)=>o.id===i),r=n.regions.find((o)=>o.id===i),a="";if(s)a=`${s.name||i} · ${s.nets??0}n · ${(s.width??1.5).toFixed(2)}mm`;else if(r)a=r.reference?`${r.net||i} · ${r.reference}`:r.net||i;if(!a)t.hoverHudEl.classList.add("bp-hidden");else t.hoverHudEl.classList.remove("bp-hidden"),t.hoverHudEl.textContent=a}onKeyDown(e){let t=this.state;if(!t)return;if(e.key==="0"||e.key==="Home"){e.preventDefault(),this.fitAll();return}if(e.key==="Escape"){this.selectedVertex=null,this.cb.onSelect("");return}if(!t.selectedId)return;let n=t.bands.find((a)=>a.id===t.selectedId),i=t.regions.find((a)=>a.id===t.selectedId),s=Boolean(n?.locked??i?.locked),r=e.key.toLowerCase();if(r==="a")e.preventDefault(),this.cb.onQuickApprove([t.selectedId],!0);else if(r==="r")e.preventDefault(),this.cb.onQuickApprove([t.selectedId],!1);else if(r==="l")e.preventDefault(),this.cb.onCommitFields(t.selectedId,{locked:!s});else if(r==="w"&&n&&!s){e.preventDefault();let a=e.shiftKey?-0.25:0.25,o=Math.round(Math.max(0.15,Math.min(25,(n.width??1.5)+a))*100)/100;this.cb.onCommitFields(t.selectedId,{width:o})}else if((e.key==="Delete"||e.key==="Backspace")&&!s&&this.selectedVertex?.id===t.selectedId){e.preventDefault();let a=Boolean(i),o=this.getItemPts(t.selectedId,a),c=rn(o,this.selectedVertex.idx,a);if(c)this.selectedVertex=null,this.cb.onCommitFields(t.selectedId,{[a?"outline":"path"]:c})}}scheduleDraw(){if(this.rafPending)return;this.rafPending=requestAnimationFrame(()=>{this.rafPending=0,this.drawAll()})}drawAll(){let e=this.state;if(!e)return;let t=Math.max(0.45,Math.min(1.25,Math.abs(this.effectiveBbox(e.board)[3]-this.effectiveBbox(e.board)[1])/Math.max(1,Math.abs(this.effectiveBbox(e.board)[2]-this.effectiveBbox(e.board)[0]))));for(let n of this.cards.values()){let i=n.canvas.parentElement;if(!i)continue;let s=Math.max(120,Math.round(i.clientWidth)),r=Math.max(165,Math.min(250,Math.round(s*t)));n.canvas.style.height=`${r}px`;let a=Math.max(1,window.devicePixelRatio||1),o=Math.round(s*a),c=Math.round(r*a);if(n.canvas.width!==o||n.canvas.height!==c)n.canvas.width=o,n.canvas.height=c;n.ctx.setTransform(a,0,0,a,0,0),this.drawLayer(n.ctx,n.layer,s,r,e)}}drawLayer(e,t,n,i,s){let r=this.getCam(t,n,i),a=(m,h)=>Ve(r,m,h,n,i);e.fillStyle=yi,e.fillRect(0,0,n,i);let o=(s.board.outline??[]).filter((m)=>m.length>=3);if(e.fillStyle=As,o.length>0){e.beginPath();for(let m of o){for(let h=0;hm.layer===t),u=this.hover?.layer===t?this.hover.hit:null;for(let m of c){let h=m.outline??[];if(h.length<3)continue;let f=s.selectedId===m.id,w=u?.id===m.id,C=Ts(m.state||"proposed",f,w),A=Et(m.net||m.id,m.color||"");e.beginPath();for(let S=0;SB)B=H;if(ae>R)R=ae}if(Math.abs(B-S)>=38&&Math.abs(R-T)>=18){let O=hi(h,m.holes??[]);if(O){let[H,ae]=a(O[0],O[1]);e.fillStyle=st(A,f?0.91:0.67),e.font="bold 10px ui-monospace, 'SFMono-Regular', Menlo, monospace",e.textAlign="center",e.textBaseline="middle",e.fillText(M,H,ae)}}}}if(e.strokeStyle=Ls,e.lineWidth=1.25,e.lineCap="round",e.lineJoin="round",o.length>0){e.beginPath();for(let m of o){for(let h=0;hm.layer===t),d=bi(p,r,n,i,s.selectedId,u?.id??""),g=d.map((m)=>[m.cx-m.pw*0.5-1,m.cy-m.ph*0.5-1,m.cx+m.pw*0.5+1,m.cy+m.ph*0.5+1]),y=[];for(let m of p){for(let h of m.from??[])y.push(h);for(let h of m.to??[])y.push(h)}e.fillStyle="rgba(143, 163, 155, 0.72)",e.font="9.5px ui-monospace, 'SFMono-Regular', Menlo, monospace",e.textAlign="center",e.textBaseline="middle";for(let m of gi(l,r,n,i,y,g))e.fillText(m.text,m.cx,m.cy);for(let m of p){let h=m.guides??[];if(h.length===0)continue;let f=s.selectedId===m.id||u?.id===m.id,w=lt(m.name||m.id,m.color||"");e.strokeStyle=st(w,f?0.38:0.17),e.lineWidth=f?1:0.7,e.beginPath();for(let C of h){let[A,M]=a(C[0],C[1]),[S,T]=a(C[2],C[3]);e.moveTo(A,M),e.lineTo(S,T)}e.stroke()}for(let m of p){let h=m.path??[];if(h.length<2)continue;let f=s.selectedId===m.id,w=u?.id===m.id,C=Ms(m.state||"proposed",f,w),A=lt(m.name||m.id,m.color||""),M=an(m.width??1.5,r.scale),S=()=>{e.beginPath();for(let T=0;T{let w=f?h.length:Math.max(0,h.length-1);for(let C=0;Cn.id===e))return;if(this.openPanel!==e)this.togglePanel(e)}getTabs(){return It(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=It(e);if(!this.digest||t.length===0){this.planCanvas?.destroy(),this.planCanvas=null,this.panelEl.classList.remove("bp-plan-expanded"),this.stripEl.classList.add("bp-hidden"),this.panelEl.classList.add("bp-hidden"),this.panelEl.removeAttribute("data-testid"),this.panelEl.replaceChildren(),this.stripEl.replaceChildren(),this.cb.onOpenChange?.(!1);return}this.stripEl.classList.remove("bp-hidden");let n=document.createDocumentFragment(),i=document.createElement("div");i.className="bp-mgmt-tabs";for(let a of t){let o=document.createElement("button");o.type="button";let c=this.openPanel===a.id;o.className="bp-mgmt-tab"+(c?" active":""),o.setAttribute("data-testid",`mgmt-tab-${a.id}`),o.setAttribute("aria-pressed",c?"true":"false");let u=document.createElement("span");u.textContent=pe(a.label),o.appendChild(u);let l=this.getPanelData(a.id),p=Yn(l);if(p){let d=document.createElement("span");d.className=`bp-mgmt-badge bp-tone-${p.tone}`,d.textContent=p.text,o.appendChild(d)}o.addEventListener("click",()=>this.togglePanel(a.id)),i.appendChild(o)}if(n.appendChild(i),this.openPanel){let a=document.createElement("button");a.type="button",a.className="icon bp-mgmt-close",a.textContent="×",a.title=b("gpui.mgmt.close","Close the panel"),a.setAttribute("aria-label",b("gpui.mgmt.close","Close the panel")),a.setAttribute("data-testid","mgmt-close"),a.addEventListener("click",()=>this.closePanel()),n.appendChild(a)}if(this.stripEl.replaceChildren(n),!this.openPanel){this.planCanvas?.destroy(),this.planCanvas=null,this.panelEl.classList.remove("bp-plan-expanded"),this.panelEl.classList.add("bp-hidden"),this.panelEl.removeAttribute("data-testid"),this.panelEl.replaceChildren(),this.cb.onOpenChange?.(!1);return}if(this.openPanel!=="plan")this.planCanvas?.destroy(),this.planCanvas=null,this.panelEl.classList.remove("bp-plan-expanded");else this.panelEl.classList.toggle("bp-plan-expanded",this.planExpanded);this.panelEl.classList.remove("bp-hidden"),this.panelEl.setAttribute("data-testid",`mgmt-panel-${this.openPanel}`),this.cb.onOpenChange?.(!0);let s=this.openPanel==="plan"&&this.planCanvas!==null&&document.activeElement instanceof HTMLElement&&this.panelEl.contains(document.activeElement)&&(document.activeElement===this.planCanvas.root||this.planCanvas.root.contains(document.activeElement)),r=document.createDocumentFragment();if(this.errorMsg){let a=document.createElement("div");a.className="bp-mgmt-note bp-tone-bad",a.textContent=this.errorMsg,r.appendChild(a)}switch(this.openPanel){case"bom":r.appendChild(this.renderBom());break;case"checks":r.appendChild(this.renderChecks());break;case"life":r.appendChild(this.renderLife());break;case"plan":r.appendChild(this.renderPlan());break;case"fab":r.appendChild(this.renderFab());break}if(this.panelEl.replaceChildren(r),s)this.planCanvas?.root.focus({preventScroll:!0})}renderBom(){let e=document.createElement("div");e.className="bp-mgmt-body";let t=this.getPanelData("bom");if(!t)return e.appendChild(this.makeEmpty("Reading the schematic…")),e;let n=Array.isArray(t.lines)?t.lines:[],i=document.createElement("div");i.className="bp-mgmt-head";let s=document.createElement("span");s.className="bp-dim",s.textContent=`${t.parts??0} parts · ${n.length} lines`;let r=document.createElement("span"),a=t.source==="kicad";if(r.className="bp-mgmt-pill"+(a?" accent":""),r.textContent=a?"live":"saved",i.append(s,r),(t.priced??0)>0&&(t.checking??0)===0&&typeof t.cost==="number"){let u=document.createElement("span");u.className="bp-dim",u.textContent=(t.priced??0)<(t.lookups??0)?`≥ ${ot(t.cost)}/board`:`${ot(t.cost)}/board`,i.appendChild(u)}if(t.paused){let u=document.createElement("span");u.className="bp-mgmt-faint",u.textContent="Stock check paused",i.appendChild(u)}if(e.appendChild(i),t.stock_note){let u=document.createElement("div");u.className="bp-mgmt-note bp-mgmt-faint",u.textContent=pe(t.stock_note),e.appendChild(u)}let o=this.bomEditingId?n.find((u)=>u.id===this.bomEditingId)??null:null;if(o)e.appendChild(this.renderBomEditor(o));else{let u=document.createElement("div");u.className="bp-mgmt-filter-row";let l=document.createElement("input");l.type="text",l.className="bp-mgmt-filter",l.placeholder="Filter BOM (ref, value, footprint, MPN, dnp)…",l.value=this.bomFilter,l.setAttribute("data-testid","mgmt-bom-filter"),l.addEventListener("input",()=>{this.bomFilter=l.value,this.renderBomRows(c,n)}),u.appendChild(l),e.appendChild(u)}let c=document.createElement("div");return c.className="bp-mgmt-rows",c.setAttribute("data-testid","mgmt-bom-rows"),this.renderBomRows(c,n),e.appendChild(c),e}renderBomRows(e,t){let n=Qn(t,this.bomFilter);if(n.length===0){e.replaceChildren(this.makeEmpty(t.length===0?"No parts found.":"No matching lines."));return}let i=t.some((r)=>Boolean(r.mpn)||Boolean(r.fab)),s=document.createDocumentFragment();for(let r of n){let a=Array.isArray(r.refs)?r.refs:[],o=document.createElement("div");o.className="bp-mgmt-row"+(this.bomSelectedId===r.id?" active":"")+(r.dnp?" faint":""),o.setAttribute("data-testid",`mgmt-bom-row-${r.id}`);let c=document.createElement("div");c.className="bp-mgmt-row-line";let u=document.createElement("span");if(u.className="bp-mgmt-strong bp-mgmt-flex1",u.textContent=Rt(a,24),c.appendChild(u),r.dnp){let m=document.createElement("span");m.className="bp-mgmt-pill",m.textContent=b("gpui.mgmt.bom.dnp","DNP"),c.appendChild(m)}else{let m=Zn(r.stock);if(m){let h=document.createElement("span");h.className=`bp-tone-${m.tone}`,h.textContent=m.text,c.appendChild(h)}}let l=document.createElement("button");l.type="button",l.className="bp-mgmt-btn",l.textContent="Edit",l.addEventListener("click",(m)=>{m.stopPropagation(),this.bomEditGen++,this.bomEditingId=r.id,this.bomEditDraft=r.mpn??"",this.bomEditStatus="",this.bomLastUndo=null,this.render()}),c.appendChild(l);let p=document.createElement("div");p.className="bp-mgmt-row-sub";let d=[`${r.qty??a.length}×`,r.value??"",Xn(r.footprint??"")].filter(Boolean).join(" · "),g=document.createElement("span");g.className="bp-dim",g.textContent=d;let y=document.createElement("span");if(y.className="bp-mgmt-flex1",r.mpn)y.textContent=r.mpn;else if(i&&!r.dnp)y.className+=" bp-tone-warn",y.textContent=b("gpui.mgmt.bom.nompn","no MPN");if(p.append(g,y),!r.dnp&&typeof r.stock?.price==="number"){let m=document.createElement("span");m.className="bp-dim",m.textContent=ot(r.stock.price),p.appendChild(m)}if(!r.dnp&&r.stock?.class){let m=document.createElement("span");m.className="bp-mgmt-faint",m.textContent=pe(r.stock.class),p.appendChild(m)}o.append(c,p),o.addEventListener("click",()=>{this.bomSelectedId=r.id,this.renderBomRows(e,t)}),s.appendChild(o)}e.replaceChildren(s)}renderBomEditor(e){let t=document.createElement("div");t.className="bp-mgmt-editor",t.setAttribute("data-testid","mgmt-bom-edit");let n=Array.isArray(e.refs)?e.refs:[],i=document.createElement("div");i.className="bp-mgmt-row-line";let s=document.createElement("span");s.className="bp-mgmt-strong",s.textContent=Rt(n,30);let r=document.createElement("button");r.type="button",r.className="icon",r.textContent="×",r.addEventListener("click",()=>{this.bomEditGen++,this.bomEditingId="",this.bomLastUndo=null,this.bomEditStatus="",this.render()}),i.append(s,r);let a=document.createElement("input");a.type="text",a.className="bp-mgmt-filter",a.placeholder="MPN",a.value=this.bomEditDraft,a.addEventListener("input",()=>{this.bomEditDraft=a.value});let o=()=>({watchGen:this.watchGen,editGen:this.bomEditGen,project:this.project,editId:this.bomEditingId}),c=async(d,g=!1)=>{let y=o();this.bomEditStatus="Writing…",this.render();try{let m=await this.cb.hub.rpc("mgmt.bom.edit",d);if(!nn(y,o()))return;this.bomLastUndo=!g&&(m.changed??0)>0?{project:d.project,editId:y.editId,refs:d.refs.slice(),field:d.field,was:typeof m.was==="string"?m.was:d.field==="mpn"?e.mpn??"":e.dnp?"yes":"no"}:null,this.bomEditStatus=g?"Restored":(m.changed??0)===0?"No change":m.via==="kicad"?"Updated in KiCad":"Saved to schematic"}catch(m){if(!nn(y,o()))return;this.bomEditStatus=m instanceof Error?m.message:"Could not save edit"}this.render()},u=document.createElement("div");u.className="bp-mgmt-btn-row";let l=document.createElement("button");l.type="button",l.className="primary bp-mgmt-btn",l.textContent="Save MPN",l.addEventListener("click",()=>{c({project:this.project,refs:n.slice(),field:"mpn",value:this.bomEditDraft.trim()})});let p=document.createElement("button");if(p.type="button",p.className="bp-mgmt-btn",p.textContent=e.dnp?"Clear DNP":"Mark DNP",p.addEventListener("click",()=>{c({project:this.project,refs:n.slice(),field:"dnp",value:e.dnp?"no":"yes"})}),u.append(l,p),this.bomLastUndo&&this.bomLastUndo.project===this.project&&this.bomLastUndo.editId===this.bomEditingId){let d=this.bomLastUndo,g=document.createElement("button");g.type="button",g.className="bp-mgmt-btn",g.textContent="Undo",g.addEventListener("click",()=>{c(oi(d),!0)}),u.appendChild(g)}if(t.append(i,a,u),this.bomEditStatus){let d=document.createElement("div");d.className="bp-mgmt-faint",d.textContent=this.bomEditStatus,t.appendChild(d)}return t}renderChecks(){let e=document.createElement("div");e.className="bp-mgmt-body";let t=this.getPanelData("checks");if(!t)return e.appendChild(this.makeEmpty("Reading checks…")),e;let n=Array.isArray(t.groups)?t.groups:[],i=Array.from(new Set(n.map((d)=>d.source).filter(Boolean))),s=(d)=>t.sources?.[d]?.label||d.toUpperCase(),r=(d)=>t.sources?.[d]?.judged===!0,a=document.createElement("div");a.className="bp-mgmt-head bp-mgmt-scroll-x";let o=document.createElement("button");o.type="button",o.className="bp-mgmt-btn"+(this.checksSource===""?" active":""),o.textContent=b("gpui.mgmt.checks.all","All"),o.addEventListener("click",()=>{this.checksSource="",this.render()}),a.appendChild(o);for(let d of i){let g=document.createElement("button");g.type="button",g.className="bp-mgmt-btn"+(this.checksSource===d?" active":""),g.textContent=s(d)+(r(d)?" · judged":""),g.addEventListener("click",()=>{this.checksSource=this.checksSource===d?"":d,this.render()}),a.appendChild(g)}let c=document.createElement("span");c.className="bp-mgmt-flex1";let u=document.createElement("button");if(u.type="button",u.className="bp-mgmt-btn",u.textContent=b("gpui.mgmt.checks.run","Run"),u.addEventListener("click",()=>{let d=this.watchGen,g=this.project;this.checksStatus="Running checks…",this.render(),this.cb.hub.rpc("kicad.checks.run",{project:g}).then(()=>{if(d!==this.watchGen||g!==this.project)return;this.checksStatus="",this.render()}).catch((y)=>{if(d!==this.watchGen||g!==this.project)return;this.checksStatus=y instanceof Error?y.message:"Could not run checks",this.render()})}),a.append(c,u),e.appendChild(a),this.checksStatus){let d=document.createElement("div");d.className="bp-mgmt-note bp-dim",d.textContent=this.checksStatus,e.appendChild(d)}let l=document.createElement("div");l.className="bp-mgmt-rows",l.setAttribute("data-testid","mgmt-checks-rows");let p=ei(n,this.checksSource);if(p.length===0)l.appendChild(this.makeEmpty("No check findings."));else for(let d of p){let g=d.severity==="error"?"bad":d.severity==="warning"?"warn":"faint",y=document.createElement("div");y.className="bp-mgmt-group-head";let m=document.createElement("span");m.className=`bp-mgmt-dot bp-tone-bg-${g}`;let h=document.createElement("span");h.className="bp-mgmt-flex1",h.textContent=`${s(d.source)} · ${d.rule}`;let f=document.createElement("span");f.className=`bp-tone-${g}`,f.textContent=String(d.n),y.append(m,h,f),l.appendChild(y);for(let w of d.rows??[]){let C=document.createElement("div");C.className="bp-mgmt-row"+(this.checksSelectedId===w.id?" active":"");let A=document.createElement("div");if(A.textContent=pe(w.title??""),C.appendChild(A),w.names||this.checksSelectedId===w.id){let M=document.createElement("div");M.className="bp-mgmt-row-sub";let S=document.createElement("span");if(S.className="bp-dim bp-mgmt-flex1",S.textContent=w.names??"",M.appendChild(S),this.checksSelectedId===w.id){let T=document.createElement("button");T.type="button",T.className="bp-mgmt-btn accent",T.textContent=b("gpui.mgmt.checks.fix","Fix with agent"),T.addEventListener("click",(B)=>{B.stopPropagation();let R={watchGen:this.watchGen,project:this.project,threadId:this.cb.getThreadId(),threadGen:this.cb.getThreadGen()};this.cb.hub.rpc("kicad.checks.fix",{project:R.project,id:w.id}).then((O)=>{let H={watchGen:this.watchGen,project:this.project,threadId:this.cb.getThreadId(),threadGen:this.cb.getThreadGen()};if(!sn(R,H))return;if(O.text)this.cb.onSendText(O.text),this.checksStatus="Sent to agent",this.render()}).catch((O)=>{let H={watchGen:this.watchGen,project:this.project,threadId:this.cb.getThreadId(),threadGen:this.cb.getThreadGen()};if(!sn(R,H))return;this.checksStatus=O instanceof Error?O.message:"Could not send finding",this.render()})}),M.appendChild(T)}C.appendChild(M)}C.addEventListener("click",()=>{this.checksSelectedId=w.id,this.cb.hub.rpc("kicad.checks.focus",{project:this.project,id:w.id}).catch(()=>{}),this.render()}),l.appendChild(C)}}return e.appendChild(l),e}renderLife(){let e=document.createElement("div");e.className="bp-mgmt-body";let t=this.getPanelData("life");if(!t)return e.appendChild(this.makeEmpty("Reading lifecycle…")),e;let n=document.createElement("div");n.className="bp-mgmt-head";let i=t.counts??{};for(let c of["active","nrnd","eol"]){let u=i[c]??0,l=tn(c),p=document.createElement("span");p.className=u>0?`bp-tone-${l.tone}`:"bp-mgmt-faint",p.textContent=`${l.label} ${u}`,n.appendChild(p)}if((i.unknown??0)>0){let c=document.createElement("span");c.className="bp-mgmt-faint",c.textContent=`${i.unknown} unknown`,n.appendChild(c)}if(t.since){let c=document.createElement("span");c.className="bp-mgmt-flex1";let u=document.createElement("span");u.className="bp-mgmt-faint",u.textContent=`since ${jt(t.since)} (${t.samples??0})`,n.append(c,u)}e.appendChild(n);let s=document.createElement("div");s.className="bp-mgmt-rows",s.setAttribute("data-testid","mgmt-life-rows");let r=t.bom?.cost??[],a=t.bom?.instock??[],o=t.bom?.lines??0;if(r.length===0)s.appendChild(this.makeEmpty(o===0?"No line has an MPN or fab part number to follow yet.":"No reading of the fab's stock yet: the BOM panel's lookups start it."));else{let c=r[r.length-1],u=a[a.length-1],l=document.createElement("div");l.className="bp-mgmt-note bp-dim",l.textContent=`Parts/board: ${ot(c[1])} · ${Math.round(u?.[1]??0)}/${o} lines in stock (${jt(c[0])})`,s.appendChild(l)}for(let c of t.parts??[]){let u=this.lifeSelectedKey===c.key,l=tn(c.lifecycle??"unknown"),p=document.createElement("div");p.className="bp-mgmt-row"+(u?" active":"");let d=document.createElement("div");d.className="bp-mgmt-row-line";let g=document.createElement("span");g.className="bp-mgmt-strong",g.textContent=Rt(c.refs??[],14);let y=document.createElement("span");y.className="bp-mgmt-flex1 bp-dim",y.textContent=c.mpn||c.key;let m=document.createElement("span");if(m.className=`bp-tone-${l.tone}`,m.textContent=l.label,d.append(g,y,m),typeof c.stock==="number"){let h=document.createElement("span");h.className="bp-dim",h.textContent=at(c.stock),d.appendChild(h)}if(p.appendChild(d),u){let h=document.createElement("div");if(h.className="bp-mgmt-row-sub bp-mgmt-faint",this.lifePartLoading)h.textContent=b("gpui.mgmt.life.reading","Reading its history…");else if(this.lifePartSamples&&this.lifePartSamples.length>0){let f=this.lifePartSamples[this.lifePartSamples.length-1];h.textContent=`${this.lifePartSamples.length} samples · latest ${f.at?jt(f.at):""}`+(typeof f.stock==="number"?` · stock ${at(f.stock)}`:"")+(typeof f.price==="number"?` · ${ot(f.price)}`:"")}else h.textContent=b("gpui.mgmt.life.nopart","No reading of this part yet.");p.appendChild(h)}p.addEventListener("click",()=>{if(this.lifeSelectedKey===c.key){this.lifeSelectedKey="",this.lifePartSamples=null,this.render();return}this.lifeSelectedKey=c.key,this.lifePartSamples=null,this.lifePartLoading=!0,this.render(),this.cb.hub.rpc("mgmt.life.part",{project:this.project,key:c.key}).then((h)=>{if(this.lifeSelectedKey!==c.key)return;this.lifePartLoading=!1,this.lifePartSamples=Array.isArray(h.samples)?h.samples:[],this.render()}).catch(()=>{if(this.lifeSelectedKey!==c.key)return;this.lifePartLoading=!1,this.lifePartSamples=[],this.render()})}),s.appendChild(p)}return e.appendChild(s),e}renderPlan(){let e=document.createElement("div");e.className="bp-mgmt-body";let t=this.getPanelData("plan");if(!t)return e.appendChild(this.makeEmpty(b("gpui.mgmt.plan.reading","Reading the routing plan…"))),e;let n=(E,k)=>{let j=this.watchGen,P=this.project;this.planStatus="",this.cb.hub.rpc(E,{pro:P,...k}).catch((K)=>{if(j!==this.watchGen||P!==this.project)return;this.planOptimistic.clear(),this.planStatus=K instanceof Error?K.message:b("gpui.mgmt.plan.refused","KiCad refused"),this.render()})};if(t.revision!==this.planOptimisticRev)this.planOptimisticRev=t.revision,this.planOptimistic.clear();let i=`${this.project}:${t.revision??0}`;if(t.board_trimmed&&this.planHydrateAskedKey!==i&&this.project){this.planHydrateAskedKey=i;let E=this.watchGen,k=++this.planHydrateGen,j=this.project,P=t.revision??0;this.cb.hub.rpc("plan.get",{pro:j,board:!0}).then((K)=>{let ee=fi(K);if(!ee)return;let D=typeof ee.revision==="number"?ee.revision:P;if(!vi(E,this.watchGen,k,this.planHydrateGen,j,this.project,D,this.planHydratedRev))return;this.planHydratedRev=D,this.planHydratedKey=`${j}:${D}`,this.planHydratedBoard=ee.board??null,this.planHydratedDraw=ee.draw??null,this.render()}).catch(()=>{})}let s=t.on===!0,r=document.createElement("div");r.className="bp-plan-header";let a=document.createElement("div");a.className="bp-plan-toggle";let o=document.createElement("span");o.className="bp-mgmt-strong",o.textContent=b("gpui.mgmt.plan.before","Plan before routing"),o.title=s?b("gpui.mgmt.plan.onwords","Before routing a board with 4 or more copper layers or more than 60 nets, the agent proposes corridors and plane regions here. It routes only what you approve."):b("gpui.mgmt.plan.offwords","Agents route as you ask. Turn it on to have them propose a routing plan first and route only what you approve here."),a.appendChild(o);let c=t.awaiting??0,u=t.blocked??0,l=t.done??0,p=t.total??0,d=t.revision??0,g=t.empty?[]:si(t),y=g.reduce((E,k)=>E+k.count,0);if(!t.empty){let E=ii(t),k=document.createElement("span");if(k.className=`bp-plan-status-badge tone-${E.tone}`,k.textContent=b(E.key,E.label),a.appendChild(k),d>0){let P=document.createElement("span");P.className="bp-dim",P.textContent=`v${d}`,a.appendChild(P)}let j=document.createElement("span");if(j.className="bp-plan-header-counts bp-mgmt-flex1 "+(c>0?"bp-tone-warn":u>0?"bp-tone-bad":"bp-dim"),j.textContent=p>0?`${l}/${p} ${b("gpui.mgmt.plan.done","done")}`:c>0?b("web.plan.awaiting","{n} awaiting approval",{n:c}):b("gpui.mgmt.plan.nothing","Nothing awaits your approval"),a.appendChild(j),!t.live){let P=document.createElement("span");P.className="bp-mgmt-pill",P.textContent=b("gpui.mgmt.plan.saved","saved plan"),a.appendChild(P)}}else{let E=document.createElement("span");E.className="bp-mgmt-flex1",a.appendChild(E)}let m=document.createElement("button");m.type="button",m.className="bp-mgmt-btn bp-plan-chip-btn"+(s?" active":""),m.setAttribute("data-testid","mgmt-plan-on"),m.setAttribute("aria-pressed",s?"true":"false"),m.textContent=b("gpui.bots.recall.on","On"),m.addEventListener("click",()=>n("plan.enable",{on:!0}));let h=document.createElement("button");if(h.type="button",h.className="bp-mgmt-btn bp-plan-chip-btn"+(!s?" active":""),h.setAttribute("data-testid","mgmt-plan-off"),h.setAttribute("aria-pressed",!s?"true":"false"),h.textContent=b("gpui.bots.recall.off","Off"),h.addEventListener("click",()=>n("plan.enable",{on:!1})),a.append(m,h),r.appendChild(a),y>0){let E=document.createElement("div");E.className="bp-plan-segbar";for(let k of g){if(k.count<=0)continue;let j=document.createElement("div");j.className=`bp-plan-seg bp-tone-bg-${k.tone}`,j.style.flexGrow=String(k.count),E.appendChild(j)}r.appendChild(E)}e.appendChild(r);for(let E of t.elsewhere??[]){let k=document.createElement("div");k.className="bp-plan-elsewhere";let j=document.createElement("span");j.className="bp-tone-warn bp-mgmt-flex1",j.textContent=b("gpui.mgmt.plan.elsewhere","A routing plan for {board} awaits your approval",{board:E.name||E.rel||""}),k.appendChild(j),e.appendChild(k)}if(t.empty){let E=document.createElement("div");E.className="bp-mgmt-note";let k=document.createElement("div");k.className="bp-dim",k.textContent=b("gpui.mgmt.plan.noboard","No routing plan for this board.");let j=document.createElement("div");return j.className="bp-mgmt-faint",j.textContent=b("gpui.mgmt.plan.emptysub","Layers, corridors, and planes appear here once a plan is proposed."),E.append(k,j),e.appendChild(E),e}let f=t.stackup_summary??"",w=Array.isArray(t.impedances)?t.impedances:[],C=Boolean(f)||w.length>0,A=document.createElement("div");if(A.className="bp-mgmt-head",c>0){let E=document.createElement("button");E.type="button",E.className="primary bp-mgmt-btn",E.setAttribute("data-testid","mgmt-plan-approve-all"),E.textContent=b("gpui.mgmt.plan.all","Approve all"),E.addEventListener("click",()=>n("plan.approve",{layer:"",ids:[],approve:!0})),A.appendChild(E)}if(t.routing){let E=document.createElement("button");E.type="button",E.className="bp-mgmt-btn",E.setAttribute("data-testid","mgmt-plan-stop"),E.textContent=b("gpui.mgmt.plan.stop","Stop routing"),E.addEventListener("click",()=>n("plan.stop",{})),A.appendChild(E)}if(t.live&&l>0){let E=document.createElement("button");E.type="button",E.className="bp-mgmt-btn",E.setAttribute("data-testid","mgmt-plan-verify"),E.textContent=b("gpui.mgmt.plan.verify","Verify"),E.addEventListener("click",()=>n("plan.verify",{})),A.appendChild(E)}let M=document.createElement("span");if(M.className="bp-mgmt-flex1",A.appendChild(M),C){let E=document.createElement("button");E.type="button",E.className="bp-mgmt-btn bp-plan-chip-btn"+(this.planStackupOpen?" active":""),E.setAttribute("data-testid","mgmt-plan-stackup-toggle"),E.setAttribute("aria-expanded",this.planStackupOpen?"true":"false"),E.textContent=`${b("gpui.mgmt.plan.stackup.short","Stackup")} ${this.planStackupOpen?"▾":"▸"}`,E.addEventListener("click",()=>{this.planStackupOpen=!this.planStackupOpen,this.render()}),A.appendChild(E)}let S=document.createElement("button");S.type="button",S.className="bp-mgmt-btn",S.setAttribute("data-testid","mgmt-plan-hide"),S.textContent=this.planHideDone?b("gpui.mgmt.plan.show","Show done"):b("gpui.mgmt.plan.hide","Hide done"),S.addEventListener("click",()=>{this.planHideDone=!this.planHideDone,this.render()}),A.appendChild(S),e.appendChild(A);let T=Array.isArray(t.asks)?t.asks:[];if(T.length>0){let E=T.map((ee)=>ee.what||"").filter(Boolean).join(", "),k=T[0]?.note||"",j=document.createElement("div");j.className="bp-plan-elsewhere";let P=document.createElement("div");P.className="bp-plan-ask-col";let K=document.createElement("div");if(K.className="bp-tone-warn",K.textContent=E?b("gpui.mgmt.plan.requested","Approval requested: {what}",{what:E}):b("gpui.mgmt.plan.reqplain","Approval requested"),P.appendChild(K),k){let ee=document.createElement("div");ee.className="bp-dim",ee.textContent=k,P.appendChild(ee)}j.appendChild(P),e.appendChild(j)}if(this.planStatus){let E=document.createElement("div");E.className="bp-mgmt-note bp-plan-err bp-tone-bad";let k=document.createElement("span");k.className="bp-mgmt-flex1",k.textContent=this.planStatus==="KiCad refused"?b("gpui.mgmt.plan.refused","KiCad refused"):pe(this.planStatus);let j=document.createElement("button");j.type="button",j.className="icon",j.textContent="×",j.title=b("common.close","Close"),j.addEventListener("click",()=>{this.planStatus="",this.render()}),E.append(k,j),e.appendChild(E)}if(t.keys_note){let E=document.createElement("div");E.className="bp-mgmt-note bp-dim";let k="On this KiCad version, approve from this panel: in plan view KiCad's A, R and W keys aren't the plan's yet (A opens Add Footprint). Update KiCad.";E.textContent=t.keys_note===k?b("gpui.mgmt.plan.keysnote",k):pe(t.keys_note),e.appendChild(E)}if(C&&this.planStackupOpen){let E=document.createElement("div");if(E.className="bp-plan-stackup-body",E.setAttribute("data-testid","mgmt-plan-stackup-body"),f){let k=document.createElement("div");k.className="bp-dim",k.textContent=f,E.appendChild(k)}for(let k of w){let j=document.createElement("div");j.className="bp-mgmt-faint",j.textContent=`· ${k}`,E.appendChild(j)}e.appendChild(E)}let B=(E,k,j,P)=>{let K=document.createElement("button");return K.type="button",K.className="bp-mgmt-btn bp-plan-chip-btn"+(k?" active":""),K.setAttribute("data-testid",j),K.setAttribute("aria-pressed",k?"true":"false"),K.textContent=E,K.addEventListener("click",P),K},R=document.createElement("div");if(R.className="bp-plan-viewbar",R.append(B(b("gpui.mgmt.plan.view.canvas","Canvas"),this.planViewMode==="canvas","mgmt-plan-view-canvas",()=>{this.planViewMode="canvas",this.render()}),B(b("gpui.mgmt.plan.view.split","Split"),this.planViewMode==="split","mgmt-plan-view-split",()=>{this.planViewMode="split",this.render()}),B(b("gpui.mgmt.plan.view.list","List"),this.planViewMode==="list","mgmt-plan-view-list",()=>{this.planViewMode="list",this.render()})),this.planViewMode!=="list"){let E=document.createElement("span");E.className="bp-plan-sep";let k=document.createElement("span");k.className="bp-plan-sep";let j=document.createElement("button");j.type="button",j.className="bp-mgmt-btn bp-plan-mini-btn",j.setAttribute("data-testid","mgmt-plan-fit"),j.textContent=b("gpui.mgmt.plan.fit","Fit"),j.addEventListener("click",()=>this.planCanvas?.fitAll()),R.append(E,B(b("gpui.mgmt.plan.grid.pair","Side by side"),this.planGridMode==="pair","mgmt-plan-grid-pair",()=>{this.planGridMode="pair",this.render()}),B(b("gpui.mgmt.plan.grid.all","All layers"),this.planGridMode==="all","mgmt-plan-grid-all",()=>{this.planGridMode="all",this.render()}),B(b("gpui.mgmt.plan.grid.single","Single"),this.planGridMode==="single","mgmt-plan-grid-single",()=>{this.planGridMode="single",this.render()}),k,B(b("gpui.mgmt.plan.sync","Link zoom"),this.planSyncZoom,"mgmt-plan-sync",()=>{this.planSyncZoom=!this.planSyncZoom,this.render()}),j)}let O=document.createElement("span");O.className="bp-mgmt-flex1";let H=document.createElement("button");H.type="button",H.className="bp-mgmt-btn bp-plan-mini-btn",H.setAttribute("data-testid","mgmt-plan-expand"),H.textContent=this.planExpanded?b("gpui.mgmt.plan.compact","Compact"):b("gpui.mgmt.plan.expand","Expand"),H.addEventListener("click",()=>{this.planExpanded=!this.planExpanded,this.render()}),R.append(O,H),e.appendChild(R);let ae=Boolean(this.planHydratedBoard)&&this.planHydratedKey.startsWith(`${this.project}:`)&&(this.planHydratedKey===i||this.planHydratedRev!==void 0&&this.planHydratedRev>=(t.revision??0)),ue=ae&&this.planHydratedBoard?this.planHydratedBoard:t.board??{bbox:[0,0,100,70],outline:[],parts:[]},oe=ae&&this.planHydratedDraw?this.planHydratedDraw:t.draw??{bands:[],regions:[]},we=(oe.bands??[]).map((E)=>{let k=this.planOptimistic.get(E.id);if(!k)return{...E};return{...E,...k,edited:!0,state:E.state==="proposed"?"edited":E.state}}),Le=(oe.regions??[]).map((E)=>{let k=this.planOptimistic.get(E.id);if(!k)return{...E};return{...E,...k,edited:!0,state:E.state==="proposed"?"edited":E.state}}),Ne=[],he=(t.layers??[]).map((E)=>{let k=[];for(let j of E.items??[]){let P=this.planOptimistic.get(j.id);if(!P){k.push(j);continue}let K={...j,width:typeof P.width==="number"?P.width:j.width,locked:typeof P.locked==="boolean"?P.locked:j.locked,edited:!0,state:j.state==="proposed"?"edited":j.state};if(typeof P.layer==="string"&&P.layer!==E.layer)Ne.push({target:P.layer,item:K});else k.push(K)}return{...E,items:k}});for(let E of Ne){let k=he.find((j)=>j.layer===E.target);if(k)k.items=[...k.items??[],E.item]}let be=Ft(he,t.copper_layers),I=this.planGridMode==="all"?be.map((E)=>E.layer):this.planGridMode==="single"?[this.planShownLayers.find((E)=>be.some((k)=>k.layer===E))??ct(be)[0]??be[0]?.layer??""].filter(Boolean):this.planShownLayers.length>0&&this.planShownLayers.every((E)=>be.some((k)=>k.layer===E))?this.planShownLayers.slice(0,2):ct(be);if(this.planViewMode!=="list"&&this.planGridMode!=="all"&&be.length>1){let E=document.createElement("div");E.className="bp-plan-layerbar";for(let k of be){let j=I.includes(k.layer),P=(k.items??[]).length,K=it(k.layer,t.copper_layers,be)||k.title||k.layer,ee=P>0?`${K} · ${P}`:K,D=B(ee,j,`mgmt-plan-layerpill-${k.layer}`,()=>{if(this.planGridMode==="single")this.planShownLayers=[k.layer];else if(this.planGridMode==="pair"){if(!I.includes(k.layer))this.planShownLayers=I.length>=2?[I[0],k.layer]:[...I,k.layer]}else this.planGridMode="single",this.planShownLayers=[k.layer];this.render()});if(P===0&&!j)D.classList.add("empty-layer");E.appendChild(D)}e.appendChild(E)}let le=(E,k)=>{let j=this.planOptimistic.get(E)??{};if(this.planOptimistic.set(E,{...j,...k}),typeof k.layer==="string"){if(this.planGridMode==="single")this.planShownLayers=[k.layer];else if(this.planGridMode==="pair"&&!I.includes(k.layer))this.planShownLayers=I.length>=2?[I[0],k.layer]:[...I,k.layer]}let P=typeof t.revision==="number"?t.revision:void 0;this.render(),n("plan.update",{ops:[{op:"set",id:E,fields:k}],...P!==void 0?{base:P}:{}})};if(this.planCommitFields=le,this.planSelectedId){let E="",k=null;for(let j of he){let P=(j.items??[]).find((K)=>K.id===this.planSelectedId);if(P){E=j.layer,k=P;break}}if(k){let j=it(E,t.copper_layers,be),P=document.createElement("div");P.className="bp-plan-inspector",P.setAttribute("data-testid","mgmt-plan-inspector");let K=document.createElement("div");K.className="bp-plan-ins-row";let ee=document.createElement("span");ee.className="bp-plan-ins-sw",ee.style.background=k.kind==="corridor"?lt(k.name||k.id,k.color||""):Et(k.name||k.id,k.color||"");let D=document.createElement("span");D.className="bp-mgmt-strong",D.textContent=k.name||k.id;let z=document.createElement("span");if(z.className="bp-dim",z.textContent=j,K.append(ee,D,z),k.edited||k.state==="edited"){let Y=document.createElement("span");Y.className="bp-plan-ins-pill warn",Y.textContent=b("gpui.mgmt.plan.edited","Edited"),K.appendChild(Y)}if(k.locked){let Y=document.createElement("span");Y.className="bp-plan-ins-pill",Y.textContent=b("gpui.mgmt.plan.locked","Locked"),K.appendChild(Y)}let je=document.createElement("span");je.className="bp-mgmt-flex1",K.appendChild(je);let Se=document.createElement("button");if(Se.type="button",Se.className="bp-mgmt-btn bp-plan-mini-btn",Se.setAttribute("data-testid","mgmt-plan-lock"),Se.textContent=k.locked?b("gpui.mgmt.plan.unlock","Unlock"):b("gpui.mgmt.plan.lock","Lock"),Se.addEventListener("click",()=>le(k.id,{locked:!k.locked})),K.appendChild(Se),k.state==="proposed"||k.state==="edited"){let Y=document.createElement("button");Y.type="button",Y.className="primary bp-mgmt-btn bp-plan-mini-btn",Y.textContent=b("android.hub.machines.approve","Approve"),Y.addEventListener("click",()=>n("plan.approve",{layer:"",ids:[k.id],approve:!0}));let fe=document.createElement("button");fe.type="button",fe.className="bp-mgmt-btn bp-plan-mini-btn",fe.textContent=b("gpui.mgmt.plan.reject","Reject"),fe.addEventListener("click",()=>n("plan.approve",{layer:"",ids:[k.id],approve:!1})),K.append(Y,fe)}let me=document.createElement("button");me.type="button",me.className="bp-mgmt-btn bp-plan-mini-btn",me.setAttribute("data-testid","mgmt-plan-note-toggle"),me.textContent=b("gpui.mgmt.plan.addnote","Add note"),me.addEventListener("click",()=>{this.planNoteOpen=!this.planNoteOpen,this.render()});let Me=document.createElement("button");if(Me.type="button",Me.className="icon",Me.textContent="×",Me.addEventListener("click",()=>{this.planSelectedId="",this.planNoteOpen=!1,this.planMoveLayerOpen=!1,this.render()}),K.append(me,Me),P.appendChild(K),!k.locked){let Y=document.createElement("div");if(Y.className="bp-plan-ins-row",k.kind==="corridor"){let ie=typeof k.width==="number"?k.width:1.5,ke=document.createElement("span");ke.className="bp-dim",ke.textContent=b("gpui.mgmt.plan.width","Width");let He=document.createElement("button");He.type="button",He.className="bp-mgmt-btn bp-plan-mini-btn",He.setAttribute("data-testid","mgmt-plan-w-down"),He.textContent="-",He.addEventListener("click",()=>{let Ue=Math.round(Math.max(0.15,ie-0.25)*100)/100;le(k.id,{width:Ue})});let re=document.createElement("span");re.className="bp-plan-ins-val",re.textContent=`${ie.toFixed(2)}mm`;let ge=document.createElement("button");ge.type="button",ge.className="bp-mgmt-btn bp-plan-mini-btn",ge.setAttribute("data-testid","mgmt-plan-w-up"),ge.textContent="+",ge.addEventListener("click",()=>{let Ue=Math.round(Math.min(25,ie+0.25)*100)/100;le(k.id,{width:Ue})});let _e=document.createElement("span");_e.className="bp-plan-sep",Y.append(ke,He,re,ge,_e)}let fe=(t.copper_layers??[]).length>0?(t.copper_layers??[]).map((ie)=>ie.layer):he.map((ie)=>ie.layer);if(fe.length>0){let ie=document.createElement("span");ie.className="bp-dim",ie.textContent=b("gpui.mgmt.plan.layer.short","Layer"),Y.appendChild(ie),Y.appendChild(B(`${j} ${this.planMoveLayerOpen?"▴":"▾"}`,this.planMoveLayerOpen,"mgmt-plan-move-toggle",()=>{this.planMoveLayerOpen=!this.planMoveLayerOpen,this.render()}))}if(P.appendChild(Y),this.planMoveLayerOpen&&fe.length>0){let ie=document.createElement("div");ie.className="bp-plan-ins-row";for(let ke of fe){let He=it(ke,t.copper_layers,be);ie.appendChild(B(He,ke===E,`mgmt-plan-move-${ke}`,()=>{if(this.planMoveLayerOpen=!1,ke!==E)le(k.id,{layer:ke});else this.render()}))}P.appendChild(ie)}}if(this.planNoteOpen){let Y=document.createElement("form");Y.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=b("gpui.mgmt.plan.note.placeholder","Steering note for router…");let ie=document.createElement("button");ie.type="submit",ie.className="primary bp-mgmt-btn bp-plan-mini-btn",ie.setAttribute("data-testid","mgmt-plan-note-submit"),ie.textContent=b("gpui.mgmt.plan.addnote","Add note"),Y.append(fe,ie),Y.addEventListener("submit",(ke)=>{ke.preventDefault();let He=fe.value.trim();if(!He)return;fe.value="",this.planNoteOpen=!1;let re=typeof t.revision==="number"?t.revision:void 0;this.render(),n("plan.update",{ops:[{op:"note",target:k.id,text:He}],...re!==void 0?{base:re}:{}})}),P.appendChild(Y)}if(this.planViewMode!=="list"&&!k.locked){let Y=document.createElement("div");Y.className="bp-plan-hint",Y.textContent=b("gpui.mgmt.plan.hint","Drag waypoints to steer · Click + on edge to insert · Right-click vertex to remove"),P.appendChild(Y)}e.appendChild(P)}}let ne=document.createElement("div");ne.className="bp-mgmt-rows"+(this.planViewMode==="split"?" bp-plan-split-list":""),ne.setAttribute("data-testid","mgmt-plan-rows");let X=b("gpui.mgmt.plan.done","done"),ce=ui(this.planViewMode,he,I);if(this.planViewMode==="split"&&ce.length===0){let E=document.createElement("div");E.className="bp-dim",E.style.padding="6px 8px",E.style.fontSize="11px",E.textContent=b("gpui.mgmt.plan.noitems","No corridors or planes on this layer"),ne.appendChild(E)}for(let E of ce){let k=E.items??[],j=it(E.layer,t.copper_layers,be)||E.layer;if(this.planViewMode==="split"){if(ce.length>1){let P=document.createElement("div");P.className="bp-plan-split-divider";let K=E.role==="power"||E.role==="plane",ee=document.createElement("span");ee.className="bp-plan-card-bar "+(K?"pwr":"sig");let D=document.createElement("span");D.className="bp-mgmt-strong",D.textContent=j;let z=document.createElement("span");z.className="bp-dim",z.textContent=`${E.done??0}/${k.length} ${X}`,P.append(ee,D,z),ne.appendChild(P)}}else{let P=document.createElement("div");P.className="bp-mgmt-group-head bp-plan-layer-head";let K=document.createElement("div");K.className="bp-mgmt-row-line";let ee=document.createElement("span");ee.className="bp-mgmt-strong",ee.textContent=j;let D=document.createElement("span");if(D.className="bp-dim bp-mgmt-flex1",D.textContent=`${E.role?`${E.role} · `:""}${E.done??0}/${k.length} ${X}`,K.append(ee,D),E.status!=="approved"&&k.length>0){let z=document.createElement("button");z.type="button",z.className="bp-mgmt-btn",z.textContent=b("gpui.mgmt.plan.layer","Approve layer"),z.addEventListener("click",()=>n("plan.approve",{layer:E.layer,ids:[],approve:!0}));let je=document.createElement("button");je.type="button",je.className="bp-mgmt-btn",je.textContent=b("gpui.mgmt.plan.reject","Reject"),je.addEventListener("click",()=>n("plan.approve",{layer:E.layer,ids:[],approve:!1})),K.append(z,je)}if(P.appendChild(K),E.stackup){let z=document.createElement("div");z.className="bp-plan-layer-stackup",z.textContent=E.stackup,P.appendChild(z)}ne.appendChild(P)}for(let P of k){if(this.planHideDone&&ti(P))continue;let K=this.planSelectedId===P.id,ee=document.createElement("div");ee.className="bp-mgmt-row bp-plan-row"+(K?" active":""),ee.setAttribute("data-testid",`mgmt-plan-row-${P.id}`);let D=document.createElement("div");D.className="bp-mgmt-row-line";let z=document.createElement("span");z.className=`bp-plan-swatch bp-plan-st-${P.state||"proposed"}`,z.style.setProperty("--swatch-color",P.color||"#8a8a8a");let je=document.createElement("span");je.className="bp-mgmt-flex1"+(P.state==="blocked"||P.state==="failed"?" bp-tone-bad":P.state==="edited"?" bp-tone-warn":P.state==="rejected"||P.state==="routed"||P.state==="verified"?" bp-dim":""),je.textContent=`${P.name||P.id}${P.locked?" \uD83D\uDD12":""}`;let Se=[];if(P.kind==="plane"){if(P.reference)Se.push(b("gpui.mgmt.plan.reference","over {layer}",{layer:P.reference}))}else{let Y=P.nets??0;Se.push(Y===1?b("web.plan.net.one","1 net"):b("web.plan.nets","{n} nets",{n:Y}))}if(typeof P.width==="number"&&Number.isFinite(P.width))Se.push(`${P.width.toFixed(2)}mm`);if(P.impedance)Se.push(P.impedance);let me=Se.join(" · "),Me=document.createElement("span");if(Me.className="bp-plan-mark "+(P.state==="blocked"||P.state==="failed"?"bp-tone-bad":P.state==="verified"||P.state==="routed"?"bp-tone-ok":P.state==="approved"?"bp-tone-accent":"bp-dim"),Me.textContent=ni(P),D.append(z,je,Me),P.state==="proposed"||P.state==="edited"){let Y=document.createElement("button");Y.type="button",Y.className="bp-mgmt-btn",Y.textContent="✓",Y.title=b("gpui.mgmt.plan.layer","Approve layer"),Y.addEventListener("click",(ie)=>{ie.stopPropagation(),n("plan.approve",{layer:"",ids:[P.id],approve:!0})});let fe=document.createElement("button");fe.type="button",fe.className="bp-mgmt-btn",fe.textContent="✗",fe.title=b("gpui.mgmt.plan.reject","Reject"),fe.addEventListener("click",(ie)=>{ie.stopPropagation(),n("plan.approve",{layer:"",ids:[P.id],approve:!1})}),D.append(Y,fe)}if(ee.appendChild(D),me){let Y=document.createElement("div");Y.className="bp-mgmt-row-sub bp-plan-detail bp-dim",Y.textContent=me,ee.appendChild(Y)}if(P.state==="routing"&&typeof P.total==="number"&&P.total>0){let Y=document.createElement("div");Y.className="bp-plan-microbar";let fe=document.createElement("div");fe.className="bp-plan-microbar-fill";let ie=Math.max(0,Math.min(100,Math.round((P.routed??0)/P.total*100)));fe.style.width=`${ie}%`,Y.appendChild(fe),ee.appendChild(Y)}if(P.problem_text){let Y=document.createElement("div");Y.className="bp-plan-problem",Y.textContent=P.problem_text,ee.appendChild(Y)}ee.addEventListener("click",()=>{this.planSelectedId=P.id,n("plan.focus",{id:P.id}),this.render()}),ne.appendChild(ee)}}if(this.planViewMode!=="list"){if(!this.planCanvas)this.planCanvas=new on({onSelect:(P)=>{if(this.planSelectedId=P,!P)this.planNoteOpen=!1;this.render()},onFocusItem:(P)=>{n("plan.focus",{id:P})},onDragEnd:()=>{if(this.planRenderDeferred)this.planRenderDeferred=!1,this.render()},onCommitFields:(P,K)=>{(this.planCommitFields??le)(P,K)},onApproveLayer:(P,K)=>{n("plan.approve",{layer:P,ids:[],approve:K})},onQuickApprove:(P,K)=>{n("plan.approve",{layer:"",ids:P,approve:K})}});let E=this.panelEl.parentElement?.classList.contains("bp-has-viewer")===!1,k=this.planExpanded||this.panelEl.clientWidth>=540||E;this.planCanvas.update({gridMode:this.planGridMode,syncZoom:this.planSyncZoom,shownLayers:I,selectedId:this.planSelectedId,board:ue,bands:we,regions:Le,layers:be,copperLayers:t.copper_layers},k);let j=document.createElement("div");j.className="bp-plan-canvas-scroll",j.appendChild(this.planCanvas.root),e.appendChild(j)}if(this.planViewMode!=="canvas")e.appendChild(ne);if((t.draw?.bands?.length??0)>0||(t.draw?.regions?.length??0)>0){let E=document.createElement("div");E.className="bp-plan-footer",E.textContent=b("gpui.mgmt.plan.drawn","The plan's corridors and planes are drawn on the board while this panel is open. Close it to hide them."),e.appendChild(E)}return e}renderFab(){let e=document.createElement("div");e.className="bp-mgmt-body";let t=this.getPanelData("fab");if(!t)return e.appendChild(this.makeEmpty("Reading the fab's profile…")),e;if(t.error){let w=document.createElement("div");return w.className="bp-mgmt-note bp-tone-warn",w.textContent=t.error,e.appendChild(w),e}let n=(w,C={})=>{let A=this.watchGen,M=this.project;this.fabStatus="",this.cb.hub.rpc("fab.profile",{pro:M,action:w,...C}).catch((S)=>{if(A!==this.watchGen||M!==this.project)return;this.fabStatus=S instanceof Error?S.message:"Fab action failed",this.render()})},i=document.createElement("div");i.className="bp-mgmt-head";let s=document.createElement("span");s.className="bp-mgmt-strong",s.textContent=b("gpui.mgmt.fab.thefab","The fab");let r=document.createElement("span");r.className="bp-dim bp-mgmt-flex1",r.textContent=`rev ${t.rev??0}${t.updated?` · ${t.updated}`:""}${t.board?` · ${t.board}`:""} · ${ai(t.tier??"")}`;let a=document.createElement("button");if(a.type="button",a.className="bp-mgmt-btn",a.textContent=b("gpui.mgmt.fab.refresh","Refresh"),a.addEventListener("click",()=>n("refresh")),i.append(s,r,a),e.appendChild(i),this.fabStatus){let w=document.createElement("div");w.className="bp-mgmt-note bp-tone-bad",w.textContent=this.fabStatus,e.appendChild(w)}let o=document.createElement("div");o.className="bp-mgmt-rows",o.setAttribute("data-testid","mgmt-fab-rows");let c=t.review,u=document.createElement("div");u.className="bp-mgmt-row";let l=document.createElement("div");l.className="bp-mgmt-row-line";let p=document.createElement("span"),d=(c?.counts?.error??0)>0;if(p.className="bp-mgmt-flex1 "+(d?"bp-tone-bad":"bp-dim"),p.textContent=c?.running?"Reviewing the design…":c?.at==null?"No design review yet":`${c.counts?.error??0} must-fix · ${c.counts?.warning??0} should-fix · ${c.counts?.info??0} notes${c.scope?` (${c.scope})`:""}`,l.appendChild(p),c?.at!=null){let w=document.createElement("button");w.type="button",w.className="bp-mgmt-btn",w.textContent=b("gpui.mgmt.fab.findings","Findings"),w.addEventListener("click",()=>this.togglePanel("checks")),l.appendChild(w)}if(!c?.running){let w=document.createElement("button");w.type="button",w.className="bp-mgmt-btn",w.textContent=b("gpui.mgmt.fab.reviewbtn","Review"),w.addEventListener("click",()=>n("review")),l.appendChild(w)}if(c?.judge){let w=document.createElement("button");w.type="button",w.className="bp-mgmt-btn",w.textContent=b("gpui.mgmt.fab.judge","Datasheets"),w.addEventListener("click",()=>{if(c.judge)this.cb.onSendText(c.judge)}),l.appendChild(w)}u.appendChild(l),o.appendChild(u);let g=ri(t.drc?.state??""),y=document.createElement("div");y.className="bp-mgmt-row";let m=document.createElement("div");m.className="bp-mgmt-row-line";let h=document.createElement("span");if(h.className="bp-mgmt-flex1 "+(g.button?"bp-tone-warn":"bp-dim"),h.textContent=g.text,m.appendChild(h),g.button){let w=document.createElement("button");w.type="button",w.className="bp-mgmt-btn",w.textContent=g.button,w.addEventListener("click",()=>n("drc")),m.appendChild(w)}y.appendChild(m),o.appendChild(y);for(let w of t.conflicts??[]){let C=document.createElement("div");C.className="bp-mgmt-row bp-tone-bad",C.textContent=w,o.appendChild(C)}for(let w of t.suggestions??[]){let C=document.createElement("div");C.className="bp-mgmt-row";let A=document.createElement("div");A.className="bp-mgmt-row-line";let M=document.createElement("span");M.className="bp-mgmt-flex1 bp-tone-warn",M.textContent=`${w.label||w.key}: board ${w.project??"?"} mm, fab ${w.fab??"?"} mm`;let S=document.createElement("button");S.type="button",S.className="bp-mgmt-btn",S.textContent=b("gpui.mgmt.fab.apply","Apply"),S.addEventListener("click",()=>n("apply",{key:w.key})),A.append(M,S),C.appendChild(A),o.appendChild(C)}if(t.stackup?.chosen){let w=document.createElement("div");w.className="bp-mgmt-row";let C=document.createElement("div");C.className="bp-mgmt-row-line";let A=t.stackup.by==="proposed",M=document.createElement("span");if(M.className="bp-mgmt-flex1 "+(A?"bp-tone-warn":"bp-dim"),M.textContent=`${A?"Proposed: ":""}${t.stackup.chosen}${t.stackup.outer_50_mm?` (50Ω ${t.stackup.outer_50_mm} mm)`:""}`,C.appendChild(M),A){let S=t.stackup.chosen,T=document.createElement("button");T.type="button",T.className="bp-mgmt-btn",T.textContent=b("gpui.mgmt.fab.use","Use"),T.addEventListener("click",()=>n("stackup",{id:S})),C.appendChild(T)}w.appendChild(C),o.appendChild(w)}if(Array.isArray(t.changed)&&t.changed.length>0){let w=document.createElement("div");w.className="bp-mgmt-row";let C=document.createElement("div");C.className="bp-mgmt-row-line";let A=document.createElement("span");A.className="bp-mgmt-flex1 bp-tone-warn",A.textContent=b("gpui.mgmt.fab.changed","Changed since you last looked");let M=document.createElement("button");M.type="button",M.className="bp-mgmt-btn",M.textContent=b("gpui.mgmt.fab.seen","Seen"),M.addEventListener("click",()=>n("seen")),C.append(A,M),w.appendChild(C);for(let S of t.changed.slice(0,12)){let T=document.createElement("div");T.className="bp-mgmt-faint",T.textContent=S,w.appendChild(T)}o.appendChild(w)}let f=Array.isArray(t.limits)?t.limits:[];if(f.length>0){let w=document.createElement("div");w.className="bp-mgmt-group-head";let C=document.createElement("span");C.className="bp-mgmt-flex1",C.textContent=b("gpui.mgmt.fab.limit","Limit");let A=document.createElement("span");A.className="bp-mgmt-col",A.textContent=b("gpui.mgmt.fab.free","Base price");let M=document.createElement("span");M.className="bp-mgmt-col",M.textContent=b("gpui.mgmt.fab.extra","Costs more");let S=document.createElement("span");S.className="bp-mgmt-col bp-mgmt-col-read",S.textContent=b("gpui.mgmt.fab.readcol","Read"),w.append(C,A,M,S),o.appendChild(w);for(let B of f){let R=document.createElement("div");R.className="bp-mgmt-row";let O=document.createElement("div");O.className="bp-mgmt-row-line";let H=document.createElement("span");H.className="bp-mgmt-flex1"+(B.changed?" bp-tone-warn":B.inherited?" bp-dim":""),H.textContent=`${B.changed?"• ":""}${B.label??""}`;let ae=document.createElement("span");ae.className="bp-mgmt-col",ae.textContent=B.free?.text||"—";let ue=document.createElement("span");ue.className="bp-mgmt-col bp-dim",ue.textContent=B.extra?.text||"—";let oe=B.free&&typeof B.free==="object"?B.free:B.extra,we=oe?.fetched??"",Le=Boolean(we)&&oe?.confidence!=="published",Ne=we?Le?`${we}*`:we:"—",he=oe?.source??"",be;if(he.startsWith("https://")&&we){let I=document.createElement("a");I.className="bp-mgmt-col bp-mgmt-col-read bp-mgmt-read-link",I.href=he,I.target="_blank",I.rel="noopener noreferrer",I.textContent=Ne,be=I}else{let I=document.createElement("span");I.className="bp-mgmt-col bp-mgmt-col-read bp-mgmt-faint",I.textContent=Ne,be=I}O.append(H,ae,ue,be),R.appendChild(O),o.appendChild(R)}let T=document.createElement("div");T.className="bp-mgmt-note bp-mgmt-faint",T.textContent=b("gpui.mgmt.fab.derived","* worked out from the fab's page. Dimmed: the rigid board's value. A date opens the source page."),o.appendChild(T)}return e.appendChild(o),e}makeEmpty(e){let t=document.createElement("div");return t.className="bp-mgmt-note bp-mgmt-faint",t.textContent=e,t}}var Is={trs:(e)=>e,t:(e,t)=>t},Rs=new Set(["/settle"]);function xi(e,t){let n=t.trim().toLowerCase();if(!n)return 1;let i=e.toLowerCase();if(i.startsWith(n))return 3;if(i.split(/[^a-z0-9]+/i).some((a)=>a.startsWith(n)))return 2;let r=0;for(let a=0;a0||e.status==="waiting")return{urgency:3,want:"waiting"};if(e.status==="asking")return{urgency:2,want:"question"};if(e.status==="failed"||e.state==="failed")return{urgency:1,want:"failed"};return{urgency:0,want:""}}function ki(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 Ai(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 Li(e,t=Is){let{t:n,trs:i}=t,s=[],r=new Map;for(let o of e.projects)r.set(o.id,o.title||o.id);let a=e.threads.find((o)=>o.id===e.selectedThreadId)??null;for(let o of e.railItems){if(o.state==="disabled"||o.id==="commands")continue;if(!a&&o.id!=="terminal")continue;s.push({label:i(o.label),place:o.id==="terminal"?"":"viewer",kind:"action",shortcut:o.key?o.key.toUpperCase():void 0,action:{type:"rail",id:o.id}})}if(a)s.push({label:a.pinned?n("menu.unpin","Unpin"):n("menu.pin","Pin"),place:"",kind:"action",action:{type:"thread-act",action:a.pinned?"unpin":"pin"}}),s.push({label:a.settled?n("phone.unsettle","Unsettle"):n("menu.settle","Settle"),place:"",kind:"action",action:{type:"thread-act",action:a.settled?"unsettle":"settle"}}),s.push({label:a.archived?n("palette.unarchive","Unarchive"):n("palette.archive","Archive"),place:"",kind:"action",action:{type:"thread-act",action:a.archived?"unarchive":"archive"}}),s.push({label:n("sheet.rename","Rename thread"),place:"",kind:"action",action:{type:"rename"}}),s.push({label:n("gpui.previous.thread","Previous thread"),place:"",kind:"action",action:{type:"prev-thread"}}),s.push({label:n("gpui.next.thread","Next thread"),place:"",kind:"action",action:{type:"next-thread"}});if(a)for(let o of e.commands){if(!o.word)continue;let c=Rs.has(o.word.toLowerCase());s.push({label:o.label?`${o.word} — ${o.label}`:o.word,place:o.desc||"command",kind:"command",action:{type:"command",word:o.word,runDirectly:c}})}s.push({label:n("gpui.improvements","Improvements"),place:"",kind:"action",action:{type:"improvements"}}),s.push({label:n("palette.settings","Settings"),place:"",kind:"action",action:{type:"settings"}}),s.push({label:n("gpui.fold.or.unfold.the.sidebar","Fold or unfold the sidebar"),place:"",kind:"action",action:{type:"sidebar"}});for(let o of e.projects)s.push({label:`New thread in ${o.title||o.id}`,place:"",kind:"action",action:{type:"new-thread",projectId:o.id}});for(let o of e.threads){let{urgency:c,want:u}=Ci(o);s.push({label:o.title||"Untitled thread",place:o.project?r.get(o.project)??"":"",kind:"thread",urgency:c,want:u,dotClass:ki(o),action:{type:"thread",id:o.id}})}for(let o of e.bots){if(!o.name||!o.thread)continue;s.push({label:o.name,place:"",kind:"bot",action:{type:"thread",id:o.thread}})}return s}function Si(e,t,n,i=[],s=10,r=14){let a=t.trim(),o=a.length===0,c=e.slice();if(n?.threads&&n.threads.length>0){let d=new Map;for(let y of i)d.set(y.id,y.title||y.id);let g=new Set;for(let y of c)if(y.action.type==="thread")g.add(y.action.id);for(let y of n.threads){if(!y.id||g.has(y.id))continue;g.add(y.id);let{urgency:m,want:h}=Ci(y);c.push({label:y.title||"Untitled thread",place:y.project?d.get(y.project)??"":"",kind:"thread",urgency:m,want:h,dotClass:ki(y),action:{type:"thread",id:y.id}})}}let u=[];for(let d=0;d0)u.push({score:h,index:d,item:g})}u.sort((d,g)=>{if(o){let h=(g.item.urgency??0)-(d.item.urgency??0);if(h!==0)return h}if(g.score!==d.score)return g.score-d.score;let y=d.item.kind==="thread"?0:1,m=g.item.kind==="thread"?0:1;if(y!==m)return y-m;return d.index-g.index});let l=new Set,p=[];for(let d of u){let g=`${d.item.label}\x00${d.item.place}\x00${d.item.kind}`;if(l.has(g))continue;if(l.add(g),p.push(d.item),p.length>=s)break}if(n?.messages&&n.messages.length>0&&p.length{if(a.target===t)this.close()}),s.addEventListener("input",()=>{this.query=s.value,this.activeIdx=0,this.renderList(),this.scheduleSearch()}),s.addEventListener("keydown",(a)=>{if(a.key==="Escape")a.preventDefault(),a.stopPropagation(),this.close();else if(a.key==="ArrowDown"){if(a.preventDefault(),this.listed.length>0)this.activeIdx=(this.activeIdx+1)%this.listed.length,this.renderList(!0)}else if(a.key==="ArrowUp"){if(a.preventDefault(),this.listed.length>0)this.activeIdx=(this.activeIdx-1+this.listed.length)%this.listed.length,this.renderList(!0)}else if(a.key==="Enter")a.preventDefault(),this.runAt(this.activeIdx)}),this.backdrop=t,this.inputEl=s,this.listEl=r,this.root.appendChild(t),this.renderList(),this.query.trim().length>=2)this.scheduleSearch();s.focus()}close(){if(this.searchTimer!==null)window.clearTimeout(this.searchTimer),this.searchTimer=null;if(this.searchGen++,this.backdrop)this.backdrop.remove(),this.backdrop=null,this.inputEl=null,this.listEl=null;this.prevFocus?.focus(),this.prevFocus=null}scheduleSearch(){if(this.searchTimer!==null)window.clearTimeout(this.searchTimer),this.searchTimer=null;let e=this.query.trim();if(e.length<2){this.searchHits=null,this.searchHitsQuery="";return}if(e===this.searchHitsQuery)return;let t=++this.searchGen;this.searchTimer=window.setTimeout(()=>{this.searchTimer=null,this.cb.onSearch(e).then((n)=>{if(t!==this.searchGen||!this.backdrop)return;if(this.query.trim()!==e)return;this.searchHits=n,this.searchHitsQuery=e,this.renderList()}).catch(()=>{})},180)}runAt(e){let t=this.listed[e];if(!t)return;this.close(),this.cb.onExecute(t.action)}renderList(e=!1){if(!this.listEl)return;let t=this.cb.getState(),n=Li(t,{t:b,trs:pe}),i=this.query.trim()===this.searchHitsQuery?this.searchHits:null;if(this.listed=Si(n,this.query,i,t.projects),this.activeIdx>=this.listed.length)this.activeIdx=Math.max(0,this.listed.length-1);if(this.listed.length===0){let a=document.createElement("div");a.className="bp-palette-empty",a.textContent=b("gpui.nothing.matches","Nothing matches"),this.listEl.replaceChildren(a);return}let s=document.createDocumentFragment(),r=null;for(let a=0;a0)u.appendChild(document.createTextNode(o.label.slice(0,d)));let y=document.createElement("strong");if(y.className="bp-palette-mark",y.textContent=o.label.slice(d,g),u.appendChild(y),g{if(this.activeIdx!==a)this.activeIdx=a,this.updateActiveClass()}),c.addEventListener("click",()=>this.runAt(a)),a===this.activeIdx)r=c;s.appendChild(c)}if(this.listEl.replaceChildren(s),e&&r)r.scrollIntoView({block:"nearest"})}updateActiveClass(){if(!this.listEl)return;let e=this.listEl.children;for(let t=0;tthis.onPress(e.id));return r}render(){let e=this.items.filter((a)=>a.group!=="tools"),t=this.items.filter((a)=>a.group==="tools"),n=document.createElement("div");n.className="bp-rail-pages";let i;for(let a of e){if(i!==void 0&&a.group!==i){let o=document.createElement("div");o.className="bp-rail-rule",n.appendChild(o)}i=a.group,n.appendChild(this.renderButton(a))}let s=()=>{let a=n.scrollLeft>2,o=n.scrollLeft+n.clientWidth0){let a=document.createElement("div");a.className="bp-rail-tools";for(let o of t)a.appendChild(this.renderButton(o));r.appendChild(a)}this.el.replaceChildren(r)}}var Hs=new Set(["resume","raise","retry","move","signin"]);function Ti(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 $t(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(Hs.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 Bi(e){let t=e&&typeof e==="object"?e.open:void 0;if(typeof t!=="string")return null;let n=t.indexOf(":"),i=n<0?"":t.slice(n+1);if(!i)return null;if(t.startsWith("account:"))return{kind:"account",id:i};if(t.startsWith("thread:"))return{kind:"thread",id:i};return null}class mn{backdrop;titleEl;closeBtn;bodyEl;cb;openState=!1;providersEl=null;constructor(e,t){this.cb=t,this.backdrop=document.createElement("div"),this.backdrop.className="bp-modal-backdrop bp-hidden",this.backdrop.setAttribute("data-testid","settings-modal");let n=document.createElement("div");n.className="bp-modal";let i=document.createElement("div");i.className="bp-modal-head",this.titleEl=document.createElement("h2"),this.titleEl.textContent=`${b("palette.settings","Settings")} · Devices`,this.closeBtn=document.createElement("button"),this.closeBtn.type="button",this.closeBtn.className="icon",this.closeBtn.textContent="×",this.closeBtn.setAttribute("aria-label",b("common.close","Close")),this.closeBtn.addEventListener("click",()=>this.close()),i.append(this.titleEl,this.closeBtn),this.bodyEl=document.createElement("div"),this.bodyEl.className="bp-modal-body",n.append(i,this.bodyEl),this.backdrop.appendChild(n),this.backdrop.addEventListener("click",(s)=>{if(s.target===this.backdrop)this.close()}),e.appendChild(this.backdrop)}isOpen(){return this.openState}async open(){this.openState=!0,this.backdrop.classList.remove("bp-hidden"),await this.refresh()}async openToAccounts(){await this.open(),this.providersEl?.scrollIntoView({block:"nearest"})}close(){this.openState=!1,this.backdrop.classList.add("bp-hidden")}refreshLocale(){if(this.titleEl.textContent=`${b("palette.settings","Settings")} · Devices`,this.closeBtn.setAttribute("aria-label",b("common.close","Close")),this.openState)this.refresh()}async refresh(){let e=document.createDocumentFragment();this.providersEl=null;let t=this.cb.onGetNoProvider?.()??null;if(t){let l=document.createElement("section");l.className="bp-set-section",l.setAttribute("data-testid","settings-providers");let p=document.createElement("div");p.className="bp-set-head",p.textContent=b("web.settings.providers","AI providers");let d=document.createElement("div");d.className="bp-set-row";let g=document.createElement("div");g.className="bp-set-info";let y=document.createElement("div");y.textContent=pe(t.head);let m=document.createElement("div");m.className="bp-dim",m.textContent=b("web.settings.providers.browser","Connect a provider in the Backplane desktop or mobile app under Settings → Accounts."),g.append(y,m);let h=document.createElement("div");h.className="bp-set-btns";let f=document.createElement("a");f.className="bp-link-btn primary",f.href=t.url||"backplane://settings/accounts",f.setAttribute("data-testid","settings-open-accounts"),f.textContent=pe(t.button),h.appendChild(f),d.append(g,h),l.append(p,d),this.providersEl=l,e.appendChild(l)}let n=this.cb.onGetHome?.()??null;if(n){let l=document.createElement("section");l.className="bp-set-section",l.setAttribute("data-testid","settings-home");let p=document.createElement("div");p.className="bp-set-head",p.textContent=b("home.machine","Home machine");let d=document.createElement("div");d.className="bp-set-row";let g=document.createElement("div");g.className="bp-set-info";let y=document.createElement("div"),m=n.kind==="local"?`${n.name||"This machine"} (this machine)`:n.kind==="boat"?`${n.name||"Boat"} (Boat)`:n.name||"Linked machine";y.textContent=m,g.appendChild(y);let h=document.createElement("div");if(h.className="bp-dim",n.moving?.state==="moving")h.textContent=n.moving.step?b("home.moving.step","Moving home to {to}: {step}").replace("{to}",n.moving.to).replace("{step}",n.moving.step):b("home.moving","Moving home to {to}…").replace("{to}",n.moving.to);else if(n.moving?.state==="failed")h.textContent=n.moving.note?b("home.move.failed.note","Home move failed: {note}").replace("{note}",n.moving.note):b("home.move.failed","Home move failed");else if(!n.online)h.textContent=n.queuedCount>0?b("home.away.queued","Home ({name}) is away · {n} queued").replace("{name}",n.name||"home").replace("{n}",String(n.queuedCount)):b("home.away","Home ({name}) is away").replace("{name}",n.name||"home");else h.textContent="Online";if(g.appendChild(h),d.appendChild(g),n.canMoveHere&&this.cb.onMoveHomeHere){let f=document.createElement("button");f.type="button",f.className="primary",f.textContent=b("home.move.here","Make this machine the home"),f.setAttribute("data-testid","home-move-here-btn"),f.addEventListener("click",()=>{f.disabled=!0,this.cb.onMoveHomeHere?.().finally(()=>{this.refresh()})}),d.appendChild(f)}l.append(p,d),e.appendChild(l)}let i=document.createElement("section");i.className="bp-set-section";let s=document.createElement("div");s.className="bp-set-head",s.textContent="This browser";let r=document.createElement("div");r.className="bp-set-row";let a=document.createElement("span");a.className="bp-dim",a.textContent="Sign out and revoke this browser's session cookie.";let o=document.createElement("button");o.type="button",o.className="primary stop",o.textContent=b("agy.signout","Sign out"),o.setAttribute("data-testid","logout-btn"),o.addEventListener("click",()=>{o.disabled=!0,this.cb.onLogout().catch(()=>{a.setAttribute("role","alert"),a.textContent=b("web.logout.failed","Could not confirm sign-out. Try again."),o.disabled=!1})}),r.append(a,o),i.append(s,r),e.appendChild(i);let c=document.createElement("section");c.className="bp-set-section";let u=document.createElement("div");u.className="bp-set-head",u.textContent="Paired devices",c.appendChild(u);try{let l=await this.cb.onLoadDevices();if(l.length===0){let p=document.createElement("div");p.className="bp-dim",p.textContent="No devices listed.",c.appendChild(p)}else for(let p of l){let d=document.createElement("div");d.className="bp-set-row";let g=document.createElement("div");g.className="bp-set-info";let y=document.createElement("div");if(y.textContent=p.title||p.head||"",g.appendChild(y),p.text||p.detail){let m=document.createElement("div");m.className="bp-dim",m.textContent=p.text||p.detail||"",g.appendChild(m)}if(d.appendChild(g),p.buttons?.length){let m=document.createElement("div");m.className="bp-set-btns";for(let h of p.buttons){let f=document.createElement("button");if(f.type="button",h.primary)f.className="primary";if(h.danger)f.className="primary stop";f.textContent=h.label||b("common.remove","Remove"),f.addEventListener("click",()=>{f.disabled=!0,this.cb.onDevicesAct(h.action,h.value).finally(()=>{this.refresh()})}),m.appendChild(f)}d.appendChild(m)}c.appendChild(d)}}catch(l){let p=document.createElement("div");p.className="bp-dim";let d=l instanceof Error&&l.message?l.message:"Not available from a browser";p.textContent=`${d} — manage paired devices in Backplane › Settings › Devices on desktop or a paired phone.`,c.appendChild(p)}e.appendChild(c),this.bodyEl.replaceChildren(e)}}function Ee(e,t,n){let i=document.createElement(e);if(t)i.className=t;if(n)i.textContent=n;return i}function xt(e,t,n=!1){let i=Ee("button",n?"primary":"bp-btn-ghost",e);return i.type="button",i.addEventListener("click",t),i}function un(e){return Ee("pre","bp-context-code",e)}function Ds(e){return Ee("span",`bp-context-badge ${e==="Native"||e==="Enabled"?"active":e==="Untrusted"||e==="Invalid"?"warn":""}`,pe(e))}function Gt(e,t){let n=Ee("div","bp-context-row");return n.append(Ee("strong",void 0,e),Ds(t)),n}class hn{fetchContext;dialog=Ee("dialog","bp-context");title=Ee("h2");cwd=Ee("div","bp-context-path");tabs=Ee("div","bp-context-tabs");body=Ee("div","bp-context-body");notice=Ee("p","bp-context-notice");current;thread="";requestId=0;tab=0;busy=!1;constructor(e,t){this.fetchContext=t;let n=Ee("div","bp-context-head"),i=Ee("div");i.append(this.title,this.cwd),this.title.id="bp-context-title",this.dialog.setAttribute("aria-labelledby",this.title.id),this.notice.setAttribute("role","status"),n.append(i,xt(b("common.refresh","Refresh"),()=>{this.load()}),xt(b("common.close","Close"),()=>this.dialog.close())),this.dialog.append(n,this.tabs,this.notice,this.body),this.dialog.addEventListener("close",()=>{this.requestId++}),e.append(this.dialog)}open(e){if(this.thread=e,this.tab=0,this.current=void 0,this.busy=!1,this.title.textContent=b("thread.context.title","Context & Prompt"),this.cwd.textContent="",!this.dialog.open)this.dialog.showModal();this.render(),this.load()}async load(e){if(this.busy)return;let t=++this.requestId;this.busy=!0,this.notice.textContent=b("thread.context.reading","Reading thread context…"),this.render();try{let n=await this.fetchContext(this.thread,e);if(t!==this.requestId)return;this.current=n,this.cwd.textContent=n.cwd,this.notice.textContent=""}catch(n){if(t===this.requestId)this.notice.textContent=String(n)}finally{if(t===this.requestId)this.busy=!1,this.render()}}render(){let e=[b("thread.context.instructions","Instructions"),b("thread.context.system","System Prompt"),b("thread.context.skills","Skills"),b("thread.context.mcp","Project MCPs")];this.tabs.replaceChildren(...e.map((n,i)=>{let s=xt(n,()=>{this.tab=i,this.render(),this.body.scrollTop=0,this.tabs.children[i].focus()});return s.setAttribute("aria-pressed",String(i===this.tab)),s})),this.body.replaceChildren();let t=this.current;if(!t)return;switch(this.tab){case 0:this.instructions(t.instructions);break;case 1:this.prompt(t);break;case 2:this.skills(t.skills);break;case 3:this.mcps(t.mcp);break}}instructions(e){if(!e.length)this.body.append(Ee("p","bp-dim",b("thread.context.none.instructions","No project instructions found.")));for(let t of e){let n=Ee("details","bp-context-card"),i=Ee("summary");if(i.append(Gt(t.path,t.status),Ee("small","bp-dim",b("thread.context.size","{bytes} B · ≈{tokens} tokens",{bytes:t.bytes,tokens:t.estimated_tokens}))),n.append(i,un(t.preview)),t.note)n.append(Ee("small","bp-dim",t.note));this.body.append(n)}}prompt(e){let t=Ee("div","bp-context-row"),n=xt(b("thread.context.copy","Copy prompt"),()=>{navigator.clipboard.writeText(e.prompt).then(()=>{this.notice.textContent=b("thread.context.copied","Prompt copied.")}).catch((i)=>{this.notice.textContent=String(i)})});t.append(Ee("p","bp-dim",b("thread.context.native.note","Backplane’s launch prompt. Native files are loaded by the provider.")),n),this.body.append(t);for(let[i,s]of[[b("thread.context.base","Backplane"),e.sections.base],[b("thread.context.injected.label","Injected project instructions"),e.sections.instructions],[b("thread.context.index","Available skills index"),e.sections.skills]])if(s)this.body.append(Ee("h3",void 0,i),un(s))}skills(e){for(let t of["Project","User","Bundled"]){let n=e.filter((i)=>i.scope===t);if(!n.length)continue;this.body.append(Ee("h3",void 0,pe(t)));for(let i of n){let s=Ee("article","bp-context-card");s.append(Gt(i.name,i.status),Ee("p",void 0,i.description),Ee("small","bp-context-path",[i.source,i.provider,i.model].filter(Boolean).join(" · ")),Ee("small","bp-context-path",i.path)),this.body.append(s)}}}mcps(e){if(!e.length)this.body.append(Ee("p","bp-dim",b("thread.context.none.mcp","No project MCP configurations found.")));for(let t of e){let n=Ee("article","bp-context-card");n.append(Gt(t.path,t.state));for(let s of t.servers){let r=s.url||[s.command,...s.args].map((a)=>JSON.stringify(a)).join(" ");if(n.append(Gt(s.name,s.status),un(r)),s.cwd)n.append(Ee("small","bp-context-path",s.cwd))}if(t.error)n.append(Ee("p","bp-warn",t.error));let i=t.state==="Untrusted"?"trust":t.state==="Enabled"?"disable":t.state==="Disabled"?"enable":"";if(i){let s=i==="trust"?b("thread.context.trust","Trust and enable"):i==="disable"?b("thread.context.disable","Disable"):b("thread.context.enable","Enable"),r=xt(s,()=>{this.load({action:i,path:t.path,sha256:t.sha256})},i==="trust");r.disabled=this.busy;let a=Ee("div","bp-context-actions");a.append(r),n.append(a)}this.body.append(n)}}}var Ii="http://www.w3.org/2000/svg";function Ri(){let e=document.createElementNS(Ii,"svg");e.setAttribute("viewBox","0 0 24 24"),e.setAttribute("width","14"),e.setAttribute("height","14"),e.setAttribute("fill","none"),e.setAttribute("stroke","currentColor"),e.setAttribute("stroke-width","1.75"),e.setAttribute("aria-hidden","true"),e.classList.add("bp-folder-icon");let t=document.createElementNS(Ii,"path");return t.setAttribute("d","M3 6h6l2 2h10v11H3z"),e.appendChild(t),e}function Fs(e,t,n,i){let s=e||t||n||"";if(s==="active"||s==="working"||s==="running"||s==="run")return"bp-dot-work";if(s==="finished"||s==="done")return"bp-dot-done";if(s==="waiting"||s==="asking"||s==="blocked"||s==="needs"||s==="failed"||s==="fail"||s==="cut"||s==="interrupted"||s==="limit"||s==="monitoring"||(i??0)>0)return"bp-dot-need";return"bp-dot-idle"}function ji(e){if(!e)return"";let t=e<10000000000?e*1000:e,n=Math.max(0,Math.floor((Date.now()-t)/1000));if(n<60)return"now";if(n<3600)return`${Math.floor(n/60)}m`;if(n<86400)return`${Math.floor(n/3600)}h`;return`${Math.floor(n/86400)}d`}class bn{el;hostLabel;homeBanner;filterInput;listEl;connEl;filterText="";showSettled=new Set;collapsedProjects=new Set;addShown=!1;sections=null;projects=[];threads=[];bots=[];rooms=[];selectedThreadId="";cb;needErr=new Map;needBusy=new Set;constructor(e,t){this.el=e,this.cb=t;let n=document.createElement("div");n.className="bp-side-host";let i=document.createElement("div");i.className="bp-side-host-left",this.hostLabel=document.createElement("span"),this.hostLabel.textContent="This computer";let s=document.createElement("span");s.className="bp-dim",s.textContent="›",i.append(this.hostLabel,s);let r=document.createElement("button");r.type="button",r.className="icon bp-side-collapse",r.textContent="‹",r.title="Collapse sidebar",r.setAttribute("aria-label","Collapse sidebar"),r.setAttribute("data-testid","sidebar-collapse"),r.addEventListener("click",()=>this.cb.onCollapseSidebar?.()),n.append(i,r);let a=document.createElement("div");a.className="bp-side-head",this.filterInput=document.createElement("input"),this.filterInput.type="search",this.filterInput.className="bp-input bp-side-search";let o=b("sidebar.search.projects","Search projects");this.filterInput.placeholder=o,this.filterInput.setAttribute("aria-label",o),this.filterInput.setAttribute("data-testid","sidebar-filter"),this.filterInput.addEventListener("input",()=>{this.filterText=this.filterInput.value.trim().toLowerCase(),this.render()});let c=document.createElement("button");c.type="button",c.className="icon bp-side-add",c.textContent="+",c.title=b("thread.new","New thread"),c.setAttribute("aria-label",b("thread.new","New thread")),c.setAttribute("data-testid","sidebar-new-thread"),c.addEventListener("click",()=>{let l=this.firstProjectId();if(l)this.cb.onNewThread(l)}),a.append(this.filterInput,c),this.homeBanner=document.createElement("div"),this.homeBanner.className="bp-side-home bp-hidden",this.homeBanner.setAttribute("data-testid","home-away-banner"),this.homeBanner.style.padding="6px 10px",this.homeBanner.style.fontSize="11px",this.homeBanner.style.borderBottom="1px solid var(--line, #2a2a2a)",this.listEl=document.createElement("div"),this.listEl.className="bp-side-list",this.listEl.setAttribute("data-testid","sidebar-list");let u=document.createElement("div");u.className="bp-side-footer",this.connEl=document.createElement("span"),this.connEl.className="bp-conn-status",this.connEl.textContent="Connecting…",this.connEl.setAttribute("data-testid","conn-status"),u.appendChild(this.connEl),this.el.append(n,a,this.homeBanner,this.listEl,u)}setHome(e){if(!e){this.homeBanner.classList.add("bp-hidden"),this.homeBanner.textContent="";return}let t="",n=!1;if(e.moving?.state==="moving")t=e.moving.step?b("home.moving.step","Moving home to {to}: {step}").replace("{to}",e.moving.to).replace("{step}",e.moving.step):b("home.moving","Moving home to {to}…").replace("{to}",e.moving.to);else if(e.moving?.state==="failed")t=e.moving.note?b("home.move.failed.note","Home move failed: {note}").replace("{note}",e.moving.note):b("home.move.failed","Home move failed"),n=!0;else if(!e.online){let i=e.name||"home",s="";if(e.awaySince&&e.awaySince>0){let r=new Date(e.awaySince);s=`${String(r.getHours()).padStart(2,"0")}:${String(r.getMinutes()).padStart(2,"0")}`}if(s&&e.queuedCount>0)t=b("home.away.since.queued","Home ({name}) is away since {time} · {n} queued").replace("{name}",i).replace("{time}",s).replace("{n}",String(e.queuedCount));else if(s)t=b("home.away.since","Home ({name}) is away since {time}").replace("{name}",i).replace("{time}",s);else if(e.queuedCount>0)t=b("home.away.queued","Home ({name}) is away · {n} queued").replace("{name}",i).replace("{n}",String(e.queuedCount));else t=b("home.away","Home ({name}) is away").replace("{name}",i)}if(!t)this.homeBanner.classList.add("bp-hidden"),this.homeBanner.textContent="";else this.homeBanner.textContent=t,this.homeBanner.className=n?"bp-side-home bp-bad":"bp-side-home bp-dim",this.homeBanner.classList.remove("bp-hidden")}setHostName(e){this.hostLabel.textContent=e||"This computer"}setConnStatus(e,t){this.connEl.textContent=e,this.connEl.className=`bp-conn-status ${t}`.trim()}setData(e,t,n,i){this.projects=e,this.threads=t,this.bots=n,this.rooms=i,this.render()}setSections(e,t,n){this.sections=e,this.bots=t,this.rooms=n,this.render()}setSelected(e){this.selectedThreadId=e,this.render()}focusFilter(){this.filterInput.focus()}firstProjectId(){if(this.sections){for(let e of this.sections)if(e.kind==="projects"&&e.rows.length>0){let t=e.rows[0];if(t.id&&!t.off)return t.id}}return this.projects[0]?.id??""}refreshLocale(){let e=b("sidebar.search.projects","Search projects");this.filterInput.placeholder=e,this.filterInput.setAttribute("aria-label",e),this.render()}projectsHead(e){let t=document.createElement("div");if(t.className="bp-side-section-head",!this.cb.onAddProject||this.addShown)return t.textContent=e,t;this.addShown=!0,t.classList.add("bp-side-section-row");let n=document.createElement("span");n.textContent=e;let i=document.createElement("button");i.type="button",i.className="bp-side-sec-plus bp-side-sec-btn",i.textContent="+";let s=b("sidebar.add.project","Add project");return i.title=s,i.setAttribute("aria-label",s),i.setAttribute("data-testid","sidebar-add-project"),i.addEventListener("click",(r)=>{r.stopPropagation(),this.cb.onAddProject?.()}),t.append(n,i),t}renderSectionThreadRow(e,t){let n=document.createElement("div");if(n.className="bp-thread-row"+(e.id===this.selectedThreadId?" active":"")+(e.off?" bp-dim":""),n.setAttribute("data-thread-id",e.id),n.setAttribute("data-testid",`thread-row-${e.id}`),t){let p=document.createElement("span");p.className="bp-tree-branch",p.setAttribute("aria-hidden","true"),n.appendChild(p)}let i=document.createElement("span");i.className=`bp-dot ${Fs(e.status,e.word,e.state)}`;let s=document.createElement("div");if(s.className="bp-thread-title",s.textContent=e.title||"Untitled thread",n.append(i,s),e.word==="needs"){let p=document.createElement("span");if(p.className="bp-badge-need",p.textContent=e.want==="approval"?"!":"•",e.say)p.title=e.say;n.appendChild(p)}else if(e.ago){let p=document.createElement("span");if(p.className="bp-thread-age",p.textContent=e.ago,e.pinned)p.title=b("tools.pinned","Pinned");n.appendChild(p)}let r=e.nav||e.id;if(!e.off&&r&&!r.startsWith("@room:"))n.addEventListener("click",()=>this.cb.onSelectThread(r));let a=e.kind==="swarm"?Ti(e.need):null;if(!a)return n;let o=document.createElement("div");o.className="bp-need-wrap";let c=document.createElement("div");c.className="bp-need"+(t?" nested":"")+(e.off?" bp-dim":""),c.setAttribute("data-testid",`need-${e.id}`);let u=document.createElement("span");u.className="bp-need-line",u.textContent=a.line,u.title=a.line,c.appendChild(u);for(let p of a.actions){if(!$t(p,Boolean(this.cb.hasRoomView)))continue;let d=document.createElement("button");d.type="button",d.className="bp-need-btn",d.textContent=p.label,d.setAttribute("data-testid",`need-${p.act}-${e.id}`),d.disabled=Boolean(e.off)||this.needBusy.has(e.id)||!this.cb.onNeedAct,d.addEventListener("click",(g)=>{g.stopPropagation();let y=this.cb.onNeedAct;if(!y)return;this.needErr.delete(e.id),this.needBusy.add(e.id),this.render(),y(p).catch((m)=>{this.needErr.set(e.id,m instanceof Error?m.message:String(m))}).finally(()=>{this.needBusy.delete(e.id),this.render()})}),c.appendChild(d)}o.append(n,c);let l=this.needErr.get(e.id);if(l){let p=document.createElement("div");p.className="bp-need-err"+(t?" nested":""),p.textContent=l,o.appendChild(p)}return o}renderHubSections(e,t){let n=this.sections??[],i=new Set;for(let a of n)if(a.kind==="threads")for(let o of a.rows)i.add(o.id);else if(a.kind==="projects")for(let o of a.rows)for(let c of o.threads??[])i.add(c.id);let s=this.selectedThreadId?this.threads.find((a)=>a.id===this.selectedThreadId)??null:null,r=!1;for(let a of n)if(a.kind==="projects"&&a.rows.length>0)r=!0;for(let a of n){if(a.kind==="bub")continue;if(a.kind==="threads"){let o=a.rows.filter((l)=>{if(!t)return!0;return`${l.title} ${l.project??""}`.toLowerCase().includes(t)});if(o.length===0)continue;let c=document.createElement("section");c.className="bp-side-section",c.setAttribute("data-section-id",a.id);let u=document.createElement("div");u.className="bp-side-section-head",u.textContent=a.title.toUpperCase(),c.appendChild(u);for(let l of o)c.appendChild(this.renderSectionThreadRow(l,!1));e.appendChild(c);continue}if(a.kind==="projects"){let o=a.rows.filter((l)=>{if(!t)return!0;if((l.title||l.id).toLowerCase().includes(t))return!0;if((l.threads??[]).some((p)=>p.title.toLowerCase().includes(t)))return!0;if((l.swarms??[]).some((p)=>p.title.toLowerCase().includes(t)))return!0;return!1}),c=Boolean(a.fold&&a.toggle);if(t&&o.length===0)continue;if(!c&&a.id!=="active"&&o.length===0)continue;let u=document.createElement("section");if(u.className="bp-side-section",u.setAttribute("data-section-id",a.id),c){let l=document.createElement("button");l.type="button",l.className="bp-side-section-head bp-side-section-toggle";let p=a.count??o.length,d=a.open?"▾":"▸";if(l.textContent=`${a.title.toUpperCase()} (${p}) ${d}`,a.hint)l.title=a.hint;l.addEventListener("click",()=>{if(a.toggle)this.cb.onToggleSection?.(a.toggle)}),u.appendChild(l)}else u.appendChild(this.projectsHead(a.title.toUpperCase()));if(!c||a.open||Boolean(t)){if(a.id==="active"&&!r&&!t){let l=document.createElement("div");l.className="bp-side-empty",l.textContent="No projects yet.",u.appendChild(l)}for(let l of o){let p=document.createElement("div");if(p.className="bp-proj-group"+(l.off?" bp-dim":""),p.setAttribute("data-project-id",l.id),l.nav||l.key)p.setAttribute("data-project-key",l.nav||l.key||"");let d=document.createElement("div");d.className="bp-proj-head";let g=document.createElement("button");g.type="button",g.className="bp-proj-toggle";let y=Ri();if(l.css)y.style.color=l.css;let m=document.createElement("span");if(m.className="bp-proj-name",m.textContent=l.title||l.id,g.append(y,m),l.fold==="project-fold"&&l.nav)g.addEventListener("click",()=>this.cb.onToggleProjectFold?.(l.nav));let h=document.createElement("button");if(h.type="button",h.className="icon bp-proj-add",h.title=b("thread.new","New thread"),h.textContent="+",h.setAttribute("data-testid",`new-thread-${l.id}`),l.off)h.disabled=!0;if(h.addEventListener("click",(f)=>{f.stopPropagation(),this.cb.onNewThread(l.id)}),d.append(g,h),p.appendChild(d),!l.folded||Boolean(t)){let f=Boolean(t)&&(l.title||l.id).toLowerCase().includes(t);for(let w of l.swarms??[]){if(t&&!f&&!w.title.toLowerCase().includes(t))continue;p.appendChild(this.renderSectionThreadRow(w,!0))}for(let w of l.threads??[]){if(t&&!f&&!w.title.toLowerCase().includes(t))continue;p.appendChild(this.renderSectionThreadRow(w,!0))}if(s&&s.project===l.id&&!i.has(s.id)&&(!t||f||s.title.toLowerCase().includes(t)))p.appendChild(this.renderSectionThreadRow({id:s.id,title:s.title,status:s.status,state:s.state,ago:ji(s.updatedAt),pinned:s.pinned,nav:s.id},!0))}u.appendChild(p)}}e.appendChild(u)}}}render(){this.addShown=!1;let e=document.createDocumentFragment(),t=this.filterText;if(this.sections!==null)this.renderHubSections(e,t);else{let n=new Map;for(let i of this.threads){if(i.archived||i.swarm)continue;if(t){if(!`${i.title} ${i.preview??""}`.toLowerCase().includes(t))continue}let s=n.get(i.project)??[];s.push(i),n.set(i.project,s)}if(e.appendChild(this.projectsHead("ACTIVE")),this.projects.length===0&&this.threads.length===0){let i=document.createElement("div");i.className="bp-side-empty",i.textContent="No projects yet.",e.appendChild(i)}for(let i of this.projects){let s=n.get(i.id)??[];if(t&&s.length===0&&!i.title.toLowerCase().includes(t))continue;let r=document.createElement("section");r.className="bp-proj-group",r.setAttribute("data-project-id",i.id);let a=document.createElement("div");a.className="bp-proj-head";let o=document.createElement("button");o.type="button",o.className="bp-proj-toggle";let c=this.collapsedProjects.has(i.id)&&!t,u=Ri();if(i.css)u.style.color=i.css;let l=document.createElement("span");l.className="bp-proj-name",l.textContent=i.title||i.id,o.append(u,l),o.addEventListener("click",()=>{if(this.collapsedProjects.has(i.id))this.collapsedProjects.delete(i.id);else this.collapsedProjects.add(i.id);this.render()});let p=document.createElement("button");if(p.type="button",p.className="icon bp-proj-add",p.title=b("thread.new","New thread"),p.textContent="+",p.setAttribute("data-testid",`new-thread-${i.id}`),p.addEventListener("click",(d)=>{d.stopPropagation(),this.cb.onNewThread(i.id)}),a.append(o,p),r.appendChild(a),!c)for(let d of s)r.appendChild(this.renderSectionThreadRow({id:d.id,title:d.title,status:d.status,state:d.state,ago:ji(d.updatedAt),pinned:d.pinned,nav:d.id},!0));e.appendChild(r)}}if(!t){let n=document.createElement("section");n.className="bp-proj-group bp-bots-group";let i=document.createElement("div");i.className="bp-side-section-head bp-side-section-row";let s=document.createElement("span");s.textContent=b("tour.title.bots","Bots").toUpperCase();let r=document.createElement("span");r.className="bp-side-sec-plus",r.textContent="+",r.setAttribute("aria-hidden","true"),i.append(s,r),n.appendChild(i);for(let l of this.bots){let p=document.createElement("div");p.className="bp-thread-row"+(l.thread===this.selectedThreadId?" active":"");let d=document.createElement("span");if(d.className="bp-dot bp-dot-idle",l.color)d.style.backgroundColor=l.color;let g=document.createElement("div");g.className="bp-thread-title",g.textContent=`@${l.name}`,p.append(d,g),p.addEventListener("click",()=>this.cb.onSelectBot(l)),n.appendChild(p)}e.appendChild(n);let a=document.createElement("section");a.className="bp-proj-group";let o=document.createElement("div");o.className="bp-side-section-head bp-side-section-row";let c=document.createElement("span");c.textContent=b("bots.rooms","Rooms").toUpperCase();let u=document.createElement("span");u.className="bp-side-sec-plus",u.textContent="+",u.setAttribute("aria-hidden","true"),o.append(c,u),a.appendChild(o);for(let l of this.rooms){let p=document.createElement("div");p.className="bp-thread-row";let d=document.createElement("div");d.className="bp-thread-title",d.textContent=`#${l.name}`,p.appendChild(d),a.appendChild(p)}e.appendChild(a)}this.listEl.replaceChildren(e)}}function $s(e){try{return new URL(e,window.location.origin).searchParams.get("s")||""}catch{return""}}function Ct(e){if(!e)return;for(let t of e.getTracks())try{t.stop()}catch{}}function Gs(e,t){if(t===16000){let r=new Int16Array(e.length);for(let a=0;a0?c/u:0));s[r]=l<0?l*32768:l*32767}return s}class gn{hub;cb;active=!1;starting=!1;sessionGen=0;activeGen=0;abortedGen=0;threadId="";sessionKey="";stream=null;audioCtx=null;processor=null;pendingPcm=[];postChain=Promise.resolve();stopDrain=Promise.resolve();mark=0;constructor(e,t){this.hub=e,this.cb=t}isRecording(){return this.active||this.starting}async toggle(){if(this.active||this.starting)await this.stop();else await this.start()}async start(){if(this.active||this.starting)return;let e=this.cb.getThreadId();if(!e)return;if(!navigator.mediaDevices?.getUserMedia){this.cb.showError("Microphone access is not available in this browser.");return}let t=++this.sessionGen;this.starting=!0,this.threadId=e,this.sessionKey="",this.pendingPcm=[],this.mark=this.cb.getCaret(),this.cb.setRecording(!0);let n;try{n=await navigator.mediaDevices.getUserMedia({audio:!0})}catch{if(t===this.sessionGen)this.starting=!1,this.cb.setRecording(!1),this.cb.showError("Microphone permission denied.");return}if(t!==this.sessionGen||this.cb.getThreadId()!==e){Ct(n);return}if(this.stream=n,await this.stopDrain,t!==this.sessionGen||this.cb.getThreadId()!==e){if(Ct(n),this.stream===n)this.stream=null;return}try{let i=await this.hub.rpc("voice.start",{thread:e,draft:this.cb.getDraft(),caret:this.mark});if(t!==this.sessionGen||this.cb.getThreadId()!==e){if(Ct(n),this.stream===n)this.stream=null;if(!this.active&&!this.starting)this.hub.rpc("voice.stop",{thread:e}).catch(()=>{});return}let s=i.session||(i.path?$s(i.path):"");if(!s)throw Error("Hub did not return a voice session.");this.sessionKey=s,this.activeGen=t,this.starting=!1,this.active=!0,this.startCapture(n,t)}catch(i){if(t===this.sessionGen)this.cleanupAudio(),this.starting=!1,this.active=!1,this.cb.setRecording(!1),this.cb.showError(i instanceof Error?i.message:"Could not start voice dictation.");else if(Ct(n),this.stream===n)this.stream=null}}async stop(){if(!this.active&&!this.starting)return;let e=this.activeGen,t=this.active,n=this.threadId,i=this.sessionKey;this.sessionGen++,this.starting=!1,this.active=!1,this.sessionKey="",this.cb.setRecording(!1),this.cb.setLevel(0),this.cleanupAudio();let r=this.stopDrain.then(async()=>{if(t&&i){let a=new Int16Array(this.pendingPcm);this.pendingPcm=[],this.enqueuePost(i,new Uint8Array(a.buffer),!0,e),await this.postChain}else this.pendingPcm=[];if(t&&n)await this.hub.rpc("voice.stop",{thread:n}).catch(()=>{})});this.stopDrain=r,await r}cancel(){if(!this.active&&!this.starting)return;let e=this.active,t=this.threadId;if(this.abortedGen=Math.max(this.abortedGen,this.sessionGen),this.sessionGen++,this.starting=!1,this.active=!1,this.sessionKey="",this.pendingPcm=[],this.cb.setRecording(!1),this.cb.setLevel(0),this.cleanupAudio(),e&&t&&this.hub.getState()==="connected")this.hub.rpc("voice.stop",{thread:t}).catch(()=>{})}handleFrame(e){let t=String(e.ev??""),n=String(e.thread??"");if(n&&this.cb.getThreadId()&&n!==this.cb.getThreadId())return;if(t==="draft"&&typeof e.text==="string")this.cb.setDraft(e.text),this.mark=e.text.length;else if(t==="edit"){let i=this.cb.getDraft(),s=Number(e.del??0),r=String(e.ins??""),a=Math.max(0,Math.min(i.length,this.mark)),o=Math.max(0,a-s),c=i.slice(0,o)+r+i.slice(a);this.mark=o+r.length,this.cb.setDraft(c)}else if(t==="level")this.cb.setLevel(Math.max(0,Math.min(100,Number(e.v??0))));else if(t==="view"){let i=e.view;if(i&&i.on===!1&&(this.active||this.starting))this.stop()}}startCapture(e,t){let i=new(window.AudioContext||window.webkitAudioContext),s=i.createMediaStreamSource(e),r=i.createScriptProcessor(4096,1,1);r.onaudioprocess=(a)=>{if(!this.active||t!==this.sessionGen||!this.sessionKey)return;let o=Gs(a.inputBuffer.getChannelData(0),i.sampleRate);for(let c=0;c=3200){let c=new Int16Array(this.pendingPcm.splice(0,3200));this.enqueuePost(this.sessionKey,new Uint8Array(c.buffer),!1,t)}},s.connect(r),r.connect(i.destination),this.audioCtx=i,this.processor=r}enqueuePost(e,t,n,i){this.postChain=this.postChain.then(async()=>{if(i<=this.abortedGen)return;try{let s={"Content-Type":"application/octet-stream","X-Voice-Session":e};if(n)s["X-Voice-End"]="1";let r=await fetch("/voice/in",{method:"POST",credentials:"same-origin",headers:s,body:t});if(!r.ok&&!n&&i===this.sessionGen&&this.active)this.failUpload(`Voice upload failed (${r.status}).`)}catch{if(!n&&i===this.sessionGen&&this.active)this.failUpload("Voice upload failed.")}})}failUpload(e){this.abortedGen=Math.max(this.abortedGen,this.sessionGen),this.sessionGen++,this.active=!1,this.starting=!1,this.sessionKey="",this.pendingPcm=[],this.cleanupAudio(),this.cb.setRecording(!1),this.cb.setLevel(0),this.cb.showError(e)}cleanupAudio(){if(this.processor)this.processor.disconnect(),this.processor.onaudioprocess=null,this.processor=null;if(this.audioCtx)this.audioCtx.close().catch(()=>{}),this.audioCtx=null;Ct(this.stream),this.stream=null}}var Hi=[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],Di=[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],Fi=[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],$i=[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],Os=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];function kt(e,t){let n=new Int32Array(16),i=0;for(let o=0;o0){if(n[c]++,c>i)i=c}}let s=new Int32Array(16),r=0;for(let o=1;o<=15;o++)s[o]=r,r+=n[o];let a=new Int32Array(r);for(let o=0;o0)a[s[c]++]=o}return{counts:n,symbols:a,maxBits:i}}var Vs=(()=>{let e=new Uint8Array(288);return e.fill(8,0,144),e.fill(9,144,256),e.fill(7,256,280),e.fill(8,280,288),kt(e,288)})(),Us=(()=>{let e=new Uint8Array(32);return e.fill(5),kt(e,32)})();class fn{win=new Uint8Array(32768);winPos=0;feed(e,t=16777216){let n=0,i=0,s=0,r=(p)=>{while(s=e.length)throw Error("truncated deflate frame");i|=e[n++]<>>=p,s-=p,d},a=(p)=>{let d=0,g=0,y=0;for(let m=1;m<=p.maxBits;m++){d|=r(1);let h=p.counts[m];if(d-h{let d=c+p;if(d>t)throw Error("inflated frame exceeds limit");if(d<=o.length)return;let g=o.length;while(g{u(1),o[c++]=p,this.win[this.winPos]=p,this.winPos=this.winPos+1&32767};while(n0){if(n>=e.length&&s<3)break;let p=r(1),d=r(2);if(d===0){if(i=0,s=0,n+4>e.length)throw Error("truncated stored block");let g=e[n]|e[n+1]<<8,y=e[n+2]|e[n+3]<<8;if(n+=4,(g^65535)!==y)throw Error("invalid stored block length");if(n+g>e.length)throw Error("truncated stored payload");u(g);for(let m=0;m=e.length)break}else if(d===1||d===2){let g=Vs,y=Us;if(d===2){let m=r(5)+257,h=r(5)+1,f=r(4)+4,w=new Uint8Array(19);for(let T=0;TA)throw Error("code length overflow");for(let O=0;OA)throw Error("code length overflow");S+=B}else if(T===18){let B=r(7)+11;if(S+B>A)throw Error("code length overflow");S+=B}else throw Error("invalid code length symbol")}g=kt(M,m),y=kt(M.subarray(m),h)}while(!0){let m=a(g);if(m<256)l(m);else if(m===256)break;else{let h=m-257;if(h>=Hi.length)throw Error("invalid length symbol");let f=Hi[h]+(Di[h]?r(Di[h]):0),w=a(y);if(w>=Fi.length)throw Error("invalid distance symbol");let C=Fi[w]+($i[w]?r($i[w]):0);u(f);let A=this.winPos-C&32767;for(let M=0;M{this.stateListeners.delete(e)}}onFrame(e){return this.frameListeners.add(e),()=>{this.frameListeners.delete(e)}}onBinary(e){return this.binaryListeners.add(e),()=>{this.binaryListeners.delete(e)}}rpc(e,t={},n=20000){return new Promise((i,s)=>{if(!this.ws||this.ws.readyState!==WebSocket.OPEN){s(Error("Not connected to hub"));return}let r=this.nextId++,a=window.setTimeout(()=>{this.pending.delete(r),s(Error(`RPC timeout: ${e}`))},n);this.pending.set(r,{resolve:i,reject:s,timer:a}),this.ws.send(JSON.stringify({id:r,m:e,p:t}))})}setState(e){this.state=e;for(let t of this.stateListeners)t(e,this.hello)}rejectAllPending(e){for(let[,t]of this.pending)window.clearTimeout(t.timer),t.reject(Error(e));this.pending.clear()}openSocket(){if(this.closed)return;this.inflater=null;let t=`${window.location.protocol==="https:"?"wss:":"ws:"}//${window.location.host}/ws?data=1&enc=json&z=deflate`,n=new WebSocket(t);n.binaryType="arraybuffer",this.ws=n;let i=(s)=>{let r;try{r=JSON.parse(s)}catch{return}if(r.t==="hub.restarting")this.restarting={reason:String(r.reason??""),build:String(r.build??""),text:String(r.text??""),at:Date.now()};if(r.t==="hello")this.restarting=null,this.hello=r,this.features=new Set(this.hello.features??[]),this.inflater=this.hello.z==="deflate"?new fn:null,this.reconnectDelay=500,this.setState("connected");else if(r.t==="reply"&&typeof r.id==="number"){let a=this.pending.get(r.id);if(a)if(this.pending.delete(r.id),window.clearTimeout(a.timer),r.ok)a.resolve(r.result??{});else{let o=r.error,c=typeof o==="string"?o:o&&typeof o==="object"&&("message"in o)?String(o.message):"Request failed";a.reject(Error(c))}return}for(let a of this.frameListeners)a(r)};n.addEventListener("message",(s)=>{if(s.data instanceof ArrayBuffer){if(this.inflater){let r;try{r=this.inflater.feed(new Uint8Array(s.data))}catch{n.close();return}if(r.length>0&&r[0]===123)i(this.textDecoder.decode(r));else{let a=r.buffer.slice(r.byteOffset,r.byteOffset+r.byteLength);for(let o of this.binaryListeners)o(a)}return}for(let r of this.binaryListeners)r(s.data);return}if(typeof s.data!=="string")return;i(s.data)}),n.addEventListener("close",(s)=>{if(this.ws===n)this.ws=null;if(this.rejectAllPending("Connection closed"),this.closed)return;if(s.code===4001||s.code===4401||s.code===1008){this.handleRevoked();return}this.probeSessionOrReconnect()}),n.addEventListener("error",()=>{})}async probeSessionOrReconnect(){try{let t=await fetch("/",{method:"GET",credentials:"same-origin",cache:"no-store"});if(t.status===401||t.status===403){this.handleRevoked();return}if(t.ok){if((await t.text()).includes('id="pair-root"')){this.handleRevoked();return}}}catch{}this.setState("reconnecting");let e=this.reconnectDelay;this.reconnectDelay=Math.min(8000,Math.round(this.reconnectDelay*1.6)),this.reconnectTimer=window.setTimeout(()=>{this.reconnectTimer=null,this.openSocket()},e)}handleRevoked(){this.closed=!0,this.setState("revoked"),window.location.replace("/")}}var Ws=new TextDecoder;function Gi(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 Oi(e){let t=0,n=0;function i(a){if(a<=23)return a;if(a===24){if(t>=e.length)return null;return e[t++]}if(a===25){if(t+2>e.length)return null;let o=e[t]<<8|e[t+1];return t+=2,o}if(a===26){if(t+4>e.length)return null;let o=(e[t]<<24|e[t+1]<<16|e[t+2]<<8|e[t+3])>>>0;return t+=4,o}return null}function s(a){if(n++,a>32||n>400000||t>=e.length)return null;let o=e[t++],c=o>>5,u=i(o&31);if(u===null)return null;switch(c){case 0:return u;case 1:return-1-u;case 2:{if(t+u>e.length)return null;let l=e.subarray(t,t+u);return t+=u,l}case 3:{if(t+u>e.length)return null;let l=Ws.decode(e.subarray(t,t+u));return t+=u,l}case 4:{if(u>e.length)return null;let l=Array(u);for(let p=0;p=this.b.length)return this.ok=!1,0;let n=this.b[this.i++],i=7*t;if(i>=28&&(n&240)!==0)return this.ok=!1,0;if(e=(e|(n&127)<>>0,n<128)return e}return this.ok=!1,0}nextI32(){let e=this.nextU32();return e>>>1^-(e&1)}}function Ui(e){let t=0xcbf29ce484222325n,n=0x100000001b3n,i=0xffffffffffffffffn;for(let s=0;stypeof e[m]==="number"?e[m]:h,n=t("l",0),i=t("c",0),s=t("a",255)/255,r=t("m",1),a=t("w",0),o=a/2,c=r===0&&a!==0,u=e.d instanceof Uint8Array?e.d:new Uint8Array(0),l=new Vi(u),p=[],d=[],g=0,y=0;while(l.more()){let m=l.nextU32(),h=p.length,f=1/0,w=1/0,C=-1/0,A=-1/0;if(r===2)g=g+l.nextI32()|0,y=y+l.nextI32()|0,p.push(g,y),f=C=g,w=A=y;else{let S=Math.min(l.nextU32(),1048576);for(let T=0;TC)C=g;if(yA)A=y}}let M=(p.length-h)/2;if(M>0){let S=r===2||M===1?2:r===0?0:1,T=r===0?0:o;d.push({info:m,x0:f-T,y0:w-T,x1:C+T,y1:A+T,at:h,n:M,kind:S})}}return{layer:n,color:i,alpha:s,mode:r,r:o,own:c,pts:new Float32Array(p),pieces:d}}function Wi(e,t,n){let i=(a)=>Array.isArray(a)&&a.length>=4?[Number(a[0])||0,Number(a[1])||0,Number(a[2])||0,Number(a[3])||0]:[0,0,0,0],s=Array.isArray(e.cs)?e.cs:[],r=[];for(let a=0;a=0&&o0){n.delete(o.h),n.set(o.h,c);while(n.size>1024){let u=n.keys().next().value;if(u!==void 0)n.delete(u);else break}}}}return{key:typeof e.key==="string"?e.key:"",fam:typeof e.fam==="string"?e.fam:"",base:typeof e.base==="string"?e.base:"",box:i(e.box),edge:i(e.edge),thick:typeof e.thick==="number"?e.thick:1600,note:typeof e.note==="string"?e.note:"",warn:typeof e.warn==="number"?e.warn!==0:!1,chunks:r}}function _i(e,t,n,i=!0){if(n.width<=0||n.height<=0||n.naturalWidth<=0||n.naturalHeight<=0)return null;let s=Math.min(n.width/n.naturalWidth,n.height/n.naturalHeight),r=n.naturalWidth*s,a=n.naturalHeight*s,o=n.left+(n.width-r)/2,c=i?n.top:n.top+(n.height-a)/2,u=(e-o)/r,l=(t-c)/a;if(u<0||u>1||l<0||l>1)return null;return{x:Math.max(0,Math.min(1000,Math.round(u*1000))),y:Math.max(0,Math.min(1000,Math.round(l*1000)))}}var qi=[["Enter","Enter"],["Tab","Tab"],["Bksp","Backspace"],["Esc","Escape"],["↑","ArrowUp"],["↓","ArrowDown"],["←","ArrowLeft"],["→","ArrowRight"]];function Ki(e){let t=e.trim();if(!t)return"";if(/^[a-zA-Z][a-zA-Z0-9+.-]*:/.test(t))return t;return`https://${t}`}class yn{tail=Promise.resolve();enqueue(e){let t=this.tail.then(e,e);return this.tail=t.catch(()=>{}),t}}function zi(e,t,n){let i=!0,s=!1,r=!1,a="",o=!1,c=!1,u=-1,l=null,p=new yn,d=document.createElement("div");d.className="bp-pane bp-browser-pane",d.setAttribute("data-testid","pane-browser");let g=document.createElement("div");g.className="bp-pane-bar bp-browser-nav";function y(X,ce,E){let k=document.createElement("button");if(k.type="button",k.className="bp-v-btn",k.textContent=X,k.setAttribute("data-testid",ce),E)k.title=E;return k}let m=y("←","browser-back","Back"),h=y("→","browser-forward","Forward"),f=y("↻","browser-reload","Reload"),w=document.createElement("form");w.className="bp-browser-url-form";let C=document.createElement("input");C.type="text",C.className="bp-browser-input",C.placeholder="https://…",C.autocomplete="off",C.spellcheck=!1,C.setAttribute("data-testid","browser-url");let A=y("Go","browser-go","Navigate");A.type="submit",w.append(C,A);let M=y("Take over","browser-takeover");M.classList.add("is-primary"),g.append(m,h,f,w,M);let S=document.createElement("div");S.className="bp-browser-drive-bar",S.hidden=!0;let T=document.createElement("div");T.className="bp-browser-keys-row";let B=document.createElement("input");B.type="text",B.className="bp-browser-input",B.placeholder="Type text or press Enter/Tab/Arrows…",B.autocomplete="off",B.spellcheck=!1,B.setAttribute("data-testid","browser-keys");let R=y("Send","browser-type-send");T.append(B,R);let O=document.createElement("div");O.className="bp-browser-quick-keys";for(let[X,ce]of qi){let E=y(X,`browser-key-${ce}`);E.addEventListener("click",()=>he("press",{key:ce})),O.append(E)}S.append(T,O);let H=document.createElement("div");H.className="bp-browser-err",H.setAttribute("data-testid","browser-error"),H.hidden=!0;let ae=document.createElement("div");ae.className="bp-browser-stage",ae.setAttribute("data-testid","browser-stage");let ue=document.createElement("img");ue.className="bp-browser-img",ue.alt="Hub browser screen",ue.draggable=!1,ue.hidden=!0,ue.setAttribute("data-testid","browser-frame");let oe=document.createElement("div");oe.className="bp-pane-empty",oe.setAttribute("data-testid","browser-empty"),oe.textContent="Loading browser screen…",ae.append(ue,oe);let we=document.createElement("div");we.className="bp-browser-hint",we.textContent="You have the page: click to tap, scroll to wheel, type in the key box. Hand it back when done.",we.hidden=!0,d.append(g,S,H,ae,we),e.replaceChildren(d);function Le(X){H.textContent=X,H.hidden=!X}function Ne(){S.hidden=!s,we.hidden=!s,M.textContent=s?"Hand back":"Take over",M.setAttribute("data-testid",s?"browser-handback":"browser-takeover"),M.classList.toggle("is-on",s),ue.classList.toggle("is-driving",s)}function he(X,ce={},E){p.enqueue(async()=>{if(!i)return;Le("");try{if(await t.hub.rpc("browser",{thread:n,op:X,...ce}),!i)return;E?.(),le()}catch(k){if(!i)return;Le(k instanceof Error?k.message:String(k))}})}function be(X){he("toolbar",{command:X},()=>{s=!0,Ne()})}m.addEventListener("click",()=>be("back")),h.addEventListener("click",()=>be("forward")),f.addEventListener("click",()=>be("reload")),w.addEventListener("submit",(X)=>{X.preventDefault();let ce=Ki(C.value);if(!ce)return;if(C.value=ce,!s)he("takeover",{},()=>{s=!0,Ne()});he("navigate",{url:ce},()=>{s=!0,Ne()})}),M.addEventListener("click",()=>{if(s)he("handback",{},()=>{s=!1,Ne()});else he("takeover",{},()=>{s=!0,Ne(),B.focus()})});function I(){let X=B.value;if(!X)return;B.value="",he("type",{text:X})}R.addEventListener("click",I),B.addEventListener("keydown",(X)=>{if(!s)return;if(X.key==="Enter"){if(X.preventDefault(),B.value)I();he("press",{key:"Enter"});return}if(X.key==="Tab"||X.key==="Escape"||X.key==="ArrowUp"||X.key==="ArrowDown"||X.key==="ArrowLeft"||X.key==="ArrowRight"||X.key==="Backspace"&&B.value==="")X.preventDefault(),he("press",{key:X.key})}),ue.addEventListener("click",(X)=>{if(!s||!r)return;let ce=ue.getBoundingClientRect(),E=_i(X.clientX,X.clientY,{left:ce.left,top:ce.top,width:ce.width,height:ce.height,naturalWidth:ue.naturalWidth,naturalHeight:ue.naturalHeight});if(!E)return;he("click",E)}),ue.addEventListener("wheel",(X)=>{if(!s||!r)return;X.preventDefault();let ce=Math.round(X.deltaX),E=Math.round(X.deltaY);if(ce===0&&E===0)return;he("scroll",{dx:ce,dy:E})},{passive:!1});async function le(){if(!i)return;if(o){c=!0;return}o=!0;try{do{c=!1,l=new AbortController;let X=await fetch(`/bots/${encodeURIComponent(n)}/screen.jpg`,{credentials:"same-origin",cache:"no-store",signal:l.signal});if(!i)return;if(X.ok){let ce=await X.blob();if(!i)return;let E=URL.createObjectURL(ce),k=a;if(a=E,ue.src=E,ue.hidden=!1,oe.hidden=!0,r=!0,k)URL.revokeObjectURL(k)}else if(!r)ue.hidden=!0,oe.hidden=!1,oe.textContent="No browser page yet. An agent opens one when it needs the web."}while(i&&c)}catch{if(!i)return;if(!r)ue.hidden=!0,oe.hidden=!1,oe.textContent="No browser page yet. An agent opens one when it needs the web."}finally{l=null,o=!1}}let ne=t.hub.onFrame((X)=>{if(!i)return;if(X.t==="shot"&&X.bot===n){if(typeof X.n==="number"){if(X.n===u)return;u=X.n}le()}});return le(),{destroy(){if(i=!1,ne(),l?.abort(),a)URL.revokeObjectURL(a),a=""}}}function _(e,t,n){let i=document.createElement(e);if(t)i.className=t;if(n!==void 0)i.textContent=n;return i}function Ot(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 Yi(e){let t=e.lastIndexOf(".");return t>=0?e.slice(t+1).toLowerCase():""}function qs(e){return["png","jpg","jpeg","gif","webp","svg","bmp","ico"].includes(e)}function Ji(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 Ks(e){let t=Yi(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 Xi(e,t,n,i){let s=!0,r="",a="",o=_("div","bp-pane bp-files-pane");o.setAttribute("data-testid","pane-files");let c=_("div","bp-pane-bar"),u=_("div","bp-files-crumbs"),l=_("button","bp-v-btn","Refresh");l.type="button",l.addEventListener("click",()=>void h(r)),c.append(u,l);let p=_("div","bp-files-split"),d=_("div","bp-files-list");d.setAttribute("data-testid","files-list");let g=_("div","bp-files-preview");g.setAttribute("data-testid","files-preview"),g.append(_("div","bp-pane-empty","Select a file to preview")),p.append(d,g),o.append(c,p),e.replaceChildren(o);function y(){u.replaceChildren();let f=_("button","bp-crumb-btn","project");if(f.type="button",f.addEventListener("click",()=>void h("")),u.append(f),!r)return;let w=r.split("/").filter(Boolean),C="";for(let A of w){C=C?`${C}/${A}`:A;let M=C;u.append(_("span","bp-vh-sep","/"));let S=_("button","bp-crumb-btn",A);S.type="button",S.addEventListener("click",()=>void h(M)),u.append(S)}}async function m(f,w,C){a=f,g.replaceChildren();let A=_("div","bp-files-prev-head");A.append(_("span","bp-files-prev-name",f));let M=_("div","bp-files-prev-acts"),S=Ks(w);if(S){let O=_("button","bp-v-btn is-primary",`Open in ${S}`);O.type="button",O.setAttribute("data-testid","files-open-viewer"),O.addEventListener("click",()=>i(S,f)),M.append(O)}let T=`/files/get?thread=${encodeURIComponent(n)}&path=${encodeURIComponent(f)}`,B=_("a","bp-v-btn","Download");B.href=T,B.download=w,M.append(B),A.append(M),g.append(A);let R=Yi(w);if(qs(R)){let O=_("div","bp-files-img-wrap"),H=document.createElement("img");H.className="bp-files-img",H.alt=w,H.src=T,O.append(H),g.append(O);return}if(C>524288&&!Ji(R)){g.append(_("div","bp-pane-empty",`Binary file (${Ot(C)}). Use Download to save.`));return}if(Ji(R)||C<=65536){let O=_("div","bp-pane-empty","Loading…");g.append(O);try{let H=await fetch(T,{credentials:"same-origin"});if(!s||a!==f)return;if(!H.ok){O.textContent=`Could not load file (${H.status})`;return}if((H.headers.get("content-type")||"").startsWith("image/")){O.remove();let ne=document.createElement("img");ne.className="bp-files-img",ne.alt=w,ne.src=T,g.append(ne);return}let ue=262144,oe=[],we=0,Le=!1;if(H.body){let ne=H.body.getReader();try{while(!0){let{done:X,value:ce}=await ne.read();if(X||!ce)break;if(we+ce.byteLength>ue){let E=ue-we;if(E>0)oe.push(ce.subarray(0,E)),we+=E;Le=!0,await ne.cancel();break}oe.push(ce),we+=ce.byteLength}}finally{ne.releaseLock()}}if(!s||a!==f)return;let Ne=new Uint8Array(we),he=0;for(let ne of oe)Ne.set(ne,he),he+=ne.byteLength;let be=!1;for(let ne=0;neA.dir===M.dir?A.name.localeCompare(M.name):A.dir?-1:1),d.replaceChildren(),f){let A=_("button","bp-file-row is-dir");A.type="button",A.append(_("span","bp-file-icon","↰"),_("span","bp-file-name",".."));let M=f.includes("/")?f.slice(0,f.lastIndexOf("/")):"";A.addEventListener("click",()=>void h(M)),d.append(A)}if(C.length===0){d.append(_("div","bp-pane-empty","Empty folder"));return}for(let A of C){let M=f?`${f}/${A.name}`:A.name,S=_("button","bp-file-row"+(A.dir?" is-dir":"")+(M===a?" is-sel":""));S.type="button",S.setAttribute("data-testid",`file-row-${A.name}`),S.append(_("span","bp-file-icon",A.dir?"▸":"·"),_("span","bp-file-name",A.name),_("span","bp-file-size",A.dir?"":Ot(A.size))),S.addEventListener("click",()=>{if(A.dir)h(M);else d.querySelectorAll(".bp-file-row.is-sel").forEach((T)=>T.classList.remove("is-sel")),S.classList.add("is-sel"),m(M,A.name,A.size)}),d.append(S)}}catch(w){if(!s)return;d.replaceChildren(_("div","bp-pane-empty",w instanceof Error?w.message:String(w)))}}return h(""),{destroy(){s=!1}}}function Zi(e,t,n){let i=!0,s=_("div","bp-pane bp-diff-pane");s.setAttribute("data-testid","pane-diff");let r=_("div","bp-pane-bar"),a=_("span","bp-diff-summary","Loading diff…"),o=_("button","bp-v-btn","Refresh");o.type="button",o.addEventListener("click",()=>void u()),r.append(a,o);let c=_("div","bp-diff-body");c.setAttribute("data-testid","diff-body"),s.append(r,c),e.replaceChildren(s);async function u(){a.textContent="Loading diff…",c.replaceChildren();try{let l=await t.hub.rpc("viewer.diff",{thread:n});if(!i)return;if(l?.nogit){a.textContent="Not a git repository",c.append(_("div","bp-pane-empty","This project is not a git repository."));return}let p=typeof l?.diff==="string"?l.diff:"";if(!p.trim()){a.textContent="Clean working tree",c.append(_("div","bp-pane-empty","No uncommitted changes."));return}let d=p.split(` +`),g=0,y=0,m=0,h=document.createDocumentFragment(),f=_("div","bp-diff-file");for(let w of d){if(w.startsWith("diff --git ")){if(f.childNodes.length>0)h.append(f);f=_("div","bp-diff-file"),g++;let C=w.match(/ b\/(.+)$/);f.append(_("div","bp-diff-file-head",C?C[1]:w));continue}if(w.startsWith("index ")||w.startsWith("--- ")||w.startsWith("+++ "))f.append(_("div","bp-diff-line is-meta",w));else if(w.startsWith("@@"))f.append(_("div","bp-diff-line is-hunk",w));else if(w.startsWith("+"))y++,f.append(_("div","bp-diff-line is-add",w));else if(w.startsWith("-"))m++,f.append(_("div","bp-diff-line is-del",w));else f.append(_("div","bp-diff-line",w))}if(f.childNodes.length>0)h.append(f);a.textContent=`${g||1} file${g===1?"":"s"} · +${y} -${m}`,c.append(h)}catch(l){if(!i)return;a.textContent="Diff unavailable",c.append(_("div","bp-pane-empty",l instanceof Error?l.message:String(l)))}}return u(),{destroy(){i=!1}}}function Qi(e,t,n){let i=!0,s="checks",r=_("div","bp-pane bp-review-pane");r.setAttribute("data-testid","pane-review");let a=_("div","bp-pane-bar"),o=_("div","bp-review-tabs"),c=_("button","bp-v-btn is-on","Checks"),u=_("button","bp-v-btn","BOM"),l=_("button","bp-v-btn","Comments");c.type=u.type=l.type="button",o.append(c,u,l);let p=_("button","bp-v-btn","Refresh");p.type="button",p.addEventListener("click",()=>void m()),a.append(o,p);let d=_("div","bp-review-body");d.setAttribute("data-testid","review-body"),r.append(a,d),e.replaceChildren(r);function g(h){s=h,c.classList.toggle("is-on",s==="checks"),u.classList.toggle("is-on",s==="bom"),l.classList.toggle("is-on",s==="comments"),m()}c.addEventListener("click",()=>g("checks")),u.addEventListener("click",()=>g("bom")),l.addEventListener("click",()=>g("comments"));function y(h){let f=_("div","bp-review-md"),w=h.split(` +`),C=0;while(C{T.preventDefault();let B=M.value.trim();if(!B)return;S.disabled=!0,t.hub.rpc("review.comment",{thread:n,text:B}).then(()=>{M.value="",S.disabled=!1,m()},()=>{S.disabled=!1})}),d.append(A),C.length===0){d.append(_("div","bp-pane-empty","No review comments yet."));return}for(let T of C){let B=_("div","bp-review-comment"+(T.resolved?" is-resolved":"")),R=[T.by||"review",T.file,T.layer,T.item].filter(Boolean).join(" · ");B.append(_("div","bp-review-comment-meta",R),_("div","bp-review-comment-text",T.text)),d.append(B)}return}let h=await t.hub.rpc("review.page",{thread:n,page:s});if(!i)return;let f=h?.report||{};if(d.replaceChildren(),f.line||f.gate){let w=_("div","bp-review-gate",[f.gate,f.line].filter(Boolean).join(" · "));d.append(w)}if(f.err)d.append(_("div","bp-review-err",f.err));if(Array.isArray(f.tasks)&&f.tasks.length>0){let w=_("div","bp-review-tasks");f.tasks.forEach((C,A)=>{let M=_("label","bp-review-task"),S=document.createElement("input");S.type="checkbox",S.checked=!!(C.done??C.checked);let T=typeof C.index==="number"?C.index:A;S.addEventListener("change",()=>{t.hub.rpc("review.tick",{thread:n,index:T}).then(()=>void m(),()=>{})}),M.append(S,_("span",void 0,C.text||C.label||`Item ${A+1}`)),w.append(M)}),d.append(w)}if(f.md&&f.md.trim())d.append(y(f.md));else if(!f.err&&(!f.tasks||f.tasks.length===0))d.append(_("div","bp-pane-empty",`No ${s==="bom"?"BOM":"design checks"} report available.`))}catch(h){if(!i)return;d.replaceChildren(_("div","bp-pane-empty",h instanceof Error?h.message:String(h)))}}return m(),{destroy(){i=!1}}}function es(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 wn{canvas;ctx;frame=null;masks={off:0,dim:0,lift:255};highlights=new Set;lightTheme=!1;cx=0;cy=0;scale=0.0001;fittedKey="";fitW=0;fitH=0;userMoved=!1;dirty=!1;rafId=0;pointers=new Map;dragStart=null;pinchStart=null;resizeObs;cbs;constructor(e,t={}){this.cbs=t,this.canvas=document.createElement("canvas"),this.canvas.className="bp-viewer-canvas",this.canvas.style.width="100%",this.canvas.style.height="100%",this.canvas.style.display="block",this.canvas.style.touchAction="none",e.appendChild(this.canvas);let n=this.canvas.getContext("2d");if(!n)throw Error("Canvas2D unavailable");this.ctx=n,this.resizeObs=new ResizeObserver(()=>this.scheduleDraw()),this.resizeObs.observe(this.canvas),this.canvas.addEventListener("pointerdown",this.onPointerDown),this.canvas.addEventListener("pointermove",this.onPointerMove),this.canvas.addEventListener("pointerup",this.onPointerUp),this.canvas.addEventListener("pointercancel",this.onPointerUp),this.canvas.addEventListener("wheel",this.onWheel,{passive:!1}),this.canvas.addEventListener("dblclick",this.onDblClick)}setTheme(e){if(this.lightTheme!==e)this.lightTheme=e,this.scheduleDraw()}setFrame(e){if(this.frame=e,e&&e.key!==this.fittedKey)this.fittedKey=e.key,this.fit();else this.scheduleDraw()}setLayers(e){this.masks=e,this.scheduleDraw()}setHighlights(e){this.highlights.clear();for(let[t,n]of e)this.highlights.add(`${t}:${n}`);this.scheduleDraw()}presentMask(){if(!this.frame)return 0;let e=0;for(let t of this.frame.chunks)if(t.layer<32)e=(e|1<>>0;return e>>>0}presentColors(){let e=new Map;if(!this.frame)return e;for(let t of this.frame.chunks)if(!e.has(t.layer))e.set(t.layer,t.color);return e}applyFit(e,t){if(!this.frame||e<10||t<10)return;let n=this.frame.box,i=Math.max(n[2]-n[0],1000),s=Math.max(n[3]-n[1],1000);this.cx=(n[0]+n[2])*0.5,this.cy=(n[1]+n[3])*0.5,this.scale=Math.min(e/i,t/s)*0.92,this.fitW=e,this.fitH=t,this.userMoved=!1}fit(){if(!this.frame)return;this.userMoved=!1,this.fitW=0,this.fitH=0;let e=this.canvas.getBoundingClientRect();if(e.width>=10&&e.height>=10)this.applyFit(e.width,e.height);this.scheduleDraw()}zoomToBoxMm(e){let t=e[0]*1000,n=e[1]*1000,i=e[2]*1000,s=e[3]*1000,r=Math.max(i-t,1000),a=Math.max(s-n,1000),o=this.canvas.getBoundingClientRect(),c=Math.max(o.width,200),u=Math.max(o.height,200);this.cx=(t+i)*0.5,this.cy=(n+s)*0.5,this.scale=Math.min(c/r,u/a)*0.85,this.userMoved=!0,this.scheduleDraw()}scheduleDraw(){if(this.dirty)return;this.dirty=!0,this.rafId=requestAnimationFrame(()=>{this.dirty=!1,this.rafId=0,this.draw()})}draw(){let e=this.canvas.getBoundingClientRect(),t=Math.max(1,Math.round(e.width)),n=Math.max(1,Math.round(e.height)),i=Math.min(window.devicePixelRatio||1,2),s=Math.round(t*i),r=Math.round(n*i);if(this.canvas.width!==s||this.canvas.height!==r)this.canvas.width=s,this.canvas.height=r;let a=this.ctx;a.setTransform(i,0,0,i,0,0),a.fillStyle=this.lightTheme?"#f5f4ef":"#08090b",a.fillRect(0,0,t,n);let o=this.frame;if(!o)return;if(!this.userMoved&&t>=10&&n>=10&&(Math.abs(this.fitW-t)>2||Math.abs(this.fitH-n)>2))this.applyFit(t,n);let c=t*0.5,u=n*0.5,l=this.scale,p=this.cx,d=this.cy,g=p-c/l,y=p+c/l,m=d-u/l,h=d+u/l,{off:f,dim:w,lift:C}=this.masks,A=[],M=[];for(let T=0;T>>B&1)===1)continue;if(B===C)M.push(T);else A.push(T)}let S=A.concat(M);a.lineCap="round",a.lineJoin="round";for(let T=0;T>>R.layer&1)===1,H=R.alpha*(O?0.25:1);if(H<=0.01)continue;this.drawChunk(a,R,H,g,m,y,h,p,d,l,c,u)}if(this.highlights.size>0){a.fillStyle=this.lightTheme?"rgba(245,244,239,0.72)":"rgba(8,9,11,0.72)",a.fillRect(0,0,t,n);let T=this.lightTheme?"rgba(27,29,33,0.77)":"rgba(217,221,228,0.77)";for(let B=0;Br||h.y1a)continue;if(h.n<3)continue;let f=(d[h.at]-o)*u+l,w=(d[h.at+1]-c)*u+p;e.moveTo(f,w);for(let C=1;C0)e.fill()}else if(t.mode===2){let y=Math.max(0.75,t.r*u);e.fillStyle=g,e.beginPath();let m=0;for(let h=0;hr||f.y1a)continue;let w=(d[f.at]-o)*u+l,C=(d[f.at+1]-c)*u+p;e.moveTo(w+y,C),e.arc(w,C,y,0,Math.PI*2),m++}if(m>0)e.fill()}else{e.strokeStyle=g,e.lineWidth=Math.max(1,t.r*2*u),e.beginPath();let y=0;for(let m=0;mr||h.y1a)continue;let f=(d[h.at]-o)*u+l,w=(d[h.at+1]-c)*u+p;if(h.n===1)e.moveTo(f,w),e.lineTo(f+0.01,w);else{e.moveTo(f,w);for(let C=1;C0)e.stroke()}}drawLitPieces(e,t,n,i,s,r,a,o,c,u,l,p,d){let g=t.pts,y=es(t.color,t.alpha);for(let m=0;ma||h.y1o)continue;let f=(g[h.at]-c)*l+p,w=(g[h.at+1]-u)*l+d;if(h.kind===2){let C=Math.max(1.5,t.r*l);e.fillStyle=y,e.beginPath(),e.arc(f,w,C,0,Math.PI*2),e.fill(),e.strokeStyle=i,e.lineWidth=1.5,e.stroke()}else if(h.kind===0&&h.n>=3){e.fillStyle=y,e.beginPath(),e.moveTo(f,w);for(let C=1;C=0;l--){let p=n.chunks[l];if(p.layer<32&&(u>>>p.layer&1)===1)continue;for(let d=0;dg.x1+a||rg.y1+a)continue;let y=(g.x1-g.x0+1)*(g.y1-g.y0+1);if(y{if(this.canvas.setPointerCapture(e.pointerId),this.pointers.set(e.pointerId,{x:e.clientX,y:e.clientY}),this.pointers.size===1)this.dragStart={x:e.clientX,y:e.clientY,cx:this.cx,cy:this.cy,moved:!1},this.pinchStart=null;else if(this.pointers.size===2){let[t,n]=Array.from(this.pointers.values());this.pinchStart={dist:Math.hypot(n.x-t.x,n.y-t.y)||1,midX:(t.x+n.x)*0.5,midY:(t.y+n.y)*0.5,scale:this.scale,cx:this.cx,cy:this.cy},this.dragStart=null}};onPointerMove=(e)=>{if(!this.pointers.has(e.pointerId))return;if(this.pointers.set(e.pointerId,{x:e.clientX,y:e.clientY}),this.pointers.size===2&&this.pinchStart){let[t,n]=Array.from(this.pointers.values()),i=Math.hypot(n.x-t.x,n.y-t.y)||1,s=(t.x+n.x)*0.5,r=(t.y+n.y)*0.5,a=i/this.pinchStart.dist,o=Math.max(0.0000001,Math.min(2,this.pinchStart.scale*a)),c=this.canvas.getBoundingClientRect(),u=this.pinchStart.midX-c.left-c.width*0.5,l=this.pinchStart.midY-c.top-c.height*0.5,p=s-c.left-c.width*0.5,d=r-c.top-c.height*0.5;this.scale=o,this.cx=this.pinchStart.cx+u/this.pinchStart.scale-p/o,this.cy=this.pinchStart.cy+l/this.pinchStart.scale-d/o,this.userMoved=!0,this.cbs.onUserMove?.(),this.scheduleDraw();return}if(this.dragStart&&this.pointers.size===1){let t=e.clientX-this.dragStart.x,n=e.clientY-this.dragStart.y;if(Math.hypot(t,n)>3)this.dragStart.moved=!0;if(this.dragStart.moved)this.cx=this.dragStart.cx-t/this.scale,this.cy=this.dragStart.cy-n/this.scale,this.userMoved=!0,this.cbs.onUserMove?.(),this.scheduleDraw()}};onPointerUp=(e)=>{let t=this.dragStart&&!this.dragStart.moved&&this.pointers.size===1;if(this.pointers.delete(e.pointerId),this.pointers.size<2)this.pinchStart=null;if(this.pointers.size===0)this.dragStart=null;if(t&&this.cbs.onPick){let n=this.canvas.getBoundingClientRect(),i=this.hitTest(e.clientX-n.left,e.clientY-n.top);this.cbs.onPick(i)}};onWheel=(e)=>{e.preventDefault();let t=this.canvas.getBoundingClientRect(),n=e.clientX-t.left-t.width*0.5,i=e.clientY-t.top-t.height*0.5,s=e.deltaY<0?1.16:0.8620689655172414,r=Math.max(0.0000001,Math.min(2,this.scale*s));this.cx+=n/this.scale-n/r,this.cy+=i/this.scale-i/r,this.scale=r,this.userMoved=!0,this.cbs.onUserMove?.(),this.scheduleDraw()};onDblClick=()=>{this.fit()};destroy(){if(this.rafId)cancelAnimationFrame(this.rafId);this.resizeObs.disconnect(),this.canvas.removeEventListener("pointerdown",this.onPointerDown),this.canvas.removeEventListener("pointermove",this.onPointerMove),this.canvas.removeEventListener("pointerup",this.onPointerUp),this.canvas.removeEventListener("pointercancel",this.onPointerUp),this.canvas.removeEventListener("wheel",this.onWheel),this.canvas.removeEventListener("dblclick",this.onDblClick),this.canvas.remove()}}var ts=[{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 ns(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 En(e,t,n,i){if(!e||!t||!n||!i)return!1;if(!e.startsWith(t))return!1;let s=e.slice(t.length).split(` +`),r=(s[0]||"").split("\t");if(r[0]!=="git"||r[2]!==n)return!1;let a=s[1]||r.slice(4).join("\t");if(!a)return!1;let o=a.replace(/\\/g,"/"),c=i.replace(/\\/g,"/");if(c.startsWith("/")||/^[A-Za-z]:\//.test(c))return o===c;return o===c||o.endsWith(`/${c}`)}class xn{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 zs=`#version 300 es precision highp float; out vec2 vUv; void main() { @@ -18,7 +18,7 @@ void main() { vUv = vec2(x * 0.5 + 0.5, 1.0 - (y * 0.5 + 0.5)); gl_Position = vec4(x, y, 0.0, 1.0); } -`,Us=`#version 300 es +`,Js=`#version 300 es precision highp float; in vec2 vUv; uniform vec3 uBgTop; @@ -35,7 +35,7 @@ void main() { vec3 lin = mix(uBgTop, uBgBot, clamp(vUv.y, 0.0, 1.0)); outColor = vec4(linearToSrgb(clamp(lin, 0.0, 1.0)), 1.0); } -`,Ws=`#version 300 es +`,Ys=`#version 300 es precision highp float; layout(location = 0) in vec3 aPos; layout(location = 1) in vec3 aNrm; @@ -53,7 +53,7 @@ void main() { vCol = aCol; gl_Position = uMvp * vec4(aPos, 1.0); } -`,_s=`#version 300 es +`,Xs=`#version 300 es precision highp float; in vec3 vPos; in vec3 vNrm; @@ -149,8 +149,8 @@ void main() { rgb = rgb / (vec3(1.0) + max(rgb - vec3(0.8), vec3(0.0)) * 0.28); outColor = vec4(linearToSrgb(clamp(rgb, 0.0, 1.0)), alpha * uFade); } -`;function Ke(e){let t=e/255;return t<=0.04045?t/12.92:Math.pow((t+0.055)/1.055,2.4)}var qs=[Ke(77),Ke(83),Ke(94)],Ks=[Ke(53),Ke(58),Ke(67)],zs=[Ke(245),Ke(246),Ke(248)],Js=[Ke(225),Ke(228),Ke(233)];function Xi(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 Zi(e,t,n){let i=Xi(e,e.VERTEX_SHADER,t),s=Xi(e,e.FRAGMENT_SHADER,n),a=e.createProgram();if(!a)throw Error("createProgram failed");if(e.attachShader(a,i),e.attachShader(a,s),e.linkProgram(a),e.deleteShader(i),e.deleteShader(s),!e.getProgramParameter(a,e.LINK_STATUS)){let r=e.getProgramInfoLog(a)||"program link error";throw e.deleteProgram(a),Error(r)}return a}function Ys(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 Xs(e,t,n,i){let s=1/Math.tan(e*0.5),a=1/(n-i),r=new Float32Array(16);return r[0]=s/t,r[5]=s,r[10]=(i+n)*a,r[11]=-1,r[14]=2*i*n*a,r}function Qi(e){let t=Math.hypot(e[0],e[1],e[2])||1;return[e[0]/t,e[1]/t,e[2]/t]}function es(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 yn(e,t){return e[0]*t[0]+e[1]*t[1]+e[2]*t[2]}class wn{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=Zi(n,Vs,Us),this.bgVao=n.createVertexArray(),this.uBgTop=n.getUniformLocation(this.bgProg,"uBgTop"),this.uBgBot=n.getUniformLocation(this.bgProg,"uBgBot"),this.prog=Zi(n,Ws,_s),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=Di(e.mesh),this.clearParts(),this.cbs.onStatus?.("Building 3D model…");let n=new Uint8Array(e.mesh),i=e.faces instanceof Uint8Array?new Uint8Array(e.faces):void 0,s=[n.buffer];if(i)s.push(i.buffer);this.worker?.postMessage({id:this.nextJobId++,kind:"solid",key:t,n:e.n,mesh:n,faces:i},s);return}if(e.parts&&typeof e.parts==="object"&&!Array.isArray(e.parts)&&!(e.parts instanceof Uint8Array)){if(this.activeKey&&t!==this.activeKey)return;if(this.activeKey=t,this.clearParts(),this.partsTotal=typeof e.parts.of==="number"?e.parts.of:0,this.partsDone=0,this.partsTotal>0)this.cbs.onStatus?.(`Loading parts 0/${this.partsTotal}…`);this.scheduleDraw();return}if(typeof e.part==="string"&&e.mesh instanceof Uint8Array&&e.at instanceof Uint8Array&&typeof e.n==="number"){if(this.activeKey&&t!==this.activeKey)return;let n=new Uint8Array(e.mesh),i=new Uint8Array(e.at),s=e.faces instanceof Uint8Array?new Uint8Array(e.faces):void 0,a=[n.buffer,i.buffer];if(s)a.push(s.buffer);this.worker?.postMessage({id:this.nextJobId++,kind:"part",key:t,partId:e.part,n:e.n,mesh:n,at:i,faces:s,refs:Array.isArray(e.refs)?e.refs:[],done:typeof e.done==="number"?e.done:0},a)}}onWorkerMessage(e){if(e.error){this.cbs.onStatus?.(e.error);return}if(e.key!==this.activeKey||!this.gl)return;if(e.kind==="solid")this.deleteBatch(this.boardBatch),this.boardBatch=this.uploadBatch(e.positions,e.normals,e.colors,0),this.center=[e.center[0],e.center[1],e.center[2]],this.target=[e.center[0],e.center[1],e.center[2]],this.radius=e.radius,this.fit(),this.cbs.onStatus?.(""),this.scheduleDraw();else if(e.kind==="part"){let t=this.uploadBatch(e.positions,e.normals,e.colors,performance.now());if(t)this.partBatches.push(t);if(this.partsDone=e.done||this.partsDone+1,this.partsTotal>0&&this.partsDone>>24===0)a++;else r++;let o=a>0?new Float32Array(a*9):null,c=a>0?new Float32Array(a*9):null,u=a>0?new Float32Array(a*12):null,l=r>0?new Float32Array(r*9):null,p=r>0?new Float32Array(r*9):null,d=r>0?new Float32Array(r*12):null,g=0,y=0;for(let f=0;f>>24&255,L=1-C/255,M=(w>>>16&255)/255,S=(w>>>8&255)/255,T=(w&255)/255,B=f*9;if(C===0&&o&&c&&u){let R=g*9;for(let D=0;D<9;D++)o[R+D]=e[B+D],c[R+D]=t[B+D];let G=g*12;for(let D=0;D<3;D++)u[G+D*4]=M,u[G+D*4+1]=S,u[G+D*4+2]=T,u[G+D*4+3]=1;g++}else if(l&&p&&d){let R=y*9;for(let D=0;D<9;D++)l[R+D]=e[B+D],p[R+D]=t[B+D];let G=y*12;for(let D=0;D<3;D++)d[G+D*4]=M,d[G+D*4+1]=S,d[G+D*4+2]=T,d[G+D*4+3]=L;y++}}let m=o&&c&&u?this.createSubBatch(o,c,u,a*3):null,h=l&&p&&d?this.createSubBatch(l,p,d,r*3):null;if(!m&&!h)return null;return{opaque:m,translucent:h,fadeStartMs:i}}deleteSubBatch(e){let t=this.gl;if(!t||!e)return;t.deleteVertexArray(e.vao),t.deleteBuffer(e.posBuf),t.deleteBuffer(e.nrmBuf),t.deleteBuffer(e.colBuf)}deleteBatch(e){if(!e)return;this.deleteSubBatch(e.opaque),this.deleteSubBatch(e.translucent)}clearParts(){for(let e of this.partBatches)this.deleteBatch(e);this.partBatches=[]}fit(){this.setView("fit")}setView(e){let t=35*Math.PI/180;this.dist=this.radius/Math.sin(t*0.5)*1.15,this.target=[this.center[0],this.center[1],this.center[2]];let{yaw:n,pitch:i}=Yi(e);this.yaw=n,this.pitch=i,this.scheduleDraw()}snapPng(){return this.draw(performance.now()),new Promise((e)=>{this.canvas.toBlob((t)=>e(t),"image/png")})}scheduleDraw(){if(this.dirty)return;this.dirty=!0,this.rafId=requestAnimationFrame((e)=>{if(this.dirty=!1,this.rafId=0,this.draw(e))this.scheduleDraw()})}drawSubBatch(e){if(!e||!this.gl)return;this.gl.bindVertexArray(e.vao),this.gl.drawArrays(this.gl.TRIANGLES,0,e.vertCount)}draw(e){let t=this.gl;if(!t||!this.prog)return!1;let n=this.canvas.getBoundingClientRect(),i=Math.max(1,Math.round(n.width)),s=Math.max(1,Math.round(n.height)),a=Math.min(window.devicePixelRatio||1,2),r=Math.round(i*a),o=Math.round(s*a);if(this.canvas.width!==r||this.canvas.height!==o)this.canvas.width=r,this.canvas.height=o;if(t.viewport(0,0,r,o),!this.boardBatch&&this.partBatches.length===0)return!1;if(t.depthMask(!0),t.clear(t.DEPTH_BUFFER_BIT),this.bgProg&&this.bgVao){t.disable(t.DEPTH_TEST),t.disable(t.BLEND),t.depthMask(!1),t.useProgram(this.bgProg);let R=this.lightTheme?zs:qs,G=this.lightTheme?Js:Ks;t.uniform3f(this.uBgTop,R[0],R[1],R[2]),t.uniform3f(this.uBgBot,G[0],G[1],G[2]),t.bindVertexArray(this.bgVao),t.drawArrays(t.TRIANGLE_STRIP,0,4),t.bindVertexArray(null)}let c=Math.cos(this.pitch),u=Math.sin(this.pitch),l=Math.cos(this.yaw),p=Math.sin(this.yaw),d=[this.target[0]+this.dist*c*p,this.target[1]-this.dist*c*l,this.target[2]+this.dist*u],g=Qi([this.target[0]-d[0],this.target[1]-d[1],this.target[2]-d[2]]),y=Math.abs(g[2])>0.99?[0,1,0]:[0,0,1],m=Qi(es(g,y)),h=es(m,g),f=new Float32Array([m[0],h[0],-g[0],0,m[1],h[1],-g[1],0,m[2],h[2],-g[2],0,-yn(m,d),-yn(h,d),yn(g,d),1]),w=Math.max(0.05,this.dist*0.01),C=Math.max(this.dist*10,this.radius*20),L=Xs(35*Math.PI/180,r/o,w,C),M=Ys(L,f);t.useProgram(this.prog),t.uniformMatrix4fv(this.uMvp,!1,M),t.uniform3f(this.uEye,d[0],d[1],d[2]),t.uniform3f(this.uRight,m[0],m[1],m[2]),t.uniform3f(this.uUp,h[0],h[1],h[2]),t.uniform3f(this.uFwd,g[0],g[1],g[2]);let S=!1,T=[],B=[];for(let R of this.partBatches){let G=e-R.fadeStartMs,D=R.fadeStartMs===0?1:Math.min(1,Math.max(0,G/300));if(D<1){if(S=!0,D>0)B.push({batch:R,fade:D})}else T.push(R)}if(t.enable(t.DEPTH_TEST),t.depthMask(!0),t.disable(t.BLEND),t.uniform1f(this.uFade,1),this.boardBatch)this.drawSubBatch(this.boardBatch.opaque);for(let R of T)this.drawSubBatch(R.opaque);if(t.depthMask(!1),t.enable(t.BLEND),t.uniform1f(this.uFade,1),this.boardBatch)this.drawSubBatch(this.boardBatch.translucent);for(let R of T)this.drawSubBatch(R.translucent);for(let{batch:R,fade:G}of B)t.uniform1f(this.uFade,G),this.drawSubBatch(R.opaque),this.drawSubBatch(R.translucent);return t.depthMask(!0),t.bindVertexArray(null),S}onPointerDown=(e)=>{if(this.canvas.setPointerCapture(e.pointerId),this.pointers.set(e.pointerId,{x:e.clientX,y:e.clientY,button:e.button,shift:e.shiftKey}),this.pointers.size===2){let[t,n]=Array.from(this.pointers.values());this.pinchDist=Math.hypot(n.x-t.x,n.y-t.y)||1}};onPointerMove=(e)=>{let t=this.pointers.get(e.pointerId);if(!t)return;let n=e.clientX-t.x,i=e.clientY-t.y;if(t.x=e.clientX,t.y=e.clientY,this.pointers.size===2){let[s,a]=Array.from(this.pointers.values()),r=Math.hypot(a.x-s.x,a.y-s.y)||1;if(this.pinchDist>0)this.dist=Math.max(this.radius*0.05,Math.min(this.radius*20,this.dist*(this.pinchDist/r)));this.pinchDist=r,this.cbs.onUserMove?.(),this.scheduleDraw();return}if(t.button===2||t.button===1||t.shift){let s=this.dist*0.0014,a=Math.cos(this.yaw),r=Math.sin(this.yaw);this.target[0]-=n*a*s,this.target[1]-=n*r*s,this.target[2]+=i*s}else this.yaw+=n*0.008,this.pitch=Math.max(-Math.PI*0.49,Math.min(Math.PI*0.49,this.pitch+i*0.008));this.cbs.onUserMove?.(),this.scheduleDraw()};onPointerUp=(e)=>{if(this.pointers.delete(e.pointerId),this.pointers.size<2)this.pinchDist=0};onWheel=(e)=>{e.preventDefault();let t=e.deltaY<0?0.8620689655172414:1.16;this.dist=Math.max(this.radius*0.05,Math.min(this.radius*20,this.dist*t)),this.cbs.onUserMove?.(),this.scheduleDraw()};onDblClick=()=>{this.fit()};onContextMenu=(e)=>{e.preventDefault()};destroy(){if(this.rafId)cancelAnimationFrame(this.rafId);if(this.resizeObs.disconnect(),this.canvas.removeEventListener("pointerdown",this.onPointerDown),this.canvas.removeEventListener("pointermove",this.onPointerMove),this.canvas.removeEventListener("pointerup",this.onPointerUp),this.canvas.removeEventListener("pointercancel",this.onPointerUp),this.canvas.removeEventListener("wheel",this.onWheel),this.canvas.removeEventListener("dblclick",this.onDblClick),this.canvas.removeEventListener("contextmenu",this.onContextMenu),this.deleteBatch(this.boardBatch),this.clearParts(),this.gl){if(this.bgVao)this.gl.deleteVertexArray(this.bgVao);if(this.bgProg)this.gl.deleteProgram(this.bgProg);if(this.prog)this.gl.deleteProgram(this.prog)}this.worker?.terminate(),this.canvas.remove()}}var ts=64,Zs=16777216;function Qs(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 Ct(e){if(!e)return"";let t=e.replace(/\\/g,"/").replace(/\/+$/,""),n=t.lastIndexOf("/");return n>=0?t.slice(n+1):t}function ns(e){switch(e){case"board":return b("viewer.board","Board");case"schematic":return b("viewer.schematic","Schematic");case"3d":return b("viewer.solid","3D");case"gerbers":return b("gpui.gerbers","Gerbers");case"mech":return b("viewer.mech","Mech");case"files":return b("viewer.files","Files");case"diff":return b("viewer.diff","Diff");case"review":return b("viewer.review","Review");case"browser":return b("bots.tab.browser","Browser");case"terminal":return b("viewer.terminal","Terminal");default:return e?e.charAt(0).toUpperCase()+e.slice(1):""}}function En(e){return e==="board"||e==="schematic"||e==="gerbers"}function ea(e){return e==="files"||e==="diff"||e==="review"||e==="browser"||e==="terminal"}function xn(e,t){let n=document.createElement("div");n.className="bp-vh";let i=document.createElement("div");i.className="bp-vh-title";let s=document.createElement("span");s.className="bp-vh-page";let a=document.createElement("span");a.className="bp-vh-sep",a.textContent="·",a.hidden=!0;let r=document.createElement("span");r.className="bp-vh-file",r.hidden=!0,i.append(s,a,r);let o=document.createElement("div");o.className="bp-vh-actions",n.append(i,o);let c=document.createElement("div");c.className="bp-solid-bar",c.setAttribute("data-testid","solid-presets-bar"),c.hidden=!0;let u=document.createElement("div");u.className="bp-v-banner",u.hidden=!0;let l=document.createElement("div");l.className="bp-v-stage-wrap";let p=document.createElement("div");p.className="bp-v-stage";let d=document.createElement("div");d.className="bp-v-overlay",d.hidden=!0;let g=document.createElement("div");g.className="bp-v-layers",g.hidden=!0;let y=document.createElement("div");y.className="bp-v-info",y.hidden=!0,l.append(p,d,g,y);let m=document.createElement("div");m.className="bp-history-bar",m.setAttribute("data-testid","viewer-history-bar"),m.hidden=!0,e.replaceChildren(n,c,u,l,m);let h="",f="",w=0,C=!1,L=new Set,M=[],S=0,T=new Map,B=new Map,R={},G=[],D="",re="",me=!1,le=!1,we=0,Se=!1,Pe=0,he="",be=0,I=null,ce=null,ne=null,X=null,de=null,E=new vn,k=0,j=!1,A="",K="",ee="",F="";document.addEventListener("click",(H)=>{if(!j)return;if(H.target instanceof Node&&m.contains(H.target))return;j=!1,pe()}),document.addEventListener("keydown",(H)=>{if(j&&H.key==="Escape")j=!1,pe()});function z(){if(k)window.clearInterval(k),k=0;E.playing=!1}function Re(){let H=f==="3d"||f==="mech";if(c.hidden=!H,!H)return;if(c.childElementCount>0)return;for(let U of Ji){let V=document.createElement("button");V.type="button",V.className="bp-v-btn",V.textContent=U.label,V.setAttribute("data-testid",`solid-view-${U.id}`),V.addEventListener("click",()=>{ne?.setView(U.id)}),c.append(V)}let O=document.createElement("button");O.type="button",O.className="bp-v-btn",O.textContent="Snap view",O.setAttribute("data-testid","solid-snap"),O.addEventListener("click",()=>{if(!ne)return;ne.snapPng().then((U)=>{if(!U)return;let V=URL.createObjectURL(U),q=document.createElement("a");q.href=V;let Z=(je()||f||"view").replace(/[^a-zA-Z0-9._-]/g,"_");q.download=`${Z}-snap.png`,q.click(),setTimeout(()=>URL.revokeObjectURL(V),1000)})}),c.append(O)}async function Ae(){if(!h||f!=="board"&&f!=="schematic")return;pe();let H=E.compareRequest();if(!H){A="",K="",ee="",F="",await $e(!1);return}let O=`${f}|${H.commit}|${H.bits}|${re}`;if(O===F&&L.size>0){ke(E.highlightEdits?`Comparing against ${E.activeRef()?.label||H.commit.slice(0,7)} (edits highlighted)`:`Comparing against ${E.activeRef()?.label||H.commit.slice(0,7)}`,!1);return}let U=++w;L.clear(),T.clear(),Ye(),C=!0,A="",K=H.commit,ee="",F=O;try{let V=re||(f==="schematic"?R.sch:R.pcb)||"";if(!V){let ve=await t.hub.rpc("viewer.files",{thread:h});if(U!==w)return;R=ve||{},ae(),V=(f==="schematic"?R.sch:R.pcb)||""}if(!V)throw Error(`Unable to resolve ${f} file path for compare`);let q=await t.hub.rpc("viewer.compare",{thread:h,kind:f,commit:H.commit,bits:H.bits,...re?{path:re}:{}});if(U!==w)return;let Z=typeof q?.root==="string"?q.root:"",Q=f==="schematic"?"1":"0";A=Z?`${Q}|${Z}|diff -`:`${Q}|`,K=H.commit,ee=V.startsWith("/")||/^[A-Za-z]:[\\/]/.test(V)||!Z?V:`${Z.replace(/\/+$/,"")}/${V.replace(/^\/+/,"")}`,C=!1;let ue=M;Ye();for(let ve of ue)if(ve.kind==="bin")Ge(ve.buf);else Ue(ve.key,ve.none,ve.retryable);ke(E.highlightEdits?`Comparing against ${E.activeRef()?.label||H.commit.slice(0,7)} (edits highlighted)`:`Viewing snapshot: ${E.activeRef()?.label||H.commit.slice(0,7)}`,!1)}catch(V){if(U!==w)return;C=!1,A="",K="",ee="",F="",Ye(),ke(V instanceof Error?V.message:String(V),!0)}}function pe(){let H=f==="board"||f==="schematic";if(m.hidden=!H,!H)return;let O=document.createElement("div");O.className="bp-history-group";let U=document.createElement("button");U.type="button",U.className="bp-v-btn",U.textContent="<",U.title="Older snapshot",U.disabled=E.refs.length===0||E.index>=E.refs.length-1,U.setAttribute("data-testid","history-prev"),U.addEventListener("click",()=>{if(z(),E.step(1))Ae()});let V=document.createElement("button");V.type="button",V.className="bp-v-btn"+(E.playing?" is-on":""),V.textContent=E.playing?"⏸":"▶",V.title=E.playing?"Pause history":"Play history",V.disabled=E.refs.length===0,V.setAttribute("data-testid","history-play"),V.addEventListener("click",()=>{if(E.playing){z(),pe();return}if(E.refs.length===0)return;if(E.playing=!0,E.isLive())E.index=E.refs.length-1,Ae();else pe();k=window.setInterval(()=>{if(!E.playing||f!=="board"&&f!=="schematic"){z(),pe();return}if(E.step(-1))Ae();else z(),pe()},1400)});let q=document.createElement("button");q.type="button",q.className="bp-v-btn",q.textContent=">",q.title="Newer snapshot",q.disabled=E.isLive(),q.setAttribute("data-testid","history-next"),q.addEventListener("click",()=>{if(z(),E.step(-1))Ae()});let Z=document.createElement("button");Z.type="button",Z.className="bp-v-btn"+(E.isLive()?" is-on":""),Z.textContent="Live",Z.setAttribute("data-testid","history-live"),Z.addEventListener("click",()=>{if(z(),E.goLive())ke("",!1),Ae()});let Q=document.createElement("span");Q.className="bp-history-label",Q.setAttribute("data-testid","history-label");let ue=E.activeRef();Q.textContent=ue?ue.label||ue.commit.slice(0,7):E.refs.length>0?`Live (${E.refs.length} saved)`:"Live",O.append(U,V,q,Z,Q);let ve=document.createElement("div");ve.className="bp-history-group";let Me=document.createElement("button");Me.type="button",Me.className="bp-v-btn"+(E.highlightEdits?" is-on":""),Me.textContent="Highlight edits",Me.disabled=E.refs.length===0,Me.setAttribute("data-testid","history-highlight"),Me.addEventListener("click",()=>{z(),E.toggleHighlight(),Ae()});let Ee=document.createElement("div");Ee.className="bp-history-menu-wrap";let Be=document.createElement("button");if(Be.type="button",Be.className="bp-v-btn"+(j||!E.isLive()?" is-on":""),Be.disabled=E.refs.length===0,Be.setAttribute("data-testid","history-compare"),Be.setAttribute("aria-haspopup","menu"),Be.setAttribute("aria-expanded",String(j)),Be.textContent=ue?`Compare: ${ue.label||ue.commit.slice(0,7)} ▾`:"Compare ▾",Be.addEventListener("click",(Ie)=>{Ie.stopPropagation(),j=!j,pe()}),Ee.append(Be),j&&E.refs.length>0){let Ie=document.createElement("div");Ie.className="bp-history-menu",Ie.setAttribute("role","menu"),Ie.setAttribute("data-testid","history-compare-menu");let qe=(De,Xe,St)=>{let We=document.createElement("button");We.type="button",We.className="bp-history-menu-item"+(St?" is-active":""),We.setAttribute("role","menuitem"),We.setAttribute("data-commit",Xe),We.textContent=De,We.addEventListener("click",()=>{if(j=!1,z(),E.selectCommit(Xe)){if(E.isLive())ke("",!1);Ae()}else pe()}),Ie.append(We)};qe("Live (working tree)","",E.isLive());for(let De of E.refs)qe(De.label||De.commit.slice(0,7),De.commit,ue?.commit===De.commit);Ee.append(Ie)}ve.append(Me,Ee),m.replaceChildren(O,ve)}async function Ne(H){if(!H)return;try{let O=await t.hub.rpc("viewer.refs",{thread:H});if(H!==h)return;E.setRefs(Array.isArray(O?.refs)?O.refs:[]),pe()}catch{if(H!==h)return;E.setRefs([]),pe()}}function Y(){return document.documentElement.classList.contains("light")}let ge=new MutationObserver(()=>{let H=Y();ce?.setTheme(H),ne?.setTheme(H),de?.setTheme(H)});ge.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]});function ie(H,O="",U=!1){if(H==="none"){d.hidden=!0,d.replaceChildren();return}d.hidden=!1,d.className=`bp-v-overlay is-${H}`;let V=document.createElement("div");V.className="bp-v-state-card";let q=document.createElement("div");if(q.className="bp-v-state-msg",q.textContent=O,V.append(q),U){let Z=document.createElement("button");Z.type="button",Z.className="bp-v-btn is-primary",Z.textContent=b("tools.retry","Retry"),Z.addEventListener("click",()=>void $e(!0)),V.append(Z)}d.replaceChildren(V)}function ke(H,O){u.textContent=H,u.hidden=!H,u.classList.toggle("is-warn",O)}function je(){if(re)return Ct(re);if(f==="board"||f==="3d")return Ct(R.pcb);if(f==="schematic")return Ct(R.sch);if(f==="mech")return Ct(D);return""}function ae(){s.textContent=ns(f);let H=je();if(a.hidden=!H,r.hidden=!H,r.textContent=H,o.replaceChildren(),f==="mech"&&G.length>1){let U=document.createElement("select");U.className="bp-v-select",U.setAttribute("aria-label",b("viewer.mech","Mech"));for(let V of G){let q=document.createElement("option");q.value=V,q.textContent=Ct(V),q.selected=V===D,U.append(q)}U.addEventListener("change",()=>{D=U.value,ae(),$e(!1)}),o.append(U)}if(En(f)){let U=document.createElement("button");U.type="button",U.className="bp-v-btn"+(Se?" is-on":""),U.textContent=I?.layerHead||"Layers",U.setAttribute("data-testid","viewer-layers-btn"),U.addEventListener("click",()=>{if(Se=!Se,g.hidden=!Se,U.classList.toggle("is-on",Se),Se)_e("","")}),o.append(U)}if(f==="board"||f==="schematic"||f==="3d"||f==="mech"||f==="gerbers"){let U=document.createElement("button");U.type="button",U.className="bp-v-btn",U.textContent="Fit",U.setAttribute("data-testid","viewer-fit-btn"),U.addEventListener("click",()=>{ce?.fit(),ne?.fit()}),o.append(U)}if((f==="board"||f==="schematic")&&t.hub.hasFeature("follow")){let U=document.createElement("button");U.type="button",U.className="bp-v-btn"+(me&&!le?" is-on":""),U.textContent=me?le?b("gpui.follow.paused","Follow (paused)"):"Follow agent":"Follow agent",U.setAttribute("data-testid","viewer-follow-btn"),U.addEventListener("click",()=>void nt()),o.append(U)}let O=document.createElement("button");O.type="button",O.className="bp-v-btn bp-v-close",O.textContent="✕",O.title=b("common.close","Close"),O.setAttribute("aria-label",b("common.close","Close")),O.setAttribute("data-testid","viewer-close-btn"),O.addEventListener("click",()=>t.closeViewer()),o.append(O)}function fe(){if(!I){g.replaceChildren();return}let H=document.createDocumentFragment(),O=document.createElement("div");O.className="bp-v-layers-head";let U=document.createElement("span");if(U.textContent=I.layerHead||"Layers",O.append(U),I.layerReset){let Q=document.createElement("button");Q.type="button",Q.className="bp-v-btn",Q.textContent="Reset",Q.addEventListener("click",()=>void _e("reset","")),O.append(Q)}if(H.append(O),I.layerModes){let Q=document.createElement("div");Q.className="bp-v-layers-modes",["All","Dim","Only"].forEach((ue,ve)=>{let Me=document.createElement("button");Me.type="button",Me.className="bp-v-btn"+(I?.layerMode===ve?" is-on":""),Me.textContent=ue,Me.addEventListener("click",()=>void _e("mode",String(ve))),Q.append(Me)}),H.append(Q)}let V=ce?.presentColors()??new Map,q=(I.layerList||[]).concat(I.layerMarks||[]),Z=document.createElement("div");Z.className="bp-v-layers-list";for(let Q of q){let ue=V.get(Q.layer);if(ue===void 0)continue;let ve=document.createElement("div");ve.className="bp-v-layer-row"+(Q.active?" is-focus":"");let Me=document.createElement("input");Me.type="checkbox",Me.checked=Q.on!==!1,Me.addEventListener("change",()=>void _e("toggle",String(Q.layer)));let Ee=document.createElement("span");Ee.className="bp-v-layer-swatch";let Be=ue>>>16&255,Ie=ue>>>8&255,qe=ue&255;Ee.style.background=Q.on!==!1?`rgb(${Be},${Ie},${qe})`:`rgba(${Be},${Ie},${qe},0.2)`;let De=document.createElement("button");De.type="button",De.className="bp-v-layer-name",De.textContent=Q.name,De.addEventListener("click",()=>void _e("pick",String(Q.layer))),ve.append(Me,Ee,De),Z.append(ve)}H.append(Z),g.replaceChildren(H)}async function _e(H,O){if(!En(f))return;let U=w;try{let V=await t.hub.rpc("viewer.layers",{kind:f,present:be,off:Pe,focus:he,...H?{action:H,value:O}:{}});if(U!==w||!V)return;Pe=Number(V.own)||0,he=typeof V.focus==="string"?V.focus:"",I=V;let q={off:Number(V.off)||0,dim:Number(V.dim)||0,lift:typeof V.lift==="number"?V.lift:255};if(ce?.setLayers(q),ae(),Se)fe()}catch{}}async function Ve(){if(!me||le||!h||!t.hub.hasFeature("follow"))return;le=!0,ae();try{await t.hub.rpc("viewer.follow",{thread:h,action:"pause"})}catch{}}async function nt(){if(!h||!t.hub.hasFeature("follow"))return;let H=!me?"on":le?"resume":"off";try{let O=await t.hub.rpc("viewer.follow",{thread:h,action:H});if(me=!!O.on,le=!!O.paused,ae(),O.on&&!O.paused&&O.focus&&Array.isArray(O.focus.box)&&O.focus.box.length===4&&(O.seq||0)>we)we=O.seq||we,ce?.zoomToBoxMm([O.focus.box[0],O.focus.box[1],O.focus.box[2],O.focus.box[3]])}catch{}}function oe(){y.hidden=!0,y.replaceChildren(),ce?.setHighlights([])}function dt(H){let O=H.split(";").filter(Boolean),U=O.shift()||H,V=[],q="",Z="";for(let Ee of O){if(Ee.startsWith("g="))continue;let Be=Ee.indexOf("=");if(Be>0){let Ie=Ee.slice(0,Be),qe=Ee.slice(Be+1);if((Ie==="ref"||Ie==="symbol")&&!q)q=qe;if(Ie==="net"&&!Z)Z=qe;V.push([Ie,qe])}else V.push([Ee,""])}let Q=document.createElement("div");Q.className="bp-v-info-head";let ue=document.createElement("span");ue.className="bp-v-info-title",ue.textContent=U;let ve=document.createElement("button");ve.type="button",ve.className="bp-v-info-x",ve.textContent="×",ve.setAttribute("aria-label","Clear selection"),ve.addEventListener("click",oe),Q.append(ue,ve);let Me=document.createElement("div");Me.className="bp-v-info-rows";for(let[Ee,Be]of V){let Ie=document.createElement("span");Ie.className="bp-v-info-chip",Ie.textContent=Be?`${Ee}: ${Be}`:Ee,Me.append(Ie)}return y.replaceChildren(Q,...V.length>0?[Me]:[]),y.hidden=!1,{ref:q||void 0,net:Z||void 0}}async function Je(H){if(!H){oe();return}let O=Array.from(L)[0]||"";if(!O)return;let U=w;try{let V=await t.hub.rpc("viewer.info",{key:O,at:H.at,idx:H.idx});if(U!==w)return;let q=typeof V.info==="string"?V.info:"";if(!q){oe();return}let{ref:Z,net:Q}=dt(q),ue=[];if(Z)ue.push(["ref",Z]);if(Q)ue.push(["net",Q]);let ve=[[H.at,H.idx]];for(let[Me,Ee]of ue){let Be=await t.hub.rpc("viewer.probe",{key:O,name:Me,value:Ee});if(U!==w)return;if(Array.isArray(Be.matches))for(let Ie of Be.matches)ve.push(Ie)}ce?.setHighlights(ve)}catch{oe()}}function pt(){X?.destroy(),X=null,de?.destroy(),de=null,ce?.destroy(),ce=null,ne?.destroy(),ne=null,p.replaceChildren(),Se=!1,g.hidden=!0,y.hidden=!0,y.replaceChildren(),ke("",!1),ie("none")}function Ye(){M=[],S=0}async function $e(H){if(!h||!f)return;let O=++w;if(L.clear(),C=!1,Ye(),pt(),ae(),Re(),pe(),(f==="board"||f==="schematic")&&h)Ne(h);if(ea(f)){if(t.hub.rpc("viewer.watch",{thread:h,kind:""}).catch(()=>{}),f==="files")X=_i(p,t,h,(q,Z)=>{if(f=q,re=Z,q==="mech")D=Z;$e(!1)});else if(f==="diff")X=qi(p,t,h);else if(f==="review")X=Ki(p,t,h);else if(f==="browser")X=Vi(p,t,h);else if(f==="terminal")ie("loading","Loading terminal…"),import("/assets/terminal.js").then((Z)=>{if(O!==w)return;if(ie("none"),Z?.mountTerminalPane)de=Z.mountTerminalPane(p,t,h,Y());else ie("error","Terminal chunk missing",!0)},(Z)=>{if(O!==w)return;ie("error",Z instanceof Error?Z.message:String(Z),!0)});return}if(ie("loading","Loading…"),!R.root)try{let q=await t.hub.rpc("viewer.files",{thread:h});if(O!==w)return;R=q||{},ae()}catch{}if(f==="gerbers"&&R.hasGerbers===!1){ie("empty","No Gerbers in this project",!1);return}let U=Y();if(f==="3d"||f==="mech")ne=new wn(p,{onStatus:(q,Z)=>{if(Z)ie("none"),ke(q,!1);else if(q)ie("loading",q);else ie("none"),ke("",!1)},onUserMove:()=>void Ve()}),ne.setTheme(U);else if(f==="board"||f==="schematic"||f==="gerbers")ce=new gn(p,{onPick:(q)=>void Je(q),onUserMove:()=>void Ve()}),ce.setTheme(U);else{ie("empty",`${ns(f)} is not available in this viewer`,!1);return}let V={thread:h};if(H)V.force=!0;if(f==="mech"){if(G.length===0)try{let q=await t.hub.rpc("mech.list",{thread:h});if(O!==w)return;if(G=Array.isArray(q.parts)?q.parts:[],!D)D=q.primary||G[0]||"";ae()}catch(q){if(O!==w)return;ie("error",q instanceof Error?q.message:String(q),!0);return}if(!D){ie("empty",b("gpui.rail.no.mech","No mechanical parts in this project"),!1);return}V.kind="3d",V.path=D}else{if(V.kind=f,re&&(f==="board"||f==="schematic"))V.path=re;if(f==="3d"&&!H&&ne){let q=ne.keptToken();if(q)V.kept=q}if((f==="board"||f==="schematic"||f==="gerbers")&&!H&&t.hub.hasFeature("keptChunks"))V.keptChunks=Array.from(B.keys())}C=!0,A="",K="",ee="",F="";try{let q=await t.hub.rpc("viewer.watch",V);if(O!==w)return;L=new Set(Array.isArray(q.keys)?q.keys:[]),C=!1;let Z=M;Ye();for(let Q of Z)if(Q.kind==="bin")Ge(Q.buf);else Ue(Q.key,Q.none,Q.retryable)}catch(q){if(O!==w)return;C=!1,L.clear(),Ye();let Z=q instanceof Error?q.message:String(q),Q=/no gerbers|not in this project|another machine/i.test(Z);ie(Q?"empty":"error",Z,!Q)}}function Ue(H,O,U){if(C){if(M.length{if(H.t==="plot"&&typeof H.none==="string"&&typeof H.key==="string")Ue(H.key,H.none,H.retryable===!0)}),$t=Pt(()=>{if(f)ae()}),Lt=(H)=>{if(H.key==="Escape"&&f&&!y.hidden)oe()};return window.addEventListener("keydown",Lt),{open(H,O){if(O!==h){if(h=O,R={},G=[],D="",T.clear(),me=!1,le=!1,we=0,Pe=0,he="",be=0,I=null,t.hub.hasFeature("follow"))t.hub.rpc("viewer.follow",{thread:O}).then((U)=>{if(O!==h)return;if(me=!!U.on,le=!!U.paused,we=Number(U.seq)||0,f)ae()}).catch(()=>{})}if(H!==f)z(),E.goLive(),Pe=0,he="",be=0,I=null;f=H,re="",$e(!1)},reconcileHas(H){if(f&&!Qs(f,H))t.closeViewer()},close(){if(w++,C=!1,z(),j=!1,A="",K="",ee="",F="",E.goLive(),c.hidden=!0,m.hidden=!0,Ye(),h)t.hub.rpc("viewer.watch",{thread:h,kind:""}).catch(()=>{});f="",L.clear(),pt()}}}var is="http://www.w3.org/2000/svg";function kt(e){let t=document.createElementNS(is,"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(is,"path");i.setAttribute("d",n),t.appendChild(i)}return t}function ta(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 ss(e,t){if(!e)return!0;if(t==="board"||t==="3d")return e.board!==!1;if(t==="schematic")return e.schematic!==!1;if(t==="mech")return e.mech!==!1;if(t==="gerbers")return e.gerbers!==!1;return!0}function as(e){if(!e)return;let t=e==="light";document.documentElement.classList.toggle("light",t);try{localStorage.setItem("bp.theme",t?"light":"dark")}catch{}}function na(){return`web-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`}function rs(){let e=document.getElementById("root");if(!e)return;try{if(localStorage.getItem("bp.theme")==="light")document.documentElement.classList.add("light")}catch{}let t=document.createElement("header");t.className="bp-topbar",t.setAttribute("data-testid","topbar");let n=document.createElement("button");n.type="button",n.className="icon bp-side-toggle",n.textContent="☰",n.title="Toggle sidebar",n.setAttribute("aria-label","Toggle sidebar");let i=document.createElement("div");i.className="bp-brand";let s=document.createElement("img");s.src="/assets/favicon.svg",s.alt="Backplane",s.className="bp-logo";let a=document.createElement("span");a.className="bp-brand-name bp-hide-phone",a.textContent="Backplane";let r=document.createElement("span");r.className="bp-crumb-sep bp-hide-phone",r.textContent="/";let o=document.createElement("span");o.className="bp-crumb-proj bp-hide-phone";let c=document.createElement("span");c.className="bp-crumb-sep bp-hide-phone",c.textContent="/";let u=document.createElement("span");u.className="bp-crumb-thread",u.setAttribute("data-testid","thread-title");let l=document.createElement("span");l.className="bp-plan-top-badge bp-hidden",l.setAttribute("data-testid","plan-top-badge"),i.append(s,a,r,o,c,u,l);let p=document.createElement("div");p.className="bp-top-state bp-hide-phone bp-hidden";let d=document.createElement("span");d.className="bp-top-state-lbl",d.textContent="STATE";let g=document.createElement("span");g.className="bp-dot bp-dot-idle";let y=document.createElement("span");y.className="bp-top-state-word",p.append(d,g,y);let m=document.createElement("div");m.className="bp-top-acts bp-hide-phone bp-hidden";let h=document.createElement("button");h.type="button",h.className="bp-btn-ghost bp-top-act";let f=document.createElement("span");f.textContent=b("menu.pin","Pin"),h.append(kt(["M12 17v5","M9 3h6l1 7 3 3H5l3-3 1-7z"]),f);let w=document.createElement("button");w.type="button",w.className="bp-btn-ghost bp-top-act";let C=document.createElement("span");C.textContent=b("menu.settle","Settle"),w.append(kt(["M12 22a10 10 0 1 0 0-20 10 10 0 0 0 0 20z","M9 12l2 2 4-4"]),C);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 S=document.createElement("div");S.className="bp-popover bp-hidden",S.setAttribute("data-testid","thread-menu"),L.append(M,S),m.append(h,w,L);let T=document.createElement("div");T.className="bp-top-right";let B=document.createElement("button");B.type="button",B.className="bp-btn-ghost bp-top-act bp-hide-tablet",B.setAttribute("data-testid","improvements-btn");let R=document.createElement("span");R.textContent=b("gpui.improvements","Improvements"),B.append(kt(["M12 2l2.4 7.4H22l-6.2 4.5 2.4 7.4L12 16.8l-6.2 4.5 2.4-7.4L2 9.4h7.6z"]),R);let G=document.createElement("button");G.type="button",G.className="bp-cmd-box bp-hide-tablet",G.textContent="> Jump or run a command";let D=document.createElement("button");D.type="button",D.className="icon bp-top-icon",D.title="Search",D.setAttribute("aria-label","Search"),D.appendChild(kt(["M11 19a8 8 0 1 0 0-16 8 8 0 0 0 0 16z","M21 21l-4.3-4.3"]));let re=document.createElement("button");re.type="button",re.className="icon bp-top-icon",re.title=b("palette.settings","Settings"),re.setAttribute("aria-label",b("palette.settings","Settings")),re.setAttribute("data-testid","settings-btn"),re.appendChild(kt(["M12 15a3 3 0 1 0 0-6 3 3 0 0 0 0 6z","M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 1 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 1 1-4 0v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 1 1-2.83-2.83l.06-.06a1.65 1.65 0 0 0 .33-1.82 1.65 1.65 0 0 0-1.51-1H3a2 2 0 1 1 0-4h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 1 1 2.83-2.83l.06.06a1.65 1.65 0 0 0 1.82.33H9a1.65 1.65 0 0 0 1-1.51V3a2 2 0 1 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 1 1 2.83 2.83l-.06.06a1.65 1.65 0 0 0-.33 1.82V9c.26.6.85 1 1.51 1H21a2 2 0 1 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z"])),T.append(B,G,D,re),t.append(n,i,p,m,T);let me=document.createElement("div");me.className="bp-body";let le=document.createElement("aside");le.className="bp-sidebar",le.setAttribute("data-testid","sidebar");let we=document.createElement("main");we.className="bp-center";let Se=document.createElement("div");Se.className="bp-right-area bp-hidden",Se.setAttribute("data-testid","right-area");let Pe=document.createElement("div");Pe.className="bp-right-top";let he=document.createElement("section");he.className="bp-viewer-pane bp-hidden",he.setAttribute("data-testid","viewer-pane"),Pe.appendChild(he),Se.appendChild(Pe);let be=document.createElement("nav");be.className="bp-rail",be.setAttribute("aria-label","Viewer rail"),be.setAttribute("data-testid","viewer-rail"),me.append(le,we,Se,be),e.append(t,me);let I=new hn,ce=null,ne=new Set,X=0,de=null,E=[],k=[],j=[],A=[],K=[],ee=[],F="",z=0,Re=0,Ae=null,pe=null,Ne="",Y=null,ge=20,ie={},ke=new Map;function je(v,x){ke.delete(v),ke.set(v,x);while(ke.size>ge){let P=ke.keys().next().value;if(P!==void 0)ke.delete(P);else break}}let ae=new pn(le,{onSelectThread:(v)=>{if(v===F&&Ae!==null){le.classList.remove("bp-sidebar-open");return}Ee(v)},onNewThread:(v)=>{De(v)},onSelectBot:(v)=>{Ee(v.thread)},onThreadAct:(v,x)=>{Qe(v,x)},onToggleSection:(v)=>{if(ne.has(v))ne.delete(v);else ne.add(v);ue()},onToggleProjectFold:(v)=>{I.rpc("sidebar.act",{action:"project-fold",value:v}).then(()=>ue()).catch(()=>{})},onCollapseSidebar:()=>{le.classList.remove("bp-sidebar-open"),le.classList.add("bp-sidebar-collapsed")},onNeedAct:async(v)=>{let x=Ht(v,!1);if(!x)return;if(x.kind==="thread"){Ee(x.id);return}if(x.kind!=="call")return;let P=Si(await I.rpc(x.method,x.params));if(P?.kind==="thread")Ee(P.id);ue()},hasRoomView:!1,onAddProject:()=>Ue.open({mode:"folder"})}),fe=new zt(we,{onLoadOlder:()=>{qe()},onGoToEntry:(v)=>{Ie(v)},onAnswerAsk:(v,x)=>{I.rpc("ask.answer",{ask:v,answer:x}).catch((P)=>{oe.showError(P instanceof Error?P.message:"Could not send answer")})},onToggleReview:(v)=>{if(!F)return;let x=z;I.rpc("thread.review",{thread:F,on:v}).then((P)=>{if(x===z)fe.setReview(P.review??null)}).catch(()=>{})},onUnansweredAction:(v,x)=>{if(!F)return;if(v==="again"||v==="thread-again")I.rpc("thread.again",{thread:F,value:x}).catch(()=>{});else I.rpc("thread.act",{thread:F,action:v,value:x}).catch(()=>{})},onReplyEntry:(v)=>{if(!I.hasFeature("reply")){let x=(v.text||"").split(` -`)[0]?.slice(0,100)??"";if(x)oe.prependDraft(`> ${x} -`);return}if(!v.text||!v.text.trim()||v.live||v.id.startsWith("local-"))return;We({id:v.id,text:v.text,role:v.kind==="user"?"user":"assistant"})},onLoadImage:async(v,x)=>{try{let P={entry:v,path:x};if(I.hasFeature("blobs"))P.metaOnly=!0;let N=await I.rpc("message.image",P);if(N.blob&&N.blob.startsWith("/blob/"))return{url:N.blob};if(N.mime&&N.data)return{mime:N.mime,data:N.data}}catch{}return null}});function _e(v){if(!v)return null;if(v.planMode)return v.planMode;if(v.provider==="claude")return{phase:"off",interaction:"default",once:!1};return null}function Ve(v,x){if(!F)return;let P=z,N=F;I.rpc(v,x).then((_)=>{if(P!==z||F!==N)return;if(_.thread){let te=k.findIndex((ye)=>ye.id===_.thread.id);if(te>=0)k[te]=_.thread;else k.unshift(_.thread);ae.setData(E,k,j,A),fe.updateThreadMeta(_.thread),H(),oe.setState(!0,_.thread.state==="working")}}).catch((_)=>{if(P===z&&F===N)oe.showError(_ instanceof Error?_.message:"Could not change Plan mode")})}let nt,oe=new Yt(we,{onSend:(v,x)=>{Cn(v,x)},onRunCommand:(v)=>{kn(v)},onInterrupt:()=>{if(F)I.rpc("turn.interrupt",{thread:F}).catch(()=>{})},onQueryMentions:async(v,x)=>{try{return(await I.rpc("mentions.list",{q:v,kind:x,limit:10})).items??[]}catch{return[]}},onToggleVoice:()=>{nt.toggle()},onCyclePlanMode:()=>{let v=k.find((P)=>P.id===F)??null,x=_e(v);if(!x||!F)return;if(x.interaction!=="plan")Ve("thread.planonce",{thread:F,on:!0});else if(x.once)Ve("thread.pick",{thread:F,action:"interaction",value:"plan"});else Ve("thread.pick",{thread:F,action:"interaction",value:"default"})},onSetPlanMode:(v)=>{if(!F)return;if(v==="once")Ve("thread.planonce",{thread:F,on:!0});else if(v==="always")Ve("thread.pick",{thread:F,action:"interaction",value:"plan"});else Ve("thread.pick",{thread:F,action:"interaction",value:"default"})}});nt=new mn(I,{getThreadId:()=>F,getDraft:()=>oe.getDraft(),getCaret:()=>oe.getCaret(),setDraft:(v)=>oe.setDraft(v),setRecording:(v)=>oe.setVoiceRecording(v),setLevel:(v)=>oe.setVoiceLevel(v),showError:(v)=>oe.showError(v)});function dt(){let v=Ne!=="",x=Je.isOpen();Se.classList.toggle("bp-hidden",!v&&!x),Se.classList.toggle("bp-has-viewer",v),Se.classList.toggle("bp-has-mgmt",x)}let Je=new an(Pe,Se,{hub:I,getThreadId:()=>F,getThreadGen:()=>z,onSendText:(v)=>{Cn(v)},onOpenChange:()=>dt()});function pt(v){let x=window.prompt("Rename thread",v.title||"");if(!x||!x.trim())return;I.rpc("thread.act",{thread:v.id,action:"rename",title:x.trim()}).then((P)=>{if(P.thread)k=k.map((N)=>N.id===P.thread.id?P.thread:N),H(),ue()}).catch((P)=>{oe.showError(P instanceof Error?P.message:"Could not rename thread")})}function Ye(v){switch(v.type){case"thread":Ee(v.id);break;case"rail":if(!F&&v.id!=="terminal")break;if(Ne===v.id)O();else U(v.id);break;case"thread-act":if(F)Qe(F,v.action);break;case"new-thread":De(v.projectId);break;case"rename":{let x=k.find((P)=>P.id===F);if(x)pt(x);break}case"prev-thread":case"next-thread":{let x=k.filter((te)=>!te.archived&&!te.swarm);if(x.length<2)break;let P=x.findIndex((te)=>te.id===F),N=v.type==="next-thread"?1:-1,_=x[(P<0?0:P+N+x.length)%x.length];if(_)Ee(_.id);break}case"command":if(v.runDirectly)kn(v.word);else oe.setDraft(`${v.word} `),oe.focus();break;case"improvements":Lt();break;case"settings":ze.open();break;case"sidebar":le.classList.toggle("bp-sidebar-open"),le.classList.toggle("bp-sidebar-collapsed");break}}let $e=new rn(e,{getState:()=>({selectedThreadId:F,threads:k,projects:E,bots:j,railItems:K,commands:ee}),onSearch:async(v)=>{if(!I.hasFeature("search"))return{threads:[],projects:[],messages:[]};return I.rpc("search",{q:v,limit:20})},onExecute:Ye}),Ue=new _t(e,{hub:I,onProjectAdded:(v)=>{if(ue(),v.id)De(v.id)},onCloneDone:(v)=>{if(ue(),v.thread)Ee(v.thread)}}),Ge=new on(be,(v)=>{if(v==="commands"){$e.open();return}if(!F)return;if(Ne===v)O();else U(v)}),it=null,ze=new ln(e,{onLoadDevices:async()=>(await I.rpc("devices.page",{})).rows??[],onDevicesAct:async(v,x)=>{await I.rpc("devices.page.act",{action:v,value:x})},onGetHome:()=>it,onMoveHomeHere:async()=>{await I.rpc("home.move",{to:"back"})},onLogout:()=>$n(()=>{I.disconnect(),window.location.replace("/")})});h.addEventListener("click",()=>{let v=k.find((x)=>x.id===F);if(v)Qe(v.id,v.pinned?"unpin":"pin")}),w.addEventListener("click",()=>{let v=k.find((x)=>x.id===F);if(v)Qe(v.id,v.settled?"unsettle":"settle")});let $t=new dn(e,(v,x)=>x?I.rpc("thread.context.mcp",{thread:v,...x}):I.rpc("thread.context",{thread:v}));M.addEventListener("click",(v)=>{v.stopPropagation();let x=k.find((_)=>_.id===F);if(!x)return;if(!S.classList.contains("bp-hidden")){S.classList.add("bp-hidden");return}let P=[{label:"Rename…",run:()=>pt(x)},{label:x.pinned?b("menu.unpin","Unpin"):b("menu.pin","Pin"),run:()=>{Qe(x.id,x.pinned?"unpin":"pin")}},{label:x.settled?b("phone.unsettle","Unsettle"):b("menu.settle","Settle"),run:()=>{Qe(x.id,x.settled?"unsettle":"settle")}},{label:x.archived?"Unarchive":"Archive",run:()=>{Qe(x.id,x.archived?"unarchive":"archive")}},{label:"Delete",danger:!0,run:()=>{if(window.confirm("Delete this thread?"))Qe(x.id,"delete")}}];if(I.hasFeature("threadContext"))P.unshift({label:b("thread.context.title","Context & Prompt"),run:()=>$t.open(x.id)});let N=document.createDocumentFragment();for(let _ of P){let te=document.createElement("button");te.type="button",te.className="bp-popover-item"+(_.danger?" danger":""),te.textContent=_.label,te.addEventListener("click",()=>{S.classList.add("bp-hidden"),_.run()}),N.appendChild(te)}S.replaceChildren(N),S.classList.remove("bp-hidden")}),document.addEventListener("click",()=>S.classList.add("bp-hidden"));async function Lt(){let v=document.createElement("div");v.className="bp-modal-backdrop",v.setAttribute("data-testid","improvements-modal");let x=document.createElement("div");x.className="bp-modal";let P=document.createElement("div");P.className="bp-modal-head";let N=document.createElement("h2");N.textContent=b("gpui.improvements","Improvements");let _=document.createElement("button");_.type="button",_.className="icon",_.textContent="×",_.addEventListener("click",()=>v.remove()),P.append(N,_);let te=document.createElement("div");te.className="bp-modal-body",te.textContent="Loading…",x.append(P,te),v.appendChild(x),v.addEventListener("click",(ye)=>{if(ye.target===v)v.remove()}),e.appendChild(v);try{let ye=await I.rpc("improvements.projects",{}),He=ye.projects??[];if(He.length===0){te.textContent="No projects available for Improvements.";return}let et=document.createDocumentFragment();for(let Le of He){let se=document.createElement("div");se.className="bp-set-row";let Ze=document.createElement("div");Ze.className="bp-set-info",Ze.textContent=Le.title||Le.name||Le.id;let tt=document.createElement("button");tt.type="button",tt.className=Le.id===ye.project?"primary":"",tt.textContent=Le.id===ye.project?"Active":"Select",tt.addEventListener("click",()=>{I.rpc("improvements.project",{project:Le.id}).then(()=>v.remove()).catch(()=>{})}),se.append(Ze,tt),et.appendChild(se)}te.replaceChildren(et)}catch(ye){te.textContent=ye instanceof Error?ye.message:"Could not load Improvements."}}B.addEventListener("click",()=>{Lt()}),G.addEventListener("click",()=>$e.open()),D.addEventListener("click",()=>$e.open()),re.addEventListener("click",()=>{ze.open()}),n.addEventListener("click",()=>{le.classList.toggle("bp-sidebar-open"),le.classList.toggle("bp-sidebar-collapsed")});function H(){let v=k.find((N)=>N.id===F)??null,x=v?E.find((N)=>N.id===v.project):void 0;o.textContent=x?.title??"",r.classList.toggle("bp-hidden",!x),c.classList.toggle("bp-hidden",!v),u.textContent=v?v.title||"Untitled thread":"";let P=_e(v);if(oe.setPlanMode(P),!P||P.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",P.phase==="executing"),l.title=b("gpui.planmode.tip","Plan before acting (1 turn, always, or off)"),l.textContent=P.phase==="armed"&&P.once?b("gpui.planmode.top.once","Plan (1 turn)"):P.phase==="armed"?b("gpui.mgmt.plan.tab","Plan"):P.phase==="planning"?b("gpui.planmode.top.planning","Planning"):P.phase==="pending"?b("gpui.planmode.top.pending","Review plan"):b("gpui.planmode.top.executing","Building plan");if(p.classList.toggle("bp-hidden",!v),m.classList.toggle("bp-hidden",!v),v){g.className=`bp-dot ${ta(v)}`,y.textContent=v.status||v.state||"idle",f.textContent=v.pinned?b("menu.unpin","Unpin"):b("menu.pin","Pin"),C.textContent=v.settled?b("phone.unsettle","Unsettle"):b("menu.settle","Settle");let N=v;oe.setModelChip(v.chip||v.model||"default",v.provider,N.ctxPct??N.contextPct),oe.setMemory(v.memory)}else oe.setModelChip("default"),oe.setMemory(null)}function O(v=!0){if(Re++,Ne="",Ge.setActive(""),he.classList.add("bp-hidden"),Y?.close(),dt(),v&&F&&I.getState()==="connected")I.rpc("viewer.watch",{thread:F,kind:""}).catch(()=>{})}function U(v){if(Re++,Ne=v,Ge.setActive(v),he.classList.remove("bp-hidden"),dt(),!Y&&typeof xn==="function")Y=xn(he,{hub:I,getThreadId:()=>F,closeViewer:()=>O(!0)});if(Y)Y.open(v,F);else{let x=document.createElement("div");x.className="bp-viewer-placeholder";let P=document.createElement("div");P.className="bp-viewer-bar";let N=document.createElement("span");N.textContent=v.toUpperCase();let _=document.createElement("button");_.type="button",_.className="icon",_.textContent="×",_.addEventListener("click",()=>O(!0)),P.append(N,_);let te=document.createElement("div");te.className="bp-dim bp-viewer-msg",te.textContent=`Viewer pane (${v}).`,x.append(P,te),he.replaceChildren(x)}}async function V(v,x){if(!v||!I.hasFeature("rail")){if(x===z)K=[],Ge.setItems([]);return}let P=++Re;try{let N=await I.rpc("viewer.rail",{thread:v,page:Ne});if(x!==z||P!==Re)return;let _=Array.isArray(N.rail)?N.rail:Array.isArray(N.items)?N.items:[];if(K=_,Ge.setItems(_),N.has){if(Y?.reconcileHas?.(N.has),Ne&&!ss(N.has,Ne))O(!0)}}catch{if(x===z&&P===Re)K=[],Ge.setItems([])}}function q(v){for(let x of v)if(x.kind==="threads"){for(let P of x.rows)if(!P.off&&(P.nav||P.id)&&!(P.nav||"").startsWith("@room:"))return P.nav||P.id}else if(x.kind==="projects"){for(let P of x.rows)for(let N of P.threads??[])if(!N.off&&(N.nav||N.id)&&!(N.nav||"").startsWith("@room:"))return N.nav||N.id}return""}function Z(v,x){for(let P of v)if(P.kind==="threads"){if(P.rows.some((N)=>(N.nav||N.id)===x))return!0}else if(P.kind==="projects"){for(let N of P.rows)if((N.threads??[]).some((_)=>(_.nav||_.id)===x))return!0}return!1}function Q(v){let x=[];for(let P of v){if(P.kind!=="projects")continue;for(let N of P.rows)x.push({id:N.id,title:N.title,css:N.css,color:N.color})}if(x.length>0)E=x}async function ue(){if(!I.hasFeature("sections"))return!1;let v=++X;try{let x=await I.rpc("sidebar.sections",{open:Array.from(ne)});if(v!==X)return!0;let P=Array.isArray(x.sections)?x.sections:[];return ce=P,Q(P),ae.setData(E,k,j,A),ae.setSections(P,j,A),H(),!0}catch{return!1}}function ve(){if(!I.hasFeature("sections"))return;if(de!==null)window.clearTimeout(de);de=window.setTimeout(()=>{de=null,ue()},150)}async function Me(){if(Ae=null,I.hasFeature("bots"))try{let x=await I.rpc("bots.list",{});j=x.bots??[],A=x.rooms??[]}catch{}if(I.hasFeature("shell")){let x=await I.rpc("shell.sync",{have:ie,settled:25}),P=new Set(x.removed??[]),N=new Set((x.projects??[]).map((_)=>_.id));if(P.size>0||N.size>0)E=[...E.filter((_)=>!P.has(_.id)&&!N.has(_.id)),...x.projects??[]],k=[...k.filter((_)=>!P.has(_.project)&&!N.has(_.project)),...x.threads??[]];else if(Array.isArray(x.threads)&&x.threads.length>0){let _=new Map(k.map((te)=>[te.id,te]));for(let te of x.threads)_.set(te.id,te);k=Array.from(_.values())}if(x.sections!==void 0){let _=Array.isArray(x.sections)?x.sections:Array.isArray(x.sections?.sections)?x.sections.sections:null;if(_)ce=_,Q(_)}if(x.h)ie=x.h;ae.setData(E,k,j,A),ae.setSections(ce,j,A)}else if(I.hasFeature("sections")){let[x,P]=await Promise.all([I.rpc("sidebar.sections",{open:Array.from(ne)}).catch(()=>null),I.rpc("threads.list",{limit:200,archived:!1}).catch(()=>({threads:[]}))]);if(k=P.threads??[],x&&Array.isArray(x.sections)){let N=x.sections;if(!N.some((te)=>te.kind==="projects"&&te.rows.length>0)){let te=N.find((ye)=>ye.kind==="projects"&&ye.fold&&ye.toggle&&(ye.count??0)>0);if(te?.toggle&&!ne.has(te.toggle)){ne.add(te.toggle);let ye=await I.rpc("sidebar.sections",{open:Array.from(ne)}).catch(()=>null);if(ye&&Array.isArray(ye.sections))N=ye.sections}}ce=N,Q(N),ae.setData(E,k,j,A),ae.setSections(N,j,A)}else ce=null,E=(await I.rpc("projects.list",{limit:100})).projects??[],ae.setSections(null,j,A),ae.setData(E,k,j,A);await I.rpc("subscribe",{topic:"lists"}).catch(()=>{})}else{ce=null;let[x,P]=await Promise.all([I.rpc("projects.list",{limit:100}),I.rpc("threads.list",{limit:200,archived:!1})]);E=x.projects??[],k=P.threads??[],ae.setSections(null,j,A),ae.setData(E,k,j,A),await I.rpc("subscribe",{topic:"lists"}).catch(()=>{})}let v=F;if(!v){let x="";try{x=localStorage.getItem("bp.lastThread")||""}catch{}if(x&&(ce&&Z(ce,x)||k.some((P)=>P.id===x)))v=x;else if(ce)v=q(ce);if(!v)v=(k.find((N)=>!N.archived&&!N.swarm&&!N.settled)??k.find((N)=>!N.archived&&!N.swarm))?.id??""}if(v&&(ce&&Z(ce,v)||k.some((x)=>x.id===v)))await Ee(v);else F="",K=[],Ge.setItems([]),oe.setState(!1,!1),H()}async function Ee(v){if(F&&F!==v){nt.cancel();let Le=fe.getEntries();if(Le.length>0){let se=ke.get(F);je(F,{entries:Le,ids:se?.ids??Le.map((Ze)=>Ze.id),olderCursor:pe,review:se?.review??null,unanswered:se?.unanswered??null,rail:se?.rail??K,hashes:se?.hashes??{}})}}let x=++z;Re++,We(null);let P=Ae;if(Ae=null,P!==null)I.rpc("unsubscribe",{sub:P}).catch(()=>{});F=v;let N=ke.get(v);pe=N?.olderCursor??null;try{localStorage.setItem("bp.lastThread",v)}catch{}ae.setSelected(v),le.classList.remove("bp-sidebar-open"),H();let _=k.find((Le)=>Le.id===v)??null;if(N)fe.setThread(_,N.entries,Boolean(N.olderCursor),N.review,N.unanswered),K=N.rail,Ge.setItems(N.rail);else fe.setLoading(_),K=[],Ge.setItems([]);if(oe.setState(!0,_?.state==="working"),I.hasFeature("open")){let Le={};if(N){for(let[Te,ut]of Object.entries(N.hashes))Le[Te]=ut;for(let Te of N.entries)if(Te.h)Le[Te.id]=Te.h}let se;try{se=await I.rpc("thread.open",{thread:v,limit:40,have:Le})}catch(Te){if(x===z){let ut=Te instanceof Error&&Te.message?Te.message:"Could not load messages.";fe.setError(_,ut,()=>{Ee(v)})}return}if(x!==z){if(se.sub!==void 0&&se.sub!==null)I.rpc("unsubscribe",{sub:se.sub}).catch(()=>{});return}if(Ae=se.sub??null,se.thread){_=se.thread;let Te=k.findIndex((ut)=>ut.id===se.thread.id);if(Te>=0)k[Te]=se.thread;else k.unshift(se.thread);H(),oe.setState(!0,_.state==="working")}if("next"in se)pe=se.next??null;let Ze=new Map;if(N)for(let Te of N.entries)Ze.set(Te.id,Te);for(let Te of se.entries??[])Ze.set(Te.id,Te);let tt=se.ids??N?.ids??(se.entries??[]).map((Te)=>Te.id),Sn=tt.map((Te)=>Ze.get(Te)).filter((Te)=>Boolean(Te)),mt=N?.rail??[];if(se.rail!==void 0){if(Array.isArray(se.rail))mt=se.rail;else if(mt=Array.isArray(se.rail?.rail)?se.rail.rail:Array.isArray(se.rail?.items)?se.rail.items:[],se.rail?.has){if(Y?.reconcileHas?.(se.rail.has),Ne&&!ss(se.rail.has,Ne))O(!0)}}K=mt,Ge.setItems(mt);let Gt=N?.review??null;if(I.hasFeature("reviewmode"))try{let Te=await I.rpc("thread.review",{thread:v});if(x!==z)return;Gt=Te.review??null}catch{}if(x!==z)return;let An="unanswered"in se?se.unanswered??null:N?.unanswered??null,os=se.h??N?.hashes??{};if(je(v,{entries:Sn,ids:tt,olderCursor:pe,review:Gt,unanswered:An,rail:mt,hashes:os}),fe.setThread(_,Sn,Boolean(pe),Gt,An),Be(v,x),Ne)U(Ne);return}let te;try{te=await I.rpc("thread.entries",{thread:v,limit:40})}catch(Le){if(x===z){let se=Le instanceof Error&&Le.message?Le.message:"Could not load messages.";fe.setError(_,se,()=>{Ee(v)})}return}if(x!==z)return;if(te.thread){let Le=k.findIndex((se)=>se.id===te.thread.id);if(Le>=0)k[Le]=te.thread;else k.unshift(te.thread);H()}pe=te.next??null;let ye=null;if(I.hasFeature("reviewmode"))try{let Le=await I.rpc("thread.review",{thread:v});if(x!==z)return;ye=Le.review??null}catch{}if(x!==z)return;let He=te.entries??[],et=te.unanswered??null;je(v,{entries:He,ids:He.map((Le)=>Le.id),olderCursor:pe,review:ye,unanswered:et,rail:N?.rail??[],hashes:N?.hashes??{}}),fe.setThread(_,He,Boolean(pe),ye,et);try{let se=(await I.rpc("subscribe",{topic:"thread",thread:v})).sub??null;if(se!==null){if(x!==z){I.rpc("unsubscribe",{sub:se}).catch(()=>{});return}Ae=se}}catch{}if(x!==z)return;if(V(v,x),Be(v,x),Ne)U(Ne)}async function Be(v,x){if(!v||!I.hasFeature("mgmt")){if(x===z)Je.clear();return}let P=k.find((_)=>_.id===v),N=P?.project?E.find((_)=>_.id===P.project)?.root??"":"";if(!N&&I.hasFeature("viewers"))try{let _=await I.rpc("viewer.files",{thread:v});if(x!==z)return;N=_.pcb||_.sch||_.root||""}catch{}if(x!==z)return;if(N)await Je.watchProject(N);else Je.clear()}async function Ie(v){let x=z;for(let P=0;P<25&&x===z;P++){if(fe.goTo(v))return;if(!pe)return;let N=pe;if(await qe(),pe===N)return}}async function qe(){if(!F||!pe){fe.clearLoadingOlder();return}let v=z,x=F,P=pe;try{let N=await I.rpc("thread.entries",{thread:x,limit:40,before:P});if(v!==z||F!==x)return;pe=N.next??null,fe.prependEntries(N.entries??[],Boolean(pe))}catch{if(v===z)fe.clearLoadingOlder()}}async function De(v){try{let x=await I.rpc("thread.create",{project:v});if(x.thread)k=[x.thread,...k.filter((P)=>P.id!==x.thread.id)],ae.setData(E,k,j,A),ue(),await Ee(x.thread.id),oe.focus()}catch(x){oe.showError(x instanceof Error?x.message:"Could not create thread")}}let Xe=null;function St(v){return(v.split(` -`).map((x)=>x.trim()).find((x)=>x.length>0)??"").slice(0,200)}function We(v){Xe=v,oe.setReply(v?{who:v.role==="user"?b("secret.you","You"):b("model.col.agent","Agent"),line:St(v.text)}:null,()=>{if(Xe)Ie(Xe.id)},()=>We(null))}async function Cn(v,x=[]){if(!F)return;let P=z,N=F,_=na(),te=`local-${_}`,ye=Xe&&v.trim()&&I.hasFeature("reply")?Xe:null;if(ye)We(null);fe.upsertEntry({id:te,kind:"user",text:v,at:Date.now(),clientId:_,...ye?{replyTo:{id:ye.id,quote:St(ye.text)}}:{},attachments:x.map((He)=>({name:He.name,mime:He.mime,previewUrl:`data:${He.mime};base64,${He.data}`}))});try{let He={thread:N,text:v,clientId:_};if(x.length>0)He.attachments=x;if(ye)He.replyTo={id:ye.id,text:ye.text};let et=await I.rpc("message.send",He);if(P!==z||F!==N)return;if(et.entry)fe.upsertEntry(et.entry)}catch(He){if(P===z&&F===N){if(fe.removeEntry(te),oe.setDraft(v),ye&&!Xe)We(ye);oe.showError(He instanceof Error?He.message:"Failed to send message")}}}async function kn(v){if(!F)return;let x=z,P=F;try{let N=await I.rpc("composer.run",{thread:P,text:v});if(x!==z||F!==P)return;if(N.error)oe.setDraft(v),oe.showError(N.error);else if(N.kind==="edit"&&typeof N.text==="string")oe.setDraft(N.text);else if(N.kind==="project")Ue.open({mode:"folder"});else if(N.kind==="clone")Ue.open({mode:"clone",repo:N.repo??"",text:N.text??""})}catch(N){if(x===z&&F===P)oe.setDraft(v),oe.showError(N instanceof Error?N.message:"Command refused")}}async function Qe(v,x){try{let P=await I.rpc("thread.act",{thread:v,action:x});if(P.thread){if(k=k.map((N)=>N.id===P.thread.id?P.thread:N),ae.setData(E,k,j,A),P.thread.id===F)fe.updateThreadMeta(P.thread),H()}ue()}catch(P){oe.showError(P instanceof Error?P.message:`Action "${x}" not allowed`)}}function Ln(v,x){if(!v||!v.text||x-v.at>=300000)return"";let P=v.build.split("-").pop()??"";if(v.reason==="build"&&P)return b("hub.restarting.build",v.text,{build:P});if(v.reason==="stop")return b("hub.stopped",v.text);return b("hub.restarting",v.text)}function At(v){if(v==="connected")ae.setConnStatus(b("gpui.acct.connected","Connected"),"bp-ok");else if(v==="reconnecting"&&Ln(I.restarting,Date.now()))ae.setConnStatus(Ln(I.restarting,Date.now()),"");else if(v==="reconnecting")ae.setConnStatus("Reconnecting…","bp-warn");else if(v==="revoked")ae.setConnStatus(b("gpui.acct.sign.in.expired","Sign-in expired"),"bp-bad");else ae.setConnStatus("Connecting…","")}Pt(()=>{At(I.getState()),R.textContent=b("gpui.improvements","Improvements"),re.title=b("palette.settings","Settings"),re.setAttribute("aria-label",b("palette.settings","Settings")),H(),ae.refreshLocale(),fe.refreshLocale(),oe.refreshLocale(),Ge.render(),ze.refreshLocale(),Ue.refreshLocale()}),I.onState((v,x)=>{if(v==="connected"&&x){if(x.locale)In(x.locale);if(x.theme)as(x.theme);if(x.name)ae.setHostName(x.name);if(it=x.home??null,ae.setHome(it),ze.isOpen())ze.refresh();At(v);let P=typeof x.hubBack==="string"?String(x.hubBack):"";if(P)try{let N=JSON.parse(P);if(N.reason==="crash")ae.setConnStatus(b("hub.back.crash",N.text??""),"bp-warn"),window.setTimeout(()=>At(I.getState()),6000)}catch{}if(oe.setFeatures(I.hasFeature("images"),I.hasFeature("voice")),Array.isArray(x.commands))ee=x.commands,oe.setCommands(ee);else ee=[];Me(),Ue.reconcile()}else nt.cancel(),At(v)}),I.onFrame((v)=>{if(v.t==="voice"){nt.handleFrame(v);return}if(v.t==="info"&&v.info&&typeof v.info==="object"){Je.handleInfo(v.info);return}if(v.t!=="d")return;let x=v;if(x.k==="clone"||x.k==="clone.repos"||x.k==="clone.signin"){Ue.handleFrame(x);return}switch(x.k){case"project":{let P=x.project;if(!P)break;let N=E.findIndex((_)=>_.id===P.id);if(N>=0)E[N]=P;else E.unshift(P);ae.setData(E,k,j,A),H(),ve();break}case"thread":{let P=x.thread;if(!P)break;let N=k.findIndex((_)=>_.id===P.id);if(N>=0)k[N]=P;else k.unshift(P);if(ae.setData(E,k,j,A),P.id===F)fe.updateThreadMeta(P),H(),oe.setState(!0,P.state==="working");ve();break}case"thread.removed":{let P=String(x.id??"");k=k.filter((N)=>N.id!==P),ae.setData(E,k,j,A),ve();break}case"entry":{if(x.thread===F&&x.entry)fe.upsertEntry(x.entry);break}case"text":{if(x.thread===F)fe.appendLiveText(String(x.entry??""),String(x.append??""),Number(x.at??Date.now()));break}case"turn":{if(x.thread===F){let P=String(x.state??"idle");oe.setState(!0,P==="working"),V(F,z)}ve();break}case"btw":{if(x.thread===F)fe.showBtw(String(x.q??""),String(x.a??""));break}case"unanswered":{if(x.thread===F)fe.setUnanswered(x.unanswered??null);break}case"theme":{if(typeof x.theme==="string")as(x.theme);break}case"home":{if(it=x.home??null,ae.setHome(it),ze.isOpen())ze.refresh();break}default:break}}),window.addEventListener("keydown",(v)=>{let x=v.key.toLowerCase();if((v.ctrlKey||v.metaKey)&&(x==="k"||v.shiftKey&&x==="p"))if(v.preventDefault(),$e.isOpen())$e.close();else $e.open();else if(v.key==="Escape"){if($e.isOpen())$e.close();else if(Ue.isOpen())Ue.escape();else if(ze.isOpen())ze.close();else if(fe.closePlanRevise());else if(Je.isOpen())Je.closePanel()}}),I.connect()}if(document.readyState==="loading")document.addEventListener("DOMContentLoaded",rs);else rs(); +`;function qe(e){let t=e/255;return t<=0.04045?t/12.92:Math.pow((t+0.055)/1.055,2.4)}var Zs=[qe(77),qe(83),qe(94)],Qs=[qe(53),qe(58),qe(67)],er=[qe(245),qe(246),qe(248)],tr=[qe(225),qe(228),qe(233)];function is(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 ss(e,t,n){let i=is(e,e.VERTEX_SHADER,t),s=is(e,e.FRAGMENT_SHADER,n),r=e.createProgram();if(!r)throw Error("createProgram failed");if(e.attachShader(r,i),e.attachShader(r,s),e.linkProgram(r),e.deleteShader(i),e.deleteShader(s),!e.getProgramParameter(r,e.LINK_STATUS)){let a=e.getProgramInfoLog(r)||"program link error";throw e.deleteProgram(r),Error(a)}return r}function nr(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 ir(e,t,n,i){let s=1/Math.tan(e*0.5),r=1/(n-i),a=new Float32Array(16);return a[0]=s/t,a[5]=s,a[10]=(i+n)*r,a[11]=-1,a[14]=2*i*n*r,a}function rs(e){let t=Math.hypot(e[0],e[1],e[2])||1;return[e[0]/t,e[1]/t,e[2]/t]}function as(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 Cn(e,t){return e[0]*t[0]+e[1]*t[1]+e[2]*t[2]}class kn{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=ss(n,zs,Js),this.bgVao=n.createVertexArray(),this.uBgTop=n.getUniformLocation(this.bgProg,"uBgTop"),this.uBgBot=n.getUniformLocation(this.bgProg,"uBgBot"),this.prog=ss(n,Ys,Xs),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=Ui(e.mesh),this.clearParts(),this.cbs.onStatus?.("Building 3D model…");let n=new Uint8Array(e.mesh),i=e.faces instanceof Uint8Array?new Uint8Array(e.faces):void 0,s=[n.buffer];if(i)s.push(i.buffer);this.worker?.postMessage({id:this.nextJobId++,kind:"solid",key:t,n:e.n,mesh:n,faces:i},s);return}if(e.parts&&typeof e.parts==="object"&&!Array.isArray(e.parts)&&!(e.parts instanceof Uint8Array)){if(this.activeKey&&t!==this.activeKey)return;if(this.activeKey=t,this.clearParts(),this.partsTotal=typeof e.parts.of==="number"?e.parts.of:0,this.partsDone=0,this.partsTotal>0)this.cbs.onStatus?.(`Loading parts 0/${this.partsTotal}…`);this.scheduleDraw();return}if(typeof e.part==="string"&&e.mesh instanceof Uint8Array&&e.at instanceof Uint8Array&&typeof e.n==="number"){if(this.activeKey&&t!==this.activeKey)return;let n=new Uint8Array(e.mesh),i=new Uint8Array(e.at),s=e.faces instanceof Uint8Array?new Uint8Array(e.faces):void 0,r=[n.buffer,i.buffer];if(s)r.push(s.buffer);this.worker?.postMessage({id:this.nextJobId++,kind:"part",key:t,partId:e.part,n:e.n,mesh:n,at:i,faces:s,refs:Array.isArray(e.refs)?e.refs:[],done:typeof e.done==="number"?e.done:0},r)}}onWorkerMessage(e){if(e.error){this.cbs.onStatus?.(e.error);return}if(e.key!==this.activeKey||!this.gl)return;if(e.kind==="solid")this.deleteBatch(this.boardBatch),this.boardBatch=this.uploadBatch(e.positions,e.normals,e.colors,0),this.center=[e.center[0],e.center[1],e.center[2]],this.target=[e.center[0],e.center[1],e.center[2]],this.radius=e.radius,this.fit(),this.cbs.onStatus?.(""),this.scheduleDraw();else if(e.kind==="part"){let t=this.uploadBatch(e.positions,e.normals,e.colors,performance.now());if(t)this.partBatches.push(t);if(this.partsDone=e.done||this.partsDone+1,this.partsTotal>0&&this.partsDone>>24===0)r++;else a++;let o=r>0?new Float32Array(r*9):null,c=r>0?new Float32Array(r*9):null,u=r>0?new Float32Array(r*12):null,l=a>0?new Float32Array(a*9):null,p=a>0?new Float32Array(a*9):null,d=a>0?new Float32Array(a*12):null,g=0,y=0;for(let f=0;f>>24&255,A=1-C/255,M=(w>>>16&255)/255,S=(w>>>8&255)/255,T=(w&255)/255,B=f*9;if(C===0&&o&&c&&u){let R=g*9;for(let H=0;H<9;H++)o[R+H]=e[B+H],c[R+H]=t[B+H];let O=g*12;for(let H=0;H<3;H++)u[O+H*4]=M,u[O+H*4+1]=S,u[O+H*4+2]=T,u[O+H*4+3]=1;g++}else if(l&&p&&d){let R=y*9;for(let H=0;H<9;H++)l[R+H]=e[B+H],p[R+H]=t[B+H];let O=y*12;for(let H=0;H<3;H++)d[O+H*4]=M,d[O+H*4+1]=S,d[O+H*4+2]=T,d[O+H*4+3]=A;y++}}let m=o&&c&&u?this.createSubBatch(o,c,u,r*3):null,h=l&&p&&d?this.createSubBatch(l,p,d,a*3):null;if(!m&&!h)return null;return{opaque:m,translucent:h,fadeStartMs:i}}deleteSubBatch(e){let t=this.gl;if(!t||!e)return;t.deleteVertexArray(e.vao),t.deleteBuffer(e.posBuf),t.deleteBuffer(e.nrmBuf),t.deleteBuffer(e.colBuf)}deleteBatch(e){if(!e)return;this.deleteSubBatch(e.opaque),this.deleteSubBatch(e.translucent)}clearParts(){for(let e of this.partBatches)this.deleteBatch(e);this.partBatches=[]}fit(){this.setView("fit")}setView(e){let t=35*Math.PI/180;this.dist=this.radius/Math.sin(t*0.5)*1.15,this.target=[this.center[0],this.center[1],this.center[2]];let{yaw:n,pitch:i}=ns(e);this.yaw=n,this.pitch=i,this.scheduleDraw()}snapPng(){return this.draw(performance.now()),new Promise((e)=>{this.canvas.toBlob((t)=>e(t),"image/png")})}scheduleDraw(){if(this.dirty)return;this.dirty=!0,this.rafId=requestAnimationFrame((e)=>{if(this.dirty=!1,this.rafId=0,this.draw(e))this.scheduleDraw()})}drawSubBatch(e){if(!e||!this.gl)return;this.gl.bindVertexArray(e.vao),this.gl.drawArrays(this.gl.TRIANGLES,0,e.vertCount)}draw(e){let t=this.gl;if(!t||!this.prog)return!1;let n=this.canvas.getBoundingClientRect(),i=Math.max(1,Math.round(n.width)),s=Math.max(1,Math.round(n.height)),r=Math.min(window.devicePixelRatio||1,2),a=Math.round(i*r),o=Math.round(s*r);if(this.canvas.width!==a||this.canvas.height!==o)this.canvas.width=a,this.canvas.height=o;if(t.viewport(0,0,a,o),!this.boardBatch&&this.partBatches.length===0)return!1;if(t.depthMask(!0),t.clear(t.DEPTH_BUFFER_BIT),this.bgProg&&this.bgVao){t.disable(t.DEPTH_TEST),t.disable(t.BLEND),t.depthMask(!1),t.useProgram(this.bgProg);let R=this.lightTheme?er:Zs,O=this.lightTheme?tr:Qs;t.uniform3f(this.uBgTop,R[0],R[1],R[2]),t.uniform3f(this.uBgBot,O[0],O[1],O[2]),t.bindVertexArray(this.bgVao),t.drawArrays(t.TRIANGLE_STRIP,0,4),t.bindVertexArray(null)}let c=Math.cos(this.pitch),u=Math.sin(this.pitch),l=Math.cos(this.yaw),p=Math.sin(this.yaw),d=[this.target[0]+this.dist*c*p,this.target[1]-this.dist*c*l,this.target[2]+this.dist*u],g=rs([this.target[0]-d[0],this.target[1]-d[1],this.target[2]-d[2]]),y=Math.abs(g[2])>0.99?[0,1,0]:[0,0,1],m=rs(as(g,y)),h=as(m,g),f=new Float32Array([m[0],h[0],-g[0],0,m[1],h[1],-g[1],0,m[2],h[2],-g[2],0,-Cn(m,d),-Cn(h,d),Cn(g,d),1]),w=Math.max(0.05,this.dist*0.01),C=Math.max(this.dist*10,this.radius*20),A=ir(35*Math.PI/180,a/o,w,C),M=nr(A,f);t.useProgram(this.prog),t.uniformMatrix4fv(this.uMvp,!1,M),t.uniform3f(this.uEye,d[0],d[1],d[2]),t.uniform3f(this.uRight,m[0],m[1],m[2]),t.uniform3f(this.uUp,h[0],h[1],h[2]),t.uniform3f(this.uFwd,g[0],g[1],g[2]);let S=!1,T=[],B=[];for(let R of this.partBatches){let O=e-R.fadeStartMs,H=R.fadeStartMs===0?1:Math.min(1,Math.max(0,O/300));if(H<1){if(S=!0,H>0)B.push({batch:R,fade:H})}else T.push(R)}if(t.enable(t.DEPTH_TEST),t.depthMask(!0),t.disable(t.BLEND),t.uniform1f(this.uFade,1),this.boardBatch)this.drawSubBatch(this.boardBatch.opaque);for(let R of T)this.drawSubBatch(R.opaque);if(t.depthMask(!1),t.enable(t.BLEND),t.uniform1f(this.uFade,1),this.boardBatch)this.drawSubBatch(this.boardBatch.translucent);for(let R of T)this.drawSubBatch(R.translucent);for(let{batch:R,fade:O}of B)t.uniform1f(this.uFade,O),this.drawSubBatch(R.opaque),this.drawSubBatch(R.translucent);return t.depthMask(!0),t.bindVertexArray(null),S}onPointerDown=(e)=>{if(this.canvas.setPointerCapture(e.pointerId),this.pointers.set(e.pointerId,{x:e.clientX,y:e.clientY,button:e.button,shift:e.shiftKey}),this.pointers.size===2){let[t,n]=Array.from(this.pointers.values());this.pinchDist=Math.hypot(n.x-t.x,n.y-t.y)||1}};onPointerMove=(e)=>{let t=this.pointers.get(e.pointerId);if(!t)return;let n=e.clientX-t.x,i=e.clientY-t.y;if(t.x=e.clientX,t.y=e.clientY,this.pointers.size===2){let[s,r]=Array.from(this.pointers.values()),a=Math.hypot(r.x-s.x,r.y-s.y)||1;if(this.pinchDist>0)this.dist=Math.max(this.radius*0.05,Math.min(this.radius*20,this.dist*(this.pinchDist/a)));this.pinchDist=a,this.cbs.onUserMove?.(),this.scheduleDraw();return}if(t.button===2||t.button===1||t.shift){let s=this.dist*0.0014,r=Math.cos(this.yaw),a=Math.sin(this.yaw);this.target[0]-=n*r*s,this.target[1]-=n*a*s,this.target[2]+=i*s}else this.yaw+=n*0.008,this.pitch=Math.max(-Math.PI*0.49,Math.min(Math.PI*0.49,this.pitch+i*0.008));this.cbs.onUserMove?.(),this.scheduleDraw()};onPointerUp=(e)=>{if(this.pointers.delete(e.pointerId),this.pointers.size<2)this.pinchDist=0};onWheel=(e)=>{e.preventDefault();let t=e.deltaY<0?0.8620689655172414:1.16;this.dist=Math.max(this.radius*0.05,Math.min(this.radius*20,this.dist*t)),this.cbs.onUserMove?.(),this.scheduleDraw()};onDblClick=()=>{this.fit()};onContextMenu=(e)=>{e.preventDefault()};destroy(){if(this.rafId)cancelAnimationFrame(this.rafId);if(this.resizeObs.disconnect(),this.canvas.removeEventListener("pointerdown",this.onPointerDown),this.canvas.removeEventListener("pointermove",this.onPointerMove),this.canvas.removeEventListener("pointerup",this.onPointerUp),this.canvas.removeEventListener("pointercancel",this.onPointerUp),this.canvas.removeEventListener("wheel",this.onWheel),this.canvas.removeEventListener("dblclick",this.onDblClick),this.canvas.removeEventListener("contextmenu",this.onContextMenu),this.deleteBatch(this.boardBatch),this.clearParts(),this.gl){if(this.bgVao)this.gl.deleteVertexArray(this.bgVao);if(this.bgProg)this.gl.deleteProgram(this.bgProg);if(this.prog)this.gl.deleteProgram(this.prog)}this.worker?.terminate(),this.canvas.remove()}}var os=64,sr=16777216;function rr(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 At(e){if(!e)return"";let t=e.replace(/\\/g,"/").replace(/\/+$/,""),n=t.lastIndexOf("/");return n>=0?t.slice(n+1):t}function ls(e){switch(e){case"board":return b("viewer.board","Board");case"schematic":return b("viewer.schematic","Schematic");case"3d":return b("viewer.solid","3D");case"gerbers":return b("gpui.gerbers","Gerbers");case"mech":return b("viewer.mech","Mech");case"files":return b("viewer.files","Files");case"diff":return b("viewer.diff","Diff");case"review":return b("viewer.review","Review");case"browser":return b("bots.tab.browser","Browser");case"terminal":return b("viewer.terminal","Terminal");default:return e?e.charAt(0).toUpperCase()+e.slice(1):""}}function An(e){return e==="board"||e==="schematic"||e==="gerbers"}function ar(e){return e==="files"||e==="diff"||e==="review"||e==="browser"||e==="terminal"}function Ln(e,t){let n=document.createElement("div");n.className="bp-vh";let i=document.createElement("div");i.className="bp-vh-title";let s=document.createElement("span");s.className="bp-vh-page";let r=document.createElement("span");r.className="bp-vh-sep",r.textContent="·",r.hidden=!0;let a=document.createElement("span");a.className="bp-vh-file",a.hidden=!0,i.append(s,r,a);let o=document.createElement("div");o.className="bp-vh-actions",n.append(i,o);let c=document.createElement("div");c.className="bp-solid-bar",c.setAttribute("data-testid","solid-presets-bar"),c.hidden=!0;let u=document.createElement("div");u.className="bp-v-banner",u.hidden=!0;let l=document.createElement("div");l.className="bp-v-stage-wrap";let p=document.createElement("div");p.className="bp-v-stage";let d=document.createElement("div");d.className="bp-v-overlay",d.hidden=!0;let g=document.createElement("div");g.className="bp-v-layers",g.hidden=!0;let y=document.createElement("div");y.className="bp-v-info",y.hidden=!0,l.append(p,d,g,y);let m=document.createElement("div");m.className="bp-history-bar",m.setAttribute("data-testid","viewer-history-bar"),m.hidden=!0,e.replaceChildren(n,c,u,l,m);let h="",f="",w=0,C=!1,A=new Set,M=[],S=0,T=new Map,B=new Map,R={},O=[],H="",ae="",ue=!1,oe=!1,we=0,Le=!1,Ne=0,he="",be=0,I=null,le=null,ne=null,X=null,ce=null,E=new xn,k=0,j=!1,P="",K="",ee="",D="";document.addEventListener("click",(F)=>{if(!j)return;if(F.target instanceof Node&&m.contains(F.target))return;j=!1,me()}),document.addEventListener("keydown",(F)=>{if(j&&F.key==="Escape")j=!1,me()});function z(){if(k)window.clearInterval(k),k=0;E.playing=!1}function je(){let F=f==="3d"||f==="mech";if(c.hidden=!F,!F)return;if(c.childElementCount>0)return;for(let W of ts){let V=document.createElement("button");V.type="button",V.className="bp-v-btn",V.textContent=W.label,V.setAttribute("data-testid",`solid-view-${W.id}`),V.addEventListener("click",()=>{ne?.setView(W.id)}),c.append(V)}let U=document.createElement("button");U.type="button",U.className="bp-v-btn",U.textContent="Snap view",U.setAttribute("data-testid","solid-snap"),U.addEventListener("click",()=>{if(!ne)return;ne.snapPng().then((W)=>{if(!W)return;let V=URL.createObjectURL(W),G=document.createElement("a");G.href=V;let Z=(He()||f||"view").replace(/[^a-zA-Z0-9._-]/g,"_");G.download=`${Z}-snap.png`,G.click(),setTimeout(()=>URL.revokeObjectURL(V),1000)})}),c.append(U)}async function Se(){if(!h||f!=="board"&&f!=="schematic")return;me();let F=E.compareRequest();if(!F){P="",K="",ee="",D="",await $e(!1);return}let U=`${f}|${F.commit}|${F.bits}|${ae}`;if(U===D&&A.size>0){ke(E.highlightEdits?`Comparing against ${E.activeRef()?.label||F.commit.slice(0,7)} (edits highlighted)`:`Comparing against ${E.activeRef()?.label||F.commit.slice(0,7)}`,!1);return}let W=++w;A.clear(),T.clear(),Ye(),C=!0,P="",K=F.commit,ee="",D=U;try{let V=ae||(f==="schematic"?R.sch:R.pcb)||"";if(!V){let Ce=await t.hub.rpc("viewer.files",{thread:h});if(W!==w)return;R=Ce||{},re(),V=(f==="schematic"?R.sch:R.pcb)||""}if(!V)throw Error(`Unable to resolve ${f} file path for compare`);let G=await t.hub.rpc("viewer.compare",{thread:h,kind:f,commit:F.commit,bits:F.bits,...ae?{path:ae}:{}});if(W!==w)return;let Z=typeof G?.root==="string"?G.root:"",Q=f==="schematic"?"1":"0";P=Z?`${Q}|${Z}|diff +`:`${Q}|`,K=F.commit,ee=V.startsWith("/")||/^[A-Za-z]:[\\/]/.test(V)||!Z?V:`${Z.replace(/\/+$/,"")}/${V.replace(/^\/+/,"")}`,C=!1;let xe=M;Ye();for(let Ce of xe)if(Ce.kind==="bin")Ge(Ce.buf);else We(Ce.key,Ce.none,Ce.retryable);ke(E.highlightEdits?`Comparing against ${E.activeRef()?.label||F.commit.slice(0,7)} (edits highlighted)`:`Viewing snapshot: ${E.activeRef()?.label||F.commit.slice(0,7)}`,!1)}catch(V){if(W!==w)return;C=!1,P="",K="",ee="",D="",Ye(),ke(V instanceof Error?V.message:String(V),!0)}}function me(){let F=f==="board"||f==="schematic";if(m.hidden=!F,!F)return;let U=document.createElement("div");U.className="bp-history-group";let W=document.createElement("button");W.type="button",W.className="bp-v-btn",W.textContent="<",W.title="Older snapshot",W.disabled=E.refs.length===0||E.index>=E.refs.length-1,W.setAttribute("data-testid","history-prev"),W.addEventListener("click",()=>{if(z(),E.step(1))Se()});let V=document.createElement("button");V.type="button",V.className="bp-v-btn"+(E.playing?" is-on":""),V.textContent=E.playing?"⏸":"▶",V.title=E.playing?"Pause history":"Play history",V.disabled=E.refs.length===0,V.setAttribute("data-testid","history-play"),V.addEventListener("click",()=>{if(E.playing){z(),me();return}if(E.refs.length===0)return;if(E.playing=!0,E.isLive())E.index=E.refs.length-1,Se();else me();k=window.setInterval(()=>{if(!E.playing||f!=="board"&&f!=="schematic"){z(),me();return}if(E.step(-1))Se();else z(),me()},1400)});let G=document.createElement("button");G.type="button",G.className="bp-v-btn",G.textContent=">",G.title="Newer snapshot",G.disabled=E.isLive(),G.setAttribute("data-testid","history-next"),G.addEventListener("click",()=>{if(z(),E.step(-1))Se()});let Z=document.createElement("button");Z.type="button",Z.className="bp-v-btn"+(E.isLive()?" is-on":""),Z.textContent="Live",Z.setAttribute("data-testid","history-live"),Z.addEventListener("click",()=>{if(z(),E.goLive())ke("",!1),Se()});let Q=document.createElement("span");Q.className="bp-history-label",Q.setAttribute("data-testid","history-label");let xe=E.activeRef();Q.textContent=xe?xe.label||xe.commit.slice(0,7):E.refs.length>0?`Live (${E.refs.length} saved)`:"Live",U.append(W,V,G,Z,Q);let Ce=document.createElement("div");Ce.className="bp-history-group";let Pe=document.createElement("button");Pe.type="button",Pe.className="bp-v-btn"+(E.highlightEdits?" is-on":""),Pe.textContent="Highlight edits",Pe.disabled=E.refs.length===0,Pe.setAttribute("data-testid","history-highlight"),Pe.addEventListener("click",()=>{z(),E.toggleHighlight(),Se()});let Re=document.createElement("div");Re.className="bp-history-menu-wrap";let ye=document.createElement("button");if(ye.type="button",ye.className="bp-v-btn"+(j||!E.isLive()?" is-on":""),ye.disabled=E.refs.length===0,ye.setAttribute("data-testid","history-compare"),ye.setAttribute("aria-haspopup","menu"),ye.setAttribute("aria-expanded",String(j)),ye.textContent=xe?`Compare: ${xe.label||xe.commit.slice(0,7)} ▾`:"Compare ▾",ye.addEventListener("click",(Te)=>{Te.stopPropagation(),j=!j,me()}),Re.append(ye),j&&E.refs.length>0){let Te=document.createElement("div");Te.className="bp-history-menu",Te.setAttribute("role","menu"),Te.setAttribute("data-testid","history-compare-menu");let Ke=(Ie,mt,Nt)=>{let ze=document.createElement("button");ze.type="button",ze.className="bp-history-menu-item"+(Nt?" is-active":""),ze.setAttribute("role","menuitem"),ze.setAttribute("data-commit",mt),ze.textContent=Ie,ze.addEventListener("click",()=>{if(j=!1,z(),E.selectCommit(mt)){if(E.isLive())ke("",!1);Se()}else me()}),Te.append(ze)};Ke("Live (working tree)","",E.isLive());for(let Ie of E.refs)Ke(Ie.label||Ie.commit.slice(0,7),Ie.commit,xe?.commit===Ie.commit);Re.append(Te)}Ce.append(Pe,Re),m.replaceChildren(U,Ce)}async function Me(F){if(!F)return;try{let U=await t.hub.rpc("viewer.refs",{thread:F});if(F!==h)return;E.setRefs(Array.isArray(U?.refs)?U.refs:[]),me()}catch{if(F!==h)return;E.setRefs([]),me()}}function Y(){return document.documentElement.classList.contains("light")}let fe=new MutationObserver(()=>{let F=Y();le?.setTheme(F),ne?.setTheme(F),ce?.setTheme(F)});fe.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]});function ie(F,U="",W=!1){if(F==="none"){d.hidden=!0,d.replaceChildren();return}d.hidden=!1,d.className=`bp-v-overlay is-${F}`;let V=document.createElement("div");V.className="bp-v-state-card";let G=document.createElement("div");if(G.className="bp-v-state-msg",G.textContent=U,V.append(G),W){let Z=document.createElement("button");Z.type="button",Z.className="bp-v-btn is-primary",Z.textContent=b("tools.retry","Retry"),Z.addEventListener("click",()=>void $e(!0)),V.append(Z)}d.replaceChildren(V)}function ke(F,U){u.textContent=F,u.hidden=!F,u.classList.toggle("is-warn",U)}function He(){if(ae)return At(ae);if(f==="board"||f==="3d")return At(R.pcb);if(f==="schematic")return At(R.sch);if(f==="mech")return At(H);return""}function re(){s.textContent=ls(f);let F=He();if(r.hidden=!F,a.hidden=!F,a.textContent=F,o.replaceChildren(),f==="mech"&&O.length>1){let W=document.createElement("select");W.className="bp-v-select",W.setAttribute("aria-label",b("viewer.mech","Mech"));for(let V of O){let G=document.createElement("option");G.value=V,G.textContent=At(V),G.selected=V===H,W.append(G)}W.addEventListener("change",()=>{H=W.value,re(),$e(!1)}),o.append(W)}if(An(f)){let W=document.createElement("button");W.type="button",W.className="bp-v-btn"+(Le?" is-on":""),W.textContent=I?.layerHead||"Layers",W.setAttribute("data-testid","viewer-layers-btn"),W.addEventListener("click",()=>{if(Le=!Le,g.hidden=!Le,W.classList.toggle("is-on",Le),Le)_e("","")}),o.append(W)}if(f==="board"||f==="schematic"||f==="3d"||f==="mech"||f==="gerbers"){let W=document.createElement("button");W.type="button",W.className="bp-v-btn",W.textContent="Fit",W.setAttribute("data-testid","viewer-fit-btn"),W.addEventListener("click",()=>{le?.fit(),ne?.fit()}),o.append(W)}if((f==="board"||f==="schematic")&&t.hub.hasFeature("follow")){let W=document.createElement("button");W.type="button",W.className="bp-v-btn"+(ue&&!oe?" is-on":""),W.textContent=ue?oe?b("gpui.follow.paused","Follow (paused)"):"Follow agent":"Follow agent",W.setAttribute("data-testid","viewer-follow-btn"),W.addEventListener("click",()=>void tt()),o.append(W)}let U=document.createElement("button");U.type="button",U.className="bp-v-btn bp-v-close",U.textContent="✕",U.title=b("common.close","Close"),U.setAttribute("aria-label",b("common.close","Close")),U.setAttribute("data-testid","viewer-close-btn"),U.addEventListener("click",()=>t.closeViewer()),o.append(U)}function ge(){if(!I){g.replaceChildren();return}let F=document.createDocumentFragment(),U=document.createElement("div");U.className="bp-v-layers-head";let W=document.createElement("span");if(W.textContent=I.layerHead||"Layers",U.append(W),I.layerReset){let Q=document.createElement("button");Q.type="button",Q.className="bp-v-btn",Q.textContent="Reset",Q.addEventListener("click",()=>void _e("reset","")),U.append(Q)}if(F.append(U),I.layerModes){let Q=document.createElement("div");Q.className="bp-v-layers-modes",["All","Dim","Only"].forEach((xe,Ce)=>{let Pe=document.createElement("button");Pe.type="button",Pe.className="bp-v-btn"+(I?.layerMode===Ce?" is-on":""),Pe.textContent=xe,Pe.addEventListener("click",()=>void _e("mode",String(Ce))),Q.append(Pe)}),F.append(Q)}let V=le?.presentColors()??new Map,G=(I.layerList||[]).concat(I.layerMarks||[]),Z=document.createElement("div");Z.className="bp-v-layers-list";for(let Q of G){let xe=V.get(Q.layer);if(xe===void 0)continue;let Ce=document.createElement("div");Ce.className="bp-v-layer-row"+(Q.active?" is-focus":"");let Pe=document.createElement("input");Pe.type="checkbox",Pe.checked=Q.on!==!1,Pe.addEventListener("change",()=>void _e("toggle",String(Q.layer)));let Re=document.createElement("span");Re.className="bp-v-layer-swatch";let ye=xe>>>16&255,Te=xe>>>8&255,Ke=xe&255;Re.style.background=Q.on!==!1?`rgb(${ye},${Te},${Ke})`:`rgba(${ye},${Te},${Ke},0.2)`;let Ie=document.createElement("button");Ie.type="button",Ie.className="bp-v-layer-name",Ie.textContent=Q.name,Ie.addEventListener("click",()=>void _e("pick",String(Q.layer))),Ce.append(Pe,Re,Ie),Z.append(Ce)}F.append(Z),g.replaceChildren(F)}async function _e(F,U){if(!An(f))return;let W=w;try{let V=await t.hub.rpc("viewer.layers",{kind:f,present:be,off:Ne,focus:he,...F?{action:F,value:U}:{}});if(W!==w||!V)return;Ne=Number(V.own)||0,he=typeof V.focus==="string"?V.focus:"",I=V;let G={off:Number(V.off)||0,dim:Number(V.dim)||0,lift:typeof V.lift==="number"?V.lift:255};if(le?.setLayers(G),re(),Le)ge()}catch{}}async function Ue(){if(!ue||oe||!h||!t.hub.hasFeature("follow"))return;oe=!0,re();try{await t.hub.rpc("viewer.follow",{thread:h,action:"pause"})}catch{}}async function tt(){if(!h||!t.hub.hasFeature("follow"))return;let F=!ue?"on":oe?"resume":"off";try{let U=await t.hub.rpc("viewer.follow",{thread:h,action:F});if(ue=!!U.on,oe=!!U.paused,re(),U.on&&!U.paused&&U.focus&&Array.isArray(U.focus.box)&&U.focus.box.length===4&&(U.seq||0)>we)we=U.seq||we,le?.zoomToBoxMm([U.focus.box[0],U.focus.box[1],U.focus.box[2],U.focus.box[3]])}catch{}}function de(){y.hidden=!0,y.replaceChildren(),le?.setHighlights([])}function dt(F){let U=F.split(";").filter(Boolean),W=U.shift()||F,V=[],G="",Z="";for(let Re of U){if(Re.startsWith("g="))continue;let ye=Re.indexOf("=");if(ye>0){let Te=Re.slice(0,ye),Ke=Re.slice(ye+1);if((Te==="ref"||Te==="symbol")&&!G)G=Ke;if(Te==="net"&&!Z)Z=Ke;V.push([Te,Ke])}else V.push([Re,""])}let Q=document.createElement("div");Q.className="bp-v-info-head";let xe=document.createElement("span");xe.className="bp-v-info-title",xe.textContent=W;let Ce=document.createElement("button");Ce.type="button",Ce.className="bp-v-info-x",Ce.textContent="×",Ce.setAttribute("aria-label","Clear selection"),Ce.addEventListener("click",de),Q.append(xe,Ce);let Pe=document.createElement("div");Pe.className="bp-v-info-rows";for(let[Re,ye]of V){let Te=document.createElement("span");Te.className="bp-v-info-chip",Te.textContent=ye?`${Re}: ${ye}`:Re,Pe.append(Te)}return y.replaceChildren(Q,...V.length>0?[Pe]:[]),y.hidden=!1,{ref:G||void 0,net:Z||void 0}}async function Je(F){if(!F){de();return}let U=Array.from(A)[0]||"";if(!U)return;let W=w;try{let V=await t.hub.rpc("viewer.info",{key:U,at:F.at,idx:F.idx});if(W!==w)return;let G=typeof V.info==="string"?V.info:"";if(!G){de();return}let{ref:Z,net:Q}=dt(G),xe=[];if(Z)xe.push(["ref",Z]);if(Q)xe.push(["net",Q]);let Ce=[[F.at,F.idx]];for(let[Pe,Re]of xe){let ye=await t.hub.rpc("viewer.probe",{key:U,name:Pe,value:Re});if(W!==w)return;if(Array.isArray(ye.matches))for(let Te of ye.matches)Ce.push(Te)}le?.setHighlights(Ce)}catch{de()}}function pt(){X?.destroy(),X=null,ce?.destroy(),ce=null,le?.destroy(),le=null,ne?.destroy(),ne=null,p.replaceChildren(),Le=!1,g.hidden=!0,y.hidden=!0,y.replaceChildren(),ke("",!1),ie("none")}function Ye(){M=[],S=0}async function $e(F){if(!h||!f)return;let U=++w;if(A.clear(),C=!1,Ye(),pt(),re(),je(),me(),(f==="board"||f==="schematic")&&h)Me(h);if(ar(f)){if(t.hub.rpc("viewer.watch",{thread:h,kind:""}).catch(()=>{}),f==="files")X=Xi(p,t,h,(G,Z)=>{if(f=G,ae=Z,G==="mech")H=Z;$e(!1)});else if(f==="diff")X=Zi(p,t,h);else if(f==="review")X=Qi(p,t,h);else if(f==="browser")X=zi(p,t,h);else if(f==="terminal")ie("loading","Loading terminal…"),import("/assets/terminal.js").then((Z)=>{if(U!==w)return;if(ie("none"),Z?.mountTerminalPane)ce=Z.mountTerminalPane(p,t,h,Y());else ie("error","Terminal chunk missing",!0)},(Z)=>{if(U!==w)return;ie("error",Z instanceof Error?Z.message:String(Z),!0)});return}if(ie("loading","Loading…"),!R.root)try{let G=await t.hub.rpc("viewer.files",{thread:h});if(U!==w)return;R=G||{},re()}catch{}if(f==="gerbers"&&R.hasGerbers===!1){ie("empty","No Gerbers in this project",!1);return}let W=Y();if(f==="3d"||f==="mech")ne=new kn(p,{onStatus:(G,Z)=>{if(Z)ie("none"),ke(G,!1);else if(G)ie("loading",G);else ie("none"),ke("",!1)},onUserMove:()=>void Ue()}),ne.setTheme(W);else if(f==="board"||f==="schematic"||f==="gerbers")le=new wn(p,{onPick:(G)=>void Je(G),onUserMove:()=>void Ue()}),le.setTheme(W);else{ie("empty",`${ls(f)} is not available in this viewer`,!1);return}let V={thread:h};if(F)V.force=!0;if(f==="mech"){if(O.length===0)try{let G=await t.hub.rpc("mech.list",{thread:h});if(U!==w)return;if(O=Array.isArray(G.parts)?G.parts:[],!H)H=G.primary||O[0]||"";re()}catch(G){if(U!==w)return;ie("error",G instanceof Error?G.message:String(G),!0);return}if(!H){ie("empty",b("gpui.rail.no.mech","No mechanical parts in this project"),!1);return}V.kind="3d",V.path=H}else{if(V.kind=f,ae&&(f==="board"||f==="schematic"))V.path=ae;if(f==="3d"&&!F&&ne){let G=ne.keptToken();if(G)V.kept=G}if((f==="board"||f==="schematic"||f==="gerbers")&&!F&&t.hub.hasFeature("keptChunks"))V.keptChunks=Array.from(B.keys())}C=!0,P="",K="",ee="",D="";try{let G=await t.hub.rpc("viewer.watch",V);if(U!==w)return;A=new Set(Array.isArray(G.keys)?G.keys:[]),C=!1;let Z=M;Ye();for(let Q of Z)if(Q.kind==="bin")Ge(Q.buf);else We(Q.key,Q.none,Q.retryable)}catch(G){if(U!==w)return;C=!1,A.clear(),Ye();let Z=G instanceof Error?G.message:String(G),Q=/no gerbers|not in this project|another machine/i.test(Z);ie(Q?"empty":"error",Z,!Q)}}function We(F,U,W){if(C){if(M.length{if(F.t==="plot"&&typeof F.none==="string"&&typeof F.key==="string")We(F.key,F.none,F.retryable===!0)}),Oe=Tt(()=>{if(f)re()}),Pt=(F)=>{if(F.key==="Escape"&&f&&!y.hidden)de()};return window.addEventListener("keydown",Pt),{open(F,U){if(U!==h){if(h=U,R={},O=[],H="",T.clear(),ue=!1,oe=!1,we=0,Ne=0,he="",be=0,I=null,t.hub.hasFeature("follow"))t.hub.rpc("viewer.follow",{thread:U}).then((W)=>{if(U!==h)return;if(ue=!!W.on,oe=!!W.paused,we=Number(W.seq)||0,f)re()}).catch(()=>{})}if(F!==f)z(),E.goLive(),Ne=0,he="",be=0,I=null;f=F,ae="",$e(!1)},reconcileHas(F){if(f&&!rr(f,F))t.closeViewer()},close(){if(w++,C=!1,z(),j=!1,P="",K="",ee="",D="",E.goLive(),c.hidden=!0,m.hidden=!0,Ye(),h)t.hub.rpc("viewer.watch",{thread:h,kind:""}).catch(()=>{});f="",A.clear(),pt()}}}var cs="http://www.w3.org/2000/svg";function Lt(e){let t=document.createElementNS(cs,"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(cs,"path");i.setAttribute("d",n),t.appendChild(i)}return t}function or(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 ds(e,t){if(!e)return!0;if(t==="board"||t==="3d")return e.board!==!1;if(t==="schematic")return e.schematic!==!1;if(t==="mech")return e.mech!==!1;if(t==="gerbers")return e.gerbers!==!1;return!0}function ps(e){if(!e)return;let t=e==="light";document.documentElement.classList.toggle("light",t);try{localStorage.setItem("bp.theme",t?"light":"dark")}catch{}}function lr(){return`web-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`}function ms(){let e=document.getElementById("root");if(!e)return;try{if(localStorage.getItem("bp.theme")==="light")document.documentElement.classList.add("light")}catch{}let t=document.createElement("header");t.className="bp-topbar",t.setAttribute("data-testid","topbar");let n=document.createElement("button");n.type="button",n.className="icon bp-side-toggle",n.textContent="☰",n.title="Toggle sidebar",n.setAttribute("aria-label","Toggle sidebar");let i=document.createElement("div");i.className="bp-brand";let s=document.createElement("img");s.src="/assets/favicon.svg",s.alt="Backplane",s.className="bp-logo";let r=document.createElement("span");r.className="bp-brand-name bp-hide-phone",r.textContent="Backplane";let a=document.createElement("span");a.className="bp-crumb-sep bp-hide-phone",a.textContent="/";let o=document.createElement("span");o.className="bp-crumb-proj bp-hide-phone";let c=document.createElement("span");c.className="bp-crumb-sep bp-hide-phone",c.textContent="/";let u=document.createElement("span");u.className="bp-crumb-thread",u.setAttribute("data-testid","thread-title");let l=document.createElement("span");l.className="bp-plan-top-badge bp-hidden",l.setAttribute("data-testid","plan-top-badge"),i.append(s,r,a,o,c,u,l);let p=document.createElement("div");p.className="bp-top-state bp-hide-phone bp-hidden";let d=document.createElement("span");d.className="bp-top-state-lbl",d.textContent="STATE";let g=document.createElement("span");g.className="bp-dot bp-dot-idle";let y=document.createElement("span");y.className="bp-top-state-word",p.append(d,g,y);let m=document.createElement("div");m.className="bp-top-acts bp-hide-phone bp-hidden";let h=document.createElement("button");h.type="button",h.className="bp-btn-ghost bp-top-act";let f=document.createElement("span");f.textContent=b("menu.pin","Pin"),h.append(Lt(["M12 17v5","M9 3h6l1 7 3 3H5l3-3 1-7z"]),f);let w=document.createElement("button");w.type="button",w.className="bp-btn-ghost bp-top-act";let C=document.createElement("span");C.textContent=b("menu.settle","Settle"),w.append(Lt(["M12 22a10 10 0 1 0 0-20 10 10 0 0 0 0 20z","M9 12l2 2 4-4"]),C);let A=document.createElement("div");A.className="bp-menu-wrap";let M=document.createElement("button");M.type="button",M.className="bp-btn-ghost bp-top-act",M.textContent="▾",M.title="Thread menu",M.setAttribute("aria-label","Thread menu"),M.setAttribute("data-testid","thread-menu-btn");let S=document.createElement("div");S.className="bp-popover bp-hidden",S.setAttribute("data-testid","thread-menu"),A.append(M,S),m.append(h,w,A);let T=document.createElement("div");T.className="bp-top-right";let B=document.createElement("button");B.type="button",B.className="bp-btn-ghost bp-top-act bp-hide-tablet",B.setAttribute("data-testid","improvements-btn");let R=document.createElement("span");R.textContent=b("gpui.improvements","Improvements"),B.append(Lt(["M12 2l2.4 7.4H22l-6.2 4.5 2.4 7.4L12 16.8l-6.2 4.5 2.4-7.4L2 9.4h7.6z"]),R);let O=document.createElement("button");O.type="button",O.className="bp-cmd-box bp-hide-tablet",O.textContent="> Jump or run a command";let H=document.createElement("button");H.type="button",H.className="icon bp-top-icon",H.title="Search",H.setAttribute("aria-label","Search"),H.appendChild(Lt(["M11 19a8 8 0 1 0 0-16 8 8 0 0 0 0 16z","M21 21l-4.3-4.3"]));let ae=document.createElement("button");ae.type="button",ae.className="icon bp-top-icon",ae.title=b("palette.settings","Settings"),ae.setAttribute("aria-label",b("palette.settings","Settings")),ae.setAttribute("data-testid","settings-btn"),ae.appendChild(Lt(["M12 15a3 3 0 1 0 0-6 3 3 0 0 0 0 6z","M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 1 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 1 1-4 0v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 1 1-2.83-2.83l.06-.06a1.65 1.65 0 0 0 .33-1.82 1.65 1.65 0 0 0-1.51-1H3a2 2 0 1 1 0-4h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 1 1 2.83-2.83l.06.06a1.65 1.65 0 0 0 1.82.33H9a1.65 1.65 0 0 0 1-1.51V3a2 2 0 1 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 1 1 2.83 2.83l-.06.06a1.65 1.65 0 0 0-.33 1.82V9c.26.6.85 1 1.51 1H21a2 2 0 1 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z"])),T.append(B,O,H,ae),t.append(n,i,p,m,T);let ue=document.createElement("div");ue.className="bp-body";let oe=document.createElement("aside");oe.className="bp-sidebar",oe.setAttribute("data-testid","sidebar");let we=document.createElement("main");we.className="bp-center";let Le=document.createElement("div");Le.className="bp-right-area bp-hidden",Le.setAttribute("data-testid","right-area");let Ne=document.createElement("div");Ne.className="bp-right-top";let he=document.createElement("section");he.className="bp-viewer-pane bp-hidden",he.setAttribute("data-testid","viewer-pane"),Ne.appendChild(he),Le.appendChild(Ne);let be=document.createElement("nav");be.className="bp-rail",be.setAttribute("aria-label","Viewer rail"),be.setAttribute("data-testid","viewer-rail"),ue.append(oe,we,Le,be),e.append(t,ue);let I=new vn,le=null,ne=new Set,X=0,ce=null,E=[],k=[],j=[],P=[],K=[],ee=[],D="",z=0,je=0,Se=null,me=null,Me="",Y=null,fe=20,ie={},ke=new Map;function He(v,x){ke.delete(v),ke.set(v,x);while(ke.size>fe){let L=ke.keys().next().value;if(L!==void 0)ke.delete(L);else break}}let re=new bn(oe,{onSelectThread:(v)=>{if(v===D&&Se!==null){oe.classList.remove("bp-sidebar-open");return}Ie(v)},onNewThread:(v)=>{Vt(v)},onSelectBot:(v)=>{Ie(v.thread)},onThreadAct:(v,x)=>{Ze(v,x)},onToggleSection:(v)=>{if(ne.has(v))ne.delete(v);else ne.add(v);ye()},onToggleProjectFold:(v)=>{I.rpc("sidebar.act",{action:"project-fold",value:v}).then(()=>ye()).catch(()=>{})},onCollapseSidebar:()=>{oe.classList.remove("bp-sidebar-open"),oe.classList.add("bp-sidebar-collapsed")},onNeedAct:async(v)=>{let x=$t(v,!1);if(!x)return;if(x.kind==="thread"){Ie(x.id);return}if(x.kind!=="call")return;let L=Bi(await I.rpc(x.method,x.params));if(L?.kind==="thread")Ie(L.id);ye()},hasRoomView:!1,onAddProject:()=>We.open({mode:"folder"})}),ge=new Xt(we,{onLoadOlder:()=>{ze()},onGoToEntry:(v)=>{Nt(v)},onOpenAccounts:()=>{F()},onAnswerAsk:(v,x)=>{I.rpc("ask.answer",{ask:v,answer:x}).catch((L)=>{de.showError(L instanceof Error?L.message:"Could not send answer")})},onToggleReview:(v)=>{if(!D)return;let x=z;I.rpc("thread.review",{thread:D,on:v}).then((L)=>{if(x===z)ge.setReview(L.review??null)}).catch(()=>{})},onUnansweredAction:(v,x)=>{if(!D)return;if(v==="again"||v==="thread-again")I.rpc("thread.again",{thread:D,value:x}).catch(()=>{});else I.rpc("thread.act",{thread:D,action:v,value:x}).catch(()=>{})},onReplyEntry:(v)=>{if(!I.hasFeature("reply")){let x=(v.text||"").split(` +`)[0]?.slice(0,100)??"";if(x)de.prependDraft(`> ${x} +`);return}if(!v.text||!v.text.trim()||v.live||v.id.startsWith("local-"))return;ut({id:v.id,text:v.text,role:v.kind==="user"?"user":"assistant"})},onLoadImage:async(v,x)=>{try{let L={entry:v,path:x};if(I.hasFeature("blobs"))L.metaOnly=!0;let N=await I.rpc("message.image",L);if(N.blob&&N.blob.startsWith("/blob/"))return{url:N.blob};if(N.mime&&N.data)return{mime:N.mime,data:N.data}}catch{}return null}});function _e(v){if(!v)return null;if(v.planMode)return v.planMode;if(v.provider==="claude")return{phase:"off",interaction:"default",once:!1};return null}function Ue(v,x){if(!D)return;let L=z,N=D;I.rpc(v,x).then((q)=>{if(L!==z||D!==N)return;if(q.thread){let te=k.findIndex((ve)=>ve.id===q.thread.id);if(te>=0)k[te]=q.thread;else k.unshift(q.thread);re.setData(E,k,j,P),ge.updateThreadMeta(q.thread),G(),de.setState(!0,q.thread.state==="working")}}).catch((q)=>{if(L===z&&D===N)de.showError(q instanceof Error?q.message:"Could not change Plan mode")})}let tt,de=new Qt(we,{onSend:(v,x)=>{Pn(v,x)},onRunCommand:(v)=>{Nn(v)},onInterrupt:()=>{if(D)I.rpc("turn.interrupt",{thread:D}).catch(()=>{})},onQueryMentions:async(v,x)=>{try{return(await I.rpc("mentions.list",{q:v,kind:x,limit:10})).items??[]}catch{return[]}},onToggleVoice:()=>{tt.toggle()},onCyclePlanMode:()=>{let v=k.find((L)=>L.id===D)??null,x=_e(v);if(!x||!D)return;if(x.interaction!=="plan")Ue("thread.planonce",{thread:D,on:!0});else if(x.once)Ue("thread.pick",{thread:D,action:"interaction",value:"plan"});else Ue("thread.pick",{thread:D,action:"interaction",value:"default"})},onSetPlanMode:(v)=>{if(!D)return;if(v==="once")Ue("thread.planonce",{thread:D,on:!0});else if(v==="always")Ue("thread.pick",{thread:D,action:"interaction",value:"plan"});else Ue("thread.pick",{thread:D,action:"interaction",value:"default"})}});tt=new gn(I,{getThreadId:()=>D,getDraft:()=>de.getDraft(),getCaret:()=>de.getCaret(),setDraft:(v)=>de.setDraft(v),setRecording:(v)=>de.setVoiceRecording(v),setLevel:(v)=>de.setVoiceLevel(v),showError:(v)=>de.showError(v)});function dt(){let v=Me!=="",x=Je.isOpen();Le.classList.toggle("bp-hidden",!v&&!x),Le.classList.toggle("bp-has-viewer",v),Le.classList.toggle("bp-has-mgmt",x)}let Je=new ln(Ne,Le,{hub:I,getThreadId:()=>D,getThreadGen:()=>z,onSendText:(v)=>{Pn(v)},onOpenChange:()=>dt()});function pt(v){let x=window.prompt("Rename thread",v.title||"");if(!x||!x.trim())return;I.rpc("thread.act",{thread:v.id,action:"rename",title:x.trim()}).then((L)=>{if(L.thread)k=k.map((N)=>N.id===L.thread.id?L.thread:N),G(),ye()}).catch((L)=>{de.showError(L instanceof Error?L.message:"Could not rename thread")})}function Ye(v){switch(v.type){case"thread":Ie(v.id);break;case"rail":if(!D&&v.id!=="terminal")break;if(Me===v.id)Z();else Q(v.id);break;case"thread-act":if(D)Ze(D,v.action);break;case"new-thread":Vt(v.projectId);break;case"rename":{let x=k.find((L)=>L.id===D);if(x)pt(x);break}case"prev-thread":case"next-thread":{let x=k.filter((te)=>!te.archived&&!te.swarm);if(x.length<2)break;let L=x.findIndex((te)=>te.id===D),N=v.type==="next-thread"?1:-1,q=x[(L<0?0:L+N+x.length)%x.length];if(q)Ie(q.id);break}case"command":if(v.runDirectly)Nn(v.word);else de.setDraft(`${v.word} `),de.focus();break;case"improvements":V();break;case"settings":Oe.open();break;case"sidebar":oe.classList.toggle("bp-sidebar-open"),oe.classList.toggle("bp-sidebar-collapsed");break}}let $e=new cn(e,{getState:()=>({selectedThreadId:D,threads:k,projects:E,bots:j,railItems:K,commands:ee}),onSearch:async(v)=>{if(!I.hasFeature("search"))return{threads:[],projects:[],messages:[]};return I.rpc("search",{q:v,limit:20})},onExecute:Ye}),We=new zt(e,{hub:I,onProjectAdded:(v)=>{if(ye(),v.id)Vt(v.id)},onCloneDone:(v)=>{if(ye(),v.thread)Ie(v.thread)}}),Ge=new pn(be,(v)=>{if(v==="commands"){$e.open();return}if(!D)return;if(Me===v)Z();else Q(v)}),nt=null,St=null,Oe=new mn(e,{onLoadDevices:async()=>(await I.rpc("devices.page",{})).rows??[],onDevicesAct:async(v,x)=>{await I.rpc("devices.page.act",{action:v,value:x})},onGetHome:()=>nt,onMoveHomeHere:async()=>{await I.rpc("home.move",{to:"back"})},onGetNoProvider:()=>St,onLogout:()=>Wn(()=>{I.disconnect(),window.location.replace("/")})});function Pt(v){if(St=v,ge.setNoProvider(v),Oe.isOpen())Oe.refresh()}function F(){Oe.openToAccounts()}function U(v,x){let L=v instanceof Error?v.message:x;de.showError(L,Pi(L)?{label:b("provider.notice.button","Open Settings → Accounts"),onClick:F}:void 0)}h.addEventListener("click",()=>{let v=k.find((x)=>x.id===D);if(v)Ze(v.id,v.pinned?"unpin":"pin")}),w.addEventListener("click",()=>{let v=k.find((x)=>x.id===D);if(v)Ze(v.id,v.settled?"unsettle":"settle")});let W=new hn(e,(v,x)=>x?I.rpc("thread.context.mcp",{thread:v,...x}):I.rpc("thread.context",{thread:v}));M.addEventListener("click",(v)=>{v.stopPropagation();let x=k.find((q)=>q.id===D);if(!x)return;if(!S.classList.contains("bp-hidden")){S.classList.add("bp-hidden");return}let L=[{label:"Rename…",run:()=>pt(x)},{label:x.pinned?b("menu.unpin","Unpin"):b("menu.pin","Pin"),run:()=>{Ze(x.id,x.pinned?"unpin":"pin")}},{label:x.settled?b("phone.unsettle","Unsettle"):b("menu.settle","Settle"),run:()=>{Ze(x.id,x.settled?"unsettle":"settle")}},{label:x.archived?"Unarchive":"Archive",run:()=>{Ze(x.id,x.archived?"unarchive":"archive")}},{label:"Delete",danger:!0,run:()=>{if(window.confirm("Delete this thread?"))Ze(x.id,"delete")}}];if(I.hasFeature("threadContext"))L.unshift({label:b("thread.context.title","Context & Prompt"),run:()=>W.open(x.id)});let N=document.createDocumentFragment();for(let q of L){let te=document.createElement("button");te.type="button",te.className="bp-popover-item"+(q.danger?" danger":""),te.textContent=q.label,te.addEventListener("click",()=>{S.classList.add("bp-hidden"),q.run()}),N.appendChild(te)}S.replaceChildren(N),S.classList.remove("bp-hidden")}),document.addEventListener("click",()=>S.classList.add("bp-hidden"));async function V(){let v=document.createElement("div");v.className="bp-modal-backdrop",v.setAttribute("data-testid","improvements-modal");let x=document.createElement("div");x.className="bp-modal";let L=document.createElement("div");L.className="bp-modal-head";let N=document.createElement("h2");N.textContent=b("gpui.improvements","Improvements");let q=document.createElement("button");q.type="button",q.className="icon",q.textContent="×",q.addEventListener("click",()=>v.remove()),L.append(N,q);let te=document.createElement("div");te.className="bp-modal-body",te.textContent="Loading…",x.append(L,te),v.appendChild(x),v.addEventListener("click",(ve)=>{if(ve.target===v)v.remove()}),e.appendChild(v);try{let ve=await I.rpc("improvements.projects",{}),De=ve.projects??[];if(De.length===0){te.textContent="No projects available for Improvements.";return}let Qe=document.createDocumentFragment();for(let Ae of De){let se=document.createElement("div");se.className="bp-set-row";let Xe=document.createElement("div");Xe.className="bp-set-info",Xe.textContent=Ae.title||Ae.name||Ae.id;let et=document.createElement("button");et.type="button",et.className=Ae.id===ve.project?"primary":"",et.textContent=Ae.id===ve.project?"Active":"Select",et.addEventListener("click",()=>{I.rpc("improvements.project",{project:Ae.id}).then(()=>v.remove()).catch(()=>{})}),se.append(Xe,et),Qe.appendChild(se)}te.replaceChildren(Qe)}catch(ve){te.textContent=ve instanceof Error?ve.message:"Could not load Improvements."}}B.addEventListener("click",()=>{V()}),O.addEventListener("click",()=>$e.open()),H.addEventListener("click",()=>$e.open()),ae.addEventListener("click",()=>{Oe.open()}),n.addEventListener("click",()=>{oe.classList.toggle("bp-sidebar-open"),oe.classList.toggle("bp-sidebar-collapsed")});function G(){let v=k.find((N)=>N.id===D)??null,x=v?E.find((N)=>N.id===v.project):void 0;o.textContent=x?.title??"",a.classList.toggle("bp-hidden",!x),c.classList.toggle("bp-hidden",!v),u.textContent=v?v.title||"Untitled thread":"";let L=_e(v);if(de.setPlanMode(L),!L||L.phase==="off")l.classList.add("bp-hidden"),l.classList.remove("is-exec"),l.textContent="";else l.classList.remove("bp-hidden"),l.classList.toggle("is-exec",L.phase==="executing"),l.title=b("gpui.planmode.tip","Plan before acting (1 turn, always, or off)"),l.textContent=L.phase==="armed"&&L.once?b("gpui.planmode.top.once","Plan (1 turn)"):L.phase==="armed"?b("gpui.mgmt.plan.tab","Plan"):L.phase==="planning"?b("gpui.planmode.top.planning","Planning"):L.phase==="pending"?b("gpui.planmode.top.pending","Review plan"):b("gpui.planmode.top.executing","Building plan");if(p.classList.toggle("bp-hidden",!v),m.classList.toggle("bp-hidden",!v),v){g.className=`bp-dot ${or(v)}`,y.textContent=v.status||v.state||"idle",f.textContent=v.pinned?b("menu.unpin","Unpin"):b("menu.pin","Pin"),C.textContent=v.settled?b("phone.unsettle","Unsettle"):b("menu.settle","Settle");let N=v;de.setModelChip(v.chip||v.model||"default",v.provider,N.ctxPct??N.contextPct),de.setMemory(v.memory)}else de.setModelChip("default"),de.setMemory(null)}function Z(v=!0){if(je++,Me="",Ge.setActive(""),he.classList.add("bp-hidden"),Y?.close(),dt(),v&&D&&I.getState()==="connected")I.rpc("viewer.watch",{thread:D,kind:""}).catch(()=>{})}function Q(v){if(je++,Me=v,Ge.setActive(v),he.classList.remove("bp-hidden"),dt(),!Y&&typeof Ln==="function")Y=Ln(he,{hub:I,getThreadId:()=>D,closeViewer:()=>Z(!0)});if(Y)Y.open(v,D);else{let x=document.createElement("div");x.className="bp-viewer-placeholder";let L=document.createElement("div");L.className="bp-viewer-bar";let N=document.createElement("span");N.textContent=v.toUpperCase();let q=document.createElement("button");q.type="button",q.className="icon",q.textContent="×",q.addEventListener("click",()=>Z(!0)),L.append(N,q);let te=document.createElement("div");te.className="bp-dim bp-viewer-msg",te.textContent=`Viewer pane (${v}).`,x.append(L,te),he.replaceChildren(x)}}async function xe(v,x){if(!v||!I.hasFeature("rail")){if(x===z)K=[],Ge.setItems([]);return}let L=++je;try{let N=await I.rpc("viewer.rail",{thread:v,page:Me});if(x!==z||L!==je)return;let q=Array.isArray(N.rail)?N.rail:Array.isArray(N.items)?N.items:[];if(K=q,Ge.setItems(q),N.has){if(Y?.reconcileHas?.(N.has),Me&&!ds(N.has,Me))Z(!0)}}catch{if(x===z&&L===je)K=[],Ge.setItems([])}}function Ce(v){for(let x of v)if(x.kind==="threads"){for(let L of x.rows)if(!L.off&&(L.nav||L.id)&&!(L.nav||"").startsWith("@room:"))return L.nav||L.id}else if(x.kind==="projects"){for(let L of x.rows)for(let N of L.threads??[])if(!N.off&&(N.nav||N.id)&&!(N.nav||"").startsWith("@room:"))return N.nav||N.id}return""}function Pe(v,x){for(let L of v)if(L.kind==="threads"){if(L.rows.some((N)=>(N.nav||N.id)===x))return!0}else if(L.kind==="projects"){for(let N of L.rows)if((N.threads??[]).some((q)=>(q.nav||q.id)===x))return!0}return!1}function Re(v){let x=[];for(let L of v){if(L.kind!=="projects")continue;for(let N of L.rows)x.push({id:N.id,title:N.title,css:N.css,color:N.color})}if(x.length>0)E=x}async function ye(){if(!I.hasFeature("sections"))return!1;let v=++X;try{let x=await I.rpc("sidebar.sections",{open:Array.from(ne)});if(v!==X)return!0;let L=Array.isArray(x.sections)?x.sections:[];return le=L,Re(L),re.setData(E,k,j,P),re.setSections(L,j,P),G(),!0}catch{return!1}}function Te(){if(!I.hasFeature("sections"))return;if(ce!==null)window.clearTimeout(ce);ce=window.setTimeout(()=>{ce=null,ye()},150)}async function Ke(){if(Se=null,I.hasFeature("bots"))try{let x=await I.rpc("bots.list",{});j=x.bots??[],P=x.rooms??[]}catch{}if(I.hasFeature("shell")){let x=await I.rpc("shell.sync",{have:ie,settled:25}),L=new Set(x.removed??[]),N=new Set((x.projects??[]).map((q)=>q.id));if(L.size>0||N.size>0)E=[...E.filter((q)=>!L.has(q.id)&&!N.has(q.id)),...x.projects??[]],k=[...k.filter((q)=>!L.has(q.project)&&!N.has(q.project)),...x.threads??[]];else if(Array.isArray(x.threads)&&x.threads.length>0){let q=new Map(k.map((te)=>[te.id,te]));for(let te of x.threads)q.set(te.id,te);k=Array.from(q.values())}if(x.sections!==void 0){let q=Array.isArray(x.sections)?x.sections:Array.isArray(x.sections?.sections)?x.sections.sections:null;if(q)le=q,Re(q)}if(x.h)ie=x.h;re.setData(E,k,j,P),re.setSections(le,j,P)}else if(I.hasFeature("sections")){let[x,L]=await Promise.all([I.rpc("sidebar.sections",{open:Array.from(ne)}).catch(()=>null),I.rpc("threads.list",{limit:200,archived:!1}).catch(()=>({threads:[]}))]);if(k=L.threads??[],x&&Array.isArray(x.sections)){let N=x.sections;if(!N.some((te)=>te.kind==="projects"&&te.rows.length>0)){let te=N.find((ve)=>ve.kind==="projects"&&ve.fold&&ve.toggle&&(ve.count??0)>0);if(te?.toggle&&!ne.has(te.toggle)){ne.add(te.toggle);let ve=await I.rpc("sidebar.sections",{open:Array.from(ne)}).catch(()=>null);if(ve&&Array.isArray(ve.sections))N=ve.sections}}le=N,Re(N),re.setData(E,k,j,P),re.setSections(N,j,P)}else le=null,E=(await I.rpc("projects.list",{limit:100})).projects??[],re.setSections(null,j,P),re.setData(E,k,j,P);await I.rpc("subscribe",{topic:"lists"}).catch(()=>{})}else{le=null;let[x,L]=await Promise.all([I.rpc("projects.list",{limit:100}),I.rpc("threads.list",{limit:200,archived:!1})]);E=x.projects??[],k=L.threads??[],re.setSections(null,j,P),re.setData(E,k,j,P),await I.rpc("subscribe",{topic:"lists"}).catch(()=>{})}let v=D;if(!v){let x="";try{x=localStorage.getItem("bp.lastThread")||""}catch{}if(x&&(le&&Pe(le,x)||k.some((L)=>L.id===x)))v=x;else if(le)v=Ce(le);if(!v)v=(k.find((N)=>!N.archived&&!N.swarm&&!N.settled)??k.find((N)=>!N.archived&&!N.swarm))?.id??""}if(v&&(le&&Pe(le,v)||k.some((x)=>x.id===v)))await Ie(v);else D="",K=[],Ge.setItems([]),de.setState(!1,!1),G()}async function Ie(v){if(D&&D!==v){tt.cancel();let Ae=ge.getEntries();if(Ae.length>0){let se=ke.get(D);He(D,{entries:Ae,ids:se?.ids??Ae.map((Xe)=>Xe.id),olderCursor:me,review:se?.review??null,unanswered:se?.unanswered??null,rail:se?.rail??K,hashes:se?.hashes??{}})}}let x=++z;je++,ut(null);let L=Se;if(Se=null,L!==null)I.rpc("unsubscribe",{sub:L}).catch(()=>{});D=v;let N=ke.get(v);me=N?.olderCursor??null;try{localStorage.setItem("bp.lastThread",v)}catch{}re.setSelected(v),oe.classList.remove("bp-sidebar-open"),G();let q=k.find((Ae)=>Ae.id===v)??null;if(N)ge.setThread(q,N.entries,Boolean(N.olderCursor),N.review,N.unanswered),K=N.rail,Ge.setItems(N.rail);else ge.setLoading(q),K=[],Ge.setItems([]);if(de.setState(!0,q?.state==="working"),I.hasFeature("open")){let Ae={};if(N){for(let[Be,bt]of Object.entries(N.hashes))Ae[Be]=bt;for(let Be of N.entries)if(Be.h)Ae[Be.id]=Be.h}let se;try{se=await I.rpc("thread.open",{thread:v,limit:40,have:Ae})}catch(Be){if(x===z){let bt=Be instanceof Error&&Be.message?Be.message:"Could not load messages.";ge.setError(q,bt,()=>{Ie(v)})}return}if(x!==z){if(se.sub!==void 0&&se.sub!==null)I.rpc("unsubscribe",{sub:se.sub}).catch(()=>{});return}if(Se=se.sub??null,se.thread){q=se.thread;let Be=k.findIndex((bt)=>bt.id===se.thread.id);if(Be>=0)k[Be]=se.thread;else k.unshift(se.thread);G(),de.setState(!0,q.state==="working")}if("next"in se)me=se.next??null;let Xe=new Map;if(N)for(let Be of N.entries)Xe.set(Be.id,Be);for(let Be of se.entries??[])Xe.set(Be.id,Be);let et=se.ids??N?.ids??(se.entries??[]).map((Be)=>Be.id),Tn=et.map((Be)=>Xe.get(Be)).filter((Be)=>Boolean(Be)),ht=N?.rail??[];if(se.rail!==void 0){if(Array.isArray(se.rail))ht=se.rail;else if(ht=Array.isArray(se.rail?.rail)?se.rail.rail:Array.isArray(se.rail?.items)?se.rail.items:[],se.rail?.has){if(Y?.reconcileHas?.(se.rail.has),Me&&!ds(se.rail.has,Me))Z(!0)}}K=ht,Ge.setItems(ht);let Ut=N?.review??null;if(I.hasFeature("reviewmode"))try{let Be=await I.rpc("thread.review",{thread:v});if(x!==z)return;Ut=Be.review??null}catch{}if(x!==z)return;let Bn="unanswered"in se?se.unanswered??null:N?.unanswered??null,us=se.h??N?.hashes??{};if(He(v,{entries:Tn,ids:et,olderCursor:me,review:Ut,unanswered:Bn,rail:ht,hashes:us}),ge.setThread(q,Tn,Boolean(me),Ut,Bn),mt(v,x),Me)Q(Me);return}let te;try{te=await I.rpc("thread.entries",{thread:v,limit:40})}catch(Ae){if(x===z){let se=Ae instanceof Error&&Ae.message?Ae.message:"Could not load messages.";ge.setError(q,se,()=>{Ie(v)})}return}if(x!==z)return;if(te.thread){let Ae=k.findIndex((se)=>se.id===te.thread.id);if(Ae>=0)k[Ae]=te.thread;else k.unshift(te.thread);G()}me=te.next??null;let ve=null;if(I.hasFeature("reviewmode"))try{let Ae=await I.rpc("thread.review",{thread:v});if(x!==z)return;ve=Ae.review??null}catch{}if(x!==z)return;let De=te.entries??[],Qe=te.unanswered??null;He(v,{entries:De,ids:De.map((Ae)=>Ae.id),olderCursor:me,review:ve,unanswered:Qe,rail:N?.rail??[],hashes:N?.hashes??{}}),ge.setThread(q,De,Boolean(me),ve,Qe);try{let se=(await I.rpc("subscribe",{topic:"thread",thread:v})).sub??null;if(se!==null){if(x!==z){I.rpc("unsubscribe",{sub:se}).catch(()=>{});return}Se=se}}catch{}if(x!==z)return;if(xe(v,x),mt(v,x),Me)Q(Me)}async function mt(v,x){if(!v||!I.hasFeature("mgmt")){if(x===z)Je.clear();return}let L=k.find((q)=>q.id===v),N=L?.project?E.find((q)=>q.id===L.project)?.root??"":"";if(!N&&I.hasFeature("viewers"))try{let q=await I.rpc("viewer.files",{thread:v});if(x!==z)return;N=q.pcb||q.sch||q.root||""}catch{}if(x!==z)return;if(N)await Je.watchProject(N);else Je.clear()}async function Nt(v){let x=z;for(let L=0;L<25&&x===z;L++){if(ge.goTo(v))return;if(!me)return;let N=me;if(await ze(),me===N)return}}async function ze(){if(!D||!me){ge.clearLoadingOlder();return}let v=z,x=D,L=me;try{let N=await I.rpc("thread.entries",{thread:x,limit:40,before:L});if(v!==z||D!==x)return;me=N.next??null,ge.prependEntries(N.entries??[],Boolean(me))}catch{if(v===z)ge.clearLoadingOlder()}}async function Vt(v){try{let x=await I.rpc("thread.create",{project:v});if(x.thread)k=[x.thread,...k.filter((L)=>L.id!==x.thread.id)],re.setData(E,k,j,P),ye(),await Ie(x.thread.id),de.focus()}catch(x){U(x,"Could not create thread")}}let rt=null;function Sn(v){return(v.split(` +`).map((x)=>x.trim()).find((x)=>x.length>0)??"").slice(0,200)}function ut(v){rt=v,de.setReply(v?{who:v.role==="user"?b("secret.you","You"):b("model.col.agent","Agent"),line:Sn(v.text)}:null,()=>{if(rt)Nt(rt.id)},()=>ut(null))}async function Pn(v,x=[]){if(!D)return;let L=z,N=D,q=lr(),te=`local-${q}`,ve=rt&&v.trim()&&I.hasFeature("reply")?rt:null;if(ve)ut(null);ge.upsertEntry({id:te,kind:"user",text:v,at:Date.now(),clientId:q,...ve?{replyTo:{id:ve.id,quote:Sn(ve.text)}}:{},attachments:x.map((De)=>({name:De.name,mime:De.mime,previewUrl:`data:${De.mime};base64,${De.data}`}))});try{let De={thread:N,text:v,clientId:q};if(x.length>0)De.attachments=x;if(ve)De.replyTo={id:ve.id,text:ve.text};let Qe=await I.rpc("message.send",De);if(L!==z||D!==N)return;if(Qe.entry)ge.upsertEntry(Qe.entry)}catch(De){if(L===z&&D===N){if(ge.removeEntry(te),de.setDraft(v),ve&&!rt)ut(ve);U(De,"Failed to send message")}}}async function Nn(v){if(!D)return;let x=z,L=D;try{let N=await I.rpc("composer.run",{thread:L,text:v});if(x!==z||D!==L)return;if(N.error)de.setDraft(v),U(Error(N.error),N.error);else if(N.kind==="edit"&&typeof N.text==="string")de.setDraft(N.text);else if(N.kind==="project")We.open({mode:"folder"});else if(N.kind==="clone")We.open({mode:"clone",repo:N.repo??"",text:N.text??""})}catch(N){if(x===z&&D===L)de.setDraft(v),U(N,"Command refused")}}async function Ze(v,x){try{let L=await I.rpc("thread.act",{thread:v,action:x});if(L.thread){if(k=k.map((N)=>N.id===L.thread.id?L.thread:N),re.setData(E,k,j,P),L.thread.id===D)ge.updateThreadMeta(L.thread),G()}ye()}catch(L){de.showError(L instanceof Error?L.message:`Action "${x}" not allowed`)}}function Mn(v,x){if(!v||!v.text||x-v.at>=300000)return"";let L=v.build.split("-").pop()??"";if(v.reason==="build"&&L)return b("hub.restarting.build",v.text,{build:L});if(v.reason==="stop")return b("hub.stopped",v.text);return b("hub.restarting",v.text)}function Mt(v){if(v==="connected")re.setConnStatus(b("gpui.acct.connected","Connected"),"bp-ok");else if(v==="reconnecting"&&Mn(I.restarting,Date.now()))re.setConnStatus(Mn(I.restarting,Date.now()),"");else if(v==="reconnecting")re.setConnStatus("Reconnecting…","bp-warn");else if(v==="revoked")re.setConnStatus(b("gpui.acct.sign.in.expired","Sign-in expired"),"bp-bad");else re.setConnStatus("Connecting…","")}Tt(()=>{Mt(I.getState()),R.textContent=b("gpui.improvements","Improvements"),ae.title=b("palette.settings","Settings"),ae.setAttribute("aria-label",b("palette.settings","Settings")),G(),re.refreshLocale(),ge.refreshLocale(),de.refreshLocale(),Ge.render(),Oe.refreshLocale(),We.refreshLocale()}),I.onState((v,x)=>{if(v==="connected"&&x){if(x.locale)Fn(x.locale);if(x.theme)ps(x.theme);if(x.name)re.setHostName(x.name);if(nt=x.home??null,re.setHome(nt),Pt(dn(x.noProvider)),Oe.isOpen())Oe.refresh();Mt(v);let L=typeof x.hubBack==="string"?String(x.hubBack):"";if(L)try{let N=JSON.parse(L);if(N.reason==="crash")re.setConnStatus(b("hub.back.crash",N.text??""),"bp-warn"),window.setTimeout(()=>Mt(I.getState()),6000)}catch{}if(de.setFeatures(I.hasFeature("images"),I.hasFeature("voice")),Array.isArray(x.commands))ee=x.commands,de.setCommands(ee);else ee=[];Ke(),We.reconcile()}else tt.cancel(),Mt(v)}),I.onFrame((v)=>{if(v.t==="voice"){tt.handleFrame(v);return}if(v.t==="info"&&v.info&&typeof v.info==="object"){let L=v.info;if(Object.prototype.hasOwnProperty.call(L,"provider.notice"))Pt(dn(L["provider.notice"]));Je.handleInfo(L);return}if(v.t!=="d")return;let x=v;if(x.k==="clone"||x.k==="clone.repos"||x.k==="clone.signin"){We.handleFrame(x);return}switch(x.k){case"project":{let L=x.project;if(!L)break;let N=E.findIndex((q)=>q.id===L.id);if(N>=0)E[N]=L;else E.unshift(L);re.setData(E,k,j,P),G(),Te();break}case"thread":{let L=x.thread;if(!L)break;let N=k.findIndex((q)=>q.id===L.id);if(N>=0)k[N]=L;else k.unshift(L);if(re.setData(E,k,j,P),L.id===D)ge.updateThreadMeta(L),G(),de.setState(!0,L.state==="working");Te();break}case"thread.removed":{let L=String(x.id??"");k=k.filter((N)=>N.id!==L),re.setData(E,k,j,P),Te();break}case"entry":{if(x.thread===D&&x.entry)ge.upsertEntry(x.entry);break}case"text":{if(x.thread===D)ge.appendLiveText(String(x.entry??""),String(x.append??""),Number(x.at??Date.now()));break}case"turn":{if(x.thread===D){let L=String(x.state??"idle");de.setState(!0,L==="working"),xe(D,z)}Te();break}case"btw":{if(x.thread===D)ge.showBtw(String(x.q??""),String(x.a??""));break}case"unanswered":{if(x.thread===D)ge.setUnanswered(x.unanswered??null);break}case"theme":{if(typeof x.theme==="string")ps(x.theme);break}case"home":{if(nt=x.home??null,re.setHome(nt),Oe.isOpen())Oe.refresh();break}default:break}}),window.addEventListener("keydown",(v)=>{let x=v.key.toLowerCase();if((v.ctrlKey||v.metaKey)&&(x==="k"||v.shiftKey&&x==="p"))if(v.preventDefault(),$e.isOpen())$e.close();else $e.open();else if(v.key==="Escape"){if($e.isOpen())$e.close();else if(We.isOpen())We.escape();else if(Oe.isOpen())Oe.close();else if(ge.closePlanRevise());else if(Je.isOpen())Je.closePanel()}}),I.connect()}if(document.readyState==="loading")document.addEventListener("DOMContentLoaded",ms);else ms(); diff --git a/web/dist/assets/pair.js b/web/dist/assets/pair.js index 4fb2f16726..d831957033 100644 --- a/web/dist/assets/pair.js +++ b/web/dist/assets/pair.js @@ -1 +1 @@ -var F={en:{"agy.signout":"Sign out","android.hub.machines.approve":"Approve","android.load.earlier":"load earlier","approval.dismiss":"Dismiss","approval.implement":"Implement","ask.plan":"Proposed plan","bots.rooms":"Rooms","bots.tab.browser":"Browser","common.cancel":"Cancel","common.close":"Close","common.copy":"Copy","common.delete":"Delete","common.refresh":"Refresh","common.remove":"Remove","common.save":"Save","composer.placeholder":"Ask anything: @bot, >thread, %project, #room, $skill, /btw","composer.send":"Send","composer.stop":"Stop","gpui.acct.connected":"Connected","gpui.acct.not.connected":"Not connected","gpui.acct.sign.in.expired":"Sign-in expired","gpui.ask.plan.ready":"Ready for review","gpui.ask.plan.revise":"Revise","gpui.ask.plan.reviseph":"What should change in the plan?","gpui.ask.plan.sendrev":"Send revision","gpui.b.in.reply.to":"↩ In reply to: {quote}","gpui.b.replying.to":"↩ Replying to: {line}","gpui.bots.recall.off":"Off","gpui.bots.recall.on":"On","gpui.c.term.collapse":"Collapse","gpui.c.term.expand":"Expand","gpui.commands":"Commands","gpui.e.open.folder":"Open folder","gpui.filter.projects.and.threads":"Filter projects and threads","gpui.fold.or.unfold.the.sidebar":"Fold or unfold the sidebar","gpui.follow.paused":"Following paused","gpui.follow.wait":"Following: waiting for the agent's next edit","gpui.gerbers":"Gerbers","gpui.improvements":"Improvements","gpui.jump.to.a.thread.run":"Jump to a thread, run a command or find what was said","gpui.mgmt.bom.dnp":"DNP","gpui.mgmt.bom.nompn":"no MPN","gpui.mgmt.checks.all":"All","gpui.mgmt.checks.fix":"Fix with agent","gpui.mgmt.checks.run":"Run","gpui.mgmt.close":"Close the panel","gpui.mgmt.fab.apply":"Apply","gpui.mgmt.fab.changed":"Changed since you last looked","gpui.mgmt.fab.derived":"* worked out from the fab's page (a mil in mm, a ring from a diameter). Dimmed: the rigid board's value, where this board's page says nothing else. A date opens the page it was read from.","gpui.mgmt.fab.extra":"Costs more","gpui.mgmt.fab.findings":"Findings","gpui.mgmt.fab.free":"Base price","gpui.mgmt.fab.judge":"Datasheets","gpui.mgmt.fab.limit":"Limit","gpui.mgmt.fab.readcol":"Read","gpui.mgmt.fab.refresh":"Refresh","gpui.mgmt.fab.reviewbtn":"Review","gpui.mgmt.fab.seen":"Seen","gpui.mgmt.fab.thefab":"The fab","gpui.mgmt.fab.use":"Use","gpui.mgmt.life.nopart":"No reading of this part yet.","gpui.mgmt.life.reading":"Reading its history…","gpui.mgmt.plan.addnote":"Add note","gpui.mgmt.plan.all":"Approve all","gpui.mgmt.plan.before":"Plan before routing","gpui.mgmt.plan.compact":"Compact","gpui.mgmt.plan.done":"done","gpui.mgmt.plan.drawn":"The plan's corridors and planes are drawn on the board while this panel is open. Close it to hide them.","gpui.mgmt.plan.edited":"Edited","gpui.mgmt.plan.elsewhere":"A routing plan for {board} awaits your approval","gpui.mgmt.plan.emptysub":"Layers, corridors, and planes appear here once a plan is proposed.","gpui.mgmt.plan.expand":"Expand","gpui.mgmt.plan.fit":"Fit","gpui.mgmt.plan.grid.all":"All layers","gpui.mgmt.plan.grid.pair":"Side by side","gpui.mgmt.plan.grid.single":"Single","gpui.mgmt.plan.hide":"Hide done","gpui.mgmt.plan.hint":"Drag waypoints to steer · Click + on edge to insert · Right-click vertex to remove","gpui.mgmt.plan.keysnote":"On this KiCad version, approve from this panel: in plan view KiCad's A, R and W keys aren't the plan's yet (A opens Add Footprint). Update KiCad.","gpui.mgmt.plan.layer":"Approve layer","gpui.mgmt.plan.layer.short":"Layer","gpui.mgmt.plan.lock":"Lock","gpui.mgmt.plan.locked":"Locked","gpui.mgmt.plan.noboard":"No routing plan for this board.","gpui.mgmt.plan.noitems":"No corridors or planes on this layer","gpui.mgmt.plan.note.placeholder":"Steering note for router…","gpui.mgmt.plan.nothing":"Nothing awaits your approval","gpui.mgmt.plan.offwords":"Agents route as you ask. Turn it on to have them propose a routing plan first and route only what you approve here.","gpui.mgmt.plan.onwords":"Before routing a board with 4 or more copper layers or more than 60 nets, the agent proposes corridors and plane regions here. It routes only what you approve.","gpui.mgmt.plan.reading":"Reading the routing plan…","gpui.mgmt.plan.reference":"over {layer}","gpui.mgmt.plan.refused":"KiCad refused","gpui.mgmt.plan.reject":"Reject","gpui.mgmt.plan.rejectlayer":"Reject layer","gpui.mgmt.plan.reqplain":"Approval requested","gpui.mgmt.plan.requested":"Approval requested: {what}","gpui.mgmt.plan.saved":"saved plan","gpui.mgmt.plan.show":"Show done","gpui.mgmt.plan.st.approved":"Approved","gpui.mgmt.plan.st.awaiting":"Awaiting review","gpui.mgmt.plan.st.blocked":"Blocked","gpui.mgmt.plan.st.empty":"Empty","gpui.mgmt.plan.st.partial":"Partial","gpui.mgmt.plan.st.rejected":"Rejected","gpui.mgmt.plan.st.routed":"Routed","gpui.mgmt.plan.st.routing":"Routing","gpui.mgmt.plan.st.verified":"Verified","gpui.mgmt.plan.stackup.short":"Stackup","gpui.mgmt.plan.stop":"Stop routing","gpui.mgmt.plan.sync":"Link zoom","gpui.mgmt.plan.tab":"Plan","gpui.mgmt.plan.unlock":"Unlock","gpui.mgmt.plan.verify":"Verify","gpui.mgmt.plan.view.canvas":"Canvas","gpui.mgmt.plan.view.list":"List","gpui.mgmt.plan.view.split":"Split","gpui.mgmt.plan.width":"Width","gpui.next.thread":"Next thread","gpui.nothing.matches":"Nothing matches","gpui.planmode.bar.always":"Plan mode — explores and proposes a plan before editing","gpui.planmode.bar.executing":"Building the approved plan","gpui.planmode.bar.once":"Plan mode (1 turn) — explores and proposes a plan before editing","gpui.planmode.bar.pending":"Proposed plan awaits review below","gpui.planmode.bar.planning":"Planning — drafting a plan before edits","gpui.planmode.chip.building":"Building","gpui.planmode.chip.once":"Plan · 1t","gpui.planmode.scope.always":"Always","gpui.planmode.scope.once":"1 turn","gpui.planmode.tip":"Plan before acting (1 turn, always, or off)","gpui.planmode.top.executing":"Building plan","gpui.planmode.top.once":"Plan (1 turn)","gpui.planmode.top.pending":"Review plan","gpui.planmode.top.planning":"Planning","gpui.previous.thread":"Previous thread","gpui.rail.no.board":"No board in this project","gpui.rail.no.mech":"No mechanical parts in this project","gpui.rail.no.schematic":"No schematic in this project","gpui.rail.split.needs.both":"Split needs a board and a schematic","home.away":"Home ({name}) is away","home.away.queued":"Home ({name}) is away · {n} queued","home.away.since":"Home ({name}) is away since {time}","home.away.since.queued":"Home ({name}) is away since {time} · {n} queued","home.machine":"Home machine","home.move.failed":"Home move failed","home.move.failed.note":"Home move failed: {note}","home.move.here":"Make this machine the home","home.moving":"Moving home to {to}…","home.moving.step":"Moving home to {to}: {step}","hub.back.crash":"Backplane is back after it stopped unexpectedly","hub.restarting":"Restarting Backplane…","hub.restarting.build":"Restarting Backplane… (new build {build})","hub.stopped":"Backplane stopped","ios.hub.address.field":"Hub address","menu.pin":"Pin","menu.settle":"Settle","menu.unpin":"Unpin","model.col.agent":"Agent","notify.settled":"Settled","palette.archive":"Archive thread","palette.command.placeholder":"Type a command or a thread","palette.diff":"Diff: what this thread changed","palette.newthread":"New thread","palette.settings":"Settings","palette.terminal":"Terminal","palette.unarchive":"Unarchive thread","phone.unsettle":"Unsettle","reply.action":"Reply","reply.cancel":"Cancel reply","reply.to":"In reply to:","secret.you":"You","settings.lang":"Language","sheet.rename":"Rename thread","sidebar.add.project":"Add project","sidebar.search.projects":"Search projects","thread.context.base":"Backplane","thread.context.copied":"Prompt copied.","thread.context.copy":"Copy prompt","thread.context.disable":"Disable","thread.context.enable":"Enable","thread.context.index":"Available skills index","thread.context.injected.label":"Injected project instructions","thread.context.instructions":"Instructions","thread.context.mcp":"Project MCPs","thread.context.native.note":"Backplane’s launch prompt. Native files are loaded by the provider.","thread.context.none.instructions":"No project instructions found.","thread.context.none.mcp":"No project MCP configurations found.","thread.context.reading":"Reading thread context…","thread.context.size":"{bytes} B · ≈{tokens} tokens","thread.context.skills":"Skills","thread.context.system":"System Prompt","thread.context.title":"Context & Prompt","thread.context.trust":"Trust and enable","thread.new":"New thread","tools.pinned":"Pinned","tools.retry":"Retry","tour.title.bots":"Bots","viewer.board":"Board","viewer.diff":"Diff","viewer.files":"Files","viewer.mech":"Mech","viewer.review":"Review","viewer.schematic":"Schematic","viewer.solid":"3D","web.chat.answer.btn":"Answer","web.chat.answer.placeholder":"Type answer…","web.chat.answered":"Answered: {answer}","web.chat.choose":"Choose a project thread on the left to begin.","web.chat.empty":"No messages yet. Type below to start a turn.","web.chat.finished":"Finished {time}","web.chat.finished.dur":"Finished {time} · {dur}","web.chat.loading":"Loading messages…","web.chat.review.mode":"Review mode","web.chat.streaming":"Streaming…","web.clone.add.dir":"Add {dir}","web.clone.back":"Back","web.clone.change.folder":"Change folder","web.clone.cloned":"Cloned {repo} into {dest}","web.clone.cloning":"Cloning {repo} into {dest}","web.clone.copied":"Copied","web.clone.first":"First message: {text}","web.clone.folder.name":"Folder name","web.clone.go":"Clone","web.clone.loading":"Loading…","web.clone.no.folders":"No folders here","web.clone.open.project":"Open the project","web.clone.open.thread":"Open the thread","web.clone.private":"private","web.clone.repo.placeholder":"https or ssh URL, or owner/repo","web.clone.retry":"Try again","web.clone.same":"Already cloned there: it is added as it is.","web.clone.signin":"Sign in to GitHub","web.clone.signin.done":"Signed in to GitHub","web.clone.signin.enter":"Enter this code on GitHub:","web.clone.signin.wait":"Starting GitHub sign-in…","web.clone.start.thread":"Start a thread","web.clone.stopped":"Stopped cloning {repo}","web.clone.tab":"Clone from git","web.clone.up":"Up","web.clone.use.dir":"Use {dir}","web.composer.attach":"Attach image","web.composer.maximages":"At most {max} images per message.","web.composer.unsupported":"Unsupported image type: {type}","web.composer.voice":"Voice dictation","web.logout.failed":"Could not confirm sign-out. Try again.","web.pair.approve.in":"Approve on desktop or paired phone · expires in {time}","web.pair.approved":"Approved. Opening Backplane…","web.pair.cancelled":"Cancelled.","web.pair.code":"Comparison code","web.pair.denied":"Pairing request was denied.","web.pair.expired":"Pairing code expired. Request a new code to try again.","web.pair.failed":"Pairing request failed ({status})","web.pair.name":"Browser name","web.pair.nocode":"Hub did not return a comparison code.","web.pair.ratelimited":"Too many pairing attempts. Wait a moment and try again.","web.pair.request":"Request pairing","web.pair.requesting":"Requesting pairing code…","web.pair.subtitle":"Pair this browser with your hub. Approve the 6-digit code in Backplane › Settings › Devices.","web.pair.unreachable":"Could not reach the hub. Check your tailnet connection.","web.plan.awaiting":"{n} awaiting approval","web.plan.net.one":"1 net","web.plan.nets":"{n} nets"},es:{"agy.signout":"Cerrar sesión","android.hub.machines.approve":"Aprobar","android.load.earlier":"cargar anteriores","approval.dismiss":"Descartar","approval.implement":"Implementar","ask.plan":"Plan propuesto","bots.rooms":"Salas","bots.tab.browser":"Navegador","common.cancel":"Cancelar","common.close":"Cerrar","common.copy":"Copiar","common.delete":"Eliminar","common.refresh":"Actualizar","common.remove":"Quitar","common.save":"Guardar","composer.placeholder":"Pregunta lo que sea: @bot, >hilo, %proyecto, #sala, $skill, /btw","composer.send":"Enviar","composer.stop":"Detener","gpui.acct.connected":"Conectado","gpui.acct.not.connected":"No conectado","gpui.acct.sign.in.expired":"Sesión caducada","gpui.ask.plan.ready":"Listo para revisar","gpui.ask.plan.revise":"Revisar","gpui.ask.plan.reviseph":"¿Qué debería cambiar en el plan?","gpui.ask.plan.sendrev":"Enviar revisión","gpui.b.in.reply.to":"↩ En respuesta a: {quote}","gpui.b.replying.to":"↩ Respondiendo a: {line}","gpui.bots.recall.off":"Desactivado","gpui.bots.recall.on":"Activado","gpui.c.term.collapse":"Contraer","gpui.c.term.expand":"Expandir","gpui.commands":"Comandos","gpui.e.open.folder":"Abrir carpeta","gpui.filter.projects.and.threads":"Filtrar proyectos e hilos","gpui.fold.or.unfold.the.sidebar":"Plegar o desplegar la barra lateral","gpui.follow.paused":"Seguimiento en pausa","gpui.follow.wait":"Siguiendo: esperando la próxima edición del agente","gpui.gerbers":"Gerbers","gpui.improvements":"Mejoras","gpui.jump.to.a.thread.run":"Saltar a un hilo, ejecutar un comando o buscar lo dicho","gpui.mgmt.bom.dnp":"DNP","gpui.mgmt.bom.nompn":"sin MPN","gpui.mgmt.checks.all":"Todas","gpui.mgmt.checks.fix":"Corregir con agente","gpui.mgmt.checks.run":"Ejecutar","gpui.mgmt.close":"Cerrar el panel","gpui.mgmt.fab.apply":"Aplicar","gpui.mgmt.fab.changed":"Cambió desde la última vez que miraste","gpui.mgmt.fab.derived":"* calculado desde la página del fabricante (un mil en mm, un anillo desde un diámetro). Atenuado: el valor de la placa rígida, cuando la página de esta placa no dice otra cosa. Una fecha abre la página de la que se leyó.","gpui.mgmt.fab.extra":"Cuesta más","gpui.mgmt.fab.findings":"Hallazgos","gpui.mgmt.fab.free":"Precio base","gpui.mgmt.fab.judge":"Hojas de datos","gpui.mgmt.fab.limit":"Límite","gpui.mgmt.fab.readcol":"Leído","gpui.mgmt.fab.refresh":"Actualizar","gpui.mgmt.fab.reviewbtn":"Revisar","gpui.mgmt.fab.seen":"Visto","gpui.mgmt.fab.thefab":"El fabricante","gpui.mgmt.fab.use":"Usar","gpui.mgmt.life.nopart":"Sin lectura de esta pieza aún.","gpui.mgmt.life.reading":"Leyendo su historial…","gpui.mgmt.plan.addnote":"Añadir nota","gpui.mgmt.plan.all":"Aprobar todo","gpui.mgmt.plan.before":"Planificar antes de rutear","gpui.mgmt.plan.compact":"Compacto","gpui.mgmt.plan.done":"hecho","gpui.mgmt.plan.drawn":"Los corredores y planos del plan se dibujan en la placa mientras este panel está abierto. Ciérralo para ocultarlos.","gpui.mgmt.plan.edited":"Editado","gpui.mgmt.plan.elsewhere":"Un plan de ruteo para {board} espera tu aprobación","gpui.mgmt.plan.emptysub":"Las capas, corredores y planos aparecerán aquí cuando se proponga un plan.","gpui.mgmt.plan.expand":"Expandir","gpui.mgmt.plan.fit":"Ajustar","gpui.mgmt.plan.grid.all":"Todas las capas","gpui.mgmt.plan.grid.pair":"Lado a lado","gpui.mgmt.plan.grid.single":"Única","gpui.mgmt.plan.hide":"Ocultar hechos","gpui.mgmt.plan.hint":"Arrastra vértices para guiar · Clic en + del borde para insertar · Clic derecho en vértice para quitar","gpui.mgmt.plan.keysnote":"En esta versión de KiCad, aprueba desde este panel: en la vista de plan las teclas A, R y W de KiCad aún no son del plan (A abre Añadir Huella). Actualiza KiCad.","gpui.mgmt.plan.layer":"Aprobar capa","gpui.mgmt.plan.layer.short":"Capa","gpui.mgmt.plan.lock":"Bloquear","gpui.mgmt.plan.locked":"Bloqueado","gpui.mgmt.plan.noboard":"No hay plan de ruteo para esta placa.","gpui.mgmt.plan.noitems":"Sin corredores ni planos en esta capa","gpui.mgmt.plan.note.placeholder":"Nota de guiado para el router…","gpui.mgmt.plan.nothing":"Nada espera tu aprobación","gpui.mgmt.plan.offwords":"Los agentes rutean como les pidas. Actívalo para que primero propongan un plan de ruteo y ruteen solo lo que apruebes aquí.","gpui.mgmt.plan.onwords":"Antes de rutear una placa con 4 o más capas de cobre o más de 60 redes, el agente propone aquí corredores y regiones de plano. Solo rutea lo que apruebes.","gpui.mgmt.plan.reading":"Leyendo el plan de ruteo…","gpui.mgmt.plan.reference":"sobre {layer}","gpui.mgmt.plan.refused":"KiCad lo rechazó","gpui.mgmt.plan.reject":"Rechazar","gpui.mgmt.plan.rejectlayer":"Rechazar capa","gpui.mgmt.plan.reqplain":"Aprobación solicitada","gpui.mgmt.plan.requested":"Aprobación solicitada: {what}","gpui.mgmt.plan.saved":"plan guardado","gpui.mgmt.plan.show":"Mostrar hechos","gpui.mgmt.plan.st.approved":"Aprobado","gpui.mgmt.plan.st.awaiting":"Esperando revisión","gpui.mgmt.plan.st.blocked":"Bloqueado","gpui.mgmt.plan.st.empty":"Vacío","gpui.mgmt.plan.st.partial":"Parcial","gpui.mgmt.plan.st.rejected":"Rechazado","gpui.mgmt.plan.st.routed":"Ruteado","gpui.mgmt.plan.st.routing":"Ruteando","gpui.mgmt.plan.st.verified":"Verificado","gpui.mgmt.plan.stackup.short":"Apilamiento","gpui.mgmt.plan.stop":"Detener ruteo","gpui.mgmt.plan.sync":"Vincular zoom","gpui.mgmt.plan.tab":"Plan","gpui.mgmt.plan.unlock":"Desbloquear","gpui.mgmt.plan.verify":"Verificar","gpui.mgmt.plan.view.canvas":"Lienzo","gpui.mgmt.plan.view.list":"Lista","gpui.mgmt.plan.view.split":"Dividido","gpui.mgmt.plan.width":"Ancho","gpui.next.thread":"Hilo siguiente","gpui.nothing.matches":"Nada coincide","gpui.planmode.bar.always":"Modo plan — explora y propone un plan antes de editar","gpui.planmode.bar.executing":"Ejecutando el plan aprobado","gpui.planmode.bar.once":"Modo plan (1 turno) — explora y propone un plan antes de editar","gpui.planmode.bar.pending":"El plan propuesto espera revisión abajo","gpui.planmode.bar.planning":"Planificando — redactando un plan antes de editar","gpui.planmode.chip.building":"Ejecutando","gpui.planmode.chip.once":"Plan · 1t","gpui.planmode.scope.always":"Siempre","gpui.planmode.scope.once":"1 turno","gpui.planmode.tip":"Planificar antes de actuar (1 turno, siempre u off)","gpui.planmode.top.executing":"Ejecutando plan","gpui.planmode.top.once":"Plan (1 turno)","gpui.planmode.top.pending":"Revisar plan","gpui.planmode.top.planning":"Planificando","gpui.previous.thread":"Hilo anterior","gpui.rail.no.board":"Este proyecto no tiene placa","gpui.rail.no.mech":"Este proyecto no tiene piezas mecánicas","gpui.rail.no.schematic":"Este proyecto no tiene esquema","gpui.rail.split.needs.both":"La vista dividida requiere una placa y un esquema","home.away":"El inicio ({name}) no está disponible","home.away.queued":"El inicio ({name}) no está disponible · {n} en cola","home.away.since":"El inicio ({name}) no está disponible desde las {time}","home.away.since.queued":"El inicio ({name}) no está disponible desde las {time} · {n} en cola","home.machine":"Máquina de inicio","home.move.failed":"No se pudo mover el inicio","home.move.failed.note":"No se pudo mover el inicio: {note}","home.move.here":"Hacer de esta máquina el inicio","home.moving":"Moviendo el inicio a {to}…","home.moving.step":"Moviendo el inicio a {to}: {step}","hub.back.crash":"Backplane volvió tras detenerse de forma inesperada","hub.restarting":"Reiniciando Backplane…","hub.restarting.build":"Reiniciando Backplane… (nueva compilación {build})","hub.stopped":"Backplane se detuvo","ios.hub.address.field":"Dirección del hub","menu.pin":"Fijar","menu.settle":"Cerrar","menu.unpin":"Desfijar","model.col.agent":"Agente","notify.settled":"Cerrado","palette.archive":"Archivar hilo","palette.command.placeholder":"Escribe un comando o un hilo","palette.diff":"Diff: qué cambió este hilo","palette.newthread":"Nuevo hilo","palette.settings":"Ajustes","palette.terminal":"Terminal","palette.unarchive":"Desarchivar hilo","phone.unsettle":"Reabrir","reply.action":"Responder","reply.cancel":"Cancelar respuesta","reply.to":"En respuesta a:","secret.you":"Tú","settings.lang":"Idioma","sheet.rename":"Renombrar hilo","sidebar.add.project":"Añadir proyecto","sidebar.search.projects":"Buscar proyectos","thread.context.base":"Backplane","thread.context.copied":"Se copiaron las instrucciones.","thread.context.copy":"Copiar instrucciones","thread.context.disable":"Desactivar","thread.context.enable":"Activar","thread.context.index":"Índice de habilidades disponibles","thread.context.injected.label":"Instrucciones del proyecto añadidas","thread.context.instructions":"Instrucciones","thread.context.mcp":"MCP del proyecto","thread.context.native.note":"Instrucciones de inicio de Backplane. El proveedor carga los archivos nativos.","thread.context.none.instructions":"No se encontraron instrucciones del proyecto.","thread.context.none.mcp":"No se encontraron configuraciones MCP del proyecto.","thread.context.reading":"Leyendo el contexto del hilo…","thread.context.size":"{bytes} B · ≈{tokens} tokens","thread.context.skills":"Habilidades","thread.context.system":"Instrucciones del sistema","thread.context.title":"Contexto e instrucciones","thread.context.trust":"Confiar y activar","thread.new":"Nuevo hilo","tools.pinned":"Fijado","tools.retry":"Reintentar","tour.title.bots":"Bots","viewer.board":"Placa","viewer.diff":"Diff","viewer.files":"Archivos","viewer.mech":"Mech","viewer.review":"Revisión","viewer.schematic":"Esquemático","viewer.solid":"3D","web.chat.answer.btn":"Responder","web.chat.answer.placeholder":"Escribe una respuesta…","web.chat.answered":"Respondido: {answer}","web.chat.choose":"Elige un hilo de proyecto a la izquierda para empezar.","web.chat.empty":"Aún no hay mensajes. Escribe abajo para iniciar un turno.","web.chat.finished":"Terminado {time}","web.chat.finished.dur":"Terminado {time} · {dur}","web.chat.loading":"Cargando mensajes…","web.chat.review.mode":"Modo de revisión","web.chat.streaming":"Transmitiendo…","web.clone.add.dir":"Añadir {dir}","web.clone.back":"Atrás","web.clone.change.folder":"Cambiar carpeta","web.clone.cloned":"{repo} clonado en {dest}","web.clone.cloning":"Clonando {repo} en {dest}","web.clone.copied":"Copiado","web.clone.first":"Primer mensaje: {text}","web.clone.folder.name":"Nombre de la carpeta","web.clone.go":"Clonar","web.clone.loading":"Cargando…","web.clone.no.folders":"No hay carpetas aquí","web.clone.open.project":"Abrir el proyecto","web.clone.open.thread":"Abrir el hilo","web.clone.private":"privado","web.clone.repo.placeholder":"URL https o ssh, o propietario/repositorio","web.clone.retry":"Reintentar","web.clone.same":"Ya está clonado ahí: se añade tal cual.","web.clone.signin":"Iniciar sesión en GitHub","web.clone.signin.done":"Sesión iniciada en GitHub","web.clone.signin.enter":"Introduce este código en GitHub:","web.clone.signin.wait":"Iniciando sesión en GitHub…","web.clone.start.thread":"Empezar un hilo","web.clone.stopped":"Se detuvo la clonación de {repo}","web.clone.tab":"Clonar desde git","web.clone.up":"Subir","web.clone.use.dir":"Usar {dir}","web.composer.attach":"Adjuntar imagen","web.composer.maximages":"Como máximo {max} imágenes por mensaje.","web.composer.unsupported":"Tipo de imagen no compatible: {type}","web.composer.voice":"Dictado por voz","web.logout.failed":"No se pudo confirmar el cierre de sesión. Inténtalo de nuevo.","web.pair.approve.in":"Aprueba en el escritorio o en un teléfono vinculado · caduca en {time}","web.pair.approved":"Aprobado. Abriendo Backplane…","web.pair.cancelled":"Cancelado.","web.pair.code":"Código de comparación","web.pair.denied":"Se rechazó la solicitud de vinculación.","web.pair.expired":"El código de vinculación caducó. Solicita uno nuevo para intentarlo otra vez.","web.pair.failed":"Falló la solicitud de vinculación ({status})","web.pair.name":"Nombre del navegador","web.pair.nocode":"El hub no devolvió un código de comparación.","web.pair.ratelimited":"Demasiados intentos de vinculación. Espera un momento e inténtalo de nuevo.","web.pair.request":"Solicitar vinculación","web.pair.requesting":"Solicitando código de vinculación…","web.pair.subtitle":"Vincula este navegador con tu hub. Aprueba el código de 6 dígitos en Backplane › Ajustes › Dispositivos.","web.pair.unreachable":"No se pudo conectar con el hub. Comprueba tu conexión de tailnet.","web.plan.awaiting":"{n} esperando aprobación","web.plan.net.one":"1 red","web.plan.nets":"{n} redes"},ja:{"agy.signout":"サインアウト","android.hub.machines.approve":"承認","android.load.earlier":"以前のメッセージを読み込む","approval.dismiss":"閉じる","approval.implement":"実装","ask.plan":"提案されたプラン","bots.rooms":"ルーム","bots.tab.browser":"ブラウザ","common.cancel":"キャンセル","common.close":"閉じる","common.copy":"コピー","common.delete":"削除","common.refresh":"更新","common.remove":"削除","common.save":"保存","composer.placeholder":"何でも質問:@bot、>thread、%project、#room、$skill、/btw","composer.send":"送信","composer.stop":"停止","gpui.acct.connected":"接続済み","gpui.acct.not.connected":"未接続","gpui.acct.sign.in.expired":"サインインの期限切れ","gpui.ask.plan.ready":"確認待ち","gpui.ask.plan.revise":"修正","gpui.ask.plan.reviseph":"計画のどこを変更しますか?","gpui.ask.plan.sendrev":"修正を送る","gpui.b.in.reply.to":"↩ 返信先:{quote}","gpui.b.replying.to":"↩ 返信中:{line}","gpui.bots.recall.off":"オフ","gpui.bots.recall.on":"オン","gpui.c.term.collapse":"折りたたむ","gpui.c.term.expand":"展開","gpui.commands":"コマンド","gpui.e.open.folder":"フォルダを開く","gpui.filter.projects.and.threads":"プロジェクトとスレッドを絞り込む","gpui.fold.or.unfold.the.sidebar":"サイドバーを折りたたむ/開く","gpui.follow.paused":"追従を一時停止中","gpui.follow.wait":"追従中: エージェントの次の編集を待っています","gpui.gerbers":"ガーバー","gpui.improvements":"改善","gpui.jump.to.a.thread.run":"スレッドへ移動、コマンドを実行、または発言を検索","gpui.mgmt.bom.dnp":"実装しない","gpui.mgmt.bom.nompn":"MPNなし","gpui.mgmt.checks.all":"すべて","gpui.mgmt.checks.fix":"エージェントに直してもらう","gpui.mgmt.checks.run":"実行","gpui.mgmt.close":"パネルを閉じる","gpui.mgmt.fab.apply":"適用","gpui.mgmt.fab.changed":"前回見てから変わったところ","gpui.mgmt.fab.derived":"* 製造元のページから計算した値です(milをmmに、径からランドを)。薄い色の項目はリジッド基板の値です(この基板のページに記載がないもの)。日付を押すと読んだページが開きます。","gpui.mgmt.fab.extra":"追加料金","gpui.mgmt.fab.findings":"指摘","gpui.mgmt.fab.free":"基本料金","gpui.mgmt.fab.judge":"データシート","gpui.mgmt.fab.limit":"項目","gpui.mgmt.fab.readcol":"読んだ日","gpui.mgmt.fab.refresh":"再読み込み","gpui.mgmt.fab.reviewbtn":"レビュー","gpui.mgmt.fab.seen":"確認済み","gpui.mgmt.fab.thefab":"製造元","gpui.mgmt.fab.use":"使う","gpui.mgmt.life.nopart":"この部品の記録はまだありません。","gpui.mgmt.life.reading":"履歴を読んでいます…","gpui.mgmt.plan.addnote":"メモを追加","gpui.mgmt.plan.all":"すべて承認","gpui.mgmt.plan.before":"配線前に計画する","gpui.mgmt.plan.compact":"標準","gpui.mgmt.plan.done":"完了","gpui.mgmt.plan.drawn":"計画の配線経路とプレーンは、このパネルを開いている間だけ基板上に表示されます。閉じると消えます。","gpui.mgmt.plan.edited":"編集済み","gpui.mgmt.plan.elsewhere":"{board}の配線計画が承認を待っています","gpui.mgmt.plan.emptysub":"計画が提案されると、レイヤー・コリドー・ベタ領域がここに表示されます。","gpui.mgmt.plan.expand":"拡大","gpui.mgmt.plan.fit":"全体表示","gpui.mgmt.plan.grid.all":"全レイヤー","gpui.mgmt.plan.grid.pair":"並べて表示","gpui.mgmt.plan.grid.single":"単一","gpui.mgmt.plan.hide":"完了を隠す","gpui.mgmt.plan.hint":"頂点をドラッグして誘導 · 辺の + をクリックで追加 · 頂点を右クリックで削除","gpui.mgmt.plan.keysnote":"このバージョンのKiCadでは、このパネルから承認してください。プランビューでのKiCadのA・R・Wキーはまだ計画のものではありません(Aはフットプリントの追加を開きます)。KiCadを更新してください。","gpui.mgmt.plan.layer":"層を承認","gpui.mgmt.plan.layer.short":"レイヤー","gpui.mgmt.plan.lock":"ロック","gpui.mgmt.plan.locked":"ロック中","gpui.mgmt.plan.noboard":"この基板の配線計画はありません。","gpui.mgmt.plan.noitems":"このレイヤーにコリドーまたはプレーンがありません","gpui.mgmt.plan.note.placeholder":"ルーターへの指示メモ…","gpui.mgmt.plan.nothing":"承認待ちはありません","gpui.mgmt.plan.offwords":"エージェントは指示どおりに配線します。オンにすると、まず配線計画を提案し、ここで承認したものだけを配線します。","gpui.mgmt.plan.onwords":"銅箔層が4層以上、またはネットが60本を超える基板では、配線の前にエージェントがここで配線経路とプレーン領域を提案します。承認したものだけを配線します。","gpui.mgmt.plan.reading":"配線計画を読んでいます…","gpui.mgmt.plan.reference":"基準 {layer}","gpui.mgmt.plan.refused":"KiCad が拒否しました","gpui.mgmt.plan.reject":"却下","gpui.mgmt.plan.rejectlayer":"レイヤーを却下","gpui.mgmt.plan.reqplain":"承認が求められています","gpui.mgmt.plan.requested":"承認が求められています: {what}","gpui.mgmt.plan.saved":"保存された計画","gpui.mgmt.plan.show":"完了を表示","gpui.mgmt.plan.st.approved":"承認済み","gpui.mgmt.plan.st.awaiting":"承認待ち","gpui.mgmt.plan.st.blocked":"ブロック","gpui.mgmt.plan.st.empty":"空","gpui.mgmt.plan.st.partial":"一部完了","gpui.mgmt.plan.st.rejected":"却下","gpui.mgmt.plan.st.routed":"配線済み","gpui.mgmt.plan.st.routing":"配線中","gpui.mgmt.plan.st.verified":"検証済み","gpui.mgmt.plan.stackup.short":"スタックアップ","gpui.mgmt.plan.stop":"配線を止める","gpui.mgmt.plan.sync":"ズーム連動","gpui.mgmt.plan.tab":"計画","gpui.mgmt.plan.unlock":"ロック解除","gpui.mgmt.plan.verify":"検証","gpui.mgmt.plan.view.canvas":"キャンバス","gpui.mgmt.plan.view.list":"リスト","gpui.mgmt.plan.view.split":"分割","gpui.mgmt.plan.width":"幅","gpui.next.thread":"次のスレッド","gpui.nothing.matches":"一致するものはありません","gpui.planmode.bar.always":"計画モード — 編集前に調査して計画を提案します","gpui.planmode.bar.executing":"承認された計画を実行しています","gpui.planmode.bar.once":"計画モード (1回) — 編集前に調査して計画を提案します","gpui.planmode.bar.pending":"提案された計画が下のレビューを待っています","gpui.planmode.bar.planning":"計画中 — 編集前の計画を作成しています","gpui.planmode.chip.building":"実行中","gpui.planmode.chip.once":"計画 · 1回","gpui.planmode.scope.always":"常時","gpui.planmode.scope.once":"1回","gpui.planmode.tip":"実行前に計画を作成 (1回・常時・オフ)","gpui.planmode.top.executing":"計画を実行中","gpui.planmode.top.once":"計画 (1回)","gpui.planmode.top.pending":"計画を確認","gpui.planmode.top.planning":"計画中","gpui.previous.thread":"前のスレッド","gpui.rail.no.board":"このプロジェクトには基板がありません","gpui.rail.no.mech":"このプロジェクトには機械部品がありません","gpui.rail.no.schematic":"このプロジェクトには回路図がありません","gpui.rail.split.needs.both":"分割表示には基板と回路図が必要です","home.away":"ホーム({name})はオフラインです","home.away.queued":"ホーム({name})はオフラインです · {n} 件待機中","home.away.since":"ホーム({name})は {time} からオフラインです","home.away.since.queued":"ホーム({name})は {time} からオフラインです · {n} 件待機中","home.machine":"ホームマシン","home.move.failed":"ホームの移動に失敗しました","home.move.failed.note":"ホームの移動に失敗しました: {note}","home.move.here":"このマシンをホームにする","home.moving":"ホームを {to} へ移動中…","home.moving.step":"ホームを {to} へ移動中: {step}","hub.back.crash":"予期せず停止したBackplaneが戻りました","hub.restarting":"Backplaneを再起動しています…","hub.restarting.build":"Backplaneを再起動しています…(新しいビルド {build})","hub.stopped":"Backplaneは停止しました","ios.hub.address.field":"ハブのアドレス","menu.pin":"ピン留め","menu.settle":"完了","menu.unpin":"ピン留めを解除","model.col.agent":"エージェント","notify.settled":"完了","palette.archive":"スレッドをアーカイブ","palette.command.placeholder":"コマンドまたはスレッドを入力","palette.diff":"差分:このスレッドの変更","palette.newthread":"新しいスレッド","palette.settings":"設定","palette.terminal":"ターミナル","palette.unarchive":"スレッドのアーカイブを解除","phone.unsettle":"未完了に戻す","reply.action":"返信","reply.cancel":"返信をやめる","reply.to":"返信先:","secret.you":"あなた","settings.lang":"言語","sheet.rename":"スレッド名を変更","sidebar.add.project":"プロジェクトを追加","sidebar.search.projects":"プロジェクトを検索","thread.context.base":"Backplane","thread.context.copied":"プロンプトをコピーしました。","thread.context.copy":"プロンプトをコピー","thread.context.disable":"無効にする","thread.context.enable":"有効にする","thread.context.index":"利用可能なスキルの一覧","thread.context.injected.label":"追加されたプロジェクトの指示","thread.context.instructions":"指示","thread.context.mcp":"プロジェクトの MCP","thread.context.native.note":"Backplane が起動時に渡すプロンプトです。ネイティブファイルはプロバイダーが読み込みます。","thread.context.none.instructions":"プロジェクトの指示が見つかりません。","thread.context.none.mcp":"プロジェクトの MCP 設定が見つかりません。","thread.context.reading":"スレッドのコンテキストを読み込み中…","thread.context.size":"{bytes} B・約{tokens}トークン","thread.context.skills":"スキル","thread.context.system":"システムプロンプト","thread.context.title":"コンテキストとプロンプト","thread.context.trust":"承認して有効にする","thread.new":"新しいスレッド","tools.pinned":"固定中","tools.retry":"再試行","tour.title.bots":"ボット","viewer.board":"基板","viewer.diff":"差分","viewer.files":"ファイル","viewer.mech":"Mech","viewer.review":"レビュー","viewer.schematic":"回路図","viewer.solid":"3D","web.chat.answer.btn":"回答","web.chat.answer.placeholder":"回答を入力…","web.chat.answered":"回答済み: {answer}","web.chat.choose":"左側からプロジェクトのスレッドを選んで開始してください。","web.chat.empty":"まだメッセージはありません。下に入力して開始してください。","web.chat.finished":"完了 {time}","web.chat.finished.dur":"完了 {time} · {dur}","web.chat.loading":"メッセージを読み込んでいます…","web.chat.review.mode":"レビューモード","web.chat.streaming":"受信中…","web.clone.add.dir":"{dir} を追加","web.clone.back":"戻る","web.clone.change.folder":"フォルダを変更","web.clone.cloned":"{repo} を {dest} にクローンしました","web.clone.cloning":"{repo} を {dest} にクローン中","web.clone.copied":"コピーしました","web.clone.first":"最初のメッセージ: {text}","web.clone.folder.name":"フォルダ名","web.clone.go":"クローン","web.clone.loading":"読み込み中…","web.clone.no.folders":"フォルダがありません","web.clone.open.project":"プロジェクトを開く","web.clone.open.thread":"スレッドを開く","web.clone.private":"非公開","web.clone.repo.placeholder":"https / ssh の URL、または owner/repo","web.clone.retry":"もう一度","web.clone.same":"すでにそこにクローンされています: そのまま追加します。","web.clone.signin":"GitHub にサインイン","web.clone.signin.done":"GitHub にサインインしました","web.clone.signin.enter":"このコードを GitHub に入力してください:","web.clone.signin.wait":"GitHub のサインインを開始しています…","web.clone.start.thread":"スレッドを開始","web.clone.stopped":"{repo} のクローンを中止しました","web.clone.tab":"git からクローン","web.clone.up":"上へ","web.clone.use.dir":"{dir} を使う","web.composer.attach":"画像を添付","web.composer.maximages":"1 件のメッセージに添付できる画像は最大 {max} 枚です。","web.composer.unsupported":"未対応の画像形式です: {type}","web.composer.voice":"音声入力","web.logout.failed":"サインアウトを確認できませんでした。もう一度お試しください。","web.pair.approve.in":"デスクトップまたはペアリング済みの端末で承認してください · 有効期限 {time}","web.pair.approved":"承認されました。Backplane を開いています…","web.pair.cancelled":"キャンセルしました。","web.pair.code":"確認コード","web.pair.denied":"ペアリングのリクエストが拒否されました。","web.pair.expired":"ペアリングコードの有効期限が切れました。新しいコードをリクエストしてください。","web.pair.failed":"ペアリングのリクエストに失敗しました ({status})","web.pair.name":"ブラウザー名","web.pair.nocode":"ハブから確認コードが返されませんでした。","web.pair.ratelimited":"ペアリングの試行回数が多すぎます。しばらく待ってからやり直してください。","web.pair.request":"ペアリングをリクエスト","web.pair.requesting":"ペアリングコードをリクエストしています…","web.pair.subtitle":"このブラウザーをハブとペアリングします。Backplane › 設定 › デバイス で 6 桁のコードを承認してください。","web.pair.unreachable":"ハブに接続できませんでした。tailnet の接続を確認してください。","web.plan.awaiting":"{n} 件が承認待ち","web.plan.net.one":"1 ネット","web.plan.nets":"{n} ネット"}};function Q(a,t){if(!t)return a;return a.replace(/\{([a-zA-Z0-9_.-]+)\}/g,(s,r)=>Object.prototype.hasOwnProperty.call(t,r)?String(t[r]):s)}var G=te(),W=new Set,V=new Map;for(let[a,t]of Object.entries(F.en||{}))if(typeof t==="string"&&!V.has(t))V.set(t,a);function te(){let a=typeof navigator<"u"&&navigator.language?navigator.language.toLowerCase():"en";if(a.startsWith("ja"))return"ja";if(a.startsWith("es"))return"es";return"en"}function Y(){if(typeof document<"u"&&document.documentElement)document.documentElement.lang=G}Y();function me(a){return W.add(a),()=>{W.delete(a)}}function ue(a){if(!a)return!1;let t=a.toLowerCase(),s=t.startsWith("ja")?"ja":t.startsWith("es")?"es":t.startsWith("en")?"en":"";if(!s)return!1;let r=s!==G;if(G=s,Y(),r)for(let d of W)d(G);return r}function c(a,t,s){let d=(F[G]||F.en||{})[a]??F.en?.[a]??t??a;return Q(d,s)}function ge(a){if(!a)return"";let t=V.get(a);if(!t)return a;return c(t,a)}var ae=[[1,26,7,1,[]],[2,44,10,1,[6,18]],[3,70,15,1,[6,22]],[4,100,20,1,[6,26]],[5,134,26,1,[6,30]],[6,172,18,2,[6,34]]],I=new Uint8Array(512),_=new Uint8Array(256);{let a=1;for(let t=0;t<255;t++)if(I[t]=a,_[a]=t,a<<=1,a&256)a^=285;for(let t=255;t<512;t++)I[t]=I[t-255]}function J(a,t){return a===0||t===0?0:I[_[a]+_[t]]}function ne(a){let t=new Uint8Array([1]);for(let s=0;s{let m=e-i*n;return Math.ceil((12+t.length*8)/8)<=m});if(!s)return null;let[r,d,u,f,E]=s,w=d-u*f,g=[],S=(e,i)=>{for(let n=i-1;n>=0;n--)g.push(e>>>n&1)};S(4,4),S(t.length,8);for(let e of t)S(e,8);for(let e=0;e<4&&g.length{if(e<0||i<0||e>=p||i>=p)return;z[e*p+i]=n?1:0,C[e*p+i]=1},R=(e,i)=>{for(let n=-1;n<=7;n++)for(let m=-1;m<=7;m++){let k=e+n,l=i+m,o=n>=0&&n<=6&&m>=0&&m<=6&&(n===0||n===6||m===0||m===6||n>=2&&n<=4&&m>=2&&m<=4);b(k,l,o)}};R(0,0),R(0,p-7),R(p-7,0);for(let e=8;e=1;e-=2){if(e===6)e=5;let i=(e+1&2)===0;for(let n=0;n>>3]>>>7-(j&7)&1,j++;let o=(m+l&1)===0?h^1:h;z[m*p+l]=o}}}let N=30660;for(let e=0;e<=5;e++)b(8,e,(N>>>14-e&1)===1);b(8,7,(N>>>8&1)===1),b(8,8,(N>>>7&1)===1),b(7,8,(N>>>6&1)===1);for(let e=0;e<=5;e++)b(5-e,8,(N>>>5-e&1)===1);for(let e=0;e<8;e++)b(8,p-1-e,(N>>>e&1)===1);for(let e=0;e<7;e++)b(p-7+e,8,(N>>>14-e&1)===1);return{size:p,modules:z}}function X(a){let t=oe(a);if(!t)return null;let s=2,r=t.size+s*2,d=document.createElementNS("http://www.w3.org/2000/svg","svg");d.setAttribute("viewBox",`0 0 ${r} ${r}`),d.setAttribute("role","img"),d.setAttribute("aria-label",`QR code for ${a}`),d.setAttribute("shape-rendering","crispEdges"),d.classList.add("bp-qr-svg");let u=document.createElementNS("http://www.w3.org/2000/svg","rect");u.setAttribute("width",String(r)),u.setAttribute("height",String(r)),u.setAttribute("fill","#ffffff"),d.appendChild(u);let f="";for(let w=0;w{let h=l.trim();if(!h)return;let o=h.startsWith("https://")?h:`https://${h}`;if(!o.startsWith("https://")||o.length<=8)return;let x=document.createElement("div");x.className="bp-pair-addr-meta";let v=document.createElement("div");v.className="bp-pair-code-label",v.textContent=c("ios.hub.address.field","Hub address");let y=document.createElement("code");y.className="bp-pair-addr-url",y.textContent=o,y.setAttribute("data-testid","pair-address");let P=document.createElement("button");P.type="button",P.className="bp-pair-copy";let H=c("common.copy","Copy");P.textContent=H,P.addEventListener("click",()=>{navigator.clipboard?.writeText(o).then(()=>{P.textContent=c("web.clone.copied","Copied"),window.setTimeout(()=>{P.textContent=H},1200)}).catch(()=>{})}),x.append(v,y,P);let U=document.createDocumentFragment();U.appendChild(x);let K=X(o);if(K){let O=document.createElement("div");O.className="bp-pair-qr",O.setAttribute("data-testid","pair-qr"),O.appendChild(K),U.appendChild(O)}p.replaceChildren(U),p.classList.remove("bp-hidden")};fetch("/auth/web/info",{credentials:"same-origin"}).then(async(l)=>{if(!l.ok)return;let h=await l.json();if(typeof h.address==="string")z(h.address)}).catch(()=>{}),t.append(s,u,f,S,A,p),a.appendChild(t);let C=null,b=null,R=null,j=0,D=0,N=150,e=1000;function i(){if(j++,R)R.abort(),R=null;if(C!==null)window.clearTimeout(C),C=null;if(b!==null)window.clearInterval(b),b=null}function n(l="",h=!1){i(),f.classList.remove("bp-hidden"),S.classList.add("bp-hidden"),g.disabled=!1,A.textContent=l,A.className=h?"bp-pair-status bp-bad":"bp-pair-status"}function m(){let l=D-Date.now();if(l<=0){n(c("web.pair.expired","Pairing code expired. Request a new code to try again."),!0);return}B.textContent=c("web.pair.approve.in","Approve on desktop or paired phone · expires in {time}",{time:pe(l)})}async function k(l){if(l!==j)return;if(D>0&&Date.now()>=D){n(c("web.pair.expired","Pairing code expired. Request a new code to try again."),!0);return}let h=new AbortController;R=h;try{let o=await fetch("/auth/web/poll",{method:"POST",credentials:"same-origin",headers:{"Content-Type":"application/json"},body:"{}",signal:h.signal});if(l!==j)return;if(e=1000,o.status===202){C=window.setTimeout(()=>{k(l)},150);return}if(o.status===200||o.status===204){let v={};if(o.status===200)try{v=await o.json()}catch{}if(l!==j)return;let y=(v.state||v.status||"").toLowerCase();if(o.status===204||v.approved===!0||y==="approved"||y==="ok"){i(),A.textContent=c("web.pair.approved","Approved. Opening Backplane…"),A.className="bp-pair-status bp-ok",window.location.replace("/");return}if(y==="denied"||y==="rejected"){n(c("web.pair.denied","Pairing request was denied."),!0);return}if(y==="expired"){n(c("web.pair.expired","Pairing code expired. Request a new code to try again."),!0);return}C=window.setTimeout(()=>{k(l)},150);return}if(o.status===429){let v=Number(o.headers.get("Retry-After")||"5"),y=Math.max(2000,(Number.isFinite(v)?v:5)*1000);C=window.setTimeout(()=>{k(l)},y);return}if(o.status===401||o.status===403||o.status===404||o.status===410){let v="";try{let y=await o.json();v=(y.state||y.status||y.error||"").toLowerCase()}catch{}if(l!==j)return;if(v==="denied"||v==="rejected"||o.status===403)n(c("web.pair.denied","Pairing request was denied."),!0);else n(c("web.pair.expired","Pairing code expired. Request a new code to try again."),!0);return}let x=e;e=Math.min(1e4,Math.round(e*1.8)),C=window.setTimeout(()=>{k(l)},x)}catch{if(l!==j)return;let o=e;e=Math.min(1e4,Math.round(e*1.8)),C=window.setTimeout(()=>{k(l)},o)}finally{if(R===h)R=null}}L.addEventListener("click",()=>{n(c("web.pair.cancelled","Cancelled."))}),f.addEventListener("submit",async(l)=>{l.preventDefault();let h=w.value.trim()||Z();g.disabled=!0,A.textContent=c("web.pair.requesting","Requesting pairing code…"),A.className="bp-pair-status";try{let o=await fetch("/auth/web/request",{method:"POST",credentials:"same-origin",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:h})});if(!o.ok){let H=c("web.pair.failed","Pairing request failed ({status})",{status:o.status});try{let U=await o.json();if(U.error)H=U.error}catch{}if(o.status===429)H=c("web.pair.ratelimited","Too many pairing attempts. Wait a moment and try again.");n(H,!0);return}let x=await o.json(),v=x.code||x.checkCode||"";if(!v){n(c("web.pair.nocode","Hub did not return a comparison code."),!0);return}let y=Date.now();D=x.expiresAt?x.expiresAt<10000000000?x.expiresAt*1000:x.expiresAt:y+(x.expiresIn?x.expiresIn*1000:120000),i();let P=j;e=1000,N=x.pollMs&&x.pollMs>=100?x.pollMs:150,M.textContent=re(v),f.classList.add("bp-hidden"),S.classList.remove("bp-hidden"),A.textContent="",m(),b=window.setInterval(m,1000),C=window.setTimeout(()=>{k(P)},N)}catch{n(c("web.pair.unreachable","Could not reach the hub. Check your tailnet connection."),!0)}})}if(document.readyState==="loading")document.addEventListener("DOMContentLoaded",ee);else ee(); +var U={en:{"agy.signout":"Sign out","android.hub.machines.approve":"Approve","android.load.earlier":"load earlier","approval.dismiss":"Dismiss","approval.implement":"Implement","ask.plan":"Proposed plan","bots.rooms":"Rooms","bots.tab.browser":"Browser","common.cancel":"Cancel","common.close":"Close","common.copy":"Copy","common.delete":"Delete","common.refresh":"Refresh","common.remove":"Remove","common.save":"Save","composer.placeholder":"Ask anything: @bot, >thread, %project, #room, $skill, /btw","composer.send":"Send","composer.stop":"Stop","gpui.acct.connected":"Connected","gpui.acct.not.connected":"Not connected","gpui.acct.sign.in.expired":"Sign-in expired","gpui.ask.plan.ready":"Ready for review","gpui.ask.plan.revise":"Revise","gpui.ask.plan.reviseph":"What should change in the plan?","gpui.ask.plan.sendrev":"Send revision","gpui.b.in.reply.to":"↩ In reply to: {quote}","gpui.b.replying.to":"↩ Replying to: {line}","gpui.bots.recall.off":"Off","gpui.bots.recall.on":"On","gpui.c.term.collapse":"Collapse","gpui.c.term.expand":"Expand","gpui.commands":"Commands","gpui.e.open.folder":"Open folder","gpui.filter.projects.and.threads":"Filter projects and threads","gpui.fold.or.unfold.the.sidebar":"Fold or unfold the sidebar","gpui.follow.paused":"Following paused","gpui.follow.wait":"Following: waiting for the agent's next edit","gpui.gerbers":"Gerbers","gpui.improvements":"Improvements","gpui.jump.to.a.thread.run":"Jump to a thread, run a command or find what was said","gpui.mgmt.bom.dnp":"DNP","gpui.mgmt.bom.nompn":"no MPN","gpui.mgmt.checks.all":"All","gpui.mgmt.checks.fix":"Fix with agent","gpui.mgmt.checks.run":"Run","gpui.mgmt.close":"Close the panel","gpui.mgmt.fab.apply":"Apply","gpui.mgmt.fab.changed":"Changed since you last looked","gpui.mgmt.fab.derived":"* worked out from the fab's page (a mil in mm, a ring from a diameter). Dimmed: the rigid board's value, where this board's page says nothing else. A date opens the page it was read from.","gpui.mgmt.fab.extra":"Costs more","gpui.mgmt.fab.findings":"Findings","gpui.mgmt.fab.free":"Base price","gpui.mgmt.fab.judge":"Datasheets","gpui.mgmt.fab.limit":"Limit","gpui.mgmt.fab.readcol":"Read","gpui.mgmt.fab.refresh":"Refresh","gpui.mgmt.fab.reviewbtn":"Review","gpui.mgmt.fab.seen":"Seen","gpui.mgmt.fab.thefab":"The fab","gpui.mgmt.fab.use":"Use","gpui.mgmt.life.nopart":"No reading of this part yet.","gpui.mgmt.life.reading":"Reading its history…","gpui.mgmt.plan.addnote":"Add note","gpui.mgmt.plan.all":"Approve all","gpui.mgmt.plan.before":"Plan before routing","gpui.mgmt.plan.compact":"Compact","gpui.mgmt.plan.done":"done","gpui.mgmt.plan.drawn":"The plan's corridors and planes are drawn on the board while this panel is open. Close it to hide them.","gpui.mgmt.plan.edited":"Edited","gpui.mgmt.plan.elsewhere":"A routing plan for {board} awaits your approval","gpui.mgmt.plan.emptysub":"Layers, corridors, and planes appear here once a plan is proposed.","gpui.mgmt.plan.expand":"Expand","gpui.mgmt.plan.fit":"Fit","gpui.mgmt.plan.grid.all":"All layers","gpui.mgmt.plan.grid.pair":"Side by side","gpui.mgmt.plan.grid.single":"Single","gpui.mgmt.plan.hide":"Hide done","gpui.mgmt.plan.hint":"Drag waypoints to steer · Click + on edge to insert · Right-click vertex to remove","gpui.mgmt.plan.keysnote":"On this KiCad version, approve from this panel: in plan view KiCad's A, R and W keys aren't the plan's yet (A opens Add Footprint). Update KiCad.","gpui.mgmt.plan.layer":"Approve layer","gpui.mgmt.plan.layer.short":"Layer","gpui.mgmt.plan.lock":"Lock","gpui.mgmt.plan.locked":"Locked","gpui.mgmt.plan.noboard":"No routing plan for this board.","gpui.mgmt.plan.noitems":"No corridors or planes on this layer","gpui.mgmt.plan.note.placeholder":"Steering note for router…","gpui.mgmt.plan.nothing":"Nothing awaits your approval","gpui.mgmt.plan.offwords":"Agents route as you ask. Turn it on to have them propose a routing plan first and route only what you approve here.","gpui.mgmt.plan.onwords":"Before routing a board with 4 or more copper layers or more than 60 nets, the agent proposes corridors and plane regions here. It routes only what you approve.","gpui.mgmt.plan.reading":"Reading the routing plan…","gpui.mgmt.plan.reference":"over {layer}","gpui.mgmt.plan.refused":"KiCad refused","gpui.mgmt.plan.reject":"Reject","gpui.mgmt.plan.rejectlayer":"Reject layer","gpui.mgmt.plan.reqplain":"Approval requested","gpui.mgmt.plan.requested":"Approval requested: {what}","gpui.mgmt.plan.saved":"saved plan","gpui.mgmt.plan.show":"Show done","gpui.mgmt.plan.st.approved":"Approved","gpui.mgmt.plan.st.awaiting":"Awaiting review","gpui.mgmt.plan.st.blocked":"Blocked","gpui.mgmt.plan.st.empty":"Empty","gpui.mgmt.plan.st.partial":"Partial","gpui.mgmt.plan.st.rejected":"Rejected","gpui.mgmt.plan.st.routed":"Routed","gpui.mgmt.plan.st.routing":"Routing","gpui.mgmt.plan.st.verified":"Verified","gpui.mgmt.plan.stackup.short":"Stackup","gpui.mgmt.plan.stop":"Stop routing","gpui.mgmt.plan.sync":"Link zoom","gpui.mgmt.plan.tab":"Plan","gpui.mgmt.plan.unlock":"Unlock","gpui.mgmt.plan.verify":"Verify","gpui.mgmt.plan.view.canvas":"Canvas","gpui.mgmt.plan.view.list":"List","gpui.mgmt.plan.view.split":"Split","gpui.mgmt.plan.width":"Width","gpui.next.thread":"Next thread","gpui.nothing.matches":"Nothing matches","gpui.planmode.bar.always":"Plan mode — explores and proposes a plan before editing","gpui.planmode.bar.executing":"Building the approved plan","gpui.planmode.bar.once":"Plan mode (1 turn) — explores and proposes a plan before editing","gpui.planmode.bar.pending":"Proposed plan awaits review below","gpui.planmode.bar.planning":"Planning — drafting a plan before edits","gpui.planmode.chip.building":"Building","gpui.planmode.chip.once":"Plan · 1t","gpui.planmode.scope.always":"Always","gpui.planmode.scope.once":"1 turn","gpui.planmode.tip":"Plan before acting (1 turn, always, or off)","gpui.planmode.top.executing":"Building plan","gpui.planmode.top.once":"Plan (1 turn)","gpui.planmode.top.pending":"Review plan","gpui.planmode.top.planning":"Planning","gpui.previous.thread":"Previous thread","gpui.rail.no.board":"No board in this project","gpui.rail.no.mech":"No mechanical parts in this project","gpui.rail.no.schematic":"No schematic in this project","gpui.rail.split.needs.both":"Split needs a board and a schematic","home.away":"Home ({name}) is away","home.away.queued":"Home ({name}) is away · {n} queued","home.away.since":"Home ({name}) is away since {time}","home.away.since.queued":"Home ({name}) is away since {time} · {n} queued","home.machine":"Home machine","home.move.failed":"Home move failed","home.move.failed.note":"Home move failed: {note}","home.move.here":"Make this machine the home","home.moving":"Moving home to {to}…","home.moving.step":"Moving home to {to}: {step}","hub.back.crash":"Backplane is back after it stopped unexpectedly","hub.restarting":"Restarting Backplane…","hub.restarting.build":"Restarting Backplane… (new build {build})","hub.stopped":"Backplane stopped","ios.hub.address.field":"Hub address","menu.pin":"Pin","menu.settle":"Settle","menu.unpin":"Unpin","model.col.agent":"Agent","notify.settled":"Settled","palette.archive":"Archive thread","palette.command.placeholder":"Type a command or a thread","palette.diff":"Diff: what this thread changed","palette.newthread":"New thread","palette.settings":"Settings","palette.terminal":"Terminal","palette.unarchive":"Unarchive thread","phone.unsettle":"Unsettle","provider.notice.button":"Open Settings → Accounts","provider.notice.head":"No AI provider connected","provider.notice.senderr":"No AI provider connected yet. Open Settings → Accounts to connect Claude, Codex, Antigravity, or another provider.","provider.notice.text.none":"Connect Claude, Codex, Antigravity, or another provider to start chatting.","provider.notice.text.signedout":"Sign in to Claude, Codex, or another provider in Settings → Accounts to start chatting.","reply.action":"Reply","reply.cancel":"Cancel reply","reply.to":"In reply to:","secret.you":"You","settings.lang":"Language","sheet.rename":"Rename thread","sidebar.add.project":"Add project","sidebar.search.projects":"Search projects","thread.context.base":"Backplane","thread.context.copied":"Prompt copied.","thread.context.copy":"Copy prompt","thread.context.disable":"Disable","thread.context.enable":"Enable","thread.context.index":"Available skills index","thread.context.injected.label":"Injected project instructions","thread.context.instructions":"Instructions","thread.context.mcp":"Project MCPs","thread.context.native.note":"Backplane’s launch prompt. Native files are loaded by the provider.","thread.context.none.instructions":"No project instructions found.","thread.context.none.mcp":"No project MCP configurations found.","thread.context.reading":"Reading thread context…","thread.context.size":"{bytes} B · ≈{tokens} tokens","thread.context.skills":"Skills","thread.context.system":"System Prompt","thread.context.title":"Context & Prompt","thread.context.trust":"Trust and enable","thread.new":"New thread","tools.pinned":"Pinned","tools.retry":"Retry","tour.title.bots":"Bots","viewer.board":"Board","viewer.diff":"Diff","viewer.files":"Files","viewer.mech":"Mech","viewer.review":"Review","viewer.schematic":"Schematic","viewer.solid":"3D","web.chat.answer.btn":"Answer","web.chat.answer.placeholder":"Type answer…","web.chat.answered":"Answered: {answer}","web.chat.choose":"Choose a project thread on the left to begin.","web.chat.empty":"No messages yet. Type below to start a turn.","web.chat.finished":"Finished {time}","web.chat.finished.dur":"Finished {time} · {dur}","web.chat.loading":"Loading messages…","web.chat.review.mode":"Review mode","web.chat.streaming":"Streaming…","web.clone.add.dir":"Add {dir}","web.clone.back":"Back","web.clone.change.folder":"Change folder","web.clone.cloned":"Cloned {repo} into {dest}","web.clone.cloning":"Cloning {repo} into {dest}","web.clone.copied":"Copied","web.clone.first":"First message: {text}","web.clone.folder.name":"Folder name","web.clone.go":"Clone","web.clone.loading":"Loading…","web.clone.no.folders":"No folders here","web.clone.open.project":"Open the project","web.clone.open.thread":"Open the thread","web.clone.private":"private","web.clone.repo.placeholder":"https or ssh URL, or owner/repo","web.clone.retry":"Try again","web.clone.same":"Already cloned there: it is added as it is.","web.clone.signin":"Sign in to GitHub","web.clone.signin.done":"Signed in to GitHub","web.clone.signin.enter":"Enter this code on GitHub:","web.clone.signin.wait":"Starting GitHub sign-in…","web.clone.start.thread":"Start a thread","web.clone.stopped":"Stopped cloning {repo}","web.clone.tab":"Clone from git","web.clone.up":"Up","web.clone.use.dir":"Use {dir}","web.composer.attach":"Attach image","web.composer.maximages":"At most {max} images per message.","web.composer.unsupported":"Unsupported image type: {type}","web.composer.voice":"Voice dictation","web.logout.failed":"Could not confirm sign-out. Try again.","web.pair.approve.in":"Approve on desktop or paired phone · expires in {time}","web.pair.approved":"Approved. Opening Backplane…","web.pair.cancelled":"Cancelled.","web.pair.code":"Comparison code","web.pair.denied":"Pairing request was denied.","web.pair.expired":"Pairing code expired. Request a new code to try again.","web.pair.failed":"Pairing request failed ({status})","web.pair.name":"Browser name","web.pair.nocode":"Hub did not return a comparison code.","web.pair.ratelimited":"Too many pairing attempts. Wait a moment and try again.","web.pair.request":"Request pairing","web.pair.requesting":"Requesting pairing code…","web.pair.subtitle":"Pair this browser with your hub. Approve the 6-digit code in Backplane › Settings › Devices.","web.pair.unreachable":"Could not reach the hub. Check your tailnet connection.","web.plan.awaiting":"{n} awaiting approval","web.plan.net.one":"1 net","web.plan.nets":"{n} nets","web.settings.providers":"AI providers","web.settings.providers.browser":"Connect a provider in the Backplane desktop or mobile app under Settings → Accounts."},es:{"agy.signout":"Cerrar sesión","android.hub.machines.approve":"Aprobar","android.load.earlier":"cargar anteriores","approval.dismiss":"Descartar","approval.implement":"Implementar","ask.plan":"Plan propuesto","bots.rooms":"Salas","bots.tab.browser":"Navegador","common.cancel":"Cancelar","common.close":"Cerrar","common.copy":"Copiar","common.delete":"Eliminar","common.refresh":"Actualizar","common.remove":"Quitar","common.save":"Guardar","composer.placeholder":"Pregunta lo que sea: @bot, >hilo, %proyecto, #sala, $skill, /btw","composer.send":"Enviar","composer.stop":"Detener","gpui.acct.connected":"Conectado","gpui.acct.not.connected":"No conectado","gpui.acct.sign.in.expired":"Sesión caducada","gpui.ask.plan.ready":"Listo para revisar","gpui.ask.plan.revise":"Revisar","gpui.ask.plan.reviseph":"¿Qué debería cambiar en el plan?","gpui.ask.plan.sendrev":"Enviar revisión","gpui.b.in.reply.to":"↩ En respuesta a: {quote}","gpui.b.replying.to":"↩ Respondiendo a: {line}","gpui.bots.recall.off":"Desactivado","gpui.bots.recall.on":"Activado","gpui.c.term.collapse":"Contraer","gpui.c.term.expand":"Expandir","gpui.commands":"Comandos","gpui.e.open.folder":"Abrir carpeta","gpui.filter.projects.and.threads":"Filtrar proyectos e hilos","gpui.fold.or.unfold.the.sidebar":"Plegar o desplegar la barra lateral","gpui.follow.paused":"Seguimiento en pausa","gpui.follow.wait":"Siguiendo: esperando la próxima edición del agente","gpui.gerbers":"Gerbers","gpui.improvements":"Mejoras","gpui.jump.to.a.thread.run":"Saltar a un hilo, ejecutar un comando o buscar lo dicho","gpui.mgmt.bom.dnp":"DNP","gpui.mgmt.bom.nompn":"sin MPN","gpui.mgmt.checks.all":"Todas","gpui.mgmt.checks.fix":"Corregir con agente","gpui.mgmt.checks.run":"Ejecutar","gpui.mgmt.close":"Cerrar el panel","gpui.mgmt.fab.apply":"Aplicar","gpui.mgmt.fab.changed":"Cambió desde la última vez que miraste","gpui.mgmt.fab.derived":"* calculado desde la página del fabricante (un mil en mm, un anillo desde un diámetro). Atenuado: el valor de la placa rígida, cuando la página de esta placa no dice otra cosa. Una fecha abre la página de la que se leyó.","gpui.mgmt.fab.extra":"Cuesta más","gpui.mgmt.fab.findings":"Hallazgos","gpui.mgmt.fab.free":"Precio base","gpui.mgmt.fab.judge":"Hojas de datos","gpui.mgmt.fab.limit":"Límite","gpui.mgmt.fab.readcol":"Leído","gpui.mgmt.fab.refresh":"Actualizar","gpui.mgmt.fab.reviewbtn":"Revisar","gpui.mgmt.fab.seen":"Visto","gpui.mgmt.fab.thefab":"El fabricante","gpui.mgmt.fab.use":"Usar","gpui.mgmt.life.nopart":"Sin lectura de esta pieza aún.","gpui.mgmt.life.reading":"Leyendo su historial…","gpui.mgmt.plan.addnote":"Añadir nota","gpui.mgmt.plan.all":"Aprobar todo","gpui.mgmt.plan.before":"Planificar antes de rutear","gpui.mgmt.plan.compact":"Compacto","gpui.mgmt.plan.done":"hecho","gpui.mgmt.plan.drawn":"Los corredores y planos del plan se dibujan en la placa mientras este panel está abierto. Ciérralo para ocultarlos.","gpui.mgmt.plan.edited":"Editado","gpui.mgmt.plan.elsewhere":"Un plan de ruteo para {board} espera tu aprobación","gpui.mgmt.plan.emptysub":"Las capas, corredores y planos aparecerán aquí cuando se proponga un plan.","gpui.mgmt.plan.expand":"Expandir","gpui.mgmt.plan.fit":"Ajustar","gpui.mgmt.plan.grid.all":"Todas las capas","gpui.mgmt.plan.grid.pair":"Lado a lado","gpui.mgmt.plan.grid.single":"Única","gpui.mgmt.plan.hide":"Ocultar hechos","gpui.mgmt.plan.hint":"Arrastra vértices para guiar · Clic en + del borde para insertar · Clic derecho en vértice para quitar","gpui.mgmt.plan.keysnote":"En esta versión de KiCad, aprueba desde este panel: en la vista de plan las teclas A, R y W de KiCad aún no son del plan (A abre Añadir Huella). Actualiza KiCad.","gpui.mgmt.plan.layer":"Aprobar capa","gpui.mgmt.plan.layer.short":"Capa","gpui.mgmt.plan.lock":"Bloquear","gpui.mgmt.plan.locked":"Bloqueado","gpui.mgmt.plan.noboard":"No hay plan de ruteo para esta placa.","gpui.mgmt.plan.noitems":"Sin corredores ni planos en esta capa","gpui.mgmt.plan.note.placeholder":"Nota de guiado para el router…","gpui.mgmt.plan.nothing":"Nada espera tu aprobación","gpui.mgmt.plan.offwords":"Los agentes rutean como les pidas. Actívalo para que primero propongan un plan de ruteo y ruteen solo lo que apruebes aquí.","gpui.mgmt.plan.onwords":"Antes de rutear una placa con 4 o más capas de cobre o más de 60 redes, el agente propone aquí corredores y regiones de plano. Solo rutea lo que apruebes.","gpui.mgmt.plan.reading":"Leyendo el plan de ruteo…","gpui.mgmt.plan.reference":"sobre {layer}","gpui.mgmt.plan.refused":"KiCad lo rechazó","gpui.mgmt.plan.reject":"Rechazar","gpui.mgmt.plan.rejectlayer":"Rechazar capa","gpui.mgmt.plan.reqplain":"Aprobación solicitada","gpui.mgmt.plan.requested":"Aprobación solicitada: {what}","gpui.mgmt.plan.saved":"plan guardado","gpui.mgmt.plan.show":"Mostrar hechos","gpui.mgmt.plan.st.approved":"Aprobado","gpui.mgmt.plan.st.awaiting":"Esperando revisión","gpui.mgmt.plan.st.blocked":"Bloqueado","gpui.mgmt.plan.st.empty":"Vacío","gpui.mgmt.plan.st.partial":"Parcial","gpui.mgmt.plan.st.rejected":"Rechazado","gpui.mgmt.plan.st.routed":"Ruteado","gpui.mgmt.plan.st.routing":"Ruteando","gpui.mgmt.plan.st.verified":"Verificado","gpui.mgmt.plan.stackup.short":"Apilamiento","gpui.mgmt.plan.stop":"Detener ruteo","gpui.mgmt.plan.sync":"Vincular zoom","gpui.mgmt.plan.tab":"Plan","gpui.mgmt.plan.unlock":"Desbloquear","gpui.mgmt.plan.verify":"Verificar","gpui.mgmt.plan.view.canvas":"Lienzo","gpui.mgmt.plan.view.list":"Lista","gpui.mgmt.plan.view.split":"Dividido","gpui.mgmt.plan.width":"Ancho","gpui.next.thread":"Hilo siguiente","gpui.nothing.matches":"Nada coincide","gpui.planmode.bar.always":"Modo plan — explora y propone un plan antes de editar","gpui.planmode.bar.executing":"Ejecutando el plan aprobado","gpui.planmode.bar.once":"Modo plan (1 turno) — explora y propone un plan antes de editar","gpui.planmode.bar.pending":"El plan propuesto espera revisión abajo","gpui.planmode.bar.planning":"Planificando — redactando un plan antes de editar","gpui.planmode.chip.building":"Ejecutando","gpui.planmode.chip.once":"Plan · 1t","gpui.planmode.scope.always":"Siempre","gpui.planmode.scope.once":"1 turno","gpui.planmode.tip":"Planificar antes de actuar (1 turno, siempre u off)","gpui.planmode.top.executing":"Ejecutando plan","gpui.planmode.top.once":"Plan (1 turno)","gpui.planmode.top.pending":"Revisar plan","gpui.planmode.top.planning":"Planificando","gpui.previous.thread":"Hilo anterior","gpui.rail.no.board":"Este proyecto no tiene placa","gpui.rail.no.mech":"Este proyecto no tiene piezas mecánicas","gpui.rail.no.schematic":"Este proyecto no tiene esquema","gpui.rail.split.needs.both":"La vista dividida requiere una placa y un esquema","home.away":"El inicio ({name}) no está disponible","home.away.queued":"El inicio ({name}) no está disponible · {n} en cola","home.away.since":"El inicio ({name}) no está disponible desde las {time}","home.away.since.queued":"El inicio ({name}) no está disponible desde las {time} · {n} en cola","home.machine":"Máquina de inicio","home.move.failed":"No se pudo mover el inicio","home.move.failed.note":"No se pudo mover el inicio: {note}","home.move.here":"Hacer de esta máquina el inicio","home.moving":"Moviendo el inicio a {to}…","home.moving.step":"Moviendo el inicio a {to}: {step}","hub.back.crash":"Backplane volvió tras detenerse de forma inesperada","hub.restarting":"Reiniciando Backplane…","hub.restarting.build":"Reiniciando Backplane… (nueva compilación {build})","hub.stopped":"Backplane se detuvo","ios.hub.address.field":"Dirección del hub","menu.pin":"Fijar","menu.settle":"Cerrar","menu.unpin":"Desfijar","model.col.agent":"Agente","notify.settled":"Cerrado","palette.archive":"Archivar hilo","palette.command.placeholder":"Escribe un comando o un hilo","palette.diff":"Diff: qué cambió este hilo","palette.newthread":"Nuevo hilo","palette.settings":"Ajustes","palette.terminal":"Terminal","palette.unarchive":"Desarchivar hilo","phone.unsettle":"Reabrir","provider.notice.button":"Abrir Configuración → Cuentas","provider.notice.head":"No hay ningún proveedor de IA conectado","provider.notice.senderr":"Aún no hay ningún proveedor de IA conectado. Abre Configuración → Cuentas para conectar Claude, Codex, Antigravity u otro proveedor.","provider.notice.text.none":"Conecta Claude, Codex, Antigravity u otro proveedor para empezar a chatear.","provider.notice.text.signedout":"Inicia sesión en Claude, Codex u otro proveedor en Configuración → Cuentas para empezar a chatear.","reply.action":"Responder","reply.cancel":"Cancelar respuesta","reply.to":"En respuesta a:","secret.you":"Tú","settings.lang":"Idioma","sheet.rename":"Renombrar hilo","sidebar.add.project":"Añadir proyecto","sidebar.search.projects":"Buscar proyectos","thread.context.base":"Backplane","thread.context.copied":"Se copiaron las instrucciones.","thread.context.copy":"Copiar instrucciones","thread.context.disable":"Desactivar","thread.context.enable":"Activar","thread.context.index":"Índice de habilidades disponibles","thread.context.injected.label":"Instrucciones del proyecto añadidas","thread.context.instructions":"Instrucciones","thread.context.mcp":"MCP del proyecto","thread.context.native.note":"Instrucciones de inicio de Backplane. El proveedor carga los archivos nativos.","thread.context.none.instructions":"No se encontraron instrucciones del proyecto.","thread.context.none.mcp":"No se encontraron configuraciones MCP del proyecto.","thread.context.reading":"Leyendo el contexto del hilo…","thread.context.size":"{bytes} B · ≈{tokens} tokens","thread.context.skills":"Habilidades","thread.context.system":"Instrucciones del sistema","thread.context.title":"Contexto e instrucciones","thread.context.trust":"Confiar y activar","thread.new":"Nuevo hilo","tools.pinned":"Fijado","tools.retry":"Reintentar","tour.title.bots":"Bots","viewer.board":"Placa","viewer.diff":"Diff","viewer.files":"Archivos","viewer.mech":"Mech","viewer.review":"Revisión","viewer.schematic":"Esquemático","viewer.solid":"3D","web.chat.answer.btn":"Responder","web.chat.answer.placeholder":"Escribe una respuesta…","web.chat.answered":"Respondido: {answer}","web.chat.choose":"Elige un hilo de proyecto a la izquierda para empezar.","web.chat.empty":"Aún no hay mensajes. Escribe abajo para iniciar un turno.","web.chat.finished":"Terminado {time}","web.chat.finished.dur":"Terminado {time} · {dur}","web.chat.loading":"Cargando mensajes…","web.chat.review.mode":"Modo de revisión","web.chat.streaming":"Transmitiendo…","web.clone.add.dir":"Añadir {dir}","web.clone.back":"Atrás","web.clone.change.folder":"Cambiar carpeta","web.clone.cloned":"{repo} clonado en {dest}","web.clone.cloning":"Clonando {repo} en {dest}","web.clone.copied":"Copiado","web.clone.first":"Primer mensaje: {text}","web.clone.folder.name":"Nombre de la carpeta","web.clone.go":"Clonar","web.clone.loading":"Cargando…","web.clone.no.folders":"No hay carpetas aquí","web.clone.open.project":"Abrir el proyecto","web.clone.open.thread":"Abrir el hilo","web.clone.private":"privado","web.clone.repo.placeholder":"URL https o ssh, o propietario/repositorio","web.clone.retry":"Reintentar","web.clone.same":"Ya está clonado ahí: se añade tal cual.","web.clone.signin":"Iniciar sesión en GitHub","web.clone.signin.done":"Sesión iniciada en GitHub","web.clone.signin.enter":"Introduce este código en GitHub:","web.clone.signin.wait":"Iniciando sesión en GitHub…","web.clone.start.thread":"Empezar un hilo","web.clone.stopped":"Se detuvo la clonación de {repo}","web.clone.tab":"Clonar desde git","web.clone.up":"Subir","web.clone.use.dir":"Usar {dir}","web.composer.attach":"Adjuntar imagen","web.composer.maximages":"Como máximo {max} imágenes por mensaje.","web.composer.unsupported":"Tipo de imagen no compatible: {type}","web.composer.voice":"Dictado por voz","web.logout.failed":"No se pudo confirmar el cierre de sesión. Inténtalo de nuevo.","web.pair.approve.in":"Aprueba en el escritorio o en un teléfono vinculado · caduca en {time}","web.pair.approved":"Aprobado. Abriendo Backplane…","web.pair.cancelled":"Cancelado.","web.pair.code":"Código de comparación","web.pair.denied":"Se rechazó la solicitud de vinculación.","web.pair.expired":"El código de vinculación caducó. Solicita uno nuevo para intentarlo otra vez.","web.pair.failed":"Falló la solicitud de vinculación ({status})","web.pair.name":"Nombre del navegador","web.pair.nocode":"El hub no devolvió un código de comparación.","web.pair.ratelimited":"Demasiados intentos de vinculación. Espera un momento e inténtalo de nuevo.","web.pair.request":"Solicitar vinculación","web.pair.requesting":"Solicitando código de vinculación…","web.pair.subtitle":"Vincula este navegador con tu hub. Aprueba el código de 6 dígitos en Backplane › Ajustes › Dispositivos.","web.pair.unreachable":"No se pudo conectar con el hub. Comprueba tu conexión de tailnet.","web.plan.awaiting":"{n} esperando aprobación","web.plan.net.one":"1 red","web.plan.nets":"{n} redes","web.settings.providers":"Proveedores de IA","web.settings.providers.browser":"Conecta un proveedor en la aplicación de escritorio o móvil de Backplane en Configuración → Cuentas."},ja:{"agy.signout":"サインアウト","android.hub.machines.approve":"承認","android.load.earlier":"以前のメッセージを読み込む","approval.dismiss":"閉じる","approval.implement":"実装","ask.plan":"提案されたプラン","bots.rooms":"ルーム","bots.tab.browser":"ブラウザ","common.cancel":"キャンセル","common.close":"閉じる","common.copy":"コピー","common.delete":"削除","common.refresh":"更新","common.remove":"削除","common.save":"保存","composer.placeholder":"何でも質問:@bot、>thread、%project、#room、$skill、/btw","composer.send":"送信","composer.stop":"停止","gpui.acct.connected":"接続済み","gpui.acct.not.connected":"未接続","gpui.acct.sign.in.expired":"サインインの期限切れ","gpui.ask.plan.ready":"確認待ち","gpui.ask.plan.revise":"修正","gpui.ask.plan.reviseph":"計画のどこを変更しますか?","gpui.ask.plan.sendrev":"修正を送る","gpui.b.in.reply.to":"↩ 返信先:{quote}","gpui.b.replying.to":"↩ 返信中:{line}","gpui.bots.recall.off":"オフ","gpui.bots.recall.on":"オン","gpui.c.term.collapse":"折りたたむ","gpui.c.term.expand":"展開","gpui.commands":"コマンド","gpui.e.open.folder":"フォルダを開く","gpui.filter.projects.and.threads":"プロジェクトとスレッドを絞り込む","gpui.fold.or.unfold.the.sidebar":"サイドバーを折りたたむ/開く","gpui.follow.paused":"追従を一時停止中","gpui.follow.wait":"追従中: エージェントの次の編集を待っています","gpui.gerbers":"ガーバー","gpui.improvements":"改善","gpui.jump.to.a.thread.run":"スレッドへ移動、コマンドを実行、または発言を検索","gpui.mgmt.bom.dnp":"実装しない","gpui.mgmt.bom.nompn":"MPNなし","gpui.mgmt.checks.all":"すべて","gpui.mgmt.checks.fix":"エージェントに直してもらう","gpui.mgmt.checks.run":"実行","gpui.mgmt.close":"パネルを閉じる","gpui.mgmt.fab.apply":"適用","gpui.mgmt.fab.changed":"前回見てから変わったところ","gpui.mgmt.fab.derived":"* 製造元のページから計算した値です(milをmmに、径からランドを)。薄い色の項目はリジッド基板の値です(この基板のページに記載がないもの)。日付を押すと読んだページが開きます。","gpui.mgmt.fab.extra":"追加料金","gpui.mgmt.fab.findings":"指摘","gpui.mgmt.fab.free":"基本料金","gpui.mgmt.fab.judge":"データシート","gpui.mgmt.fab.limit":"項目","gpui.mgmt.fab.readcol":"読んだ日","gpui.mgmt.fab.refresh":"再読み込み","gpui.mgmt.fab.reviewbtn":"レビュー","gpui.mgmt.fab.seen":"確認済み","gpui.mgmt.fab.thefab":"製造元","gpui.mgmt.fab.use":"使う","gpui.mgmt.life.nopart":"この部品の記録はまだありません。","gpui.mgmt.life.reading":"履歴を読んでいます…","gpui.mgmt.plan.addnote":"メモを追加","gpui.mgmt.plan.all":"すべて承認","gpui.mgmt.plan.before":"配線前に計画する","gpui.mgmt.plan.compact":"標準","gpui.mgmt.plan.done":"完了","gpui.mgmt.plan.drawn":"計画の配線経路とプレーンは、このパネルを開いている間だけ基板上に表示されます。閉じると消えます。","gpui.mgmt.plan.edited":"編集済み","gpui.mgmt.plan.elsewhere":"{board}の配線計画が承認を待っています","gpui.mgmt.plan.emptysub":"計画が提案されると、レイヤー・コリドー・ベタ領域がここに表示されます。","gpui.mgmt.plan.expand":"拡大","gpui.mgmt.plan.fit":"全体表示","gpui.mgmt.plan.grid.all":"全レイヤー","gpui.mgmt.plan.grid.pair":"並べて表示","gpui.mgmt.plan.grid.single":"単一","gpui.mgmt.plan.hide":"完了を隠す","gpui.mgmt.plan.hint":"頂点をドラッグして誘導 · 辺の + をクリックで追加 · 頂点を右クリックで削除","gpui.mgmt.plan.keysnote":"このバージョンのKiCadでは、このパネルから承認してください。プランビューでのKiCadのA・R・Wキーはまだ計画のものではありません(Aはフットプリントの追加を開きます)。KiCadを更新してください。","gpui.mgmt.plan.layer":"層を承認","gpui.mgmt.plan.layer.short":"レイヤー","gpui.mgmt.plan.lock":"ロック","gpui.mgmt.plan.locked":"ロック中","gpui.mgmt.plan.noboard":"この基板の配線計画はありません。","gpui.mgmt.plan.noitems":"このレイヤーにコリドーまたはプレーンがありません","gpui.mgmt.plan.note.placeholder":"ルーターへの指示メモ…","gpui.mgmt.plan.nothing":"承認待ちはありません","gpui.mgmt.plan.offwords":"エージェントは指示どおりに配線します。オンにすると、まず配線計画を提案し、ここで承認したものだけを配線します。","gpui.mgmt.plan.onwords":"銅箔層が4層以上、またはネットが60本を超える基板では、配線の前にエージェントがここで配線経路とプレーン領域を提案します。承認したものだけを配線します。","gpui.mgmt.plan.reading":"配線計画を読んでいます…","gpui.mgmt.plan.reference":"基準 {layer}","gpui.mgmt.plan.refused":"KiCad が拒否しました","gpui.mgmt.plan.reject":"却下","gpui.mgmt.plan.rejectlayer":"レイヤーを却下","gpui.mgmt.plan.reqplain":"承認が求められています","gpui.mgmt.plan.requested":"承認が求められています: {what}","gpui.mgmt.plan.saved":"保存された計画","gpui.mgmt.plan.show":"完了を表示","gpui.mgmt.plan.st.approved":"承認済み","gpui.mgmt.plan.st.awaiting":"承認待ち","gpui.mgmt.plan.st.blocked":"ブロック","gpui.mgmt.plan.st.empty":"空","gpui.mgmt.plan.st.partial":"一部完了","gpui.mgmt.plan.st.rejected":"却下","gpui.mgmt.plan.st.routed":"配線済み","gpui.mgmt.plan.st.routing":"配線中","gpui.mgmt.plan.st.verified":"検証済み","gpui.mgmt.plan.stackup.short":"スタックアップ","gpui.mgmt.plan.stop":"配線を止める","gpui.mgmt.plan.sync":"ズーム連動","gpui.mgmt.plan.tab":"計画","gpui.mgmt.plan.unlock":"ロック解除","gpui.mgmt.plan.verify":"検証","gpui.mgmt.plan.view.canvas":"キャンバス","gpui.mgmt.plan.view.list":"リスト","gpui.mgmt.plan.view.split":"分割","gpui.mgmt.plan.width":"幅","gpui.next.thread":"次のスレッド","gpui.nothing.matches":"一致するものはありません","gpui.planmode.bar.always":"計画モード — 編集前に調査して計画を提案します","gpui.planmode.bar.executing":"承認された計画を実行しています","gpui.planmode.bar.once":"計画モード (1回) — 編集前に調査して計画を提案します","gpui.planmode.bar.pending":"提案された計画が下のレビューを待っています","gpui.planmode.bar.planning":"計画中 — 編集前の計画を作成しています","gpui.planmode.chip.building":"実行中","gpui.planmode.chip.once":"計画 · 1回","gpui.planmode.scope.always":"常時","gpui.planmode.scope.once":"1回","gpui.planmode.tip":"実行前に計画を作成 (1回・常時・オフ)","gpui.planmode.top.executing":"計画を実行中","gpui.planmode.top.once":"計画 (1回)","gpui.planmode.top.pending":"計画を確認","gpui.planmode.top.planning":"計画中","gpui.previous.thread":"前のスレッド","gpui.rail.no.board":"このプロジェクトには基板がありません","gpui.rail.no.mech":"このプロジェクトには機械部品がありません","gpui.rail.no.schematic":"このプロジェクトには回路図がありません","gpui.rail.split.needs.both":"分割表示には基板と回路図が必要です","home.away":"ホーム({name})はオフラインです","home.away.queued":"ホーム({name})はオフラインです · {n} 件待機中","home.away.since":"ホーム({name})は {time} からオフラインです","home.away.since.queued":"ホーム({name})は {time} からオフラインです · {n} 件待機中","home.machine":"ホームマシン","home.move.failed":"ホームの移動に失敗しました","home.move.failed.note":"ホームの移動に失敗しました: {note}","home.move.here":"このマシンをホームにする","home.moving":"ホームを {to} へ移動中…","home.moving.step":"ホームを {to} へ移動中: {step}","hub.back.crash":"予期せず停止したBackplaneが戻りました","hub.restarting":"Backplaneを再起動しています…","hub.restarting.build":"Backplaneを再起動しています…(新しいビルド {build})","hub.stopped":"Backplaneは停止しました","ios.hub.address.field":"ハブのアドレス","menu.pin":"ピン留め","menu.settle":"完了","menu.unpin":"ピン留めを解除","model.col.agent":"エージェント","notify.settled":"完了","palette.archive":"スレッドをアーカイブ","palette.command.placeholder":"コマンドまたはスレッドを入力","palette.diff":"差分:このスレッドの変更","palette.newthread":"新しいスレッド","palette.settings":"設定","palette.terminal":"ターミナル","palette.unarchive":"スレッドのアーカイブを解除","phone.unsettle":"未完了に戻す","provider.notice.button":"設定 → アカウントを開く","provider.notice.head":"AI プロバイダーが接続されていません","provider.notice.senderr":"AI プロバイダーがまだ接続されていません。設定 → アカウントを開いて、Claude、Codex、Antigravity などのプロバイダーを接続してください。","provider.notice.text.none":"チャットを始めるには、Claude、Codex、Antigravity などのプロバイダーを接続してください。","provider.notice.text.signedout":"チャットを始めるには、設定 → アカウントで Claude、Codex などのプロバイダーにサインインしてください。","reply.action":"返信","reply.cancel":"返信をやめる","reply.to":"返信先:","secret.you":"あなた","settings.lang":"言語","sheet.rename":"スレッド名を変更","sidebar.add.project":"プロジェクトを追加","sidebar.search.projects":"プロジェクトを検索","thread.context.base":"Backplane","thread.context.copied":"プロンプトをコピーしました。","thread.context.copy":"プロンプトをコピー","thread.context.disable":"無効にする","thread.context.enable":"有効にする","thread.context.index":"利用可能なスキルの一覧","thread.context.injected.label":"追加されたプロジェクトの指示","thread.context.instructions":"指示","thread.context.mcp":"プロジェクトの MCP","thread.context.native.note":"Backplane が起動時に渡すプロンプトです。ネイティブファイルはプロバイダーが読み込みます。","thread.context.none.instructions":"プロジェクトの指示が見つかりません。","thread.context.none.mcp":"プロジェクトの MCP 設定が見つかりません。","thread.context.reading":"スレッドのコンテキストを読み込み中…","thread.context.size":"{bytes} B・約{tokens}トークン","thread.context.skills":"スキル","thread.context.system":"システムプロンプト","thread.context.title":"コンテキストとプロンプト","thread.context.trust":"承認して有効にする","thread.new":"新しいスレッド","tools.pinned":"固定中","tools.retry":"再試行","tour.title.bots":"ボット","viewer.board":"基板","viewer.diff":"差分","viewer.files":"ファイル","viewer.mech":"Mech","viewer.review":"レビュー","viewer.schematic":"回路図","viewer.solid":"3D","web.chat.answer.btn":"回答","web.chat.answer.placeholder":"回答を入力…","web.chat.answered":"回答済み: {answer}","web.chat.choose":"左側からプロジェクトのスレッドを選んで開始してください。","web.chat.empty":"まだメッセージはありません。下に入力して開始してください。","web.chat.finished":"完了 {time}","web.chat.finished.dur":"完了 {time} · {dur}","web.chat.loading":"メッセージを読み込んでいます…","web.chat.review.mode":"レビューモード","web.chat.streaming":"受信中…","web.clone.add.dir":"{dir} を追加","web.clone.back":"戻る","web.clone.change.folder":"フォルダを変更","web.clone.cloned":"{repo} を {dest} にクローンしました","web.clone.cloning":"{repo} を {dest} にクローン中","web.clone.copied":"コピーしました","web.clone.first":"最初のメッセージ: {text}","web.clone.folder.name":"フォルダ名","web.clone.go":"クローン","web.clone.loading":"読み込み中…","web.clone.no.folders":"フォルダがありません","web.clone.open.project":"プロジェクトを開く","web.clone.open.thread":"スレッドを開く","web.clone.private":"非公開","web.clone.repo.placeholder":"https / ssh の URL、または owner/repo","web.clone.retry":"もう一度","web.clone.same":"すでにそこにクローンされています: そのまま追加します。","web.clone.signin":"GitHub にサインイン","web.clone.signin.done":"GitHub にサインインしました","web.clone.signin.enter":"このコードを GitHub に入力してください:","web.clone.signin.wait":"GitHub のサインインを開始しています…","web.clone.start.thread":"スレッドを開始","web.clone.stopped":"{repo} のクローンを中止しました","web.clone.tab":"git からクローン","web.clone.up":"上へ","web.clone.use.dir":"{dir} を使う","web.composer.attach":"画像を添付","web.composer.maximages":"1 件のメッセージに添付できる画像は最大 {max} 枚です。","web.composer.unsupported":"未対応の画像形式です: {type}","web.composer.voice":"音声入力","web.logout.failed":"サインアウトを確認できませんでした。もう一度お試しください。","web.pair.approve.in":"デスクトップまたはペアリング済みの端末で承認してください · 有効期限 {time}","web.pair.approved":"承認されました。Backplane を開いています…","web.pair.cancelled":"キャンセルしました。","web.pair.code":"確認コード","web.pair.denied":"ペアリングのリクエストが拒否されました。","web.pair.expired":"ペアリングコードの有効期限が切れました。新しいコードをリクエストしてください。","web.pair.failed":"ペアリングのリクエストに失敗しました ({status})","web.pair.name":"ブラウザー名","web.pair.nocode":"ハブから確認コードが返されませんでした。","web.pair.ratelimited":"ペアリングの試行回数が多すぎます。しばらく待ってからやり直してください。","web.pair.request":"ペアリングをリクエスト","web.pair.requesting":"ペアリングコードをリクエストしています…","web.pair.subtitle":"このブラウザーをハブとペアリングします。Backplane › 設定 › デバイス で 6 桁のコードを承認してください。","web.pair.unreachable":"ハブに接続できませんでした。tailnet の接続を確認してください。","web.plan.awaiting":"{n} 件が承認待ち","web.plan.net.one":"1 ネット","web.plan.nets":"{n} ネット","web.settings.providers":"AI プロバイダー","web.settings.providers.browser":"Backplane のデスクトップまたはモバイルアプリの設定 → アカウントからプロバイダーを接続してください。"}};function Q(a,t){if(!t)return a;return a.replace(/\{([a-zA-Z0-9_.-]+)\}/g,(s,r)=>Object.prototype.hasOwnProperty.call(t,r)?String(t[r]):s)}var F=te(),W=new Set,V=new Map;for(let[a,t]of Object.entries(U.en||{}))if(typeof t==="string"&&!V.has(t))V.set(t,a);function te(){let a=typeof navigator<"u"&&navigator.language?navigator.language.toLowerCase():"en";if(a.startsWith("ja"))return"ja";if(a.startsWith("es"))return"es";return"en"}function Y(){if(typeof document<"u"&&document.documentElement)document.documentElement.lang=F}Y();function me(a){return W.add(a),()=>{W.delete(a)}}function ue(a){if(!a)return!1;let t=a.toLowerCase(),s=t.startsWith("ja")?"ja":t.startsWith("es")?"es":t.startsWith("en")?"en":"";if(!s)return!1;let r=s!==F;if(F=s,Y(),r)for(let d of W)d(F);return r}function c(a,t,s){let d=(U[F]||U.en||{})[a]??U.en?.[a]??t??a;return Q(d,s)}function ge(a){if(!a)return"";let t=V.get(a);if(!t)return a;return c(t,a)}var ae=[[1,26,7,1,[]],[2,44,10,1,[6,18]],[3,70,15,1,[6,22]],[4,100,20,1,[6,26]],[5,134,26,1,[6,30]],[6,172,18,2,[6,34]]],O=new Uint8Array(512),_=new Uint8Array(256);{let a=1;for(let t=0;t<255;t++)if(O[t]=a,_[a]=t,a<<=1,a&256)a^=285;for(let t=255;t<512;t++)O[t]=O[t-255]}function J(a,t){return a===0||t===0?0:O[_[a]+_[t]]}function ne(a){let t=new Uint8Array([1]);for(let s=0;s{let m=e-i*n;return Math.ceil((12+t.length*8)/8)<=m});if(!s)return null;let[r,d,u,f,S]=s,w=d-u*f,g=[],E=(e,i)=>{for(let n=i-1;n>=0;n--)g.push(e>>>n&1)};E(4,4),E(t.length,8);for(let e of t)E(e,8);for(let e=0;e<4&&g.length{if(e<0||i<0||e>=p||i>=p)return;H[e*p+i]=n?1:0,A[e*p+i]=1},N=(e,i)=>{for(let n=-1;n<=7;n++)for(let m=-1;m<=7;m++){let k=e+n,l=i+m,o=n>=0&&n<=6&&m>=0&&m<=6&&(n===0||n===6||m===0||m===6||n>=2&&n<=4&&m>=2&&m<=4);b(k,l,o)}};N(0,0),N(0,p-7),N(p-7,0);for(let e=8;e=1;e-=2){if(e===6)e=5;let i=(e+1&2)===0;for(let n=0;n>>3]>>>7-(j&7)&1,j++;let o=(m+l&1)===0?h^1:h;H[m*p+l]=o}}}let R=30660;for(let e=0;e<=5;e++)b(8,e,(R>>>14-e&1)===1);b(8,7,(R>>>8&1)===1),b(8,8,(R>>>7&1)===1),b(7,8,(R>>>6&1)===1);for(let e=0;e<=5;e++)b(5-e,8,(R>>>5-e&1)===1);for(let e=0;e<8;e++)b(8,p-1-e,(R>>>e&1)===1);for(let e=0;e<7;e++)b(p-7+e,8,(R>>>14-e&1)===1);return{size:p,modules:H}}function X(a){let t=oe(a);if(!t)return null;let s=2,r=t.size+s*2,d=document.createElementNS("http://www.w3.org/2000/svg","svg");d.setAttribute("viewBox",`0 0 ${r} ${r}`),d.setAttribute("role","img"),d.setAttribute("aria-label",`QR code for ${a}`),d.setAttribute("shape-rendering","crispEdges"),d.classList.add("bp-qr-svg");let u=document.createElementNS("http://www.w3.org/2000/svg","rect");u.setAttribute("width",String(r)),u.setAttribute("height",String(r)),u.setAttribute("fill","#ffffff"),d.appendChild(u);let f="";for(let w=0;w{let h=l.trim();if(!h)return;let o=h.startsWith("https://")?h:`https://${h}`;if(!o.startsWith("https://")||o.length<=8)return;let x=document.createElement("div");x.className="bp-pair-addr-meta";let v=document.createElement("div");v.className="bp-pair-code-label",v.textContent=c("ios.hub.address.field","Hub address");let y=document.createElement("code");y.className="bp-pair-addr-url",y.textContent=o,y.setAttribute("data-testid","pair-address");let P=document.createElement("button");P.type="button",P.className="bp-pair-copy";let I=c("common.copy","Copy");P.textContent=I,P.addEventListener("click",()=>{navigator.clipboard?.writeText(o).then(()=>{P.textContent=c("web.clone.copied","Copied"),window.setTimeout(()=>{P.textContent=I},1200)}).catch(()=>{})}),x.append(v,y,P);let z=document.createDocumentFragment();z.appendChild(x);let K=X(o);if(K){let G=document.createElement("div");G.className="bp-pair-qr",G.setAttribute("data-testid","pair-qr"),G.appendChild(K),z.appendChild(G)}p.replaceChildren(z),p.classList.remove("bp-hidden")};fetch("/auth/web/info",{credentials:"same-origin"}).then(async(l)=>{if(!l.ok)return;let h=await l.json();if(typeof h.address==="string")H(h.address)}).catch(()=>{}),t.append(s,u,f,E,C,p),a.appendChild(t);let A=null,b=null,N=null,j=0,D=0,R=150,e=1000;function i(){if(j++,N)N.abort(),N=null;if(A!==null)window.clearTimeout(A),A=null;if(b!==null)window.clearInterval(b),b=null}function n(l="",h=!1){i(),f.classList.remove("bp-hidden"),E.classList.add("bp-hidden"),g.disabled=!1,C.textContent=l,C.className=h?"bp-pair-status bp-bad":"bp-pair-status"}function m(){let l=D-Date.now();if(l<=0){n(c("web.pair.expired","Pairing code expired. Request a new code to try again."),!0);return}B.textContent=c("web.pair.approve.in","Approve on desktop or paired phone · expires in {time}",{time:pe(l)})}async function k(l){if(l!==j)return;if(D>0&&Date.now()>=D){n(c("web.pair.expired","Pairing code expired. Request a new code to try again."),!0);return}let h=new AbortController;N=h;try{let o=await fetch("/auth/web/poll",{method:"POST",credentials:"same-origin",headers:{"Content-Type":"application/json"},body:"{}",signal:h.signal});if(l!==j)return;if(e=1000,o.status===202){A=window.setTimeout(()=>{k(l)},150);return}if(o.status===200||o.status===204){let v={};if(o.status===200)try{v=await o.json()}catch{}if(l!==j)return;let y=(v.state||v.status||"").toLowerCase();if(o.status===204||v.approved===!0||y==="approved"||y==="ok"){i(),C.textContent=c("web.pair.approved","Approved. Opening Backplane…"),C.className="bp-pair-status bp-ok",window.location.replace("/");return}if(y==="denied"||y==="rejected"){n(c("web.pair.denied","Pairing request was denied."),!0);return}if(y==="expired"){n(c("web.pair.expired","Pairing code expired. Request a new code to try again."),!0);return}A=window.setTimeout(()=>{k(l)},150);return}if(o.status===429){let v=Number(o.headers.get("Retry-After")||"5"),y=Math.max(2000,(Number.isFinite(v)?v:5)*1000);A=window.setTimeout(()=>{k(l)},y);return}if(o.status===401||o.status===403||o.status===404||o.status===410){let v="";try{let y=await o.json();v=(y.state||y.status||y.error||"").toLowerCase()}catch{}if(l!==j)return;if(v==="denied"||v==="rejected"||o.status===403)n(c("web.pair.denied","Pairing request was denied."),!0);else n(c("web.pair.expired","Pairing code expired. Request a new code to try again."),!0);return}let x=e;e=Math.min(1e4,Math.round(e*1.8)),A=window.setTimeout(()=>{k(l)},x)}catch{if(l!==j)return;let o=e;e=Math.min(1e4,Math.round(e*1.8)),A=window.setTimeout(()=>{k(l)},o)}finally{if(N===h)N=null}}L.addEventListener("click",()=>{n(c("web.pair.cancelled","Cancelled."))}),f.addEventListener("submit",async(l)=>{l.preventDefault();let h=w.value.trim()||Z();g.disabled=!0,C.textContent=c("web.pair.requesting","Requesting pairing code…"),C.className="bp-pair-status";try{let o=await fetch("/auth/web/request",{method:"POST",credentials:"same-origin",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:h})});if(!o.ok){let I=c("web.pair.failed","Pairing request failed ({status})",{status:o.status});try{let z=await o.json();if(z.error)I=z.error}catch{}if(o.status===429)I=c("web.pair.ratelimited","Too many pairing attempts. Wait a moment and try again.");n(I,!0);return}let x=await o.json(),v=x.code||x.checkCode||"";if(!v){n(c("web.pair.nocode","Hub did not return a comparison code."),!0);return}let y=Date.now();D=x.expiresAt?x.expiresAt<10000000000?x.expiresAt*1000:x.expiresAt:y+(x.expiresIn?x.expiresIn*1000:120000),i();let P=j;e=1000,R=x.pollMs&&x.pollMs>=100?x.pollMs:150,M.textContent=re(v),f.classList.add("bp-hidden"),E.classList.remove("bp-hidden"),C.textContent="",m(),b=window.setInterval(m,1000),A=window.setTimeout(()=>{k(P)},R)}catch{n(c("web.pair.unreachable","Could not reach the hub. Check your tailnet connection."),!0)}})}if(document.readyState==="loading")document.addEventListener("DOMContentLoaded",ee);else ee(); diff --git a/web/dist/assets/style.css b/web/dist/assets/style.css index f85ab1e03e..bc519082e0 100644 --- a/web/dist/assets/style.css +++ b/web/dist/assets/style.css @@ -471,6 +471,8 @@ button.primary.stop { font-size: 12px; } .bp-review-bar { border-left: 2px solid var(--warn); } +.bp-no-provider { border-left: 2px solid var(--warn); } +.bp-no-provider-body { display: flex; flex-direction: column; gap: 2px; min-width: 0; } .bp-unanswered { border-left: 2px solid var(--bad); } .bp-unanswered-body { display: flex; flex-direction: column; gap: 2px; } .bp-banner-actions { display: flex; gap: 6px; flex-shrink: 0; } @@ -645,7 +647,39 @@ html.light .bp-code-block { background: var(--panel); } .bp-popup-row.active, .bp-popup-row:hover { background: var(--raise); } .bp-popup-name { font-family: var(--mono); color: var(--accent); font-weight: 600; flex-shrink: 0; } .bp-popup-desc { color: var(--dim); font-size: 12px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } -.bp-composer-err { color: var(--bad); font-size: 12px; } +.bp-composer-err { + color: var(--bad); + font-size: 12px; + display: flex; + flex-wrap: wrap; + align-items: center; + justify-content: space-between; + gap: 8px; +} +.bp-composer-err-act { + font-size: 11px; + padding: 2px 8px; + background: var(--panel); + border: 1px solid var(--line); + color: var(--accent); +} +.bp-composer-err-act:hover { background: var(--raise); } +.bp-link-btn { + display: inline-flex; + align-items: center; + padding: 4px 10px; + text-decoration: none; + background: var(--raise); + border: 1px solid var(--line); + color: var(--text); + cursor: pointer; +} +.bp-link-btn.primary { + background: var(--accent); + border-color: var(--accent); + color: var(--on-accent); + font-weight: 600; +} .bp-composer-input { width: 100%; min-height: 68px; diff --git a/web/dist/manifest.json b/web/dist/manifest.json index 422815e9cb..b0d0c6598a 100644 --- a/web/dist/manifest.json +++ b/web/dist/manifest.json @@ -1,6 +1,6 @@ { "version": 1, - "totalAssetGzipBytes": 202653, + "totalAssetGzipBytes": 204447, "styleTokensSha256": "a4fed1b1c7bc676acc328907343eb5dcf87e426383d05617c632e48c0c3f2b80", "i18nKeys": [ "agy.signout", @@ -169,6 +169,11 @@ "palette.terminal", "palette.unarchive", "phone.unsettle", + "provider.notice.button", + "provider.notice.head", + "provider.notice.senderr", + "provider.notice.text.none", + "provider.notice.text.signedout", "reply.action", "reply.cancel", "reply.to", @@ -264,15 +269,17 @@ "web.pair.unreachable", "web.plan.awaiting", "web.plan.net.one", - "web.plan.nets" + "web.plan.nets", + "web.settings.providers", + "web.settings.providers.browser" ], - "i18nSubsetSha256": "8f0d892e7c575a1dedf067f05dae0f256f7ca1f47aac198e270e8bb42a39e327", + "i18nSubsetSha256": "c5451f43bfc32b547a5384f4d92d2a92e87fcc59aca5173e30ba302c9768b39f", "inputs": { "web/src/addproject.ts": "06a7ff3e13cd78d993ebca7f638d5d623da06c0099186ad534bae8f184dbe44f", - "web/src/app.ts": "89f69e24aaafeea13d4ec613ac7743a665870ea3b0e238a7f28134f209f2180c", - "web/src/chat.ts": "88c480f2246c28a27b5eb08b569eec78137e57b822cbbda66e021977dbb94f00", + "web/src/app.ts": "4f9001b183913757804743d4016c9966566e6859ecd73da01c6480995083b32d", + "web/src/chat.ts": "27730f5adfcbb51eecf2f3a7cbd75562c964105dbb6a131697898977432c7892", "web/src/clone-model.ts": "d265df49436e14f415bbeb2a271ffa3552f9163be62bdc0158cecc10c3cdae45", - "web/src/composer.ts": "3fb6a080d876f34564effe4bae30a3173830a5a30f0bc2fa5d43308639717ec5", + "web/src/composer.ts": "f351b271d59ae560ae57360a8a301fc7df7d4d3adbe2c8933577fd7201399dc0", "web/src/i18n-format.ts": "8561ca443ba371ad804b1cba75c144df666b1871a8250026c9806b66318c0c7b", "web/src/i18n.ts": "068561f33d911ed7c71d8c5f86d7a024b2ea9fe1dcd0bb766169cf19b82513b8", "web/src/index.html": "a661afef2f425bd880bccd134f90969b4d037cf455da827c921a99764ffd83a4", @@ -286,10 +293,11 @@ "web/src/palette-model.ts": "ae359cc71e98e84774428355a5048fd9ba0e1da2d45fa18290b4313c50c50ee4", "web/src/palette.ts": "bcd5c4585f57cc80a9cf29bf1b9da6ebbd33a3ab68f8f2a918c37c58060c8e48", "web/src/plan-canvas.ts": "49a0af6ef960301d4ea75f2fcd48628e01d983431d96329f37e6a3704bafd498", + "web/src/provider-notice.ts": "93be1b0fc2658ec18f7f74e1db30db4e0626e391fa88b10950b1cc314039f677", "web/src/qr.ts": "04b634557884b8f512a7b03ad9638c1c15a299ffaea0103d1bdeec6338d9b9d3", "web/src/rail.ts": "5fb391094992578cb6f54d35d53559951a584c43fcfc2ee6f4f2cc3897acfe46", - "web/src/settings.ts": "7b4d8be26fabc6c2a0b8af94a64572a0e3c1e589bf079bfa58c8985a8acd984a", - "web/src/shell.css": "2ade2f882105e6ac14cf55c7d63458e9b73ae0a901930dc8b661ca0afedd14b6", + "web/src/settings.ts": "62c4555c27efcedfda8024e1b7b9e3c63b1c1d4cef5fb6d8be0614ee997ec609", + "web/src/shell.css": "a029915be277456b83f1cb11f2cae2db131294fb469bd535e9c14764fbc73762", "web/src/sidebar.ts": "0c326c895375f8a2718ec424b07ca59006d7bc0938f05fe8e3e231ffb6af375f", "web/src/swarm-need.ts": "503bbf5ffe0389f068847571c792321b0ad5c8d26a18c73b8e41c0a8989e227f", "web/src/thread-context.ts": "b9fbd5b3ef0b1357b5a4444a1e9a0ac0606afe1c8a5377c4777752e918af0ac2", @@ -306,21 +314,21 @@ "web/src/viewers/viewer-pane.ts": "0021e2ac702c7b4960f685d822b6f3cf4728589b4cca54498556695de7ddb1eb", "web/src/viewers/viewer-tools.ts": "7db4587ad1410cf21364b1121454e0520fd515c82b63916d31a5fdc1443615b4", "web/src/voice.ts": "f401f1d5bd1685c7d7270fc02a8ff16f54bde7ae98aee21b4e802f0357063345", - "web/src/ws.ts": "58d6701077833fd5713854427245d9ad35d23a042e35df581a490c36bfd36e90", + "web/src/ws.ts": "9fdd6388ad44277dbd8e1e702c5d623a4159238bf0338e282a1f56c7493355fe", "web/vendor/xterm/LICENSE": "b569f629d00f2626a8100df2a1798210535621e42164dfd426a6fe5aac7b0ccd", "web/vendor/xterm/VERSION": "d8a60d9ace43d33ee184e5679b0b6815e8c6750331b6e6787b98e6f03d77180c", "web/vendor/xterm/addon-fit.js": "bdaefa370b1bfc42ee88d46fe6072400902a4d4b2d45cd93438dda9b23c97089", "web/vendor/xterm/xterm.css": "ba8e6985669488981ccf40c0cefe3aba80722cb6c92de7ad628b0bd717faf2b6", "web/vendor/xterm/xterm.js": "1f991ac3b4b283ebf96e60ae23a00a52765dd3a2e46fa6fdda9f1aab032f7495", - "web/build.ts": "8c7350de6def036513d509d9118d90c1e332388a32c4d3c6cc1154332a1c287f", + "web/build.ts": "ca51d13a44473f40f3af33d4c3ba928117613d15c9dda59abefd2c418d088426", "assets/web/favicon.svg": "5b0f22a3329f59809216aabe58d8dbbedbd46d29e4a2373a727529daa2441a2c", "assets/web/favicon-light.svg": "9aa4fb973f8a719c602e351c84d3344bac377db049f59eaa52d617e84eada5b6" }, "outputs": { "assets/app.js": { - "bytes": 339747, - "gzipBytes": 95988, - "sha256": "a0224fa3d692b11020b10700dad14490527946e350227679b63d611111b9ab51" + "bytes": 345371, + "gzipBytes": 97244, + "sha256": "38e41ef2564d036ec8450bf3305c4562bbed7044b6f41735e419b5eec6cb972d" }, "assets/favicon-light.svg": { "bytes": 1207, @@ -338,14 +346,14 @@ "sha256": "123b6a27f255d339b505c8fd83609674f0bddf9b46c0e907fce23befa96b1eec" }, "assets/pair.js": { - "bytes": 50746, - "gzipBytes": 15688, - "sha256": "d78d88635e645c0123294dfb81acaea0a69b8866a664eb0a5d5d26feb4052df9" + "bytes": 53024, + "gzipBytes": 16152, + "sha256": "4485eb13b87c0267e74385a82adb5f4de89b586e82ba34f4c8ecf20ad9d89fca" }, "assets/style.css": { - "bytes": 72556, - "gzipBytes": 12678, - "sha256": "25504312c4498085db5b15a8fcb77f817986cfe8583e96db8a9b552e878e49ae" + "bytes": 73359, + "gzipBytes": 12752, + "sha256": "93c3d1c33c2955966d5323f10950331c2c69e78c1ca65c70142c1fa1324867ad" }, "assets/terminal.js": { "bytes": 296616, diff --git a/web/src/app.ts b/web/src/app.ts index 0c5eab6f3f..f45d09501d 100644 --- a/web/src/app.ts +++ b/web/src/app.ts @@ -10,6 +10,7 @@ import { onLocaleChange, setLocale, t } from "./i18n"; import { signOut } from "./logout"; import { MgmtStrip } from "./mgmt"; import { CommandPalette, type PaletteAction, type PaletteSearchResult } from "./palette"; +import { isNoProviderError, parseNoProvider, type NoProviderNotice } from "./provider-notice"; import { RailView, type RailEntry } from "./rail"; import { needAfter, needPress } from "./swarm-need"; import { SettingsModal, type SettingsRow } from "./settings"; @@ -353,6 +354,7 @@ function mountApp(): void { const chat = new ChatView(centerEl, { onLoadOlder: () => { void loadOlderEntries(); }, onGoToEntry: (id) => { void goToEntry(id); }, + onOpenAccounts: () => { openAccounts(); }, onAnswerAsk: (askId, answer) => { void hub.rpc("ask.answer", { ask: askId, answer }).catch((e) => { composer.showError(e instanceof Error ? e.message : "Could not send answer"); @@ -600,6 +602,7 @@ function mountApp(): void { }); let homeInfo: HomeInfo | null = null; + let noProvider: NoProviderNotice | null = null; const settings = new SettingsModal(root, { onLoadDevices: async () => { const res = await hub.rpc<{ rows?: SettingsRow[] }>("devices.page", {}); @@ -612,11 +615,27 @@ function mountApp(): void { onMoveHomeHere: async () => { await hub.rpc("home.move", { to: "back" }); }, + onGetNoProvider: () => noProvider, onLogout: () => signOut(() => { hub.disconnect(); window.location.replace("/"); }), }); + function applyNoProvider(next: NoProviderNotice | null): void { + noProvider = next; + chat.setNoProvider(next); + if (settings.isOpen()) void settings.refresh(); + } + function openAccounts(): void { + void settings.openToAccounts(); + } + function showSendError(err: unknown, fallback: string): void { + const msg = err instanceof Error ? err.message : fallback; + composer.showError( + msg, + isNoProviderError(msg) ? { label: t("provider.notice.button", "Open Settings → Accounts"), onClick: openAccounts } : undefined, + ); + } pinBtn.addEventListener("click", () => { const th = threads.find((x) => x.id === selectedThreadId); @@ -1327,7 +1346,7 @@ function mountApp(): void { composer.focus(); } } catch (e) { - composer.showError(e instanceof Error ? e.message : "Could not create thread"); + showSendError(e, "Could not create thread"); } } @@ -1385,7 +1404,7 @@ function mountApp(): void { chat.removeEntry(localId); composer.setDraft(text); if (reply && !replying) startReply(reply); - composer.showError(e instanceof Error ? e.message : "Failed to send message"); + showSendError(e, "Failed to send message"); } } } @@ -1402,7 +1421,7 @@ function mountApp(): void { if (gen !== threadGen || selectedThreadId !== threadId) return; if (res.error) { composer.setDraft(text); - composer.showError(res.error); + showSendError(new Error(res.error), res.error); } else if (res.kind === "edit" && typeof res.text === "string") { composer.setDraft(res.text); } else if (res.kind === "project") { @@ -1413,7 +1432,7 @@ function mountApp(): void { } catch (e) { if (gen === threadGen && selectedThreadId === threadId) { composer.setDraft(text); - composer.showError(e instanceof Error ? e.message : "Command refused"); + showSendError(e, "Command refused"); } } } @@ -1479,6 +1498,7 @@ function mountApp(): void { if (hello.name) sidebar.setHostName(hello.name); homeInfo = hello.home ?? null; sidebar.setHome(homeInfo); + applyNoProvider(parseNoProvider(hello.noProvider)); if (settings.isOpen()) void settings.refresh(); renderConnStatus(state); // back after a crash (hello.hubBack): said once, for a few seconds @@ -1506,7 +1526,11 @@ function mountApp(): void { return; } if (frame.t === "info" && frame.info && typeof frame.info === "object") { - mgmt.handleInfo(frame.info as Record); + const info = frame.info as Record; + if (Object.prototype.hasOwnProperty.call(info, "provider.notice")) { + applyNoProvider(parseNoProvider(info["provider.notice"])); + } + mgmt.handleInfo(info); return; } if (frame.t !== "d") return; diff --git a/web/src/chat.ts b/web/src/chat.ts index 53e1407c5b..42717211a0 100644 --- a/web/src/chat.ts +++ b/web/src/chat.ts @@ -4,6 +4,7 @@ // hidden routine git/system notes, load-on-scroll pagination, asks, #1309 review bar, #1311 unanswered notice. import { t, trs } from "./i18n"; import { renderMarkdown } from "./md"; +import type { NoProviderNotice } from "./provider-notice"; import type { ThreadItem } from "./sidebar"; export interface EntryTool { name: string; summary?: string; state?: string; } @@ -53,6 +54,7 @@ export interface ChatCallbacks { onToggleReview: (nextOn: boolean) => void; onUnansweredAction: (action: string, value: string) => void; onReplyEntry: (entry: EntryItem) => void; + onOpenAccounts?: () => void; /** a reply's quote: go to the message it answers, reading older pages until it is loaded */ onGoToEntry?: (entryId: string) => void; onLoadImage: (entryId: string, path: string) => Promise<{ url?: string; mime?: string; data?: string } | null>; @@ -124,6 +126,7 @@ export class ChatView { private loadingOlder = false; private review: ReviewBar | null = null; private unanswered: UnansweredNotice | null = null; + private noProvider: NoProviderNotice | null = null; private btwNote: { q: string; a: string } | null = null; private liveNodes = new Map(); private imageCache = new Map(); @@ -283,6 +286,11 @@ export class ChatView { this.renderBanners(); } + public setNoProvider(noProvider: NoProviderNotice | null): void { + this.noProvider = noProvider; + this.renderBanners(); + } + public showBtw(q: string, a: string): void { this.btwNote = { q, a }; this.renderBanners(); @@ -367,6 +375,33 @@ export class ChatView { private renderBanners(): void { const frag = document.createDocumentFragment(); + if (this.noProvider && !(this.thread?.id.includes("~"))) { + const card = document.createElement("div"); + card.className = "bp-banner bp-no-provider"; + card.setAttribute("data-testid", "no-provider-banner"); + const body = document.createElement("div"); + body.className = "bp-no-provider-body"; + const h = document.createElement("strong"); + h.textContent = trs(this.noProvider.head); + body.appendChild(h); + if (this.noProvider.text) { + const p = document.createElement("span"); + p.className = "bp-dim"; + p.textContent = trs(this.noProvider.text); + body.appendChild(p); + } + const acts = document.createElement("div"); + acts.className = "bp-banner-actions"; + const btn = document.createElement("button"); + btn.type = "button"; + btn.className = "primary"; + btn.setAttribute("data-testid", "no-provider-accounts-btn"); + btn.textContent = trs(this.noProvider.button); + btn.addEventListener("click", () => this.cb.onOpenAccounts?.()); + acts.appendChild(btn); + card.append(body, acts); + frag.appendChild(card); + } if (this.review && (this.review.text || this.review.button)) { const bar = document.createElement("div"); bar.className = "bp-banner bp-review-bar"; diff --git a/web/src/composer.ts b/web/src/composer.ts index 34c07c40c9..bd4118f3e6 100644 --- a/web/src/composer.ts +++ b/web/src/composer.ts @@ -2,7 +2,7 @@ // Tall bordered input box ("Ask anything: @bot, >thread, %project, #room, $skill, /btw"), // slash-command popup (hello.commands), mentions popup, and bottom toolbar row // with model chip on the left and accent-blue Send / red Stop on the right. -import { t } from "./i18n"; +import { t, trs } from "./i18n"; import type { PlanModeInfo } from "./sidebar"; export interface SlashCommand { @@ -508,13 +508,25 @@ export class ComposerView { this.textarea.focus(); } - public showError(msg: string): void { - this.errorEl.textContent = msg; + public showError(msg: string, action?: { label: string; onClick: () => void }): void { + const txt = document.createElement("span"); + txt.textContent = trs(msg); + if (action) { + const btn = document.createElement("button"); + btn.type = "button"; + btn.className = "bp-composer-err-act"; + btn.setAttribute("data-testid", "composer-err-accounts"); + btn.textContent = action.label; + btn.addEventListener("click", action.onClick); + this.errorEl.replaceChildren(txt, btn); + } else { + this.errorEl.replaceChildren(txt); + } this.errorEl.classList.remove("bp-hidden"); } public clearError(): void { - this.errorEl.textContent = ""; + this.errorEl.replaceChildren(); this.errorEl.classList.add("bp-hidden"); } diff --git a/web/src/provider-notice.ts b/web/src/provider-notice.ts new file mode 100644 index 0000000000..84687872a2 --- /dev/null +++ b/web/src/provider-notice.ts @@ -0,0 +1,39 @@ +export interface NoProviderNotice { + reason?: string; + head: string; + text: string; + button: string; + url: string; +} + +export function parseNoProvider(raw: unknown): NoProviderNotice | null { + let obj: Record | null = null; + if (typeof raw === "string") { + const trimmed = raw.trim(); + if (!trimmed) return null; + try { + const parsed: unknown = JSON.parse(trimmed); + if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) { + obj = parsed as Record; + } + } catch { + return null; + } + } else if (raw && typeof raw === "object" && !Array.isArray(raw)) { + obj = raw as Record; + } + if (!obj) return null; + const head = typeof obj.head === "string" ? obj.head.trim() : ""; + if (!head) return null; + return { + reason: typeof obj.reason === "string" ? obj.reason : "", + head, + text: typeof obj.text === "string" ? obj.text : "", + button: typeof obj.button === "string" && obj.button.trim() ? obj.button : "Open Settings → Accounts", + url: typeof obj.url === "string" && obj.url.trim() ? obj.url : "backplane://settings/accounts", + }; +} + +export function isNoProviderError(msg: string): boolean { + return msg.includes("No AI provider connected"); +} diff --git a/web/src/settings.ts b/web/src/settings.ts index e192a6cf9d..e81b9abd56 100644 --- a/web/src/settings.ts +++ b/web/src/settings.ts @@ -1,5 +1,6 @@ // Settings › Devices modal + Appearance (Dark/Light) + Browser Sign Out + Home machine. -import { t } from "./i18n"; +import { t, trs } from "./i18n"; +import type { NoProviderNotice } from "./provider-notice"; import type { HomeInfo } from "./ws"; export interface SettingsRowButton { @@ -24,6 +25,7 @@ export interface SettingsCallbacks { onLogout: () => Promise; onGetHome?: () => HomeInfo | null; onMoveHomeHere?: () => Promise; + onGetNoProvider?: () => NoProviderNotice | null; } export class SettingsModal { @@ -33,6 +35,7 @@ export class SettingsModal { private bodyEl: HTMLElement; private cb: SettingsCallbacks; private openState = false; + private providersEl: HTMLElement | null = null; constructor(root: HTMLElement, cb: SettingsCallbacks) { this.cb = cb; @@ -77,6 +80,11 @@ export class SettingsModal { await this.refresh(); } + public async openToAccounts(): Promise { + await this.open(); + this.providersEl?.scrollIntoView({ block: "nearest" }); + } + public close(): void { this.openState = false; this.backdrop.classList.add("bp-hidden"); @@ -90,6 +98,42 @@ export class SettingsModal { public async refresh(): Promise { const frag = document.createDocumentFragment(); + this.providersEl = null; + + const noProvider = this.cb.onGetNoProvider?.() ?? null; + if (noProvider) { + const provSec = document.createElement("section"); + provSec.className = "bp-set-section"; + provSec.setAttribute("data-testid", "settings-providers"); + const provHead = document.createElement("div"); + provHead.className = "bp-set-head"; + provHead.textContent = t("web.settings.providers", "AI providers"); + const provRow = document.createElement("div"); + provRow.className = "bp-set-row"; + const info = document.createElement("div"); + info.className = "bp-set-info"; + const title = document.createElement("div"); + title.textContent = trs(noProvider.head); + const sub = document.createElement("div"); + sub.className = "bp-dim"; + sub.textContent = t( + "web.settings.providers.browser", + "Connect a provider in the Backplane desktop or mobile app under Settings → Accounts.", + ); + info.append(title, sub); + const btns = document.createElement("div"); + btns.className = "bp-set-btns"; + const link = document.createElement("a"); + link.className = "bp-link-btn primary"; + link.href = noProvider.url || "backplane://settings/accounts"; + link.setAttribute("data-testid", "settings-open-accounts"); + link.textContent = trs(noProvider.button); + btns.appendChild(link); + provRow.append(info, btns); + provSec.append(provHead, provRow); + this.providersEl = provSec; + frag.appendChild(provSec); + } // Home machine section (docs/PHONE-DATA.md, The home) const home = this.cb.onGetHome?.() ?? null; diff --git a/web/src/shell.css b/web/src/shell.css index d0f01146eb..f458a0ce50 100644 --- a/web/src/shell.css +++ b/web/src/shell.css @@ -378,6 +378,8 @@ button.primary.stop { font-size: 12px; } .bp-review-bar { border-left: 2px solid var(--warn); } +.bp-no-provider { border-left: 2px solid var(--warn); } +.bp-no-provider-body { display: flex; flex-direction: column; gap: 2px; min-width: 0; } .bp-unanswered { border-left: 2px solid var(--bad); } .bp-unanswered-body { display: flex; flex-direction: column; gap: 2px; } .bp-banner-actions { display: flex; gap: 6px; flex-shrink: 0; } @@ -552,7 +554,39 @@ html.light .bp-code-block { background: var(--panel); } .bp-popup-row.active, .bp-popup-row:hover { background: var(--raise); } .bp-popup-name { font-family: var(--mono); color: var(--accent); font-weight: 600; flex-shrink: 0; } .bp-popup-desc { color: var(--dim); font-size: 12px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } -.bp-composer-err { color: var(--bad); font-size: 12px; } +.bp-composer-err { + color: var(--bad); + font-size: 12px; + display: flex; + flex-wrap: wrap; + align-items: center; + justify-content: space-between; + gap: 8px; +} +.bp-composer-err-act { + font-size: 11px; + padding: 2px 8px; + background: var(--panel); + border: 1px solid var(--line); + color: var(--accent); +} +.bp-composer-err-act:hover { background: var(--raise); } +.bp-link-btn { + display: inline-flex; + align-items: center; + padding: 4px 10px; + text-decoration: none; + background: var(--raise); + border: 1px solid var(--line); + color: var(--text); + cursor: pointer; +} +.bp-link-btn.primary { + background: var(--accent); + border-color: var(--accent); + color: var(--on-accent); + font-weight: 600; +} .bp-composer-input { width: 100%; min-height: 68px; diff --git a/web/src/ws.ts b/web/src/ws.ts index 482512704c..4615fb9b51 100644 --- a/web/src/ws.ts +++ b/web/src/ws.ts @@ -1,6 +1,7 @@ // data/1 JSON + binary CBOR WebSocket client for Backplane web UI. // Authenticates strictly via the HttpOnly __Host-bp_web cookie (never ?token=). import { RawInflater } from "./inflate"; +import type { NoProviderNotice } from "./provider-notice"; export interface HomeMoving { to: string; @@ -35,6 +36,7 @@ export interface HelloFrame { theme?: string; locale?: string; notice?: unknown; + noProvider?: NoProviderNotice | null; } export interface DataPush { diff --git a/web/test/provider-notice.test.ts b/web/test/provider-notice.test.ts new file mode 100644 index 0000000000..4442225dbe --- /dev/null +++ b/web/test/provider-notice.test.ts @@ -0,0 +1,29 @@ +import { describe, expect, test } from "bun:test"; +import { isNoProviderError, parseNoProvider } from "../src/provider-notice"; + +describe("provider-notice", () => { + test("parses hello object and info JSON string payloads", () => { + const obj = { + reason: "none_installed", + head: "No AI provider connected", + text: "Connect Claude, Codex, Antigravity, or another provider to start chatting.", + button: "Open Settings → Accounts", + url: "backplane://settings/accounts", + }; + expect(parseNoProvider(obj)).toEqual(obj); + expect(parseNoProvider(JSON.stringify(obj))).toEqual(obj); + }); + + test("returns null for empty, null, or malformed payloads", () => { + expect(parseNoProvider(null)).toBeNull(); + expect(parseNoProvider(undefined)).toBeNull(); + expect(parseNoProvider("")).toBeNull(); + expect(parseNoProvider("not json")).toBeNull(); + expect(parseNoProvider({ head: " " })).toBeNull(); + }); + + test("detects no-provider send guard errors", () => { + expect(isNoProviderError("No AI provider connected yet. Open Settings → Accounts to connect Claude, Codex, Antigravity, or another provider.")).toBe(true); + expect(isNoProviderError("Network timeout")).toBe(false); + }); +}); From 981408a11c7b9c7d56d5b25ce4f53c40ec049c39 Mon Sep 17 00:00:00 2001 From: i2cjak Date: Sun, 22 Nov 2026 15:11:41 -0500 Subject: [PATCH 2/2] Address zero-provider review findings across hub, web, desktop, and mobile --- i18n/en.msg | 1 + i18n/es.msg | 1 + i18n/ja.msg | 1 + .../java/dev/backplane/mobile/DataClient.kt | 4 +- .../src/main/java/dev/backplane/mobile/Msg.kt | 15 +- mobile/ios/Backplane/DataClient.swift | 4 +- mobile/ios/Backplane/DataModels.swift | 2 +- mobile/ios/Shared/TrCatalog.swift | 4 + native/gpui/src/screens/provider_notice.rs | 3 +- native/host/src/agents/mod.rs | 12 +- native/host/src/agents/tests.rs | 32 ++++ native/host/src/bots/rpc.rs | 2 +- native/host/src/bots/tests.rs | 17 ++ native/host/src/commands/mod.rs | 26 +++- native/host/src/commands/tests.rs | 22 +++ native/host/src/data/ext.rs | 26 +++- native/host/src/data/mod.rs | 87 ++++++++++- native/host/src/data/tests.rs | 59 +++++++ native/host/src/net/homemove.rs | 110 ++++++++++++- native/host/src/net/rpc.rs | 21 ++- native/host/src/present/screen.rs | 9 +- native/host/src/settings/models.rs | 4 + native/host/src/settings/models_probe.rs | 15 +- native/host/src/settings/provider_notice.rs | 146 +++++++++++++++++- web/build.ts | 1 + web/dist/assets/app.js | 30 ++-- web/dist/assets/pair.js | 2 +- web/dist/manifest.json | 27 ++-- web/src/app.ts | 26 +++- web/src/provider-notice.ts | 8 +- web/src/settings.ts | 11 +- web/src/ws.ts | 18 ++- web/test/provider-notice.test.ts | 15 +- 33 files changed, 672 insertions(+), 89 deletions(-) diff --git a/i18n/en.msg b/i18n/en.msg index 9a3fb04d5e..8256bbfffa 100644 --- a/i18n/en.msg +++ b/i18n/en.msg @@ -5046,5 +5046,6 @@ provider.notice.text.none = Connect Claude, Codex, Antigravity, or another provi provider.notice.text.signedout = Sign in to Claude, Codex, or another provider in Settings → Accounts to start chatting. provider.notice.button = Open Settings → Accounts 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. web.settings.providers = AI providers web.settings.providers.browser = Connect a provider in the Backplane desktop or mobile app under Settings → Accounts. diff --git a/i18n/es.msg b/i18n/es.msg index 5953df5dce..17f392eb0e 100644 --- a/i18n/es.msg +++ b/i18n/es.msg @@ -5046,5 +5046,6 @@ provider.notice.text.none = Conecta Claude, Codex, Antigravity u otro proveedor provider.notice.text.signedout = Inicia sesión en Claude, Codex u otro proveedor en Configuración → Cuentas para empezar a chatear. provider.notice.button = Abrir Configuración → Cuentas 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. 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. diff --git a/i18n/ja.msg b/i18n/ja.msg index 4f9f69370f..cc3c8d3b79 100644 --- a/i18n/ja.msg +++ b/i18n/ja.msg @@ -5069,5 +5069,6 @@ provider.notice.text.none = チャットを始めるには、Claude、Codex、An provider.notice.text.signedout = チャットを始めるには、設定 → アカウントで Claude、Codex などのプロバイダーにサインインしてください。 provider.notice.button = 設定 → アカウントを開く provider.notice.senderr = AI プロバイダーがまだ接続されていません。設定 → アカウントを開いて、Claude、Codex、Antigravity などのプロバイダーを接続してください。 +provider.notice.senderr.remote = {machine} に AI プロバイダーが接続されていません。{machine} で設定 → アカウントを開いて、Claude、Codex、Antigravity などのプロバイダーを接続してください。 web.settings.providers = AI プロバイダー web.settings.providers.browser = Backplane のデスクトップまたはモバイルアプリの設定 → アカウントからプロバイダーを接続してください。 diff --git a/mobile/android/app/src/main/java/dev/backplane/mobile/DataClient.kt b/mobile/android/app/src/main/java/dev/backplane/mobile/DataClient.kt index d0f91b68f0..a4b32d9f9f 100644 --- a/mobile/android/app/src/main/java/dev/backplane/mobile/DataClient.kt +++ b/mobile/android/app/src/main/java/dev/backplane/mobile/DataClient.kt @@ -913,7 +913,7 @@ object DataClient { suspend fun runCommand(tid: String, text: String): JSONObject { // `exists`: this app offers Add existing on a folder /project found not empty (the answer's kind "exists") val r = call("composer.run", JSONObject().put("thread", tid).put("text", text).put("exists", true)) - if (r.optString("kind") == "btw") btw = btw + (tid to Btw(r.optString("q"), Msg.android_thinking)) + if (r.optString("kind") == "btw") btw = btw + (tid to Btw(r.optString("q"), r.optString("a").ifEmpty { Msg.android_thinking })) return r } fun closeBtw(tid: String) { btw = btw - tid } @@ -1424,6 +1424,6 @@ data class DNoProvider(val reason: String, val head: String, val text: String, v if (head.isEmpty()) return null return DNoProvider(o.optString("reason"), head, o.optString("text"), o.optString("button"), o.optString("url")) } - fun isSendError(msg: String): Boolean = msg.contains("No AI provider connected") + fun isSendError(msg: String): Boolean = msg.startsWith("No AI provider connected yet.") } } diff --git a/mobile/android/app/src/main/java/dev/backplane/mobile/Msg.kt b/mobile/android/app/src/main/java/dev/backplane/mobile/Msg.kt index 290461128b..988687be93 100644 --- a/mobile/android/app/src/main/java/dev/backplane/mobile/Msg.kt +++ b/mobile/android/app/src/main/java/dev/backplane/mobile/Msg.kt @@ -4945,6 +4945,7 @@ object Msg { "provider.notice.text.signedout", "provider.notice.button", "provider.notice.senderr", + "provider.notice.senderr.remote", "web.settings.providers", "web.settings.providers.browser", ) @@ -9891,6 +9892,7 @@ object Msg { "Sign in to Claude, Codex, or another provider in Settings → Accounts to start chatting.", "Open Settings → Accounts", "No AI provider connected yet. Open Settings → Accounts to connect Claude, Codex, Antigravity, or another provider.", + "No AI provider connected on {machine}. Open Settings → Accounts on {machine} to connect Claude, Codex, Antigravity, or another provider.", "AI providers", "Connect a provider in the Backplane desktop or mobile app under Settings → Accounts.", ) @@ -14837,6 +14839,7 @@ object Msg { "チャットを始めるには、設定 → アカウントで Claude、Codex などのプロバイダーにサインインしてください。", "設定 → アカウントを開く", "AI プロバイダーがまだ接続されていません。設定 → アカウントを開いて、Claude、Codex、Antigravity などのプロバイダーを接続してください。", + "{machine} に AI プロバイダーが接続されていません。{machine} で設定 → アカウントを開いて、Claude、Codex、Antigravity などのプロバイダーを接続してください。", "AI プロバイダー", "Backplane のデスクトップまたはモバイルアプリの設定 → アカウントからプロバイダーを接続してください。", ) @@ -19783,6 +19786,7 @@ object Msg { "Inicia sesión en Claude, Codex u otro proveedor en Configuración → Cuentas para empezar a chatear.", "Abrir Configuración → Cuentas", "Aún no hay ningún proveedor de IA conectado. Abre Configuración → Cuentas para conectar Claude, Codex, Antigravity u otro proveedor.", + "No hay ningún proveedor de IA conectado en {machine}. Abre Configuración → Cuentas en {machine} para conectar Claude, Codex, Antigravity u otro proveedor.", "Proveedores de IA", "Conecta un proveedor en la aplicación de escritorio o móvil de Backplane en Configuración → Cuentas.", ) @@ -23182,9 +23186,9 @@ object Msg { "Connect a provider in the Backplane desktop or mobile app under Settings → Accounts.", ) internal val exactText: Array by lazy { arrayOf(*exactText0(), *exactText1(), *exactText2(), *exactText3(), *exactText4(), *exactText5(), *exactText6(), *exactText7(), *exactText8(), *exactText9(), *exactText10(), *exactText11(), *exactText12(), *exactText13()) } - internal val exactKey: IntArray by lazy { intArrayOf(0, 1, 2, 3, 4, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 3152, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 43, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 3720, 61, 62, 63, 64, 66, 68, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 84, 85, 3759, 87, 88, 98, 99, 3081, 3758, 102, 103, 105, 106, 107, 109, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 155, 156, 157, 159, 161, 162, 163, 3201, 165, 166, 3203, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 3162, 183, 187, 189, 193, 194, 195, 197, 198, 199, 200, 201, 202, 206, 209, 213, 215, 216, 217, 219, 220, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 234, 235, 2968, 237, 238, 239, 240, 3719, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255, 256, 260, 262, 263, 264, 265, 266, 267, 270, 271, 272, 273, 275, 279, 280, 281, 282, 286, 287, 289, 290, 291, 292, 293, 294, 295, 296, 297, 298, 300, 301, 3173, 305, 306, 307, 308, 309, 310, 311, 313, 314, 315, 317, 319, 333, 3767, 336, 3766, 3769, 340, 3779, 342, 343, 344, 345, 354, 3150, 357, 358, 359, 360, 361, 362, 363, 364, 365, 366, 367, 368, 369, 370, 371, 372, 373, 2971, 376, 377, 378, 379, 380, 381, 382, 383, 384, 385, 386, 387, 388, 389, 390, 391, 392, 393, 394, 395, 396, 397, 398, 399, 400, 401, 402, 403, 404, 405, 406, 407, 408, 409, 410, 411, 412, 413, 414, 415, 416, 417, 419, 420, 421, 422, 423, 424, 425, 426, 427, 428, 429, 2963, 2964, 432, 433, 434, 435, 436, 437, 438, 439, 440, 441, 442, 443, 444, 445, 446, 447, 448, 449, 450, 451, 453, 454, 455, 3180, 457, 458, 459, 460, 461, 2953, 463, 464, 465, 3083, 467, 468, 469, 470, 471, 472, 473, 474, 475, 476, 477, 478, 479, 480, 481, 482, 483, 484, 485, 486, 487, 488, 489, 490, 491, 492, 493, 494, 495, 496, 497, 498, 499, 500, 501, 502, 503, 504, 505, 506, 507, 508, 509, 510, 511, 512, 513, 514, 515, 516, 517, 518, 519, 520, 521, 522, 523, 524, 525, 526, 527, 528, 529, 530, 531, 532, 533, 534, 535, 536, 537, 538, 539, 540, 541, 542, 543, 544, 545, 546, 547, 548, 549, 550, 551, 552, 553, 554, 556, 557, 558, 559, 560, 561, 562, 563, 565, 566, 567, 568, 569, 570, 571, 572, 573, 574, 575, 576, 577, 578, 592, 628, 629, 630, 3188, 3189, 636, 637, 638, 639, 640, 641, 642, 643, 644, 645, 646, 647, 651, 652, 3832, 654, 656, 657, 659, 663, 664, 665, 666, 667, 668, 669, 670, 671, 672, 673, 674, 675, 676, 677, 678, 680, 681, 682, 683, 684, 686, 687, 689, 690, 692, 693, 694, 695, 698, 704, 724, 728, 729, 730, 731, 732, 3764, 734, 735, 736, 737, 3187, 739, 740, 741, 742, 743, 744, 745, 746, 747, 748, 749, 750, 751, 752, 753, 754, 755, 756, 757, 758, 759, 760, 761, 762, 763, 764, 765, 766, 767, 768, 769, 770, 771, 772, 773, 774, 775, 776, 777, 778, 779, 780, 781, 782, 783, 784, 785, 786, 787, 788, 789, 790, 791, 792, 793, 794, 795, 796, 797, 798, 799, 800, 801, 802, 803, 3747, 805, 806, 807, 808, 809, 810, 811, 812, 813, 814, 815, 816, 817, 818, 819, 820, 821, 822, 823, 824, 825, 826, 827, 828, 829, 832, 833, 834, 835, 836, 837, 838, 839, 840, 841, 843, 844, 845, 847, 848, 3183, 850, 852, 853, 854, 857, 858, 859, 860, 861, 862, 863, 864, 865, 866, 867, 3757, 869, 870, 871, 872, 873, 874, 875, 876, 877, 878, 879, 880, 881, 882, 883, 884, 885, 886, 887, 888, 889, 890, 891, 892, 893, 894, 895, 896, 897, 898, 899, 900, 901, 3834, 903, 904, 907, 908, 909, 910, 911, 912, 913, 914, 915, 916, 917, 918, 919, 920, 921, 922, 923, 924, 925, 926, 927, 928, 929, 930, 931, 932, 933, 934, 935, 936, 937, 938, 939, 940, 941, 942, 943, 944, 945, 946, 947, 948, 949, 950, 951, 952, 953, 954, 955, 956, 957, 958, 959, 960, 961, 962, 3153, 964, 965, 966, 967, 968, 969, 3782, 971, 3008, 3065, 974, 975, 976, 978, 979, 987, 988, 989, 991, 992, 993, 995, 996, 997, 998, 999, 1000, 1001, 1002, 1003, 1005, 1006, 1007, 1008, 1009, 1010, 1011, 1012, 1013, 1014, 1015, 1016, 1017, 1018, 3785, 1020, 1021, 1022, 1025, 1029, 1030, 1031, 2960, 3034, 1034, 1035, 1036, 1037, 1038, 1039, 1040, 1041, 1042, 1043, 1045, 1046, 1049, 1050, 1051, 1052, 1053, 1054, 1055, 1056, 1057, 1058, 1059, 1060, 1061, 1062, 1063, 1064, 1065, 1066, 1067, 1068, 1069, 1070, 1071, 1072, 1074, 1082, 1083, 1086, 1087, 1088, 1090, 1091, 1092, 3799, 1094, 1095, 1098, 1099, 1100, 3182, 1102, 1103, 1104, 1105, 1106, 1107, 1108, 1110, 1111, 1112, 1113, 1114, 1115, 1116, 3784, 1120, 1123, 1124, 1125, 1127, 1128, 1129, 1130, 1131, 1132, 1133, 1134, 1135, 1136, 1137, 1138, 1139, 1140, 1141, 1142, 1143, 1144, 1145, 1146, 1150, 1151, 1152, 1153, 1154, 1155, 1158, 1162, 1163, 1165, 1170, 1171, 1172, 1173, 1176, 1178, 1180, 1181, 1182, 1184, 1185, 1186, 1187, 1188, 1189, 1190, 1191, 1192, 1193, 1194, 1195, 1197, 1198, 1199, 1200, 1201, 1202, 1203, 1206, 1207, 1208, 1209, 1210, 1211, 1212, 1213, 1214, 1215, 1216, 1217, 1218, 1220, 1222, 1223, 2962, 1225, 1226, 1227, 1228, 1229, 1230, 1231, 1232, 1233, 1234, 1235, 1236, 1237, 1240, 1241, 1244, 1245, 1246, 1247, 1248, 1250, 1253, 1254, 1255, 1256, 1257, 1258, 1260, 1261, 1262, 1263, 1264, 1265, 1266, 1267, 1269, 1270, 1271, 1272, 1273, 1274, 1275, 1277, 1278, 1279, 1280, 1281, 1288, 1289, 1290, 1291, 1294, 1296, 1297, 1298, 1299, 1301, 1305, 1306, 1308, 1309, 1310, 1311, 1315, 1316, 1318, 1319, 1320, 1322, 1323, 1324, 1325, 1326, 1327, 1328, 1329, 1330, 1335, 1338, 1339, 1340, 1341, 1344, 1347, 1348, 1356, 1357, 3497, 1361, 1362, 1363, 1364, 1365, 1366, 3564, 1373, 1375, 1380, 1384, 1385, 3038, 1387, 1388, 1389, 1390, 1391, 1392, 1393, 1394, 1395, 1396, 1397, 1398, 1399, 1400, 1401, 1402, 1403, 1404, 1405, 1406, 1407, 1408, 1409, 1410, 1411, 1412, 2965, 1417, 1418, 1419, 1420, 1421, 1422, 1423, 1424, 1425, 1426, 1427, 1428, 1429, 1430, 1431, 1432, 1433, 3082, 3575, 1436, 1438, 1439, 1440, 1441, 1442, 1443, 1444, 1445, 1446, 1447, 1448, 1449, 1450, 1451, 1452, 1453, 1454, 1455, 1456, 1457, 1458, 1459, 1460, 1461, 1462, 1463, 1464, 1465, 1466, 1467, 1468, 1469, 3577, 1473, 1474, 1475, 1477, 1478, 1479, 1480, 1481, 1482, 1483, 1484, 1485, 1486, 1487, 1488, 1489, 1490, 1493, 1494, 3722, 1496, 1497, 1498, 3734, 3740, 1501, 1502, 1503, 1504, 1505, 1507, 1508, 1509, 1510, 1511, 1512, 1513, 1514, 1515, 1516, 1523, 1525, 1526, 1527, 1528, 1529, 1530, 1531, 1532, 1533, 1534, 1535, 1536, 1537, 1538, 1539, 1540, 1541, 1542, 1543, 1544, 1545, 1546, 1547, 1548, 1549, 1550, 1551, 1552, 1553, 1554, 1555, 1556, 1557, 1558, 1559, 1560, 1561, 1562, 1563, 1564, 1565, 1566, 1568, 1569, 1570, 1571, 1573, 1574, 1575, 1576, 1577, 1580, 1581, 1582, 1583, 1584, 1585, 1586, 1587, 1589, 1590, 1591, 1592, 1593, 1594, 1595, 1596, 1597, 1598, 1599, 1600, 1601, 1602, 1603, 1604, 1605, 1606, 1607, 1608, 1609, 1610, 1611, 1612, 1613, 1614, 1615, 1616, 1617, 1618, 1619, 1620, 1622, 1623, 1624, 1625, 1626, 1627, 1628, 1629, 3041, 1631, 1632, 1633, 1634, 1635, 1636, 1637, 1638, 1639, 1640, 1641, 1642, 1643, 1645, 1646, 1647, 1648, 1649, 1650, 1651, 1656, 1657, 1658, 1659, 1660, 1661, 1662, 1663, 3451, 1665, 1666, 1667, 1668, 3452, 1670, 1671, 1672, 1673, 1674, 1675, 1676, 1677, 1678, 1679, 1680, 1681, 2974, 1687, 1689, 1691, 1693, 1697, 1701, 1707, 1709, 1710, 1711, 1713, 1714, 1715, 1716, 1717, 1718, 1720, 1722, 1723, 1724, 1725, 1726, 1728, 1729, 3746, 1731, 1732, 1733, 1734, 1735, 1736, 1737, 1739, 1740, 1742, 1743, 1744, 1745, 1746, 1747, 1748, 1749, 1750, 1751, 1752, 1753, 1754, 1755, 1756, 1757, 1760, 1761, 1762, 1763, 1764, 1765, 1766, 1767, 1768, 1769, 1770, 1771, 1772, 1773, 1774, 1775, 1776, 1777, 1778, 1779, 1780, 1781, 1782, 1783, 1784, 1785, 1786, 1787, 1788, 1789, 1790, 1791, 1792, 1793, 1794, 1795, 1796, 1797, 1798, 1799, 1800, 1801, 1802, 1803, 1804, 1805, 1806, 1807, 1808, 1809, 1810, 1811, 1812, 1813, 1814, 1815, 1816, 1817, 1818, 1819, 1821, 1822, 3017, 1831, 1833, 1837, 2999, 1839, 1840, 3000, 1842, 1843, 1847, 3064, 1849, 1850, 1851, 1852, 1853, 1854, 1855, 1856, 1857, 1859, 1864, 1866, 1867, 1868, 1869, 1870, 1871, 3079, 1873, 1874, 1877, 1878, 1888, 1889, 1893, 1894, 1895, 1896, 1897, 1898, 1899, 1900, 1902, 1903, 1904, 1905, 1906, 1907, 1908, 1909, 1910, 1911, 1912, 1913, 1914, 1915, 1916, 1917, 1922, 1923, 1924, 1925, 1926, 1927, 1928, 1929, 1930, 1931, 1932, 1933, 1934, 1935, 1937, 1938, 1940, 1941, 1951, 1953, 1954, 1957, 1958, 1961, 1962, 1963, 1965, 1966, 1967, 1968, 1969, 1970, 1971, 1972, 1973, 1974, 1975, 1976, 1977, 1978, 1979, 1980, 1981, 1983, 1989, 1990, 1991, 1992, 1996, 3140, 2002, 2003, 2005, 2006, 2007, 2008, 3792, 3793, 2017, 2019, 2020, 2021, 2023, 2024, 2025, 2026, 2027, 2028, 2029, 2030, 2031, 2034, 2035, 2037, 2038, 2041, 2042, 3125, 3126, 3127, 2050, 3353, 2052, 2054, 2055, 2056, 2057, 2058, 2059, 2060, 2061, 2062, 2063, 2064, 2065, 2066, 2069, 2070, 2071, 2072, 2073, 2074, 2078, 2079, 2080, 2081, 2082, 2083, 2084, 2085, 2086, 2087, 2088, 2089, 2090, 2091, 2092, 2093, 2094, 2095, 2097, 2098, 2099, 2100, 2101, 2102, 2103, 2104, 2105, 2107, 2113, 2114, 2115, 2116, 2117, 2118, 2119, 2120, 3067, 2125, 2126, 2127, 2129, 2131, 2132, 2133, 2134, 2990, 3115, 3116, 3117, 3118, 3119, 2141, 2142, 2143, 2145, 2992, 2993, 2983, 2982, 2151, 2984, 2153, 2988, 2155, 3351, 2160, 2164, 2166, 2167, 2168, 2169, 2170, 2171, 2172, 2173, 2174, 2175, 2176, 3018, 2180, 2181, 2182, 2183, 3051, 2185, 2186, 2187, 2188, 2189, 2190, 2191, 2192, 2193, 2196, 3364, 2198, 2199, 2200, 2201, 3033, 2203, 2204, 2205, 2206, 2981, 2208, 3096, 2211, 2215, 2216, 3641, 2218, 2219, 3728, 3729, 2223, 3178, 2226, 3717, 2229, 2230, 2231, 2232, 2233, 3777, 2235, 3148, 2237, 3147, 2239, 2241, 2243, 2244, 2245, 2249, 2252, 2254, 2256, 2257, 2258, 2259, 2260, 2261, 2262, 2263, 2264, 2265, 2266, 2268, 2269, 2270, 3735, 2272, 2273, 2275, 3025, 3023, 3027, 2281, 2283, 2284, 2290, 2291, 2292, 2293, 3063, 2298, 2299, 2301, 2306, 2307, 3007, 3576, 2970, 2969, 2972, 3092, 3095, 2320, 2321, 2323, 2324, 2326, 2327, 2328, 2329, 2330, 2331, 2332, 2333, 2334, 3796, 2338, 2339, 2340, 2341, 2342, 2343, 2344, 2345, 2346, 2347, 2348, 2349, 2350, 2351, 2352, 2357, 2359, 2360, 2361, 2365, 2366, 2369, 2370, 2377, 2378, 2379, 2380, 2381, 2382, 2383, 2384, 2385, 2386, 2387, 2388, 2389, 2391, 2392, 2393, 2394, 2395, 2396, 2418, 2419, 2422, 2423, 2424, 2425, 2426, 2427, 2428, 2438, 2442, 2443, 2444, 2445, 2446, 2447, 2448, 2449, 2450, 2452, 2453, 2454, 2455, 2457, 2458, 2459, 2461, 2464, 2465, 2466, 2469, 2470, 2471, 2472, 2473, 2474, 2475, 2476, 2482, 2483, 2484, 2485, 2486, 2487, 2488, 2489, 2490, 2491, 2492, 2493, 2494, 2495, 2496, 2497, 2498, 2499, 2500, 2501, 2502, 2503, 2504, 2506, 2507, 2508, 2509, 2510, 2511, 2512, 2513, 2514, 2515, 2516, 2517, 2518, 2519, 2520, 2521, 2522, 2523, 2524, 2525, 2526, 2527, 2529, 2530, 2531, 2532, 3129, 2534, 2536, 2537, 2539, 2540, 2541, 2542, 2543, 2544, 2545, 2548, 2549, 2550, 2551, 2554, 2555, 2556, 2557, 2558, 2559, 2560, 2561, 2562, 2570, 2571, 2572, 2573, 2576, 2577, 2578, 2579, 2580, 2581, 2582, 2583, 2584, 2586, 2587, 2588, 2589, 2590, 2591, 2592, 2593, 2594, 2597, 2599, 2600, 2603, 2604, 2605, 2606, 2607, 2608, 2609, 2610, 2611, 2613, 2614, 2616, 2617, 2618, 2619, 2620, 2621, 2622, 2623, 2624, 2625, 2626, 2628, 2630, 2633, 2635, 3725, 2640, 2641, 2642, 2643, 2644, 2645, 2646, 2650, 2651, 2653, 2654, 2655, 2656, 2657, 2658, 2659, 2661, 2662, 2663, 2668, 2669, 2670, 2672, 2673, 2674, 2675, 2677, 2678, 2679, 2680, 2681, 2682, 2683, 2684, 2685, 2686, 2687, 2688, 2689, 3698, 2691, 2692, 2694, 3695, 2696, 2697, 3699, 3696, 2709, 2713, 3706, 3202, 3707, 2717, 3708, 2719, 2721, 3710, 2723, 3711, 2725, 2727, 3715, 3693, 3686, 3694, 2746, 2747, 2749, 2750, 2760, 2761, 2763, 2764, 2765, 2766, 2767, 2768, 2769, 2770, 2771, 2775, 2778, 2781, 2783, 2785, 2791, 2792, 2793, 2794, 2795, 2796, 2797, 2798, 2799, 2800, 2801, 2802, 2803, 3373, 2805, 2806, 2807, 2808, 2809, 2811, 2813, 2814, 3405, 2820, 2821, 2822, 2823, 2824, 2825, 2826, 2827, 2828, 2829, 2830, 2831, 2833, 2834, 2835, 2836, 2839, 2840, 2842, 2843, 2844, 2845, 2997, 2847, 2849, 2850, 2852, 2853, 2854, 2855, 2856, 2858, 2859, 2863, 2866, 2867, 2868, 2870, 2871, 2872, 2874, 2875, 2876, 2877, 2879, 2880, 2883, 2886, 2887, 2888, 2889, 2890, 2892, 2894, 2895, 2897, 2898, 2899, 2900, 2901, 2902, 2903, 2904, 2906, 2907, 2908, 2909, 2910, 2911, 2912, 2913, 2914, 2915, 2916, 2917, 2918, 2919, 2920, 2921, 2922, 2923, 2924, 2925, 2931, 2932, 2933, 2935, 2936, 2937, 2941, 2942, 2943, 2944, 2945, 2949, 2950, 2954, 2955, 2956, 2957, 2958, 2959, 2961, 2966, 2967, 2973, 2978, 2980, 2985, 2986, 2987, 2989, 2991, 2994, 2995, 2996, 2998, 3002, 3009, 3010, 3011, 3012, 3013, 3014, 3015, 3016, 3019, 3020, 3021, 3022, 3026, 3028, 3029, 3030, 3031, 3035, 3036, 3040, 3042, 3043, 3044, 3046, 3047, 3048, 3049, 3050, 3053, 3054, 3055, 3056, 3057, 3058, 3059, 3060, 3061, 3068, 3069, 3070, 3071, 3076, 3077, 3078, 3080, 3084, 3085, 3086, 3087, 3088, 3091, 3093, 3094, 3097, 3098, 3099, 3100, 3101, 3102, 3103, 3104, 3105, 3107, 3109, 3110, 3111, 3112, 3113, 3114, 3120, 3121, 3122, 3123, 3124, 3128, 3130, 3131, 3132, 3133, 3134, 3135, 3136, 3138, 3139, 3142, 3144, 3145, 3146, 3149, 3154, 3155, 3156, 3158, 3161, 3163, 3164, 3166, 3167, 3168, 3170, 3171, 3172, 3174, 3175, 3176, 3177, 3181, 3186, 3191, 3192, 3193, 3194, 3195, 3196, 3197, 3199, 3204, 3205, 3206, 3207, 3208, 3209, 3210, 3211, 3212, 3213, 3214, 3215, 3216, 3219, 3220, 3223, 3224, 3225, 3226, 3227, 3228, 3229, 3230, 3233, 3234, 3235, 3236, 3237, 3238, 3239, 3240, 3241, 3242, 3243, 3246, 3247, 3249, 3250, 3251, 3252, 3253, 3254, 3255, 3256, 3257, 3258, 3259, 3260, 3261, 3262, 3263, 3264, 3265, 3266, 3267, 3268, 3269, 3270, 3271, 3272, 3273, 3274, 3275, 3278, 3279, 3280, 3281, 3282, 3283, 3284, 3285, 3286, 3287, 3289, 3290, 3291, 3292, 3293, 3294, 3295, 3296, 3297, 3298, 3299, 3300, 3301, 3302, 3303, 3304, 3305, 3306, 3307, 3308, 3309, 3310, 3311, 3312, 3313, 3314, 3315, 3316, 3317, 3318, 3319, 3320, 3321, 3324, 3325, 3326, 3327, 3328, 3329, 3330, 3331, 3332, 3333, 3334, 3335, 3336, 3337, 3338, 3339, 3340, 3341, 3342, 3343, 3344, 3345, 3347, 3348, 3352, 3354, 3355, 3356, 3358, 3359, 3360, 3363, 3365, 3366, 3367, 3368, 3369, 3372, 3374, 3377, 3379, 3380, 3385, 3386, 3387, 3388, 3391, 3398, 3399, 3400, 3401, 3402, 3403, 3406, 3407, 3408, 3409, 3412, 3413, 3414, 3415, 3416, 3417, 3418, 3419, 3420, 3421, 3423, 3424, 3425, 3426, 3427, 3428, 3430, 3431, 3433, 3434, 3435, 3436, 3437, 3443, 3444, 3445, 3446, 3447, 3448, 3449, 3450, 3453, 3456, 3459, 3460, 3461, 3462, 3463, 3464, 3465, 3466, 3467, 3468, 3469, 3470, 3471, 3472, 3473, 3474, 3475, 3476, 3477, 3479, 3480, 3481, 3482, 3483, 3484, 3485, 3487, 3488, 3489, 3490, 3491, 3492, 3493, 3494, 3496, 3501, 3507, 3509, 3510, 3511, 3512, 3513, 3514, 3515, 3516, 3517, 3518, 3519, 3520, 3521, 3522, 3523, 3525, 3526, 3527, 3528, 3529, 3530, 3534, 3535, 3539, 3540, 3546, 3547, 3548, 3549, 3550, 3551, 3552, 3553, 3554, 3556, 3557, 3558, 3559, 3562, 3563, 3565, 3566, 3578, 3579, 3580, 3581, 3582, 3583, 3584, 3585, 3586, 3587, 3588, 3589, 3590, 3591, 3592, 3593, 3594, 3595, 3597, 3598, 3599, 3603, 3604, 3605, 3606, 3612, 3613, 3614, 3615, 3619, 3621, 3622, 3623, 3625, 3628, 3629, 3633, 3640, 3642, 3645, 3647, 3648, 3649, 3650, 3651, 3652, 3654, 3655, 3656, 3657, 3658, 3659, 3660, 3661, 3662, 3663, 3664, 3665, 3666, 3667, 3668, 3669, 3670, 3671, 3672, 3673, 3674, 3675, 3676, 3677, 3678, 3679, 3680, 3681, 3682, 3683, 3684, 3685, 3703, 3718, 3721, 3723, 3724, 3726, 3730, 3732, 3736, 3745, 3748, 3749, 3750, 3751, 3752, 3753, 3755, 3761, 3762, 3765, 3768, 3770, 3771, 3772, 3773, 3774, 3775, 3778, 3781, 3783, 3787, 3788, 3789, 3790, 3791, 3794, 3795, 3797, 3798, 3800, 3801, 3802, 3803, 3804, 3805, 3806, 3807, 3809, 3810, 3811, 3812, 3813, 3814, 3815, 3816, 3817, 3818, 3819, 3820, 3821, 3822, 3823, 3824, 3825, 3826, 3829, 3831, 3833, 3842, 3843, 3845, 3846, 3855, 3861, 3867, 3876, 3878, 3879, 3880, 3881, 3884, 3885, 3887, 3893, 3897, 3901, 3906, 3907, 3909, 3910, 3911, 3913, 3914, 3915, 3920, 3921, 3922, 3923, 3924, 3925, 3926, 3927, 3928, 3931, 3932, 3933, 3978, 3979, 3984, 3986, 3987, 3989, 3995, 3998, 4013, 4014, 4015, 4016, 4017, 4018, 4020, 4021, 4023, 4024, 4026, 4028, 4029, 4042, 4045, 4046, 4048, 4049, 4053, 4058, 4061, 4062, 4064, 4065, 4071, 4073, 4074, 4077, 4079, 4084, 4085, 4086, 4091, 4102, 4125, 4141, 4149, 4158, 4159, 4163, 4168, 4184, 4185, 4186, 4187, 4189, 4191, 4192, 4194, 4197, 4201, 4204, 4207, 4208, 4209, 4210, 4214, 4215, 4216, 4217, 4220, 4221, 4222, 4223, 4224, 4225, 4226, 4227, 4228, 4229, 4230, 4231, 4232, 4233, 4234, 4235, 4236, 4237, 4238, 4239, 4240, 4241, 4242, 4243, 4251, 4254, 4255, 4261, 4266, 4267, 4268, 4269, 4273, 4277, 4279, 4280, 4281, 4282, 4283, 4284, 4285, 4286, 4288, 4289, 4290, 4291, 4293, 4294, 4295, 4296, 4297, 4298, 4299, 4309, 4321, 4322, 4324, 4325, 4326, 4327, 4331, 4332, 4333, 4334, 4335, 4336, 4338, 4339, 4340, 4346, 4347, 4348, 4349, 4350, 4351, 4355, 4359, 4360, 4362, 4363, 4364, 4365, 4366, 4368, 4378, 4380, 4385, 4386, 4387, 4388, 4389, 4390, 4391, 4392, 4393, 4394, 4395, 4396, 4397, 4398, 4399, 4400, 4402, 4403, 4404, 4405, 4406, 4407, 4408, 4413, 4416, 4417, 4418, 4419, 4420, 4421, 4422, 4423, 4424, 4425, 4426, 4427, 4428, 4429, 4430, 4431, 4432, 4433, 4434, 4435, 4436, 4438, 4439, 4440, 4442, 4443, 4444, 4445, 4448, 4449, 4450, 4452, 4453, 4454, 4456, 4457, 4458, 4459, 4460, 4461, 4463, 4465, 4468, 4469, 4470, 4471, 4473, 4474, 4475, 4476, 4477, 4478, 4479, 4480, 4481, 4482, 4483, 4487, 4489, 4490, 4491, 4492, 4493, 4497, 4498, 4502, 4503, 4504, 4506, 4508, 4509, 4510, 4511, 4512, 4513, 4514, 4516, 4517, 4518, 4519, 4520, 4521, 4522, 4529, 4530, 4531, 4532, 4533, 4534, 4535, 4536, 4537, 4538, 4539, 4540, 4546, 4547, 4549, 4550, 4551, 4552, 4553, 4554, 4555, 4556, 4557, 4558, 4559, 4560, 4561, 4562, 4563, 4564, 4568, 4569, 4570, 4571, 4572, 4573, 4574, 4575, 4576, 4581, 4582, 4585, 4586, 4587, 4588, 4589, 4590, 4591, 4592, 4593, 4594, 4595, 4596, 4597, 4598, 4600, 4601, 4602, 4603, 4612, 4613, 4614, 4615, 4616, 4617, 4619, 4622, 4623, 4624, 4626, 4627, 4628, 4629, 4630, 4631, 4632, 4633, 4634, 4635, 4636, 4637, 4638, 4639, 4640, 4641, 4642, 4643, 4644, 4645, 4646, 4647, 4648, 4649, 4650, 4651, 4652, 4653, 4654, 4655, 4656, 4657, 4658, 4659, 4660, 4661, 4662, 4663, 4664, 4665, 4666, 4667, 4668, 4669, 4670, 4671, 4672, 4673, 4674, 4675, 4676, 4677, 4678, 4679, 4680, 4681, 4682, 4683, 4684, 4685, 4686, 4687, 4688, 4689, 4690, 4691, 4692, 4693, 4694, 4695, 4696, 4697, 4698, 4699, 4700, 4701, 4702, 4703, 4704, 4705, 4706, 4707, 4708, 4709, 4710, 4711, 4712, 4713, 4714, 4715, 4716, 4717, 4718, 4719, 4720, 4721, 4722, 4723, 4724, 4725, 4726, 4727, 4732, 4733, 4734, 4740, 4753, 4757, 4758, 4759, 4760, 4761, 4762, 4763, 4764, 4765, 4766, 4767, 4768, 4769, 4770, 4771, 4772, 4774, 4775, 4776, 4777, 4778, 4780, 4781, 4782, 4783, 4784, 4785, 4786, 4789, 4790, 4792, 4793, 4794, 4797, 4798, 4799, 4800, 4801, 4802, 4803, 4804, 4805, 4806, 4807, 4808, 4809, 4810, 4811, 4812, 4813, 4814, 4815, 4816, 4817, 4818, 4819, 4820, 4821, 4822, 4823, 4825, 4826, 4827, 4828, 4829, 4830, 4831, 4832, 4833, 4834, 4835, 4836, 4837, 4838, 4839, 4840, 4841, 4842, 4843, 4844, 4845, 4846, 4847, 4848, 4849, 4850, 4851, 4852, 4853, 4854, 4855, 4856, 4858, 4859, 4860, 4862, 4864, 4866, 4867, 4868, 4869, 4872, 4874, 4875, 4876, 4877, 4879, 4880, 4881, 4882, 4883, 4884, 4885, 4886, 4889, 4893, 4894, 4898, 4899, 4900, 4901, 4902, 4903, 4904) } - internal val templates: IntArray by lazy { intArrayOf(2358, 2837, 2649, 2648, 2647, 2869, 2891, 3371, 2612, 418, 2782, 2780, 2676, 2367, 2373, 2784, 2881, 2596, 2595, 285, 2325, 2786, 2893, 3221, 4173, 2535, 2585, 2045, 2363, 3705, 2110, 2712, 2368, 3222, 1336, 4193, 4213, 3704, 2553, 2710, 1862, 4188, 2121, 2159, 2165, 4542, 283, 2111, 4484, 3383, 3404, 2068, 2336, 3701, 452, 2744, 2776, 2777, 3384, 3700, 2745, 3632, 609, 1706, 3709, 1863, 2720, 3712, 2726, 3375, 616, 617, 2762, 3073, 3687, 1654, 2779, 3631, 303, 614, 69, 711, 621, 2335, 4211, 1121, 2477, 3454, 3827, 1242, 2194, 2564, 3376, 2157, 3716, 714, 1758, 1959, 2732, 2741, 2952, 4218, 3378, 3390, 136, 594, 596, 2552, 2707, 1860, 4206, 3024, 610, 2278, 2575, 3864, 1302, 4205, 3500, 3637, 3638, 158, 2075, 2077, 2112, 2832, 4341, 2163, 2362, 2505, 3626, 214, 284, 1276, 2009, 4773, 3495, 3504, 3505, 67, 83, 218, 619, 4578, 3524, 1360, 4300, 3349, 3714, 726, 1023, 1372, 2376, 2468, 2730, 4343, 89, 2375, 2390, 2905, 624, 1652, 1949, 2819, 4472, 3397, 1572, 2096, 2282, 2566, 4524, 3392, 3458, 3508, 650, 1883, 3919, 3157, 3499, 3545, 3609, 3828, 1317, 1861, 2040, 2414, 2701, 3847, 4543, 3411, 3457, 1836, 1858, 3346, 593, 1292, 1346, 1371, 1948, 3486, 3688, 221, 1696, 2733, 2930, 3075, 3143, 3432, 258, 591, 1026, 1379, 1960, 1984, 4126, 3429, 3555, 655, 1342, 1712, 2046, 3151, 3350, 3611, 3630, 710, 1283, 1370, 1382, 1653, 1727, 1890, 2364, 2467, 2565, 3934, 4212, 4409, 3410, 3478, 3624, 649, 699, 1044, 2601, 3169, 3288, 3691, 108, 184, 606, 721, 1081, 1964, 2044, 2106, 2161, 2400, 2481, 2737, 2773, 2817, 3939, 4455, 4796, 3370, 3441, 3602, 160, 623, 701, 1332, 1333, 1345, 1520, 1655, 2158, 2162, 2255, 2399, 2627, 4181, 4485, 3106, 3198, 3245, 3323, 3537, 3692, 3702, 703, 1183, 1567, 1892, 2250, 2253, 2480, 2738, 2758, 2759, 2927, 2928, 3949, 3969, 4202, 4446, 4779, 4795, 3610, 3627, 3733, 1378, 1492, 1579, 1698, 1950, 2420, 2432, 2757, 4145, 4203, 4486, 4577, 3072, 3074, 3089, 3607, 3620, 3786, 723, 1024, 1827, 2130, 2195, 2410, 2753, 2754, 3954, 4200, 4276, 4287, 3276, 3396, 91, 93, 595, 715, 1027, 1350, 1355, 2015, 2322, 2415, 2700, 2752, 2756, 3916, 4525, 4857, 3003, 3004, 3506, 3570, 3713, 94, 1251, 1259, 1353, 1377, 1519, 1578, 1875, 2178, 2210, 2460, 2478, 2728, 3856, 3857, 4199, 4352, 4415, 4861, 3322, 3361, 3362, 3440, 3596, 299, 599, 618, 700, 1109, 1117, 1175, 1367, 1518, 1621, 1943, 2122, 2128, 2146, 2213, 2430, 2435, 2437, 2660, 2693, 2751, 2929, 2946, 2947, 4170, 4196, 4313, 3005, 3159, 3536, 3569, 3738, 211, 585, 590, 605, 717, 720, 906, 990, 1084, 1159, 1334, 1470, 1524, 1700, 1881, 1901, 1921, 1956, 1986, 2067, 2305, 2413, 2479, 2934, 3883, 3935, 4153, 4526, 4544, 4545, 4744, 3066, 3422, 3617, 3618, 92, 96, 269, 603, 648, 712, 980, 1331, 1702, 1882, 1939, 2109, 2408, 2434, 2436, 2439, 2528, 2666, 2702, 2884, 2896, 4244, 4528, 4756, 2979, 3244, 3277, 3357, 3455, 3574, 3608, 208, 277, 316, 329, 330, 1287, 1352, 1376, 1521, 1522, 1944, 2014, 2039, 2108, 2212, 2240, 2288, 2402, 2417, 2429, 2703, 2706, 2787, 2788, 3854, 4541, 4739, 3001, 3389, 3393, 3442, 3498, 3653, 3690, 3743, 6, 244, 304, 600, 604, 1047, 1221, 1286, 1354, 1359, 1703, 1704, 1879, 1952, 1955, 2013, 2016, 2144, 2179, 2227, 2401, 2409, 2629, 2735, 2774, 2851, 3851, 3852, 3912, 4169, 4742, 4754, 4755, 3439, 3561, 3568, 3573, 3635, 3643, 268, 318, 322, 331, 583, 707, 722, 1076, 1160, 1164, 1284, 1285, 1312, 1517, 1705, 1823, 1884, 2004, 2214, 2220, 2372, 2398, 2404, 2431, 2563, 2664, 3917, 4142, 4195, 4258, 4344, 4414, 4625, 4743, 3052, 3137, 3502, 3503, 3601, 3634, 65, 210, 274, 587, 608, 613, 708, 713, 984, 1075, 1167, 1369, 1708, 1738, 1824, 1829, 1844, 1880, 2043, 2076, 2267, 2285, 2294, 2397, 2451, 2463, 2755, 4180, 3032, 3382, 3567, 3636, 3644, 3689, 90, 207, 288, 320, 323, 324, 349, 597, 607, 709, 855, 905, 1166, 1169, 1252, 1437, 1885, 2000, 2010, 2403, 2412, 2456, 2734, 2772, 2926, 2940, 3889, 4787, 4788, 4791, 4887, 3006, 3037, 3090, 3160, 3218, 3231, 3232, 3395, 3543, 3544, 3616, 3639, 3646, 3697, 110, 186, 190, 191, 212, 321, 327, 328, 352, 375, 580, 582, 589, 625, 727, 851, 977, 1077, 1118, 1147, 1243, 1304, 1314, 1741, 1825, 1826, 1834, 1945, 1946, 1947, 2036, 2246, 2248, 2274, 2286, 2287, 2309, 2371, 2405, 2406, 2462, 2568, 2569, 2652, 2667, 2699, 2704, 2705, 2742, 2789, 2790, 3835, 3853, 3899, 3953, 4198, 4292, 4310, 4342, 4412, 4447, 4499, 4523, 4584, 4824, 3039, 3141, 3165, 3179, 3200, 3381, 3394, 3538, 3542, 3572, 3600, 3731, 3741, 3742, 3754, 3756, 3763, 5, 8, 82, 185, 188, 192, 257, 276, 325, 326, 348, 351, 356, 598, 620, 658, 696, 705, 856, 985, 1048, 1122, 1148, 1149, 1168, 1179, 1239, 1383, 1491, 1644, 1688, 1699, 1845, 1876, 1942, 1988, 2001, 2022, 2242, 2247, 2297, 2303, 2304, 2311, 2416, 2602, 2638, 2812, 3900, 3908, 3938, 3955, 4122, 4157, 4171, 4219, 4259, 4311, 4337, 4500, 4527, 3062, 3108, 3184, 3185, 3190, 3248, 3532, 154, 259, 261, 347, 350, 353, 579, 602, 612, 702, 706, 982, 1078, 1381, 1588, 1828, 1920, 1982, 1985, 2295, 2308, 2374, 2421, 2567, 2615, 2857, 3858, 3905, 3971, 4138, 4496, 4583, 3438, 3531, 3533, 3541, 3560, 3571, 3739, 3760, 3780, 95, 196, 203, 204, 205, 242, 243, 346, 581, 586, 601, 615, 622, 626, 627, 691, 716, 725, 983, 986, 1085, 1089, 1161, 1174, 1204, 1349, 1471, 1506, 1683, 1684, 1686, 1721, 1846, 1886, 2225, 2300, 2310, 2411, 2433, 2441, 2948, 4124, 4154, 4155, 4245, 4270, 4308, 4410, 4466, 4507, 4863, 4888) } - internal val argNames: Map> by lazy { mapOf(5 to arrayOf("n"), 6 to arrayOf("n"), 7 to arrayOf("who"), 8 to arrayOf("title"), 65 to arrayOf("state"), 67 to arrayOf("listen"), 69 to arrayOf("listen"), 82 to arrayOf("version"), 83 to arrayOf("count", "plural"), 89 to arrayOf("size", "limit"), 90 to arrayOf("name"), 91 to arrayOf("dir"), 92 to arrayOf("dir"), 93 to arrayOf("name"), 94 to arrayOf("name"), 95 to arrayOf("path"), 96 to arrayOf("path"), 97 to arrayOf("name"), 108 to arrayOf("first"), 110 to arrayOf("n"), 136 to arrayOf("count", "plural"), 154 to arrayOf("tool"), 158 to arrayOf("n"), 160 to arrayOf("name"), 184 to arrayOf("pid", "cmd"), 185 to arrayOf("title", "ago"), 186 to arrayOf("name", "who", "n"), 188 to arrayOf("line"), 190 to arrayOf("n"), 191 to arrayOf("n"), 192 to arrayOf("n"), 196 to arrayOf("name"), 203 to arrayOf("when"), 204 to arrayOf("text", "when"), 205 to arrayOf("when"), 207 to arrayOf("count", "plural"), 208 to arrayOf("count", "plural"), 210 to arrayOf("took", "ago"), 211 to arrayOf("ago"), 212 to arrayOf("kind"), 214 to arrayOf("kind", "code", "why"), 218 to arrayOf("clock"), 221 to arrayOf("build"), 242 to arrayOf("step"), 243 to arrayOf("turn"), 244 to arrayOf("branch"), 257 to arrayOf("step", "total"), 258 to arrayOf("step", "total"), 259 to arrayOf("when"), 261 to arrayOf("tool"), 268 to arrayOf("count", "plural"), 269 to arrayOf("count", "total"), 274 to arrayOf("old", "new"), 276 to arrayOf("version"), 277 to arrayOf("count"), 278 to arrayOf("tag"), 283 to arrayOf("version"), 284 to arrayOf("old", "version"), 285 to arrayOf("version"), 288 to arrayOf("version"), 299 to arrayOf("project", "location"), 303 to arrayOf("account"), 304 to arrayOf("account"), 316 to arrayOf("n"), 318 to arrayOf("n"), 320 to arrayOf("minute"), 321 to arrayOf("time"), 322 to arrayOf("time"), 323 to arrayOf("clock"), 324 to arrayOf("clock", "took"), 325 to arrayOf("clock"), 326 to arrayOf("clock", "took"), 327 to arrayOf("clock"), 328 to arrayOf("clock", "took"), 329 to arrayOf("clock"), 330 to arrayOf("clock", "took"), 331 to arrayOf("clock"), 346 to arrayOf("target"), 347 to arrayOf("target"), 348 to arrayOf("target"), 349 to arrayOf("target"), 350 to arrayOf("target"), 351 to arrayOf("target"), 352 to arrayOf("target"), 353 to arrayOf("target"), 356 to arrayOf("name"), 375 to arrayOf("t"), 418 to arrayOf("minutes", "plural"), 452 to arrayOf("path"), 579 to arrayOf("count"), 580 to arrayOf("count"), 581 to arrayOf("title"), 582 to arrayOf("path"), 583 to arrayOf("path", "error"), 584 to arrayOf("first", "last", "count"), 585 to arrayOf("task", "step"), 586 to arrayOf("count"), 587 to arrayOf("path"), 588 to arrayOf("count", "plural"), 589 to arrayOf("label"), 590 to arrayOf("provider"), 591 to arrayOf("version"), 593 to arrayOf("key"), 594 to arrayOf("device"), 595 to arrayOf("kind", "device"), 596 to arrayOf("status"), 597 to arrayOf("kind", "title"), 598 to arrayOf("layer"), 599 to arrayOf("error"), 600 to arrayOf("page"), 601 to arrayOf("page", "kind", "total"), 602 to arrayOf("reason"), 603 to arrayOf("tag"), 604 to arrayOf("tag"), 605 to arrayOf("title"), 606 to arrayOf("title"), 607 to arrayOf("text", "time"), 608 to arrayOf("kind", "device"), 609 to arrayOf("device"), 610 to arrayOf("device"), 611 to arrayOf("word"), 612 to arrayOf("word", "kind", "count"), 613 to arrayOf("error"), 614 to arrayOf("count"), 615 to arrayOf("time", "relative", "rel", "zoned", "zone"), 616 to arrayOf("zone"), 617 to arrayOf("zone"), 618 to arrayOf("id", "state", "count", "age"), 619 to arrayOf("id"), 620 to arrayOf("name"), 621 to arrayOf("name"), 622 to arrayOf("clock", "count", "plural"), 623 to arrayOf("name"), 624 to arrayOf("name"), 625 to arrayOf("name"), 626 to arrayOf("count"), 627 to arrayOf("count"), 631 to arrayOf("name", "state"), 632 to arrayOf("author", "place", "state"), 633 to arrayOf("title", "state"), 648 to arrayOf("error"), 649 to arrayOf("error"), 650 to arrayOf("host"), 655 to arrayOf("email"), 658 to arrayOf("version"), 660 to arrayOf("first", "last", "count"), 661 to arrayOf("n"), 662 to arrayOf("n"), 691 to arrayOf("ref"), 696 to arrayOf("name"), 697 to arrayOf("name"), 699 to arrayOf("name"), 700 to arrayOf("name"), 701 to arrayOf("action"), 702 to arrayOf("label"), 703 to arrayOf("count", "plural"), 705 to arrayOf("path"), 706 to arrayOf("word", "kind", "count"), 707 to arrayOf("name"), 708 to arrayOf("name"), 709 to arrayOf("name"), 710 to arrayOf("name"), 711 to arrayOf("url"), 712 to arrayOf("count"), 713 to arrayOf("count"), 714 to arrayOf("device"), 715 to arrayOf("device"), 716 to arrayOf("count"), 717 to arrayOf("label"), 718 to arrayOf("label"), 719 to arrayOf("label"), 720 to arrayOf("title"), 721 to arrayOf("title"), 722 to arrayOf("state"), 723 to arrayOf("open", "kind"), 725 to arrayOf("count"), 726 to arrayOf("email"), 727 to arrayOf("email"), 851 to arrayOf("at", "count"), 855 to arrayOf("name"), 856 to arrayOf("name"), 905 to arrayOf("name"), 906 to arrayOf("name"), 977 to arrayOf("count"), 980 to arrayOf("name"), 981 to arrayOf("name", "count"), 982 to arrayOf("label", "n"), 983 to arrayOf("action"), 984 to arrayOf("count", "plural"), 985 to arrayOf("count"), 986 to arrayOf("waiting", "busy", "done"), 990 to arrayOf("count", "plural"), 1023 to arrayOf("name"), 1024 to arrayOf("name"), 1026 to arrayOf("seconds", "long"), 1027 to arrayOf("size", "triangles", "delayed", "waited", "built"), 1028 to arrayOf("size", "delayed", "waited"), 1044 to arrayOf("name"), 1047 to arrayOf("name"), 1048 to arrayOf("count"), 1075 to arrayOf("state"), 1076 to arrayOf("bytes"), 1077 to arrayOf("count"), 1078 to arrayOf("when"), 1079 to arrayOf("state", "name"), 1080 to arrayOf("name", "state"), 1081 to arrayOf("reason", "code"), 1084 to arrayOf("kind", "code"), 1085 to arrayOf("number"), 1089 to arrayOf("x", "y"), 1096 to arrayOf("state"), 1097 to arrayOf("label", "example"), 1109 to arrayOf("text"), 1117 to arrayOf("error"), 1118 to arrayOf("kind", "count"), 1121 to arrayOf("name"), 1122 to arrayOf("n"), 1147 to arrayOf("ago"), 1148 to arrayOf("name"), 1149 to arrayOf("kind", "place", "hub"), 1159 to arrayOf("label"), 1160 to arrayOf("word"), 1161 to arrayOf("count"), 1164 to arrayOf("hub"), 1166 to arrayOf("count"), 1167 to arrayOf("state"), 1168 to arrayOf("label"), 1169 to arrayOf("label"), 1174 to arrayOf("state", "text"), 1175 to arrayOf("text"), 1177 to arrayOf("question"), 1179 to arrayOf("label"), 1183 to arrayOf("title"), 1204 to arrayOf("count"), 1205 to arrayOf("name", "counts"), 1219 to arrayOf("n"), 1221 to arrayOf("mode"), 1238 to arrayOf("first", "last", "total"), 1239 to arrayOf("count"), 1242 to arrayOf("n"), 1243 to arrayOf("who", "name"), 1251 to arrayOf("name"), 1252 to arrayOf("when"), 1259 to arrayOf("why"), 1276 to arrayOf("name"), 1283 to arrayOf("kind"), 1284 to arrayOf("title"), 1285 to arrayOf("title"), 1286 to arrayOf("title"), 1287 to arrayOf("title"), 1292 to arrayOf("name"), 1302 to arrayOf("heard"), 1303 to arrayOf("out", "heard"), 1304 to arrayOf("heard"), 1312 to arrayOf("name", "mb"), 1314 to arrayOf("name"), 1317 to arrayOf("platform"), 1321 to arrayOf("heard", "out", "yes"), 1331 to arrayOf("name", "done", "total", "percent"), 1332 to arrayOf("name", "done"), 1333 to arrayOf("name"), 1334 to arrayOf("error"), 1336 to arrayOf("mb"), 1342 to arrayOf("mb"), 1345 to arrayOf("n"), 1346 to arrayOf("n"), 1349 to arrayOf("n"), 1350 to arrayOf("pct"), 1351 to arrayOf("px"), 1352 to arrayOf("version"), 1353 to arrayOf("tag"), 1354 to arrayOf("tag"), 1355 to arrayOf("hub"), 1359 to arrayOf("tag"), 1360 to arrayOf("tag"), 1367 to arrayOf("when"), 1369 to arrayOf("tag"), 1370 to arrayOf("tag", "when"), 1371 to arrayOf("tag"), 1372 to arrayOf("tag", "when"), 1376 to arrayOf("channel"), 1377 to arrayOf("tag"), 1378 to arrayOf("app", "hub"), 1379 to arrayOf("hub", "app"), 1381 to arrayOf("key"), 1382 to arrayOf("key"), 1383 to arrayOf("why"), 1437 to arrayOf("n"), 1470 to arrayOf("title"), 1471 to arrayOf("note"), 1491 to arrayOf("title"), 1492 to arrayOf("more"), 1506 to arrayOf("bots"), 1517 to arrayOf("name"), 1518 to arrayOf("name", "time"), 1519 to arrayOf("name", "n"), 1520 to arrayOf("name", "time", "n"), 1521 to arrayOf("to"), 1522 to arrayOf("to", "step"), 1524 to arrayOf("note"), 1567 to arrayOf("why"), 1572 to arrayOf("e"), 1578 to arrayOf("max"), 1579 to arrayOf("secs", "max", "mib"), 1588 to arrayOf("path"), 1621 to arrayOf("secs"), 1644 to arrayOf("pct", "scope"), 1652 to arrayOf("n"), 1653 to arrayOf("n"), 1654 to arrayOf("n"), 1655 to arrayOf("n"), 1683 to arrayOf("d", "h"), 1684 to arrayOf("h", "m"), 1685 to arrayOf("m"), 1686 to arrayOf("window", "pct"), 1688 to arrayOf("when"), 1690 to arrayOf("label", "e"), 1692 to arrayOf("from", "to", "total"), 1696 to arrayOf("messages", "lines", "left"), 1698 to arrayOf("pct", "view", "max"), 1699 to arrayOf("pct"), 1700 to arrayOf("done", "total"), 1702 to arrayOf("n"), 1703 to arrayOf("n"), 1704 to arrayOf("time"), 1705 to arrayOf("view", "max"), 1706 to arrayOf("view", "max"), 1708 to arrayOf("more"), 1712 to arrayOf("n"), 1721 to arrayOf("n"), 1727 to arrayOf("page"), 1738 to arrayOf("title"), 1741 to arrayOf("n"), 1758 to arrayOf("name"), 1823 to arrayOf("line"), 1824 to arrayOf("quote"), 1825 to arrayOf("n"), 1826 to arrayOf("n"), 1827 to arrayOf("n"), 1828 to arrayOf("n"), 1829 to arrayOf("n"), 1834 to arrayOf("held"), 1835 to arrayOf("machine"), 1836 to arrayOf("machine"), 1844 to arrayOf("count", "total"), 1845 to arrayOf("count"), 1846 to arrayOf("n"), 1858 to arrayOf("name"), 1860 to arrayOf("n", "c", "total"), 1861 to arrayOf("n", "c"), 1862 to arrayOf("n", "c", "total", "before"), 1863 to arrayOf("n", "c", "before"), 1875 to arrayOf("name"), 1876 to arrayOf("path"), 1879 to arrayOf("file"), 1880 to arrayOf("path", "n"), 1881 to arrayOf("why"), 1882 to arrayOf("n"), 1883 to arrayOf("name"), 1884 to arrayOf("name"), 1885 to arrayOf("name"), 1886 to arrayOf("n"), 1887 to arrayOf("shown", "n"), 1890 to arrayOf("path"), 1892 to arrayOf("n"), 1901 to arrayOf("status"), 1918 to arrayOf("name", "pct"), 1919 to arrayOf("name", "mb"), 1920 to arrayOf("name"), 1921 to arrayOf("name", "why"), 1939 to arrayOf("machine"), 1942 to arrayOf("n"), 1943 to arrayOf("ref"), 1944 to arrayOf("ref", "sheet"), 1945 to arrayOf("name"), 1946 to arrayOf("name"), 1947 to arrayOf("file", "folder"), 1948 to arrayOf("name", "error"), 1949 to arrayOf("name", "status"), 1950 to arrayOf("name", "error"), 1952 to arrayOf("name"), 1955 to arrayOf("code"), 1956 to arrayOf("error"), 1959 to arrayOf("error"), 1960 to arrayOf("error"), 1964 to arrayOf("error"), 1982 to arrayOf("done", "of"), 1984 to arrayOf("why"), 1985 to arrayOf("path"), 1986 to arrayOf("error"), 1987 to arrayOf("secs"), 1988 to arrayOf("secs"), 2000 to arrayOf("code"), 2001 to arrayOf("code"), 2004 to arrayOf("state"), 2009 to arrayOf("hide", "copy", "paste"), 2010 to arrayOf("n"), 2013 to arrayOf("name"), 2014 to arrayOf("name", "folder"), 2015 to arrayOf("name"), 2016 to arrayOf("name", "percent"), 2022 to arrayOf("folder"), 2032 to arrayOf("w", "h"), 2036 to arrayOf("path"), 2039 to arrayOf("why"), 2040 to arrayOf("mb"), 2043 to arrayOf("n"), 2044 to arrayOf("delete", "undo"), 2045 to arrayOf("delete", "undo"), 2046 to arrayOf("undo"), 2067 to arrayOf("what", "secs"), 2068 to arrayOf("file", "holder"), 2075 to arrayOf("what"), 2076 to arrayOf("what"), 2077 to arrayOf("editor", "why"), 2096 to arrayOf("files"), 2106 to arrayOf("why"), 2108 to arrayOf("title"), 2109 to arrayOf("title"), 2110 to arrayOf("version"), 2111 to arrayOf("version", "size", "folder"), 2112 to arrayOf("version", "size", "folder"), 2121 to arrayOf("title"), 2122 to arrayOf("dir", "files"), 2128 to arrayOf("why"), 2130 to arrayOf("code"), 2144 to arrayOf("origin"), 2146 to arrayOf("why"), 2157 to arrayOf("dir"), 2158 to arrayOf("path"), 2159 to arrayOf("home", "other"), 2161 to arrayOf("path"), 2162 to arrayOf("code", "log"), 2163 to arrayOf("log"), 2165 to arrayOf("addr"), 2178 to arrayOf("home"), 2179 to arrayOf("addr"), 2194 to arrayOf("dir", "why"), 2195 to arrayOf("dir"), 2210 to arrayOf("phase"), 2212 to arrayOf("why"), 2213 to arrayOf("what"), 2214 to arrayOf("code"), 2220 to arrayOf("label"), 2225 to arrayOf("kind"), 2227 to arrayOf("project"), 2240 to arrayOf("what"), 2242 to arrayOf("when"), 2246 to arrayOf("n"), 2247 to arrayOf("n"), 2248 to arrayOf("n"), 2250 to arrayOf("agent"), 2251 to arrayOf("effort"), 2253 to arrayOf("n"), 2255 to arrayOf("model"), 2267 to arrayOf("word"), 2274 to arrayOf("more", "step"), 2278 to arrayOf("name"), 2282 to arrayOf("max", "skipped"), 2285 to arrayOf("name"), 2286 to arrayOf("n"), 2287 to arrayOf("name"), 2288 to arrayOf("name"), 2294 to arrayOf("n"), 2295 to arrayOf("name"), 2297 to arrayOf("price"), 2300 to arrayOf("name"), 2302 to arrayOf("name"), 2303 to arrayOf("name"), 2304 to arrayOf("name"), 2305 to arrayOf("text"), 2308 to arrayOf("key"), 2309 to arrayOf("key"), 2310 to arrayOf("pct"), 2311 to arrayOf("when"), 2322 to arrayOf("n", "upstream"), 2325 to arrayOf("mb"), 2335 to arrayOf("path"), 2336 to arrayOf("path"), 2358 to arrayOf("id"), 2362 to arrayOf("model"), 2363 to arrayOf("platform"), 2364 to arrayOf("version"), 2367 to arrayOf("version", "from", "into"), 2368 to arrayOf("version", "from"), 2371 to arrayOf("version", "path"), 2372 to arrayOf("version", "path"), 2373 to arrayOf("version", "pin", "from"), 2374 to arrayOf("path"), 2375 to arrayOf("version", "path"), 2376 to arrayOf("version", "path", "set"), 2390 to arrayOf("turns", "input", "cread", "cwrite", "output", "cost"), 2397 to arrayOf("tool"), 2398 to arrayOf("tool"), 2399 to arrayOf("tool", "word"), 2400 to arrayOf("tool", "word"), 2401 to arrayOf("tool"), 2402 to arrayOf("tool"), 2403 to arrayOf("due"), 2404 to arrayOf("due"), 2405 to arrayOf("due"), 2406 to arrayOf("due"), 2407 to arrayOf("zone"), 2408 to arrayOf("zone"), 2409 to arrayOf("zone"), 2410 to arrayOf("zone"), 2411 to arrayOf("n"), 2412 to arrayOf("who"), 2413 to arrayOf("n", "who"), 2414 to arrayOf("harness"), 2415 to arrayOf("path"), 2416 to arrayOf("path"), 2417 to arrayOf("path"), 2420 to arrayOf("error", "line"), 2421 to arrayOf("label"), 2429 to arrayOf("who"), 2430 to arrayOf("who"), 2431 to arrayOf("label", "left", "when"), 2432 to arrayOf("left"), 2433 to arrayOf("name", "left"), 2434 to arrayOf("used"), 2435 to arrayOf("used", "limit"), 2436 to arrayOf("used", "reason"), 2437 to arrayOf("used", "limit", "reason"), 2439 to arrayOf("provider"), 2440 to arrayOf("used", "window", "pct"), 2441 to arrayOf("rate"), 2451 to arrayOf("n", "r"), 2456 to arrayOf("time", "n"), 2460 to arrayOf("n", "m"), 2462 to arrayOf("pct"), 2463 to arrayOf("cost", "n"), 2467 to arrayOf("in", "out", "cread", "cwrite"), 2468 to arrayOf("in", "out", "cread", "cwrite", "n"), 2477 to arrayOf("turns", "input", "cread", "cwrite", "output"), 2478 to arrayOf("left", "when"), 2479 to arrayOf("left", "when"), 2480 to arrayOf("left", "when"), 2481 to arrayOf("left", "when"), 2505 to arrayOf("n"), 2528 to arrayOf("when"), 2535 to arrayOf("phrase", "now"), 2546 to arrayOf("s"), 2552 to arrayOf("now"), 2553 to arrayOf("now", "nudge", "sent", "undone"), 2563 to arrayOf("e"), 2564 to arrayOf("a", "ams", "b", "bms"), 2565 to arrayOf("ms"), 2566 to arrayOf("e"), 2567 to arrayOf("t"), 2568 to arrayOf("t"), 2569 to arrayOf("t"), 2575 to arrayOf("why"), 2585 to arrayOf("apps"), 2595 to arrayOf("n"), 2596 to arrayOf("n", "k"), 2601 to arrayOf("stt", "conf"), 2602 to arrayOf("words"), 2612 to arrayOf("into"), 2615 to arrayOf("origin"), 2627 to arrayOf("url"), 2629 to arrayOf("url"), 2637 to arrayOf("i", "n"), 2638 to arrayOf("d", "n"), 2647 to arrayOf("version"), 2648 to arrayOf("version"), 2649 to arrayOf("version"), 2652 to arrayOf("path"), 2660 to arrayOf("addr"), 2664 to arrayOf("label"), 2666 to arrayOf("label"), 2667 to arrayOf("label"), 2671 to arrayOf("label"), 2676 to arrayOf("from"), 2693 to arrayOf("done", "of"), 2699 to arrayOf("n"), 2700 to arrayOf("t", "m"), 2701 to arrayOf("m"), 2702 to arrayOf("b", "m"), 2703 to arrayOf("r", "p"), 2704 to arrayOf("n"), 2705 to arrayOf("n"), 2706 to arrayOf("n"), 2707 to arrayOf("n"), 2710 to arrayOf("n"), 2712 to arrayOf("n"), 2720 to arrayOf("n"), 2726 to arrayOf("name", "gb", "path"), 2728 to arrayOf("path", "why"), 2730 to arrayOf("names"), 2732 to arrayOf("why"), 2733 to arrayOf("p", "pn", "t", "tn", "e", "en"), 2734 to arrayOf("done", "total"), 2735 to arrayOf("n"), 2736 to arrayOf("what"), 2737 to arrayOf("n"), 2738 to arrayOf("n"), 2741 to arrayOf("what"), 2742 to arrayOf("n"), 2744 to arrayOf("why", "from"), 2745 to arrayOf("why"), 2751 to arrayOf("path"), 2752 to arrayOf("path", "who"), 2753 to arrayOf("path"), 2754 to arrayOf("path", "cmd"), 2755 to arrayOf("version", "path"), 2756 to arrayOf("version", "path"), 2757 to arrayOf("version", "path", "who"), 2758 to arrayOf("version", "path"), 2759 to arrayOf("version", "path", "cmd"), 2762 to arrayOf("cmd"), 2772 to arrayOf("name", "version", "path"), 2773 to arrayOf("path", "why"), 2774 to arrayOf("name"), 2776 to arrayOf("version", "cli"), 2777 to arrayOf("cli"), 2779 to arrayOf("version"), 2780 to arrayOf("version"), 2782 to arrayOf("version"), 2784 to arrayOf("version"), 2786 to arrayOf("computer"), 2787 to arrayOf("version", "cli"), 2788 to arrayOf("cli"), 2789 to arrayOf("version", "cli"), 2790 to arrayOf("cli"), 2812 to arrayOf("n"), 2817 to arrayOf("code"), 2819 to arrayOf("e"), 2832 to arrayOf("n"), 2837 to arrayOf("channel"), 2851 to arrayOf("project"), 2857 to arrayOf("n"), 2869 to arrayOf("m"), 2881 to arrayOf("m"), 2884 to arrayOf("m"), 2891 to arrayOf("pages"), 2893 to arrayOf("name"), 2896 to arrayOf("name"), 2905 to arrayOf("d", "n"), 2926 to arrayOf("n", "tools"), 2927 to arrayOf("n", "tools", "d"), 2928 to arrayOf("n", "d"), 2929 to arrayOf("n", "what"), 2930 to arrayOf("n", "d", "what"), 2934 to arrayOf("head"), 2940 to arrayOf("name", "path"), 2946 to arrayOf("page", "net", "near"), 2947 to arrayOf("page", "what"), 2948 to arrayOf("ref"), 2952 to arrayOf("page"), 2975 to arrayOf("n"), 2976 to arrayOf("n"), 2977 to arrayOf("n"), 2979 to arrayOf("hub"), 3001 to arrayOf("project"), 3003 to arrayOf("n"), 3004 to arrayOf("n"), 3005 to arrayOf("word"), 3006 to arrayOf("n"), 3024 to arrayOf("name"), 3032 to arrayOf("answer"), 3037 to arrayOf("why"), 3039 to arrayOf("hub"), 3045 to arrayOf("from", "to"), 3052 to arrayOf("project"), 3062 to arrayOf("name"), 3066 to arrayOf("n"), 3072 to arrayOf("code"), 3073 to arrayOf("hub"), 3074 to arrayOf("hub"), 3075 to arrayOf("hub"), 3089 to arrayOf("n"), 3090 to arrayOf("n"), 3106 to arrayOf("status"), 3108 to arrayOf("status"), 3137 to arrayOf("project"), 3141 to arrayOf("code"), 3143 to arrayOf("why"), 3151 to arrayOf("title"), 3157 to arrayOf("title"), 3159 to arrayOf("q"), 3160 to arrayOf("title"), 3165 to arrayOf("room"), 3169 to arrayOf("q"), 3179 to arrayOf("title"), 3184 to arrayOf("n"), 3185 to arrayOf("n"), 3190 to arrayOf("at"), 3198 to arrayOf("size"), 3200 to arrayOf("n", "total"), 3217 to arrayOf("n"), 3218 to arrayOf("what"), 3221 to arrayOf("device"), 3222 to arrayOf("device"), 3231 to arrayOf("word", "count"), 3232 to arrayOf("heard"), 3244 to arrayOf("files"), 3245 to arrayOf("files"), 3248 to arrayOf("name"), 3276 to arrayOf("n"), 3277 to arrayOf("n"), 3288 to arrayOf("n"), 3322 to arrayOf("root"), 3323 to arrayOf("path"), 3346 to arrayOf("name"), 3349 to arrayOf("until"), 3350 to arrayOf("error"), 3357 to arrayOf("url"), 3361 to arrayOf("name"), 3362 to arrayOf("name"), 3370 to arrayOf("code", "hub", "until"), 3371 to arrayOf("url"), 3375 to arrayOf("kinds"), 3376 to arrayOf("address"), 3378 to arrayOf("address"), 3381 to arrayOf("url"), 3382 to arrayOf("url"), 3383 to arrayOf("url"), 3384 to arrayOf("url", "via"), 3389 to arrayOf("name"), 3390 to arrayOf("url", "check", "left"), 3392 to arrayOf("check"), 3393 to arrayOf("address"), 3394 to arrayOf("name"), 3395 to arrayOf("error"), 3396 to arrayOf("url"), 3397 to arrayOf("url"), 3404 to arrayOf("code", "address", "left"), 3410 to arrayOf("name"), 3411 to arrayOf("name"), 3422 to arrayOf("address"), 3429 to arrayOf("code", "body"), 3432 to arrayOf("code", "body"), 3438 to arrayOf("window", "used"), 3439 to arrayOf("window", "used", "when"), 3440 to arrayOf("window", "used"), 3441 to arrayOf("window", "used", "when"), 3442 to arrayOf("provider"), 3454 to arrayOf("label"), 3455 to arrayOf("when"), 3457 to arrayOf("provider"), 3458 to arrayOf("provider", "title", "why"), 3478 to arrayOf("reason"), 3486 to arrayOf("code"), 3495 to arrayOf("name"), 3498 to arrayOf("version"), 3499 to arrayOf("version"), 3500 to arrayOf("version"), 3502 to arrayOf("version"), 3503 to arrayOf("version"), 3504 to arrayOf("version"), 3505 to arrayOf("version", "why"), 3506 to arrayOf("version"), 3508 to arrayOf("code"), 3524 to arrayOf("name"), 3531 to arrayOf("count"), 3532 to arrayOf("title"), 3533 to arrayOf("name"), 3536 to arrayOf("n", "holder"), 3537 to arrayOf("n", "title"), 3538 to arrayOf("title"), 3541 to arrayOf("n"), 3542 to arrayOf("n"), 3543 to arrayOf("n"), 3544 to arrayOf("n"), 3545 to arrayOf("harness", "typed", "type", "remote", "host", "wt", "branch"), 3555 to arrayOf("pid"), 3560 to arrayOf("left"), 3561 to arrayOf("left"), 3567 to arrayOf("left"), 3568 to arrayOf("left"), 3569 to arrayOf("left"), 3570 to arrayOf("left"), 3571 to arrayOf("label", "left"), 3572 to arrayOf("when"), 3573 to arrayOf("used"), 3574 to arrayOf("used", "limit"), 3596 to arrayOf("tracking"), 3600 to arrayOf("total"), 3601 to arrayOf("price"), 3602 to arrayOf("price"), 3607 to arrayOf("n"), 3608 to arrayOf("parts"), 3609 to arrayOf("note"), 3610 to arrayOf("error"), 3611 to arrayOf("error", "parts"), 3616 to arrayOf("state"), 3617 to arrayOf("name", "path"), 3618 to arrayOf("name", "path", "why"), 3620 to arrayOf("code"), 3624 to arrayOf("detail"), 3626 to arrayOf("why"), 3627 to arrayOf("parts"), 3630 to arrayOf("build", "to"), 3631 to arrayOf("build"), 3632 to arrayOf("build", "skip"), 3634 to arrayOf("why"), 3635 to arrayOf("why"), 3636 to arrayOf("build"), 3637 to arrayOf("build", "why"), 3638 to arrayOf("build"), 3639 to arrayOf("build"), 3643 to arrayOf("build"), 3644 to arrayOf("build"), 3646 to arrayOf("build"), 3653 to arrayOf("build"), 3687 to arrayOf("step"), 3688 to arrayOf("p", "pt", "t", "tt", "e", "et"), 3689 to arrayOf("done", "total"), 3690 to arrayOf("n"), 3691 to arrayOf("n"), 3692 to arrayOf("n"), 3697 to arrayOf("n"), 3700 to arrayOf("why"), 3701 to arrayOf("why", "from"), 3702 to arrayOf("error"), 3704 to arrayOf("n"), 3705 to arrayOf("n"), 3709 to arrayOf("n"), 3712 to arrayOf("name", "gb", "path"), 3713 to arrayOf("path", "why"), 3714 to arrayOf("names"), 3716 to arrayOf("why"), 3727 to arrayOf("n", "total"), 3731 to arrayOf("title"), 3733 to arrayOf("n"), 3737 to arrayOf("name"), 3738 to arrayOf("title"), 3739 to arrayOf("note"), 3741 to arrayOf("machine"), 3742 to arrayOf("machines"), 3743 to arrayOf("machine"), 3754 to arrayOf("n"), 3756 to arrayOf("n"), 3760 to arrayOf("name"), 3763 to arrayOf("name"), 3780 to arrayOf("why"), 3786 to arrayOf("project"), 3827 to arrayOf("path"), 3828 to arrayOf("path"), 3830 to arrayOf("have", "total"), 3835 to arrayOf("n"), 3844 to arrayOf("hub"), 3847 to arrayOf("title"), 3851 to arrayOf("project"), 3852 to arrayOf("project"), 3853 to arrayOf("n"), 3854 to arrayOf("hub"), 3856 to arrayOf("n"), 3857 to arrayOf("n"), 3858 to arrayOf("model"), 3864 to arrayOf("name"), 3883 to arrayOf("word"), 3889 to arrayOf("answer"), 3899 to arrayOf("version", "build"), 3900 to arrayOf("hub"), 3905 to arrayOf("name"), 3908 to arrayOf("when", "who", "mark"), 3912 to arrayOf("who"), 3916 to arrayOf("time"), 3917 to arrayOf("address"), 3919 to arrayOf("kind", "name"), 3934 to arrayOf("title"), 3935 to arrayOf("query"), 3938 to arrayOf("room"), 3939 to arrayOf("query"), 3941 to arrayOf("n"), 3942 to arrayOf("n"), 3943 to arrayOf("n"), 3949 to arrayOf("size"), 3953 to arrayOf("n"), 3954 to arrayOf("n"), 3955 to arrayOf("n"), 3969 to arrayOf("status"), 3971 to arrayOf("status"), 4122 to arrayOf("code"), 4124 to arrayOf("n"), 4126 to arrayOf("why"), 4138 to arrayOf("done", "of"), 4142 to arrayOf("thread"), 4145 to arrayOf("n"), 4153 to arrayOf("title"), 4154 to arrayOf("note"), 4155 to arrayOf("label"), 4156 to arrayOf("machine"), 4157 to arrayOf("machine"), 4164 to arrayOf("at", "total"), 4165 to arrayOf("at", "total"), 4169 to arrayOf("machine"), 4170 to arrayOf("machine"), 4171 to arrayOf("machines"), 4173 to arrayOf("device"), 4180 to arrayOf("price"), 4181 to arrayOf("price"), 4188 to arrayOf("home"), 4193 to arrayOf("from"), 4195 to arrayOf("note"), 4196 to arrayOf("note"), 4198 to arrayOf("v"), 4199 to arrayOf("v"), 4200 to arrayOf("v", "who"), 4202 to arrayOf("who"), 4203 to arrayOf("v"), 4205 to arrayOf("v", "cmd"), 4206 to arrayOf("cmd"), 4211 to arrayOf("v", "path"), 4212 to arrayOf("v", "note"), 4213 to arrayOf("v"), 4218 to arrayOf("tool"), 4219 to arrayOf("tool"), 4244 to arrayOf("n", "w"), 4245 to arrayOf("why"), 4246 to arrayOf("state", "why"), 4258 to arrayOf("project"), 4259 to arrayOf("n"), 4270 to arrayOf("why"), 4276 to arrayOf("name"), 4287 to arrayOf("project"), 4292 to arrayOf("n"), 4300 to arrayOf("names"), 4308 to arrayOf("dest"), 4310 to arrayOf("repo"), 4311 to arrayOf("repo"), 4313 to arrayOf("url"), 4337 to arrayOf("group"), 4341 to arrayOf("project"), 4342 to arrayOf("n"), 4343 to arrayOf("n"), 4344 to arrayOf("n"), 4352 to arrayOf("n"), 4409 to arrayOf("n"), 4410 to arrayOf("n"), 4411 to arrayOf("a", "b"), 4412 to arrayOf("n"), 4414 to arrayOf("parts", "lines"), 4415 to arrayOf("n"), 4446 to arrayOf("what", "project", "fab"), 4447 to arrayOf("rev", "day"), 4455 to arrayOf("n"), 4466 to arrayOf("layer"), 4467 to arrayOf("n"), 4472 to arrayOf("board"), 4484 to arrayOf("others"), 4485 to arrayOf("must", "should", "notes"), 4486 to arrayOf("id", "w"), 4496 to arrayOf("what"), 4499 to arrayOf("why"), 4500 to arrayOf("why"), 4507 to arrayOf("n"), 4523 to arrayOf("price", "n"), 4524 to arrayOf("n", "need"), 4525 to arrayOf("n"), 4526 to arrayOf("n"), 4527 to arrayOf("cost"), 4528 to arrayOf("cost"), 4541 to arrayOf("day", "n"), 4542 to arrayOf("day"), 4543 to arrayOf("cost", "n", "lines"), 4544 to arrayOf("stock", "price"), 4545 to arrayOf("lines"), 4566 to arrayOf("host"), 4577 to arrayOf("n"), 4578 to arrayOf("a", "b"), 4579 to arrayOf("n"), 4580 to arrayOf("n"), 4583 to arrayOf("day"), 4584 to arrayOf("n"), 4625 to arrayOf("turn"), 4739 to arrayOf("text"), 4742 to arrayOf("repo", "dest"), 4743 to arrayOf("repo", "dest"), 4744 to arrayOf("repo"), 4749 to arrayOf("dir"), 4750 to arrayOf("dir"), 4754 to arrayOf("editor", "job", "secs"), 4755 to arrayOf("editor", "secs"), 4756 to arrayOf("editor"), 4773 to arrayOf("time"), 4779 to arrayOf("status"), 4787 to arrayOf("time"), 4788 to arrayOf("time", "dur"), 4791 to arrayOf("answer"), 4795 to arrayOf("type"), 4796 to arrayOf("max"), 4824 to arrayOf("bytes", "tokens"), 4857 to arrayOf("what"), 4861 to arrayOf("n"), 4863 to arrayOf("n"), 4887 to arrayOf("n"), 4888 to arrayOf("done", "total"), 4896 to arrayOf("v"), 4897 to arrayOf("x", "y")) } + internal val exactKey: IntArray by lazy { intArrayOf(0, 1, 2, 3, 4, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 3152, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 43, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 3720, 61, 62, 63, 64, 66, 68, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 84, 85, 3759, 87, 88, 98, 99, 3081, 3758, 102, 103, 105, 106, 107, 109, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 155, 156, 157, 159, 161, 162, 163, 3201, 165, 166, 3203, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 3162, 183, 187, 189, 193, 194, 195, 197, 198, 199, 200, 201, 202, 206, 209, 213, 215, 216, 217, 219, 220, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 234, 235, 2968, 237, 238, 239, 240, 3719, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255, 256, 260, 262, 263, 264, 265, 266, 267, 270, 271, 272, 273, 275, 279, 280, 281, 282, 286, 287, 289, 290, 291, 292, 293, 294, 295, 296, 297, 298, 300, 301, 3173, 305, 306, 307, 308, 309, 310, 311, 313, 314, 315, 317, 319, 333, 3767, 336, 3766, 3769, 340, 3779, 342, 343, 344, 345, 354, 3150, 357, 358, 359, 360, 361, 362, 363, 364, 365, 366, 367, 368, 369, 370, 371, 372, 373, 2971, 376, 377, 378, 379, 380, 381, 382, 383, 384, 385, 386, 387, 388, 389, 390, 391, 392, 393, 394, 395, 396, 397, 398, 399, 400, 401, 402, 403, 404, 405, 406, 407, 408, 409, 410, 411, 412, 413, 414, 415, 416, 417, 419, 420, 421, 422, 423, 424, 425, 426, 427, 428, 429, 2963, 2964, 432, 433, 434, 435, 436, 437, 438, 439, 440, 441, 442, 443, 444, 445, 446, 447, 448, 449, 450, 451, 453, 454, 455, 3180, 457, 458, 459, 460, 461, 2953, 463, 464, 465, 3083, 467, 468, 469, 470, 471, 472, 473, 474, 475, 476, 477, 478, 479, 480, 481, 482, 483, 484, 485, 486, 487, 488, 489, 490, 491, 492, 493, 494, 495, 496, 497, 498, 499, 500, 501, 502, 503, 504, 505, 506, 507, 508, 509, 510, 511, 512, 513, 514, 515, 516, 517, 518, 519, 520, 521, 522, 523, 524, 525, 526, 527, 528, 529, 530, 531, 532, 533, 534, 535, 536, 537, 538, 539, 540, 541, 542, 543, 544, 545, 546, 547, 548, 549, 550, 551, 552, 553, 554, 556, 557, 558, 559, 560, 561, 562, 563, 565, 566, 567, 568, 569, 570, 571, 572, 573, 574, 575, 576, 577, 578, 592, 628, 629, 630, 3188, 3189, 636, 637, 638, 639, 640, 641, 642, 643, 644, 645, 646, 647, 651, 652, 3832, 654, 656, 657, 659, 663, 664, 665, 666, 667, 668, 669, 670, 671, 672, 673, 674, 675, 676, 677, 678, 680, 681, 682, 683, 684, 686, 687, 689, 690, 692, 693, 694, 695, 698, 704, 724, 728, 729, 730, 731, 732, 3764, 734, 735, 736, 737, 3187, 739, 740, 741, 742, 743, 744, 745, 746, 747, 748, 749, 750, 751, 752, 753, 754, 755, 756, 757, 758, 759, 760, 761, 762, 763, 764, 765, 766, 767, 768, 769, 770, 771, 772, 773, 774, 775, 776, 777, 778, 779, 780, 781, 782, 783, 784, 785, 786, 787, 788, 789, 790, 791, 792, 793, 794, 795, 796, 797, 798, 799, 800, 801, 802, 803, 3747, 805, 806, 807, 808, 809, 810, 811, 812, 813, 814, 815, 816, 817, 818, 819, 820, 821, 822, 823, 824, 825, 826, 827, 828, 829, 832, 833, 834, 835, 836, 837, 838, 839, 840, 841, 843, 844, 845, 847, 848, 3183, 850, 852, 853, 854, 857, 858, 859, 860, 861, 862, 863, 864, 865, 866, 867, 3757, 869, 870, 871, 872, 873, 874, 875, 876, 877, 878, 879, 880, 881, 882, 883, 884, 885, 886, 887, 888, 889, 890, 891, 892, 893, 894, 895, 896, 897, 898, 899, 900, 901, 3834, 903, 904, 907, 908, 909, 910, 911, 912, 913, 914, 915, 916, 917, 918, 919, 920, 921, 922, 923, 924, 925, 926, 927, 928, 929, 930, 931, 932, 933, 934, 935, 936, 937, 938, 939, 940, 941, 942, 943, 944, 945, 946, 947, 948, 949, 950, 951, 952, 953, 954, 955, 956, 957, 958, 959, 960, 961, 962, 3153, 964, 965, 966, 967, 968, 969, 3782, 971, 3008, 3065, 974, 975, 976, 978, 979, 987, 988, 989, 991, 992, 993, 995, 996, 997, 998, 999, 1000, 1001, 1002, 1003, 1005, 1006, 1007, 1008, 1009, 1010, 1011, 1012, 1013, 1014, 1015, 1016, 1017, 1018, 3785, 1020, 1021, 1022, 1025, 1029, 1030, 1031, 2960, 3034, 1034, 1035, 1036, 1037, 1038, 1039, 1040, 1041, 1042, 1043, 1045, 1046, 1049, 1050, 1051, 1052, 1053, 1054, 1055, 1056, 1057, 1058, 1059, 1060, 1061, 1062, 1063, 1064, 1065, 1066, 1067, 1068, 1069, 1070, 1071, 1072, 1074, 1082, 1083, 1086, 1087, 1088, 1090, 1091, 1092, 3799, 1094, 1095, 1098, 1099, 1100, 3182, 1102, 1103, 1104, 1105, 1106, 1107, 1108, 1110, 1111, 1112, 1113, 1114, 1115, 1116, 3784, 1120, 1123, 1124, 1125, 1127, 1128, 1129, 1130, 1131, 1132, 1133, 1134, 1135, 1136, 1137, 1138, 1139, 1140, 1141, 1142, 1143, 1144, 1145, 1146, 1150, 1151, 1152, 1153, 1154, 1155, 1158, 1162, 1163, 1165, 1170, 1171, 1172, 1173, 1176, 1178, 1180, 1181, 1182, 1184, 1185, 1186, 1187, 1188, 1189, 1190, 1191, 1192, 1193, 1194, 1195, 1197, 1198, 1199, 1200, 1201, 1202, 1203, 1206, 1207, 1208, 1209, 1210, 1211, 1212, 1213, 1214, 1215, 1216, 1217, 1218, 1220, 1222, 1223, 2962, 1225, 1226, 1227, 1228, 1229, 1230, 1231, 1232, 1233, 1234, 1235, 1236, 1237, 1240, 1241, 1244, 1245, 1246, 1247, 1248, 1250, 1253, 1254, 1255, 1256, 1257, 1258, 1260, 1261, 1262, 1263, 1264, 1265, 1266, 1267, 1269, 1270, 1271, 1272, 1273, 1274, 1275, 1277, 1278, 1279, 1280, 1281, 1288, 1289, 1290, 1291, 1294, 1296, 1297, 1298, 1299, 1301, 1305, 1306, 1308, 1309, 1310, 1311, 1315, 1316, 1318, 1319, 1320, 1322, 1323, 1324, 1325, 1326, 1327, 1328, 1329, 1330, 1335, 1338, 1339, 1340, 1341, 1344, 1347, 1348, 1356, 1357, 3497, 1361, 1362, 1363, 1364, 1365, 1366, 3564, 1373, 1375, 1380, 1384, 1385, 3038, 1387, 1388, 1389, 1390, 1391, 1392, 1393, 1394, 1395, 1396, 1397, 1398, 1399, 1400, 1401, 1402, 1403, 1404, 1405, 1406, 1407, 1408, 1409, 1410, 1411, 1412, 2965, 1417, 1418, 1419, 1420, 1421, 1422, 1423, 1424, 1425, 1426, 1427, 1428, 1429, 1430, 1431, 1432, 1433, 3082, 3575, 1436, 1438, 1439, 1440, 1441, 1442, 1443, 1444, 1445, 1446, 1447, 1448, 1449, 1450, 1451, 1452, 1453, 1454, 1455, 1456, 1457, 1458, 1459, 1460, 1461, 1462, 1463, 1464, 1465, 1466, 1467, 1468, 1469, 3577, 1473, 1474, 1475, 1477, 1478, 1479, 1480, 1481, 1482, 1483, 1484, 1485, 1486, 1487, 1488, 1489, 1490, 1493, 1494, 3722, 1496, 1497, 1498, 3734, 3740, 1501, 1502, 1503, 1504, 1505, 1507, 1508, 1509, 1510, 1511, 1512, 1513, 1514, 1515, 1516, 1523, 1525, 1526, 1527, 1528, 1529, 1530, 1531, 1532, 1533, 1534, 1535, 1536, 1537, 1538, 1539, 1540, 1541, 1542, 1543, 1544, 1545, 1546, 1547, 1548, 1549, 1550, 1551, 1552, 1553, 1554, 1555, 1556, 1557, 1558, 1559, 1560, 1561, 1562, 1563, 1564, 1565, 1566, 1568, 1569, 1570, 1571, 1573, 1574, 1575, 1576, 1577, 1580, 1581, 1582, 1583, 1584, 1585, 1586, 1587, 1589, 1590, 1591, 1592, 1593, 1594, 1595, 1596, 1597, 1598, 1599, 1600, 1601, 1602, 1603, 1604, 1605, 1606, 1607, 1608, 1609, 1610, 1611, 1612, 1613, 1614, 1615, 1616, 1617, 1618, 1619, 1620, 1622, 1623, 1624, 1625, 1626, 1627, 1628, 1629, 3041, 1631, 1632, 1633, 1634, 1635, 1636, 1637, 1638, 1639, 1640, 1641, 1642, 1643, 1645, 1646, 1647, 1648, 1649, 1650, 1651, 1656, 1657, 1658, 1659, 1660, 1661, 1662, 1663, 3451, 1665, 1666, 1667, 1668, 3452, 1670, 1671, 1672, 1673, 1674, 1675, 1676, 1677, 1678, 1679, 1680, 1681, 2974, 1687, 1689, 1691, 1693, 1697, 1701, 1707, 1709, 1710, 1711, 1713, 1714, 1715, 1716, 1717, 1718, 1720, 1722, 1723, 1724, 1725, 1726, 1728, 1729, 3746, 1731, 1732, 1733, 1734, 1735, 1736, 1737, 1739, 1740, 1742, 1743, 1744, 1745, 1746, 1747, 1748, 1749, 1750, 1751, 1752, 1753, 1754, 1755, 1756, 1757, 1760, 1761, 1762, 1763, 1764, 1765, 1766, 1767, 1768, 1769, 1770, 1771, 1772, 1773, 1774, 1775, 1776, 1777, 1778, 1779, 1780, 1781, 1782, 1783, 1784, 1785, 1786, 1787, 1788, 1789, 1790, 1791, 1792, 1793, 1794, 1795, 1796, 1797, 1798, 1799, 1800, 1801, 1802, 1803, 1804, 1805, 1806, 1807, 1808, 1809, 1810, 1811, 1812, 1813, 1814, 1815, 1816, 1817, 1818, 1819, 1821, 1822, 3017, 1831, 1833, 1837, 2999, 1839, 1840, 3000, 1842, 1843, 1847, 3064, 1849, 1850, 1851, 1852, 1853, 1854, 1855, 1856, 1857, 1859, 1864, 1866, 1867, 1868, 1869, 1870, 1871, 3079, 1873, 1874, 1877, 1878, 1888, 1889, 1893, 1894, 1895, 1896, 1897, 1898, 1899, 1900, 1902, 1903, 1904, 1905, 1906, 1907, 1908, 1909, 1910, 1911, 1912, 1913, 1914, 1915, 1916, 1917, 1922, 1923, 1924, 1925, 1926, 1927, 1928, 1929, 1930, 1931, 1932, 1933, 1934, 1935, 1937, 1938, 1940, 1941, 1951, 1953, 1954, 1957, 1958, 1961, 1962, 1963, 1965, 1966, 1967, 1968, 1969, 1970, 1971, 1972, 1973, 1974, 1975, 1976, 1977, 1978, 1979, 1980, 1981, 1983, 1989, 1990, 1991, 1992, 1996, 3140, 2002, 2003, 2005, 2006, 2007, 2008, 3792, 3793, 2017, 2019, 2020, 2021, 2023, 2024, 2025, 2026, 2027, 2028, 2029, 2030, 2031, 2034, 2035, 2037, 2038, 2041, 2042, 3125, 3126, 3127, 2050, 3353, 2052, 2054, 2055, 2056, 2057, 2058, 2059, 2060, 2061, 2062, 2063, 2064, 2065, 2066, 2069, 2070, 2071, 2072, 2073, 2074, 2078, 2079, 2080, 2081, 2082, 2083, 2084, 2085, 2086, 2087, 2088, 2089, 2090, 2091, 2092, 2093, 2094, 2095, 2097, 2098, 2099, 2100, 2101, 2102, 2103, 2104, 2105, 2107, 2113, 2114, 2115, 2116, 2117, 2118, 2119, 2120, 3067, 2125, 2126, 2127, 2129, 2131, 2132, 2133, 2134, 2990, 3115, 3116, 3117, 3118, 3119, 2141, 2142, 2143, 2145, 2992, 2993, 2983, 2982, 2151, 2984, 2153, 2988, 2155, 3351, 2160, 2164, 2166, 2167, 2168, 2169, 2170, 2171, 2172, 2173, 2174, 2175, 2176, 3018, 2180, 2181, 2182, 2183, 3051, 2185, 2186, 2187, 2188, 2189, 2190, 2191, 2192, 2193, 2196, 3364, 2198, 2199, 2200, 2201, 3033, 2203, 2204, 2205, 2206, 2981, 2208, 3096, 2211, 2215, 2216, 3641, 2218, 2219, 3728, 3729, 2223, 3178, 2226, 3717, 2229, 2230, 2231, 2232, 2233, 3777, 2235, 3148, 2237, 3147, 2239, 2241, 2243, 2244, 2245, 2249, 2252, 2254, 2256, 2257, 2258, 2259, 2260, 2261, 2262, 2263, 2264, 2265, 2266, 2268, 2269, 2270, 3735, 2272, 2273, 2275, 3025, 3023, 3027, 2281, 2283, 2284, 2290, 2291, 2292, 2293, 3063, 2298, 2299, 2301, 2306, 2307, 3007, 3576, 2970, 2969, 2972, 3092, 3095, 2320, 2321, 2323, 2324, 2326, 2327, 2328, 2329, 2330, 2331, 2332, 2333, 2334, 3796, 2338, 2339, 2340, 2341, 2342, 2343, 2344, 2345, 2346, 2347, 2348, 2349, 2350, 2351, 2352, 2357, 2359, 2360, 2361, 2365, 2366, 2369, 2370, 2377, 2378, 2379, 2380, 2381, 2382, 2383, 2384, 2385, 2386, 2387, 2388, 2389, 2391, 2392, 2393, 2394, 2395, 2396, 2418, 2419, 2422, 2423, 2424, 2425, 2426, 2427, 2428, 2438, 2442, 2443, 2444, 2445, 2446, 2447, 2448, 2449, 2450, 2452, 2453, 2454, 2455, 2457, 2458, 2459, 2461, 2464, 2465, 2466, 2469, 2470, 2471, 2472, 2473, 2474, 2475, 2476, 2482, 2483, 2484, 2485, 2486, 2487, 2488, 2489, 2490, 2491, 2492, 2493, 2494, 2495, 2496, 2497, 2498, 2499, 2500, 2501, 2502, 2503, 2504, 2506, 2507, 2508, 2509, 2510, 2511, 2512, 2513, 2514, 2515, 2516, 2517, 2518, 2519, 2520, 2521, 2522, 2523, 2524, 2525, 2526, 2527, 2529, 2530, 2531, 2532, 3129, 2534, 2536, 2537, 2539, 2540, 2541, 2542, 2543, 2544, 2545, 2548, 2549, 2550, 2551, 2554, 2555, 2556, 2557, 2558, 2559, 2560, 2561, 2562, 2570, 2571, 2572, 2573, 2576, 2577, 2578, 2579, 2580, 2581, 2582, 2583, 2584, 2586, 2587, 2588, 2589, 2590, 2591, 2592, 2593, 2594, 2597, 2599, 2600, 2603, 2604, 2605, 2606, 2607, 2608, 2609, 2610, 2611, 2613, 2614, 2616, 2617, 2618, 2619, 2620, 2621, 2622, 2623, 2624, 2625, 2626, 2628, 2630, 2633, 2635, 3725, 2640, 2641, 2642, 2643, 2644, 2645, 2646, 2650, 2651, 2653, 2654, 2655, 2656, 2657, 2658, 2659, 2661, 2662, 2663, 2668, 2669, 2670, 2672, 2673, 2674, 2675, 2677, 2678, 2679, 2680, 2681, 2682, 2683, 2684, 2685, 2686, 2687, 2688, 2689, 3698, 2691, 2692, 2694, 3695, 2696, 2697, 3699, 3696, 2709, 2713, 3706, 3202, 3707, 2717, 3708, 2719, 2721, 3710, 2723, 3711, 2725, 2727, 3715, 3693, 3686, 3694, 2746, 2747, 2749, 2750, 2760, 2761, 2763, 2764, 2765, 2766, 2767, 2768, 2769, 2770, 2771, 2775, 2778, 2781, 2783, 2785, 2791, 2792, 2793, 2794, 2795, 2796, 2797, 2798, 2799, 2800, 2801, 2802, 2803, 3373, 2805, 2806, 2807, 2808, 2809, 2811, 2813, 2814, 3405, 2820, 2821, 2822, 2823, 2824, 2825, 2826, 2827, 2828, 2829, 2830, 2831, 2833, 2834, 2835, 2836, 2839, 2840, 2842, 2843, 2844, 2845, 2997, 2847, 2849, 2850, 2852, 2853, 2854, 2855, 2856, 2858, 2859, 2863, 2866, 2867, 2868, 2870, 2871, 2872, 2874, 2875, 2876, 2877, 2879, 2880, 2883, 2886, 2887, 2888, 2889, 2890, 2892, 2894, 2895, 2897, 2898, 2899, 2900, 2901, 2902, 2903, 2904, 2906, 2907, 2908, 2909, 2910, 2911, 2912, 2913, 2914, 2915, 2916, 2917, 2918, 2919, 2920, 2921, 2922, 2923, 2924, 2925, 2931, 2932, 2933, 2935, 2936, 2937, 2941, 2942, 2943, 2944, 2945, 2949, 2950, 2954, 2955, 2956, 2957, 2958, 2959, 2961, 2966, 2967, 2973, 2978, 2980, 2985, 2986, 2987, 2989, 2991, 2994, 2995, 2996, 2998, 3002, 3009, 3010, 3011, 3012, 3013, 3014, 3015, 3016, 3019, 3020, 3021, 3022, 3026, 3028, 3029, 3030, 3031, 3035, 3036, 3040, 3042, 3043, 3044, 3046, 3047, 3048, 3049, 3050, 3053, 3054, 3055, 3056, 3057, 3058, 3059, 3060, 3061, 3068, 3069, 3070, 3071, 3076, 3077, 3078, 3080, 3084, 3085, 3086, 3087, 3088, 3091, 3093, 3094, 3097, 3098, 3099, 3100, 3101, 3102, 3103, 3104, 3105, 3107, 3109, 3110, 3111, 3112, 3113, 3114, 3120, 3121, 3122, 3123, 3124, 3128, 3130, 3131, 3132, 3133, 3134, 3135, 3136, 3138, 3139, 3142, 3144, 3145, 3146, 3149, 3154, 3155, 3156, 3158, 3161, 3163, 3164, 3166, 3167, 3168, 3170, 3171, 3172, 3174, 3175, 3176, 3177, 3181, 3186, 3191, 3192, 3193, 3194, 3195, 3196, 3197, 3199, 3204, 3205, 3206, 3207, 3208, 3209, 3210, 3211, 3212, 3213, 3214, 3215, 3216, 3219, 3220, 3223, 3224, 3225, 3226, 3227, 3228, 3229, 3230, 3233, 3234, 3235, 3236, 3237, 3238, 3239, 3240, 3241, 3242, 3243, 3246, 3247, 3249, 3250, 3251, 3252, 3253, 3254, 3255, 3256, 3257, 3258, 3259, 3260, 3261, 3262, 3263, 3264, 3265, 3266, 3267, 3268, 3269, 3270, 3271, 3272, 3273, 3274, 3275, 3278, 3279, 3280, 3281, 3282, 3283, 3284, 3285, 3286, 3287, 3289, 3290, 3291, 3292, 3293, 3294, 3295, 3296, 3297, 3298, 3299, 3300, 3301, 3302, 3303, 3304, 3305, 3306, 3307, 3308, 3309, 3310, 3311, 3312, 3313, 3314, 3315, 3316, 3317, 3318, 3319, 3320, 3321, 3324, 3325, 3326, 3327, 3328, 3329, 3330, 3331, 3332, 3333, 3334, 3335, 3336, 3337, 3338, 3339, 3340, 3341, 3342, 3343, 3344, 3345, 3347, 3348, 3352, 3354, 3355, 3356, 3358, 3359, 3360, 3363, 3365, 3366, 3367, 3368, 3369, 3372, 3374, 3377, 3379, 3380, 3385, 3386, 3387, 3388, 3391, 3398, 3399, 3400, 3401, 3402, 3403, 3406, 3407, 3408, 3409, 3412, 3413, 3414, 3415, 3416, 3417, 3418, 3419, 3420, 3421, 3423, 3424, 3425, 3426, 3427, 3428, 3430, 3431, 3433, 3434, 3435, 3436, 3437, 3443, 3444, 3445, 3446, 3447, 3448, 3449, 3450, 3453, 3456, 3459, 3460, 3461, 3462, 3463, 3464, 3465, 3466, 3467, 3468, 3469, 3470, 3471, 3472, 3473, 3474, 3475, 3476, 3477, 3479, 3480, 3481, 3482, 3483, 3484, 3485, 3487, 3488, 3489, 3490, 3491, 3492, 3493, 3494, 3496, 3501, 3507, 3509, 3510, 3511, 3512, 3513, 3514, 3515, 3516, 3517, 3518, 3519, 3520, 3521, 3522, 3523, 3525, 3526, 3527, 3528, 3529, 3530, 3534, 3535, 3539, 3540, 3546, 3547, 3548, 3549, 3550, 3551, 3552, 3553, 3554, 3556, 3557, 3558, 3559, 3562, 3563, 3565, 3566, 3578, 3579, 3580, 3581, 3582, 3583, 3584, 3585, 3586, 3587, 3588, 3589, 3590, 3591, 3592, 3593, 3594, 3595, 3597, 3598, 3599, 3603, 3604, 3605, 3606, 3612, 3613, 3614, 3615, 3619, 3621, 3622, 3623, 3625, 3628, 3629, 3633, 3640, 3642, 3645, 3647, 3648, 3649, 3650, 3651, 3652, 3654, 3655, 3656, 3657, 3658, 3659, 3660, 3661, 3662, 3663, 3664, 3665, 3666, 3667, 3668, 3669, 3670, 3671, 3672, 3673, 3674, 3675, 3676, 3677, 3678, 3679, 3680, 3681, 3682, 3683, 3684, 3685, 3703, 3718, 3721, 3723, 3724, 3726, 3730, 3732, 3736, 3745, 3748, 3749, 3750, 3751, 3752, 3753, 3755, 3761, 3762, 3765, 3768, 3770, 3771, 3772, 3773, 3774, 3775, 3778, 3781, 3783, 3787, 3788, 3789, 3790, 3791, 3794, 3795, 3797, 3798, 3800, 3801, 3802, 3803, 3804, 3805, 3806, 3807, 3809, 3810, 3811, 3812, 3813, 3814, 3815, 3816, 3817, 3818, 3819, 3820, 3821, 3822, 3823, 3824, 3825, 3826, 3829, 3831, 3833, 3842, 3843, 3845, 3846, 3855, 3861, 3867, 3876, 3878, 3879, 3880, 3881, 3884, 3885, 3887, 3893, 3897, 3901, 3906, 3907, 3909, 3910, 3911, 3913, 3914, 3915, 3920, 3921, 3922, 3923, 3924, 3925, 3926, 3927, 3928, 3931, 3932, 3933, 3978, 3979, 3984, 3986, 3987, 3989, 3995, 3998, 4013, 4014, 4015, 4016, 4017, 4018, 4020, 4021, 4023, 4024, 4026, 4028, 4029, 4042, 4045, 4046, 4048, 4049, 4053, 4058, 4061, 4062, 4064, 4065, 4071, 4073, 4074, 4077, 4079, 4084, 4085, 4086, 4091, 4102, 4125, 4141, 4149, 4158, 4159, 4163, 4168, 4184, 4185, 4186, 4187, 4189, 4191, 4192, 4194, 4197, 4201, 4204, 4207, 4208, 4209, 4210, 4214, 4215, 4216, 4217, 4220, 4221, 4222, 4223, 4224, 4225, 4226, 4227, 4228, 4229, 4230, 4231, 4232, 4233, 4234, 4235, 4236, 4237, 4238, 4239, 4240, 4241, 4242, 4243, 4251, 4254, 4255, 4261, 4266, 4267, 4268, 4269, 4273, 4277, 4279, 4280, 4281, 4282, 4283, 4284, 4285, 4286, 4288, 4289, 4290, 4291, 4293, 4294, 4295, 4296, 4297, 4298, 4299, 4309, 4321, 4322, 4324, 4325, 4326, 4327, 4331, 4332, 4333, 4334, 4335, 4336, 4338, 4339, 4340, 4346, 4347, 4348, 4349, 4350, 4351, 4355, 4359, 4360, 4362, 4363, 4364, 4365, 4366, 4368, 4378, 4380, 4385, 4386, 4387, 4388, 4389, 4390, 4391, 4392, 4393, 4394, 4395, 4396, 4397, 4398, 4399, 4400, 4402, 4403, 4404, 4405, 4406, 4407, 4408, 4413, 4416, 4417, 4418, 4419, 4420, 4421, 4422, 4423, 4424, 4425, 4426, 4427, 4428, 4429, 4430, 4431, 4432, 4433, 4434, 4435, 4436, 4438, 4439, 4440, 4442, 4443, 4444, 4445, 4448, 4449, 4450, 4452, 4453, 4454, 4456, 4457, 4458, 4459, 4460, 4461, 4463, 4465, 4468, 4469, 4470, 4471, 4473, 4474, 4475, 4476, 4477, 4478, 4479, 4480, 4481, 4482, 4483, 4487, 4489, 4490, 4491, 4492, 4493, 4497, 4498, 4502, 4503, 4504, 4506, 4508, 4509, 4510, 4511, 4512, 4513, 4514, 4516, 4517, 4518, 4519, 4520, 4521, 4522, 4529, 4530, 4531, 4532, 4533, 4534, 4535, 4536, 4537, 4538, 4539, 4540, 4546, 4547, 4549, 4550, 4551, 4552, 4553, 4554, 4555, 4556, 4557, 4558, 4559, 4560, 4561, 4562, 4563, 4564, 4568, 4569, 4570, 4571, 4572, 4573, 4574, 4575, 4576, 4581, 4582, 4585, 4586, 4587, 4588, 4589, 4590, 4591, 4592, 4593, 4594, 4595, 4596, 4597, 4598, 4600, 4601, 4602, 4603, 4612, 4613, 4614, 4615, 4616, 4617, 4619, 4622, 4623, 4624, 4626, 4627, 4628, 4629, 4630, 4631, 4632, 4633, 4634, 4635, 4636, 4637, 4638, 4639, 4640, 4641, 4642, 4643, 4644, 4645, 4646, 4647, 4648, 4649, 4650, 4651, 4652, 4653, 4654, 4655, 4656, 4657, 4658, 4659, 4660, 4661, 4662, 4663, 4664, 4665, 4666, 4667, 4668, 4669, 4670, 4671, 4672, 4673, 4674, 4675, 4676, 4677, 4678, 4679, 4680, 4681, 4682, 4683, 4684, 4685, 4686, 4687, 4688, 4689, 4690, 4691, 4692, 4693, 4694, 4695, 4696, 4697, 4698, 4699, 4700, 4701, 4702, 4703, 4704, 4705, 4706, 4707, 4708, 4709, 4710, 4711, 4712, 4713, 4714, 4715, 4716, 4717, 4718, 4719, 4720, 4721, 4722, 4723, 4724, 4725, 4726, 4727, 4732, 4733, 4734, 4740, 4753, 4757, 4758, 4759, 4760, 4761, 4762, 4763, 4764, 4765, 4766, 4767, 4768, 4769, 4770, 4771, 4772, 4774, 4775, 4776, 4777, 4778, 4780, 4781, 4782, 4783, 4784, 4785, 4786, 4789, 4790, 4792, 4793, 4794, 4797, 4798, 4799, 4800, 4801, 4802, 4803, 4804, 4805, 4806, 4807, 4808, 4809, 4810, 4811, 4812, 4813, 4814, 4815, 4816, 4817, 4818, 4819, 4820, 4821, 4822, 4823, 4825, 4826, 4827, 4828, 4829, 4830, 4831, 4832, 4833, 4834, 4835, 4836, 4837, 4838, 4839, 4840, 4841, 4842, 4843, 4844, 4845, 4846, 4847, 4848, 4849, 4850, 4851, 4852, 4853, 4854, 4855, 4856, 4858, 4859, 4860, 4862, 4864, 4866, 4867, 4868, 4869, 4872, 4874, 4875, 4876, 4877, 4879, 4880, 4881, 4882, 4883, 4884, 4885, 4886, 4889, 4893, 4894, 4898, 4899, 4900, 4901, 4902, 4904, 4905) } + internal val templates: IntArray by lazy { intArrayOf(2358, 2837, 2649, 2648, 2647, 2869, 2891, 3371, 2612, 418, 2782, 2780, 2676, 2367, 2373, 2784, 2881, 2596, 2595, 285, 2325, 2786, 2893, 3221, 4173, 2535, 4903, 2585, 2045, 2363, 3705, 2110, 2712, 2368, 3222, 1336, 4193, 4213, 3704, 2553, 2710, 1862, 4188, 2121, 2159, 2165, 4542, 283, 2111, 4484, 3383, 3404, 2068, 2336, 3701, 452, 2744, 2776, 2777, 3384, 3700, 2745, 3632, 609, 1706, 3709, 1863, 2720, 3712, 2726, 3375, 616, 617, 2762, 3073, 3687, 1654, 2779, 3631, 303, 614, 69, 711, 621, 2335, 4211, 1121, 2477, 3454, 3827, 1242, 2194, 2564, 3376, 2157, 3716, 714, 1758, 1959, 2732, 2741, 2952, 4218, 3378, 3390, 136, 594, 596, 2552, 2707, 1860, 4206, 3024, 610, 2278, 2575, 3864, 1302, 4205, 3500, 3637, 3638, 158, 2075, 2077, 2112, 2832, 4341, 2163, 2362, 2505, 3626, 214, 284, 1276, 2009, 4773, 3495, 3504, 3505, 67, 83, 218, 619, 4578, 3524, 1360, 4300, 3349, 3714, 726, 1023, 1372, 2376, 2468, 2730, 4343, 89, 2375, 2390, 2905, 624, 1652, 1949, 2819, 4472, 3397, 1572, 2096, 2282, 2566, 4524, 3392, 3458, 3508, 650, 1883, 3919, 3157, 3499, 3545, 3609, 3828, 1317, 1861, 2040, 2414, 2701, 3847, 4543, 3411, 3457, 1836, 1858, 3346, 593, 1292, 1346, 1371, 1948, 3486, 3688, 221, 1696, 2733, 2930, 3075, 3143, 3432, 258, 591, 1026, 1379, 1960, 1984, 4126, 3429, 3555, 655, 1342, 1712, 2046, 3151, 3350, 3611, 3630, 710, 1283, 1370, 1382, 1653, 1727, 1890, 2364, 2467, 2565, 3934, 4212, 4409, 3410, 3478, 3624, 649, 699, 1044, 2601, 3169, 3288, 3691, 108, 184, 606, 721, 1081, 1964, 2044, 2106, 2161, 2400, 2481, 2737, 2773, 2817, 3939, 4455, 4796, 3370, 3441, 3602, 160, 623, 701, 1332, 1333, 1345, 1520, 1655, 2158, 2162, 2255, 2399, 2627, 4181, 4485, 3106, 3198, 3245, 3323, 3537, 3692, 3702, 703, 1183, 1567, 1892, 2250, 2253, 2480, 2738, 2758, 2759, 2927, 2928, 3949, 3969, 4202, 4446, 4779, 4795, 3610, 3627, 3733, 1378, 1492, 1579, 1698, 1950, 2420, 2432, 2757, 4145, 4203, 4486, 4577, 3072, 3074, 3089, 3607, 3620, 3786, 723, 1024, 1827, 2130, 2195, 2410, 2753, 2754, 3954, 4200, 4276, 4287, 3276, 3396, 91, 93, 595, 715, 1027, 1350, 1355, 2015, 2322, 2415, 2700, 2752, 2756, 3916, 4525, 4857, 3003, 3004, 3506, 3570, 3713, 94, 1251, 1259, 1353, 1377, 1519, 1578, 1875, 2178, 2210, 2460, 2478, 2728, 3856, 3857, 4199, 4352, 4415, 4861, 3322, 3361, 3362, 3440, 3596, 299, 599, 618, 700, 1109, 1117, 1175, 1367, 1518, 1621, 1943, 2122, 2128, 2146, 2213, 2430, 2435, 2437, 2660, 2693, 2751, 2929, 2946, 2947, 4170, 4196, 4313, 3005, 3159, 3536, 3569, 3738, 211, 585, 590, 605, 717, 720, 906, 990, 1084, 1159, 1334, 1470, 1524, 1700, 1881, 1901, 1921, 1956, 1986, 2067, 2305, 2413, 2479, 2934, 3883, 3935, 4153, 4526, 4544, 4545, 4744, 3066, 3422, 3617, 3618, 92, 96, 269, 603, 648, 712, 980, 1331, 1702, 1882, 1939, 2109, 2408, 2434, 2436, 2439, 2528, 2666, 2702, 2884, 2896, 4244, 4528, 4756, 2979, 3244, 3277, 3357, 3455, 3574, 3608, 208, 277, 316, 329, 330, 1287, 1352, 1376, 1521, 1522, 1944, 2014, 2039, 2108, 2212, 2240, 2288, 2402, 2417, 2429, 2703, 2706, 2787, 2788, 3854, 4541, 4739, 3001, 3389, 3393, 3442, 3498, 3653, 3690, 3743, 6, 244, 304, 600, 604, 1047, 1221, 1286, 1354, 1359, 1703, 1704, 1879, 1952, 1955, 2013, 2016, 2144, 2179, 2227, 2401, 2409, 2629, 2735, 2774, 2851, 3851, 3852, 3912, 4169, 4742, 4754, 4755, 3439, 3561, 3568, 3573, 3635, 3643, 268, 318, 322, 331, 583, 707, 722, 1076, 1160, 1164, 1284, 1285, 1312, 1517, 1705, 1823, 1884, 2004, 2214, 2220, 2372, 2398, 2404, 2431, 2563, 2664, 3917, 4142, 4195, 4258, 4344, 4414, 4625, 4743, 3052, 3137, 3502, 3503, 3601, 3634, 65, 210, 274, 587, 608, 613, 708, 713, 984, 1075, 1167, 1369, 1708, 1738, 1824, 1829, 1844, 1880, 2043, 2076, 2267, 2285, 2294, 2397, 2451, 2463, 2755, 4180, 3032, 3382, 3567, 3636, 3644, 3689, 90, 207, 288, 320, 323, 324, 349, 597, 607, 709, 855, 905, 1166, 1169, 1252, 1437, 1885, 2000, 2010, 2403, 2412, 2456, 2734, 2772, 2926, 2940, 3889, 4787, 4788, 4791, 4887, 3006, 3037, 3090, 3160, 3218, 3231, 3232, 3395, 3543, 3544, 3616, 3639, 3646, 3697, 110, 186, 190, 191, 212, 321, 327, 328, 352, 375, 580, 582, 589, 625, 727, 851, 977, 1077, 1118, 1147, 1243, 1304, 1314, 1741, 1825, 1826, 1834, 1945, 1946, 1947, 2036, 2246, 2248, 2274, 2286, 2287, 2309, 2371, 2405, 2406, 2462, 2568, 2569, 2652, 2667, 2699, 2704, 2705, 2742, 2789, 2790, 3835, 3853, 3899, 3953, 4198, 4292, 4310, 4342, 4412, 4447, 4499, 4523, 4584, 4824, 3039, 3141, 3165, 3179, 3200, 3381, 3394, 3538, 3542, 3572, 3600, 3731, 3741, 3742, 3754, 3756, 3763, 5, 8, 82, 185, 188, 192, 257, 276, 325, 326, 348, 351, 356, 598, 620, 658, 696, 705, 856, 985, 1048, 1122, 1148, 1149, 1168, 1179, 1239, 1383, 1491, 1644, 1688, 1699, 1845, 1876, 1942, 1988, 2001, 2022, 2242, 2247, 2297, 2303, 2304, 2311, 2416, 2602, 2638, 2812, 3900, 3908, 3938, 3955, 4122, 4157, 4171, 4219, 4259, 4311, 4337, 4500, 4527, 3062, 3108, 3184, 3185, 3190, 3248, 3532, 154, 259, 261, 347, 350, 353, 579, 602, 612, 702, 706, 982, 1078, 1381, 1588, 1828, 1920, 1982, 1985, 2295, 2308, 2374, 2421, 2567, 2615, 2857, 3858, 3905, 3971, 4138, 4496, 4583, 3438, 3531, 3533, 3541, 3560, 3571, 3739, 3760, 3780, 95, 196, 203, 204, 205, 242, 243, 346, 581, 586, 601, 615, 622, 626, 627, 691, 716, 725, 983, 986, 1085, 1089, 1161, 1174, 1204, 1349, 1471, 1506, 1683, 1684, 1686, 1721, 1846, 1886, 2225, 2300, 2310, 2411, 2433, 2441, 2948, 4124, 4154, 4155, 4245, 4270, 4308, 4410, 4466, 4507, 4863, 4888) } + internal val argNames: Map> by lazy { mapOf(5 to arrayOf("n"), 6 to arrayOf("n"), 7 to arrayOf("who"), 8 to arrayOf("title"), 65 to arrayOf("state"), 67 to arrayOf("listen"), 69 to arrayOf("listen"), 82 to arrayOf("version"), 83 to arrayOf("count", "plural"), 89 to arrayOf("size", "limit"), 90 to arrayOf("name"), 91 to arrayOf("dir"), 92 to arrayOf("dir"), 93 to arrayOf("name"), 94 to arrayOf("name"), 95 to arrayOf("path"), 96 to arrayOf("path"), 97 to arrayOf("name"), 108 to arrayOf("first"), 110 to arrayOf("n"), 136 to arrayOf("count", "plural"), 154 to arrayOf("tool"), 158 to arrayOf("n"), 160 to arrayOf("name"), 184 to arrayOf("pid", "cmd"), 185 to arrayOf("title", "ago"), 186 to arrayOf("name", "who", "n"), 188 to arrayOf("line"), 190 to arrayOf("n"), 191 to arrayOf("n"), 192 to arrayOf("n"), 196 to arrayOf("name"), 203 to arrayOf("when"), 204 to arrayOf("text", "when"), 205 to arrayOf("when"), 207 to arrayOf("count", "plural"), 208 to arrayOf("count", "plural"), 210 to arrayOf("took", "ago"), 211 to arrayOf("ago"), 212 to arrayOf("kind"), 214 to arrayOf("kind", "code", "why"), 218 to arrayOf("clock"), 221 to arrayOf("build"), 242 to arrayOf("step"), 243 to arrayOf("turn"), 244 to arrayOf("branch"), 257 to arrayOf("step", "total"), 258 to arrayOf("step", "total"), 259 to arrayOf("when"), 261 to arrayOf("tool"), 268 to arrayOf("count", "plural"), 269 to arrayOf("count", "total"), 274 to arrayOf("old", "new"), 276 to arrayOf("version"), 277 to arrayOf("count"), 278 to arrayOf("tag"), 283 to arrayOf("version"), 284 to arrayOf("old", "version"), 285 to arrayOf("version"), 288 to arrayOf("version"), 299 to arrayOf("project", "location"), 303 to arrayOf("account"), 304 to arrayOf("account"), 316 to arrayOf("n"), 318 to arrayOf("n"), 320 to arrayOf("minute"), 321 to arrayOf("time"), 322 to arrayOf("time"), 323 to arrayOf("clock"), 324 to arrayOf("clock", "took"), 325 to arrayOf("clock"), 326 to arrayOf("clock", "took"), 327 to arrayOf("clock"), 328 to arrayOf("clock", "took"), 329 to arrayOf("clock"), 330 to arrayOf("clock", "took"), 331 to arrayOf("clock"), 346 to arrayOf("target"), 347 to arrayOf("target"), 348 to arrayOf("target"), 349 to arrayOf("target"), 350 to arrayOf("target"), 351 to arrayOf("target"), 352 to arrayOf("target"), 353 to arrayOf("target"), 356 to arrayOf("name"), 375 to arrayOf("t"), 418 to arrayOf("minutes", "plural"), 452 to arrayOf("path"), 579 to arrayOf("count"), 580 to arrayOf("count"), 581 to arrayOf("title"), 582 to arrayOf("path"), 583 to arrayOf("path", "error"), 584 to arrayOf("first", "last", "count"), 585 to arrayOf("task", "step"), 586 to arrayOf("count"), 587 to arrayOf("path"), 588 to arrayOf("count", "plural"), 589 to arrayOf("label"), 590 to arrayOf("provider"), 591 to arrayOf("version"), 593 to arrayOf("key"), 594 to arrayOf("device"), 595 to arrayOf("kind", "device"), 596 to arrayOf("status"), 597 to arrayOf("kind", "title"), 598 to arrayOf("layer"), 599 to arrayOf("error"), 600 to arrayOf("page"), 601 to arrayOf("page", "kind", "total"), 602 to arrayOf("reason"), 603 to arrayOf("tag"), 604 to arrayOf("tag"), 605 to arrayOf("title"), 606 to arrayOf("title"), 607 to arrayOf("text", "time"), 608 to arrayOf("kind", "device"), 609 to arrayOf("device"), 610 to arrayOf("device"), 611 to arrayOf("word"), 612 to arrayOf("word", "kind", "count"), 613 to arrayOf("error"), 614 to arrayOf("count"), 615 to arrayOf("time", "relative", "rel", "zoned", "zone"), 616 to arrayOf("zone"), 617 to arrayOf("zone"), 618 to arrayOf("id", "state", "count", "age"), 619 to arrayOf("id"), 620 to arrayOf("name"), 621 to arrayOf("name"), 622 to arrayOf("clock", "count", "plural"), 623 to arrayOf("name"), 624 to arrayOf("name"), 625 to arrayOf("name"), 626 to arrayOf("count"), 627 to arrayOf("count"), 631 to arrayOf("name", "state"), 632 to arrayOf("author", "place", "state"), 633 to arrayOf("title", "state"), 648 to arrayOf("error"), 649 to arrayOf("error"), 650 to arrayOf("host"), 655 to arrayOf("email"), 658 to arrayOf("version"), 660 to arrayOf("first", "last", "count"), 661 to arrayOf("n"), 662 to arrayOf("n"), 691 to arrayOf("ref"), 696 to arrayOf("name"), 697 to arrayOf("name"), 699 to arrayOf("name"), 700 to arrayOf("name"), 701 to arrayOf("action"), 702 to arrayOf("label"), 703 to arrayOf("count", "plural"), 705 to arrayOf("path"), 706 to arrayOf("word", "kind", "count"), 707 to arrayOf("name"), 708 to arrayOf("name"), 709 to arrayOf("name"), 710 to arrayOf("name"), 711 to arrayOf("url"), 712 to arrayOf("count"), 713 to arrayOf("count"), 714 to arrayOf("device"), 715 to arrayOf("device"), 716 to arrayOf("count"), 717 to arrayOf("label"), 718 to arrayOf("label"), 719 to arrayOf("label"), 720 to arrayOf("title"), 721 to arrayOf("title"), 722 to arrayOf("state"), 723 to arrayOf("open", "kind"), 725 to arrayOf("count"), 726 to arrayOf("email"), 727 to arrayOf("email"), 851 to arrayOf("at", "count"), 855 to arrayOf("name"), 856 to arrayOf("name"), 905 to arrayOf("name"), 906 to arrayOf("name"), 977 to arrayOf("count"), 980 to arrayOf("name"), 981 to arrayOf("name", "count"), 982 to arrayOf("label", "n"), 983 to arrayOf("action"), 984 to arrayOf("count", "plural"), 985 to arrayOf("count"), 986 to arrayOf("waiting", "busy", "done"), 990 to arrayOf("count", "plural"), 1023 to arrayOf("name"), 1024 to arrayOf("name"), 1026 to arrayOf("seconds", "long"), 1027 to arrayOf("size", "triangles", "delayed", "waited", "built"), 1028 to arrayOf("size", "delayed", "waited"), 1044 to arrayOf("name"), 1047 to arrayOf("name"), 1048 to arrayOf("count"), 1075 to arrayOf("state"), 1076 to arrayOf("bytes"), 1077 to arrayOf("count"), 1078 to arrayOf("when"), 1079 to arrayOf("state", "name"), 1080 to arrayOf("name", "state"), 1081 to arrayOf("reason", "code"), 1084 to arrayOf("kind", "code"), 1085 to arrayOf("number"), 1089 to arrayOf("x", "y"), 1096 to arrayOf("state"), 1097 to arrayOf("label", "example"), 1109 to arrayOf("text"), 1117 to arrayOf("error"), 1118 to arrayOf("kind", "count"), 1121 to arrayOf("name"), 1122 to arrayOf("n"), 1147 to arrayOf("ago"), 1148 to arrayOf("name"), 1149 to arrayOf("kind", "place", "hub"), 1159 to arrayOf("label"), 1160 to arrayOf("word"), 1161 to arrayOf("count"), 1164 to arrayOf("hub"), 1166 to arrayOf("count"), 1167 to arrayOf("state"), 1168 to arrayOf("label"), 1169 to arrayOf("label"), 1174 to arrayOf("state", "text"), 1175 to arrayOf("text"), 1177 to arrayOf("question"), 1179 to arrayOf("label"), 1183 to arrayOf("title"), 1204 to arrayOf("count"), 1205 to arrayOf("name", "counts"), 1219 to arrayOf("n"), 1221 to arrayOf("mode"), 1238 to arrayOf("first", "last", "total"), 1239 to arrayOf("count"), 1242 to arrayOf("n"), 1243 to arrayOf("who", "name"), 1251 to arrayOf("name"), 1252 to arrayOf("when"), 1259 to arrayOf("why"), 1276 to arrayOf("name"), 1283 to arrayOf("kind"), 1284 to arrayOf("title"), 1285 to arrayOf("title"), 1286 to arrayOf("title"), 1287 to arrayOf("title"), 1292 to arrayOf("name"), 1302 to arrayOf("heard"), 1303 to arrayOf("out", "heard"), 1304 to arrayOf("heard"), 1312 to arrayOf("name", "mb"), 1314 to arrayOf("name"), 1317 to arrayOf("platform"), 1321 to arrayOf("heard", "out", "yes"), 1331 to arrayOf("name", "done", "total", "percent"), 1332 to arrayOf("name", "done"), 1333 to arrayOf("name"), 1334 to arrayOf("error"), 1336 to arrayOf("mb"), 1342 to arrayOf("mb"), 1345 to arrayOf("n"), 1346 to arrayOf("n"), 1349 to arrayOf("n"), 1350 to arrayOf("pct"), 1351 to arrayOf("px"), 1352 to arrayOf("version"), 1353 to arrayOf("tag"), 1354 to arrayOf("tag"), 1355 to arrayOf("hub"), 1359 to arrayOf("tag"), 1360 to arrayOf("tag"), 1367 to arrayOf("when"), 1369 to arrayOf("tag"), 1370 to arrayOf("tag", "when"), 1371 to arrayOf("tag"), 1372 to arrayOf("tag", "when"), 1376 to arrayOf("channel"), 1377 to arrayOf("tag"), 1378 to arrayOf("app", "hub"), 1379 to arrayOf("hub", "app"), 1381 to arrayOf("key"), 1382 to arrayOf("key"), 1383 to arrayOf("why"), 1437 to arrayOf("n"), 1470 to arrayOf("title"), 1471 to arrayOf("note"), 1491 to arrayOf("title"), 1492 to arrayOf("more"), 1506 to arrayOf("bots"), 1517 to arrayOf("name"), 1518 to arrayOf("name", "time"), 1519 to arrayOf("name", "n"), 1520 to arrayOf("name", "time", "n"), 1521 to arrayOf("to"), 1522 to arrayOf("to", "step"), 1524 to arrayOf("note"), 1567 to arrayOf("why"), 1572 to arrayOf("e"), 1578 to arrayOf("max"), 1579 to arrayOf("secs", "max", "mib"), 1588 to arrayOf("path"), 1621 to arrayOf("secs"), 1644 to arrayOf("pct", "scope"), 1652 to arrayOf("n"), 1653 to arrayOf("n"), 1654 to arrayOf("n"), 1655 to arrayOf("n"), 1683 to arrayOf("d", "h"), 1684 to arrayOf("h", "m"), 1685 to arrayOf("m"), 1686 to arrayOf("window", "pct"), 1688 to arrayOf("when"), 1690 to arrayOf("label", "e"), 1692 to arrayOf("from", "to", "total"), 1696 to arrayOf("messages", "lines", "left"), 1698 to arrayOf("pct", "view", "max"), 1699 to arrayOf("pct"), 1700 to arrayOf("done", "total"), 1702 to arrayOf("n"), 1703 to arrayOf("n"), 1704 to arrayOf("time"), 1705 to arrayOf("view", "max"), 1706 to arrayOf("view", "max"), 1708 to arrayOf("more"), 1712 to arrayOf("n"), 1721 to arrayOf("n"), 1727 to arrayOf("page"), 1738 to arrayOf("title"), 1741 to arrayOf("n"), 1758 to arrayOf("name"), 1823 to arrayOf("line"), 1824 to arrayOf("quote"), 1825 to arrayOf("n"), 1826 to arrayOf("n"), 1827 to arrayOf("n"), 1828 to arrayOf("n"), 1829 to arrayOf("n"), 1834 to arrayOf("held"), 1835 to arrayOf("machine"), 1836 to arrayOf("machine"), 1844 to arrayOf("count", "total"), 1845 to arrayOf("count"), 1846 to arrayOf("n"), 1858 to arrayOf("name"), 1860 to arrayOf("n", "c", "total"), 1861 to arrayOf("n", "c"), 1862 to arrayOf("n", "c", "total", "before"), 1863 to arrayOf("n", "c", "before"), 1875 to arrayOf("name"), 1876 to arrayOf("path"), 1879 to arrayOf("file"), 1880 to arrayOf("path", "n"), 1881 to arrayOf("why"), 1882 to arrayOf("n"), 1883 to arrayOf("name"), 1884 to arrayOf("name"), 1885 to arrayOf("name"), 1886 to arrayOf("n"), 1887 to arrayOf("shown", "n"), 1890 to arrayOf("path"), 1892 to arrayOf("n"), 1901 to arrayOf("status"), 1918 to arrayOf("name", "pct"), 1919 to arrayOf("name", "mb"), 1920 to arrayOf("name"), 1921 to arrayOf("name", "why"), 1939 to arrayOf("machine"), 1942 to arrayOf("n"), 1943 to arrayOf("ref"), 1944 to arrayOf("ref", "sheet"), 1945 to arrayOf("name"), 1946 to arrayOf("name"), 1947 to arrayOf("file", "folder"), 1948 to arrayOf("name", "error"), 1949 to arrayOf("name", "status"), 1950 to arrayOf("name", "error"), 1952 to arrayOf("name"), 1955 to arrayOf("code"), 1956 to arrayOf("error"), 1959 to arrayOf("error"), 1960 to arrayOf("error"), 1964 to arrayOf("error"), 1982 to arrayOf("done", "of"), 1984 to arrayOf("why"), 1985 to arrayOf("path"), 1986 to arrayOf("error"), 1987 to arrayOf("secs"), 1988 to arrayOf("secs"), 2000 to arrayOf("code"), 2001 to arrayOf("code"), 2004 to arrayOf("state"), 2009 to arrayOf("hide", "copy", "paste"), 2010 to arrayOf("n"), 2013 to arrayOf("name"), 2014 to arrayOf("name", "folder"), 2015 to arrayOf("name"), 2016 to arrayOf("name", "percent"), 2022 to arrayOf("folder"), 2032 to arrayOf("w", "h"), 2036 to arrayOf("path"), 2039 to arrayOf("why"), 2040 to arrayOf("mb"), 2043 to arrayOf("n"), 2044 to arrayOf("delete", "undo"), 2045 to arrayOf("delete", "undo"), 2046 to arrayOf("undo"), 2067 to arrayOf("what", "secs"), 2068 to arrayOf("file", "holder"), 2075 to arrayOf("what"), 2076 to arrayOf("what"), 2077 to arrayOf("editor", "why"), 2096 to arrayOf("files"), 2106 to arrayOf("why"), 2108 to arrayOf("title"), 2109 to arrayOf("title"), 2110 to arrayOf("version"), 2111 to arrayOf("version", "size", "folder"), 2112 to arrayOf("version", "size", "folder"), 2121 to arrayOf("title"), 2122 to arrayOf("dir", "files"), 2128 to arrayOf("why"), 2130 to arrayOf("code"), 2144 to arrayOf("origin"), 2146 to arrayOf("why"), 2157 to arrayOf("dir"), 2158 to arrayOf("path"), 2159 to arrayOf("home", "other"), 2161 to arrayOf("path"), 2162 to arrayOf("code", "log"), 2163 to arrayOf("log"), 2165 to arrayOf("addr"), 2178 to arrayOf("home"), 2179 to arrayOf("addr"), 2194 to arrayOf("dir", "why"), 2195 to arrayOf("dir"), 2210 to arrayOf("phase"), 2212 to arrayOf("why"), 2213 to arrayOf("what"), 2214 to arrayOf("code"), 2220 to arrayOf("label"), 2225 to arrayOf("kind"), 2227 to arrayOf("project"), 2240 to arrayOf("what"), 2242 to arrayOf("when"), 2246 to arrayOf("n"), 2247 to arrayOf("n"), 2248 to arrayOf("n"), 2250 to arrayOf("agent"), 2251 to arrayOf("effort"), 2253 to arrayOf("n"), 2255 to arrayOf("model"), 2267 to arrayOf("word"), 2274 to arrayOf("more", "step"), 2278 to arrayOf("name"), 2282 to arrayOf("max", "skipped"), 2285 to arrayOf("name"), 2286 to arrayOf("n"), 2287 to arrayOf("name"), 2288 to arrayOf("name"), 2294 to arrayOf("n"), 2295 to arrayOf("name"), 2297 to arrayOf("price"), 2300 to arrayOf("name"), 2302 to arrayOf("name"), 2303 to arrayOf("name"), 2304 to arrayOf("name"), 2305 to arrayOf("text"), 2308 to arrayOf("key"), 2309 to arrayOf("key"), 2310 to arrayOf("pct"), 2311 to arrayOf("when"), 2322 to arrayOf("n", "upstream"), 2325 to arrayOf("mb"), 2335 to arrayOf("path"), 2336 to arrayOf("path"), 2358 to arrayOf("id"), 2362 to arrayOf("model"), 2363 to arrayOf("platform"), 2364 to arrayOf("version"), 2367 to arrayOf("version", "from", "into"), 2368 to arrayOf("version", "from"), 2371 to arrayOf("version", "path"), 2372 to arrayOf("version", "path"), 2373 to arrayOf("version", "pin", "from"), 2374 to arrayOf("path"), 2375 to arrayOf("version", "path"), 2376 to arrayOf("version", "path", "set"), 2390 to arrayOf("turns", "input", "cread", "cwrite", "output", "cost"), 2397 to arrayOf("tool"), 2398 to arrayOf("tool"), 2399 to arrayOf("tool", "word"), 2400 to arrayOf("tool", "word"), 2401 to arrayOf("tool"), 2402 to arrayOf("tool"), 2403 to arrayOf("due"), 2404 to arrayOf("due"), 2405 to arrayOf("due"), 2406 to arrayOf("due"), 2407 to arrayOf("zone"), 2408 to arrayOf("zone"), 2409 to arrayOf("zone"), 2410 to arrayOf("zone"), 2411 to arrayOf("n"), 2412 to arrayOf("who"), 2413 to arrayOf("n", "who"), 2414 to arrayOf("harness"), 2415 to arrayOf("path"), 2416 to arrayOf("path"), 2417 to arrayOf("path"), 2420 to arrayOf("error", "line"), 2421 to arrayOf("label"), 2429 to arrayOf("who"), 2430 to arrayOf("who"), 2431 to arrayOf("label", "left", "when"), 2432 to arrayOf("left"), 2433 to arrayOf("name", "left"), 2434 to arrayOf("used"), 2435 to arrayOf("used", "limit"), 2436 to arrayOf("used", "reason"), 2437 to arrayOf("used", "limit", "reason"), 2439 to arrayOf("provider"), 2440 to arrayOf("used", "window", "pct"), 2441 to arrayOf("rate"), 2451 to arrayOf("n", "r"), 2456 to arrayOf("time", "n"), 2460 to arrayOf("n", "m"), 2462 to arrayOf("pct"), 2463 to arrayOf("cost", "n"), 2467 to arrayOf("in", "out", "cread", "cwrite"), 2468 to arrayOf("in", "out", "cread", "cwrite", "n"), 2477 to arrayOf("turns", "input", "cread", "cwrite", "output"), 2478 to arrayOf("left", "when"), 2479 to arrayOf("left", "when"), 2480 to arrayOf("left", "when"), 2481 to arrayOf("left", "when"), 2505 to arrayOf("n"), 2528 to arrayOf("when"), 2535 to arrayOf("phrase", "now"), 2546 to arrayOf("s"), 2552 to arrayOf("now"), 2553 to arrayOf("now", "nudge", "sent", "undone"), 2563 to arrayOf("e"), 2564 to arrayOf("a", "ams", "b", "bms"), 2565 to arrayOf("ms"), 2566 to arrayOf("e"), 2567 to arrayOf("t"), 2568 to arrayOf("t"), 2569 to arrayOf("t"), 2575 to arrayOf("why"), 2585 to arrayOf("apps"), 2595 to arrayOf("n"), 2596 to arrayOf("n", "k"), 2601 to arrayOf("stt", "conf"), 2602 to arrayOf("words"), 2612 to arrayOf("into"), 2615 to arrayOf("origin"), 2627 to arrayOf("url"), 2629 to arrayOf("url"), 2637 to arrayOf("i", "n"), 2638 to arrayOf("d", "n"), 2647 to arrayOf("version"), 2648 to arrayOf("version"), 2649 to arrayOf("version"), 2652 to arrayOf("path"), 2660 to arrayOf("addr"), 2664 to arrayOf("label"), 2666 to arrayOf("label"), 2667 to arrayOf("label"), 2671 to arrayOf("label"), 2676 to arrayOf("from"), 2693 to arrayOf("done", "of"), 2699 to arrayOf("n"), 2700 to arrayOf("t", "m"), 2701 to arrayOf("m"), 2702 to arrayOf("b", "m"), 2703 to arrayOf("r", "p"), 2704 to arrayOf("n"), 2705 to arrayOf("n"), 2706 to arrayOf("n"), 2707 to arrayOf("n"), 2710 to arrayOf("n"), 2712 to arrayOf("n"), 2720 to arrayOf("n"), 2726 to arrayOf("name", "gb", "path"), 2728 to arrayOf("path", "why"), 2730 to arrayOf("names"), 2732 to arrayOf("why"), 2733 to arrayOf("p", "pn", "t", "tn", "e", "en"), 2734 to arrayOf("done", "total"), 2735 to arrayOf("n"), 2736 to arrayOf("what"), 2737 to arrayOf("n"), 2738 to arrayOf("n"), 2741 to arrayOf("what"), 2742 to arrayOf("n"), 2744 to arrayOf("why", "from"), 2745 to arrayOf("why"), 2751 to arrayOf("path"), 2752 to arrayOf("path", "who"), 2753 to arrayOf("path"), 2754 to arrayOf("path", "cmd"), 2755 to arrayOf("version", "path"), 2756 to arrayOf("version", "path"), 2757 to arrayOf("version", "path", "who"), 2758 to arrayOf("version", "path"), 2759 to arrayOf("version", "path", "cmd"), 2762 to arrayOf("cmd"), 2772 to arrayOf("name", "version", "path"), 2773 to arrayOf("path", "why"), 2774 to arrayOf("name"), 2776 to arrayOf("version", "cli"), 2777 to arrayOf("cli"), 2779 to arrayOf("version"), 2780 to arrayOf("version"), 2782 to arrayOf("version"), 2784 to arrayOf("version"), 2786 to arrayOf("computer"), 2787 to arrayOf("version", "cli"), 2788 to arrayOf("cli"), 2789 to arrayOf("version", "cli"), 2790 to arrayOf("cli"), 2812 to arrayOf("n"), 2817 to arrayOf("code"), 2819 to arrayOf("e"), 2832 to arrayOf("n"), 2837 to arrayOf("channel"), 2851 to arrayOf("project"), 2857 to arrayOf("n"), 2869 to arrayOf("m"), 2881 to arrayOf("m"), 2884 to arrayOf("m"), 2891 to arrayOf("pages"), 2893 to arrayOf("name"), 2896 to arrayOf("name"), 2905 to arrayOf("d", "n"), 2926 to arrayOf("n", "tools"), 2927 to arrayOf("n", "tools", "d"), 2928 to arrayOf("n", "d"), 2929 to arrayOf("n", "what"), 2930 to arrayOf("n", "d", "what"), 2934 to arrayOf("head"), 2940 to arrayOf("name", "path"), 2946 to arrayOf("page", "net", "near"), 2947 to arrayOf("page", "what"), 2948 to arrayOf("ref"), 2952 to arrayOf("page"), 2975 to arrayOf("n"), 2976 to arrayOf("n"), 2977 to arrayOf("n"), 2979 to arrayOf("hub"), 3001 to arrayOf("project"), 3003 to arrayOf("n"), 3004 to arrayOf("n"), 3005 to arrayOf("word"), 3006 to arrayOf("n"), 3024 to arrayOf("name"), 3032 to arrayOf("answer"), 3037 to arrayOf("why"), 3039 to arrayOf("hub"), 3045 to arrayOf("from", "to"), 3052 to arrayOf("project"), 3062 to arrayOf("name"), 3066 to arrayOf("n"), 3072 to arrayOf("code"), 3073 to arrayOf("hub"), 3074 to arrayOf("hub"), 3075 to arrayOf("hub"), 3089 to arrayOf("n"), 3090 to arrayOf("n"), 3106 to arrayOf("status"), 3108 to arrayOf("status"), 3137 to arrayOf("project"), 3141 to arrayOf("code"), 3143 to arrayOf("why"), 3151 to arrayOf("title"), 3157 to arrayOf("title"), 3159 to arrayOf("q"), 3160 to arrayOf("title"), 3165 to arrayOf("room"), 3169 to arrayOf("q"), 3179 to arrayOf("title"), 3184 to arrayOf("n"), 3185 to arrayOf("n"), 3190 to arrayOf("at"), 3198 to arrayOf("size"), 3200 to arrayOf("n", "total"), 3217 to arrayOf("n"), 3218 to arrayOf("what"), 3221 to arrayOf("device"), 3222 to arrayOf("device"), 3231 to arrayOf("word", "count"), 3232 to arrayOf("heard"), 3244 to arrayOf("files"), 3245 to arrayOf("files"), 3248 to arrayOf("name"), 3276 to arrayOf("n"), 3277 to arrayOf("n"), 3288 to arrayOf("n"), 3322 to arrayOf("root"), 3323 to arrayOf("path"), 3346 to arrayOf("name"), 3349 to arrayOf("until"), 3350 to arrayOf("error"), 3357 to arrayOf("url"), 3361 to arrayOf("name"), 3362 to arrayOf("name"), 3370 to arrayOf("code", "hub", "until"), 3371 to arrayOf("url"), 3375 to arrayOf("kinds"), 3376 to arrayOf("address"), 3378 to arrayOf("address"), 3381 to arrayOf("url"), 3382 to arrayOf("url"), 3383 to arrayOf("url"), 3384 to arrayOf("url", "via"), 3389 to arrayOf("name"), 3390 to arrayOf("url", "check", "left"), 3392 to arrayOf("check"), 3393 to arrayOf("address"), 3394 to arrayOf("name"), 3395 to arrayOf("error"), 3396 to arrayOf("url"), 3397 to arrayOf("url"), 3404 to arrayOf("code", "address", "left"), 3410 to arrayOf("name"), 3411 to arrayOf("name"), 3422 to arrayOf("address"), 3429 to arrayOf("code", "body"), 3432 to arrayOf("code", "body"), 3438 to arrayOf("window", "used"), 3439 to arrayOf("window", "used", "when"), 3440 to arrayOf("window", "used"), 3441 to arrayOf("window", "used", "when"), 3442 to arrayOf("provider"), 3454 to arrayOf("label"), 3455 to arrayOf("when"), 3457 to arrayOf("provider"), 3458 to arrayOf("provider", "title", "why"), 3478 to arrayOf("reason"), 3486 to arrayOf("code"), 3495 to arrayOf("name"), 3498 to arrayOf("version"), 3499 to arrayOf("version"), 3500 to arrayOf("version"), 3502 to arrayOf("version"), 3503 to arrayOf("version"), 3504 to arrayOf("version"), 3505 to arrayOf("version", "why"), 3506 to arrayOf("version"), 3508 to arrayOf("code"), 3524 to arrayOf("name"), 3531 to arrayOf("count"), 3532 to arrayOf("title"), 3533 to arrayOf("name"), 3536 to arrayOf("n", "holder"), 3537 to arrayOf("n", "title"), 3538 to arrayOf("title"), 3541 to arrayOf("n"), 3542 to arrayOf("n"), 3543 to arrayOf("n"), 3544 to arrayOf("n"), 3545 to arrayOf("harness", "typed", "type", "remote", "host", "wt", "branch"), 3555 to arrayOf("pid"), 3560 to arrayOf("left"), 3561 to arrayOf("left"), 3567 to arrayOf("left"), 3568 to arrayOf("left"), 3569 to arrayOf("left"), 3570 to arrayOf("left"), 3571 to arrayOf("label", "left"), 3572 to arrayOf("when"), 3573 to arrayOf("used"), 3574 to arrayOf("used", "limit"), 3596 to arrayOf("tracking"), 3600 to arrayOf("total"), 3601 to arrayOf("price"), 3602 to arrayOf("price"), 3607 to arrayOf("n"), 3608 to arrayOf("parts"), 3609 to arrayOf("note"), 3610 to arrayOf("error"), 3611 to arrayOf("error", "parts"), 3616 to arrayOf("state"), 3617 to arrayOf("name", "path"), 3618 to arrayOf("name", "path", "why"), 3620 to arrayOf("code"), 3624 to arrayOf("detail"), 3626 to arrayOf("why"), 3627 to arrayOf("parts"), 3630 to arrayOf("build", "to"), 3631 to arrayOf("build"), 3632 to arrayOf("build", "skip"), 3634 to arrayOf("why"), 3635 to arrayOf("why"), 3636 to arrayOf("build"), 3637 to arrayOf("build", "why"), 3638 to arrayOf("build"), 3639 to arrayOf("build"), 3643 to arrayOf("build"), 3644 to arrayOf("build"), 3646 to arrayOf("build"), 3653 to arrayOf("build"), 3687 to arrayOf("step"), 3688 to arrayOf("p", "pt", "t", "tt", "e", "et"), 3689 to arrayOf("done", "total"), 3690 to arrayOf("n"), 3691 to arrayOf("n"), 3692 to arrayOf("n"), 3697 to arrayOf("n"), 3700 to arrayOf("why"), 3701 to arrayOf("why", "from"), 3702 to arrayOf("error"), 3704 to arrayOf("n"), 3705 to arrayOf("n"), 3709 to arrayOf("n"), 3712 to arrayOf("name", "gb", "path"), 3713 to arrayOf("path", "why"), 3714 to arrayOf("names"), 3716 to arrayOf("why"), 3727 to arrayOf("n", "total"), 3731 to arrayOf("title"), 3733 to arrayOf("n"), 3737 to arrayOf("name"), 3738 to arrayOf("title"), 3739 to arrayOf("note"), 3741 to arrayOf("machine"), 3742 to arrayOf("machines"), 3743 to arrayOf("machine"), 3754 to arrayOf("n"), 3756 to arrayOf("n"), 3760 to arrayOf("name"), 3763 to arrayOf("name"), 3780 to arrayOf("why"), 3786 to arrayOf("project"), 3827 to arrayOf("path"), 3828 to arrayOf("path"), 3830 to arrayOf("have", "total"), 3835 to arrayOf("n"), 3844 to arrayOf("hub"), 3847 to arrayOf("title"), 3851 to arrayOf("project"), 3852 to arrayOf("project"), 3853 to arrayOf("n"), 3854 to arrayOf("hub"), 3856 to arrayOf("n"), 3857 to arrayOf("n"), 3858 to arrayOf("model"), 3864 to arrayOf("name"), 3883 to arrayOf("word"), 3889 to arrayOf("answer"), 3899 to arrayOf("version", "build"), 3900 to arrayOf("hub"), 3905 to arrayOf("name"), 3908 to arrayOf("when", "who", "mark"), 3912 to arrayOf("who"), 3916 to arrayOf("time"), 3917 to arrayOf("address"), 3919 to arrayOf("kind", "name"), 3934 to arrayOf("title"), 3935 to arrayOf("query"), 3938 to arrayOf("room"), 3939 to arrayOf("query"), 3941 to arrayOf("n"), 3942 to arrayOf("n"), 3943 to arrayOf("n"), 3949 to arrayOf("size"), 3953 to arrayOf("n"), 3954 to arrayOf("n"), 3955 to arrayOf("n"), 3969 to arrayOf("status"), 3971 to arrayOf("status"), 4122 to arrayOf("code"), 4124 to arrayOf("n"), 4126 to arrayOf("why"), 4138 to arrayOf("done", "of"), 4142 to arrayOf("thread"), 4145 to arrayOf("n"), 4153 to arrayOf("title"), 4154 to arrayOf("note"), 4155 to arrayOf("label"), 4156 to arrayOf("machine"), 4157 to arrayOf("machine"), 4164 to arrayOf("at", "total"), 4165 to arrayOf("at", "total"), 4169 to arrayOf("machine"), 4170 to arrayOf("machine"), 4171 to arrayOf("machines"), 4173 to arrayOf("device"), 4180 to arrayOf("price"), 4181 to arrayOf("price"), 4188 to arrayOf("home"), 4193 to arrayOf("from"), 4195 to arrayOf("note"), 4196 to arrayOf("note"), 4198 to arrayOf("v"), 4199 to arrayOf("v"), 4200 to arrayOf("v", "who"), 4202 to arrayOf("who"), 4203 to arrayOf("v"), 4205 to arrayOf("v", "cmd"), 4206 to arrayOf("cmd"), 4211 to arrayOf("v", "path"), 4212 to arrayOf("v", "note"), 4213 to arrayOf("v"), 4218 to arrayOf("tool"), 4219 to arrayOf("tool"), 4244 to arrayOf("n", "w"), 4245 to arrayOf("why"), 4246 to arrayOf("state", "why"), 4258 to arrayOf("project"), 4259 to arrayOf("n"), 4270 to arrayOf("why"), 4276 to arrayOf("name"), 4287 to arrayOf("project"), 4292 to arrayOf("n"), 4300 to arrayOf("names"), 4308 to arrayOf("dest"), 4310 to arrayOf("repo"), 4311 to arrayOf("repo"), 4313 to arrayOf("url"), 4337 to arrayOf("group"), 4341 to arrayOf("project"), 4342 to arrayOf("n"), 4343 to arrayOf("n"), 4344 to arrayOf("n"), 4352 to arrayOf("n"), 4409 to arrayOf("n"), 4410 to arrayOf("n"), 4411 to arrayOf("a", "b"), 4412 to arrayOf("n"), 4414 to arrayOf("parts", "lines"), 4415 to arrayOf("n"), 4446 to arrayOf("what", "project", "fab"), 4447 to arrayOf("rev", "day"), 4455 to arrayOf("n"), 4466 to arrayOf("layer"), 4467 to arrayOf("n"), 4472 to arrayOf("board"), 4484 to arrayOf("others"), 4485 to arrayOf("must", "should", "notes"), 4486 to arrayOf("id", "w"), 4496 to arrayOf("what"), 4499 to arrayOf("why"), 4500 to arrayOf("why"), 4507 to arrayOf("n"), 4523 to arrayOf("price", "n"), 4524 to arrayOf("n", "need"), 4525 to arrayOf("n"), 4526 to arrayOf("n"), 4527 to arrayOf("cost"), 4528 to arrayOf("cost"), 4541 to arrayOf("day", "n"), 4542 to arrayOf("day"), 4543 to arrayOf("cost", "n", "lines"), 4544 to arrayOf("stock", "price"), 4545 to arrayOf("lines"), 4566 to arrayOf("host"), 4577 to arrayOf("n"), 4578 to arrayOf("a", "b"), 4579 to arrayOf("n"), 4580 to arrayOf("n"), 4583 to arrayOf("day"), 4584 to arrayOf("n"), 4625 to arrayOf("turn"), 4739 to arrayOf("text"), 4742 to arrayOf("repo", "dest"), 4743 to arrayOf("repo", "dest"), 4744 to arrayOf("repo"), 4749 to arrayOf("dir"), 4750 to arrayOf("dir"), 4754 to arrayOf("editor", "job", "secs"), 4755 to arrayOf("editor", "secs"), 4756 to arrayOf("editor"), 4773 to arrayOf("time"), 4779 to arrayOf("status"), 4787 to arrayOf("time"), 4788 to arrayOf("time", "dur"), 4791 to arrayOf("answer"), 4795 to arrayOf("type"), 4796 to arrayOf("max"), 4824 to arrayOf("bytes", "tokens"), 4857 to arrayOf("what"), 4861 to arrayOf("n"), 4863 to arrayOf("n"), 4887 to arrayOf("n"), 4888 to arrayOf("done", "total"), 4896 to arrayOf("v"), 4897 to arrayOf("x", "y"), 4903 to arrayOf("machine")) } val common_cancel: String get() = Tr.s(0) val common_delete: String get() = Tr.s(1) @@ -28089,6 +28093,7 @@ object Msg { val provider_notice_text_signedout: String get() = Tr.s(4900) val provider_notice_button: String get() = Tr.s(4901) val provider_notice_senderr: String get() = Tr.s(4902) - val web_settings_providers: String get() = Tr.s(4903) - val web_settings_providers_browser: String get() = Tr.s(4904) + fun provider_notice_senderr_remote(machine: Any): String = Tr.f(4903, arrayOf(machine)) + val web_settings_providers: String get() = Tr.s(4904) + val web_settings_providers_browser: String get() = Tr.s(4905) } diff --git a/mobile/ios/Backplane/DataClient.swift b/mobile/ios/Backplane/DataClient.swift index e52c962b68..ae89328843 100644 --- a/mobile/ios/Backplane/DataClient.swift +++ b/mobile/ios/Backplane/DataClient.swift @@ -1267,7 +1267,7 @@ final class DataClient { } // MARK: the composer's own commands (feature commands): the hub runs them, the draft stays until it said yes - struct CommandResult: Decodable { let kind: String; var q: String?; var name: String?; var text: String?; var thread: String?; var path: String?; var error: String?; var note: String?; var repo: String? } + struct CommandResult: Decodable { let kind: String; var q: String?; var a: String?; var name: String?; var text: String?; var thread: String?; var path: String?; var error: String?; var note: String?; var repo: String? } private struct SecretAsks: Decodable { let asks: [SecretAsk] } /// The command this draft is, by the hub's own rule (session/composer.rs command_is): the word alone, or followed by a space or a new line. func commandOf(_ draft: String) -> Word? { @@ -1282,7 +1282,7 @@ final class DataClient { func runCommand(_ tid: String, _ text: String) async throws -> CommandResult { // `exists`: this app offers Add existing on a folder /project found not empty (the answer's kind "exists") let r: CommandResult = try await call("composer.run", ["thread": tid, "text": text, "exists": true]) - if r.kind == "btw" { btw[tid] = Btw(q: r.q ?? "", a: "Thinking…") } + if r.kind == "btw" { btw[tid] = Btw(q: r.q ?? "", a: (r.a?.isEmpty == false ? r.a! : "Thinking…")) } return r } func closeBtw(_ tid: String) { btw[tid] = nil } diff --git a/mobile/ios/Backplane/DataModels.swift b/mobile/ios/Backplane/DataModels.swift index 226b333955..1e1af202b2 100644 --- a/mobile/ios/Backplane/DataModels.swift +++ b/mobile/ios/Backplane/DataModels.swift @@ -680,5 +680,5 @@ struct DNoProvider: Equatable { url: o["url"] as? String ?? "backplane://settings/accounts" ) } - static func isSendError(_ msg: String) -> Bool { msg.contains("No AI provider connected") } + static func isSendError(_ msg: String) -> Bool { msg.hasPrefix("No AI provider connected yet.") } } diff --git a/mobile/ios/Shared/TrCatalog.swift b/mobile/ios/Shared/TrCatalog.swift index 5c4ed34ccd..ace6ffb390 100644 --- a/mobile/ios/Shared/TrCatalog.swift +++ b/mobile/ios/Shared/TrCatalog.swift @@ -4906,6 +4906,7 @@ provider.notice.text.none Connect Claude, Codex, Antigravity, or another provide provider.notice.text.signedout Sign in to Claude, Codex, or another provider in Settings → Accounts to start chatting. チャットを始めるには、設定 → アカウントで Claude、Codex などのプロバイダーにサインインしてください。 Inicia sesión en Claude, Codex u otro proveedor en Configuración → Cuentas para empezar a chatear. provider.notice.button Open Settings → Accounts 設定 → アカウントを開く Abrir Configuración → Cuentas provider.notice.senderr No AI provider connected yet. Open Settings → Accounts to connect Claude, Codex, Antigravity, or another provider. AI プロバイダーがまだ接続されていません。設定 → アカウントを開いて、Claude、Codex、Antigravity などのプロバイダーを接続してください。 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 AI provider connected on {machine}. Open Settings → Accounts on {machine} to connect Claude, Codex, Antigravity, or another provider. {machine} に AI プロバイダーが接続されていません。{machine} で設定 → アカウントを開いて、Claude、Codex、Antigravity などのプロバイダーを接続してください。 No hay ningún proveedor de IA conectado en {machine}. Abre Configuración → Cuentas en {machine} para conectar Claude, Codex, Antigravity u otro proveedor. web.settings.providers AI providers AI プロバイダー Proveedores de IA web.settings.providers.browser Connect a provider in the Backplane desktop or mobile app under Settings → Accounts. Backplane のデスクトップまたはモバイルアプリの設定 → アカウントからプロバイダーを接続してください。 Conecta un proveedor en la aplicación de escritorio o móvil de Backplane en Configuración → Cuentas. """# @@ -7885,4 +7886,7 @@ web.settings.providers.browser Connect a provider in the Backplane desktop or mo /// mobile.plan.coord = ({x}, {y} mm) static func mobile_plan_coord(x: String, y: String) -> String { f("mobile.plan.coord", ["x": x, "y": y]) } + + /// provider.notice.senderr.remote = No AI provider connected on {machine}. Open Settings → Accounts on {machine} to connect Claude, Codex, Antigravity, or another provider. + static func provider_notice_senderr_remote(machine: String) -> String { f("provider.notice.senderr.remote", ["machine": machine]) } } diff --git a/native/gpui/src/screens/provider_notice.rs b/native/gpui/src/screens/provider_notice.rs index 3ba140a411..17a043ddac 100644 --- a/native/gpui/src/screens/provider_notice.rs +++ b/native/gpui/src/screens/provider_notice.rs @@ -22,7 +22,7 @@ pub fn parse(v: &Value) -> Option { } pub fn is_send_error(err: &str) -> bool { - err.contains("No AI provider connected") + err.starts_with("No AI provider connected yet.") } pub fn view(cx: &mut Context, light: bool, v: &Value, hidden: bool) -> Option { @@ -82,6 +82,7 @@ mod tests { assert_eq!(parse(&Value::Null), None); assert_eq!(parse(&serde_json::json!({"head": ""})), None); assert!(is_send_error("No AI provider connected yet. Open Settings → Accounts to connect Claude, Codex, Antigravity, or another provider.")); + assert!(!is_send_error("No AI provider connected on boat-hub. Open Settings → Accounts on boat-hub to connect Claude, Codex, Antigravity, or another provider.")); assert!(!is_send_error("Some other error")); let icons: serde_json::Map = serde_json::from_str(include_str!("../../../../assets/icons.json")).unwrap(); assert!(icons.contains_key("plug")); diff --git a/native/host/src/agents/mod.rs b/native/host/src/agents/mod.rs index ec5d600ac2..e3c6e2ea27 100644 --- a/native/host/src/agents/mod.rs +++ b/native/host/src/agents/mod.rs @@ -557,7 +557,7 @@ impl RpcHandler for Rpc { if q.is_empty() { return vec![err(id, crate::session::composer::BTW_EMPTY)] } if who.client > 0 { if let Some(why) = crate::settings::provider_notice::send_guard(hub).await { - return vec![err(id, why)]; + return vec![crate::settings::provider_notice::rpc_error_reply(id, why)]; } } let (ag, th, id2) = (self.0.clone(), th.to_string(), id.clone()); @@ -598,7 +598,13 @@ impl RpcHandler for Rpc { "turn.start" => match crate::net::homemove::intercept(&self.0.hub, th, p).await { Some(r) => r, None => self.0.turn_start(who, th, p).await }, _ => { let r = self.0.interrupt(th).await; if let Some(m) = self.0.mailroom() { m.stopping(th).await } r } }; - match r { Ok(()) => vec![ok(id)], Err(e) => vec![err(id, &e)] } + match r { + Ok(()) => vec![ok(id)], + Err(e) if e == crate::settings::provider_notice::SEND_GUARD_ERROR => { + vec![crate::settings::provider_notice::rpc_error_reply(id, &e)] + } + Err(e) => vec![err(id, &e)], + } }) } } @@ -617,7 +623,7 @@ impl Agents { let attached: Vec = p.get("attachments").filter(|a| a.as_array().map_or(false, |x| !x.is_empty())).map(|a| vec![json!({"$":"MessageAttached","thread":th,"msg":msg,"attachments":a,"at":now_s()})]).unwrap_or_default(); // `/restore [turn]` from the person: the hub puts the project back to before that turn itself, no agent turn (snapguard.rs) if who.client > 0 && !retry { if let Some(n) = snapguard::restore_command(text) { return self.restore_command(th, n).await } } - if who.client > 0 && !retry && (!text.trim().is_empty() || !attached.is_empty()) { + if who.client > 0 && who.gen != "home" && !retry && (!text.trim().is_empty() || !attached.is_empty()) { if let Some(why) = crate::settings::provider_notice::send_guard(&self.hub).await { return Err(why.to_string()); } diff --git a/native/host/src/agents/tests.rs b/native/host/src/agents/tests.rs index 80712071be..881c9eaea2 100644 --- a/native/host/src/agents/tests.rs +++ b/native/host/src/agents/tests.rs @@ -2719,3 +2719,35 @@ impl mailroom::Mailroom for ChatRoom { drop(drv); assert!(!prof_path.exists(), "profile config file removed when turn ends"); } + +#[tokio::test(flavor = "multi_thread")] async fn zero_provider_turn_start_refuses_cleanly_and_homemove_replay_bypasses_guard() { + let sd = dir("np-ag-bin"); + perf_standin(&sd, 1); + let (hub, ag, _h, _w) = start("np-ag", |w| base_log(w, 1, ""), |_| Cli::standin(&sd)).await; + let mut about = serde_json::Map::new(); + for (agent, _) in crate::present::keys::AGENTS { + about.insert((*agent).to_string(), json!({"cli": ""})); + } + let _guard = crate::settings::provider_notice::override_for_test(&hub, true, json!({"probed": true, "about": about})); + let from = len(&hub).await; + + let r = rpc(&hub, "turn.start", json!({"thread": T1, "text": "hello"})).await; + assert_eq!(r["ok"], false, "{r}"); + assert_eq!(r["errorCode"], crate::settings::provider_notice::SEND_GUARD_CODE); + assert_eq!(r["error"], crate::settings::provider_notice::SEND_GUARD_ERROR); + + let btw = rpc(&hub, "thread.btw", json!({"thread": T1, "q": "why?"})).await; + assert_eq!(btw["ok"], false, "{btw}"); + assert_eq!(btw["errorCode"], crate::settings::provider_notice::SEND_GUARD_CODE); + + let ev = log_from(&hub, from).await; + assert!(ev.is_empty(), "refused turn.start and thread.btw must leave zero log events, got {ev:?}"); + + let h_turn = hub.rpc_for("turn.start").unwrap(); + let replay_caller = Caller { gen: "home".into(), client: 1 }; + let rr = h_turn.call(&hub, &replay_caller, &json!(8), "turn.start", &json!({"thread": T1, "text": "replayed prompt", "msg": "hm-replay"})).await; + assert_eq!(rr[0]["ok"], true, "home-move replay must not be blocked by send guard: {:?}", rr); + let posted = until(&hub, from, 10, |ev| ev.iter().any(|e| is(e, "MessagePosted") && e["msg"] == "hm-replay")).await; + assert!(posted.iter().any(|e| is(e, "MessagePosted") && e["msg"] == "hm-replay")); + ag.shutdown(); +} diff --git a/native/host/src/bots/rpc.rs b/native/host/src/bots/rpc.rs index a9977079ef..86495ebf8c 100644 --- a/native/host/src/bots/rpc.rs +++ b/native/host/src/bots/rpc.rs @@ -342,7 +342,7 @@ impl Bots { if star.is_some() && !text.trim().is_empty() { drop(w); if let Some(why) = crate::settings::provider_notice::send_guard(&self.hub).await { - return vec![err(id, why)]; + return vec![crate::settings::provider_notice::rpc_error_reply(id, why)]; } w = self.world().await; if !w.live(bot) { return vec![err(id, "no such bot")] } diff --git a/native/host/src/bots/tests.rs b/native/host/src/bots/tests.rs index e01bce68d0..1b1d2c6361 100644 --- a/native/host/src/bots/tests.rs +++ b/native/host/src/bots/tests.rs @@ -1907,3 +1907,20 @@ async fn three(tag: &str) -> Three { assert_eq!(member_in("cy@mid2", "L10", bot_id, lom).as_deref(), Some("cy@L12")); assert_eq!(member_in("dee@mid7", "L10", bot_id, lom), None, "a machine this one has no link to is dropped"); } + +#[tokio::test] async fn bots_say_refuses_when_no_provider_without_waking_or_posting() { + let (hub, _b, rec) = start("np-say", "").await; + let b = bot(&hub, "ada").await; + let from = log(&hub).len(); + let mut about = serde_json::Map::new(); + for (agent, _) in crate::present::keys::AGENTS { + about.insert((*agent).to_string(), json!({"cli": ""})); + } + let _guard = crate::settings::provider_notice::override_for_test(&hub, true, json!({"probed": true, "about": about})); + let r = rpc(&hub, "bots.say", json!({"bot": b, "text": "hello"})).await; + assert_eq!(r["ok"], false, "{r}"); + assert_eq!(r["errorCode"], crate::settings::provider_notice::SEND_GUARD_CODE); + assert_eq!(r["error"], crate::settings::provider_notice::SEND_GUARD_ERROR); + assert!(kinds(&hub, from).is_empty(), "refused bots.say must emit zero BotWoke/MessagePosted events"); + assert!(rec.got.lock().unwrap().is_empty(), "refused bots.say must deliver nothing to Inbox"); +} diff --git a/native/host/src/commands/mod.rs b/native/host/src/commands/mod.rs index 08bb736b0c..f4fad8ed76 100644 --- a/native/host/src/commands/mod.rs +++ b/native/host/src/commands/mod.rs @@ -120,6 +120,16 @@ impl RpcHandler for Commands { if method == "accounts.select" && !crate::settings::accounts_hub::is_granted(who) { return vec![json!({"t":"reply","id":id,"ok":false,"error":crate::settings::accounts::GATE})] } // the hub's own requests: an agent's tool and the failover driver, which name who chose. A connection (client 1 and up) could say anything there, so it is never heard if matches!(method, "accounts.choose" | "fallback.switch") && who.client != 0 { return vec![json!({"t":"reply","id":id,"ok":false,"error":"unknown method"})] } + let preflight_send = match method { + "project.new" | "project.start" => !p["text"].as_str().map(str::trim).unwrap_or("").is_empty(), + "thread.create" => p["preflightSend"] == true || !p["text"].as_str().map(str::trim).unwrap_or("").is_empty(), + _ => false, + }; + if who.client > 0 && preflight_send { + if let Some(why) = crate::settings::provider_notice::send_guard(hub).await { + return vec![crate::settings::provider_notice::rpc_error_reply(id, why)]; + } + } let create_in: Option = match method { "fs.list" => return answer(fs::list(&path).await), "fs.mkdir" => return answer(fs::mkdir(&path).await), @@ -168,7 +178,14 @@ impl RpcHandler for Commands { if method == "project.new" && !first.is_empty() && pl.reply["ok"] == true { if let Some(th) = pl.reply["thread"].as_str() { let msg = format!("np-{}", th.chars().filter(|c| c.is_ascii_alphanumeric() || *c == '-').collect::()); let r = match hub.rpc_for("turn.start") { Some(h) => h.call(hub, who, &json!(0), "turn.start", &json!({"thread": th, "text": first, "msg": msg})).await.into_iter().next().unwrap_or(Value::Null), None => json!({"ok": false, "error": "no agent module is running"}) }; - if r["ok"] != true { let mut x = pl.reply.clone(); x["note"] = json!(format!("The project is made, but its first message did not go: {}", r["error"].as_str().unwrap_or("send it again"))); return vec![x] } + if r["ok"] != true { + if r["errorCode"].as_str().is_some_and(|c| c == crate::settings::provider_notice::SEND_GUARD_CODE || c == crate::settings::provider_notice::SEND_GUARD_REMOTE_CODE) { + let mut x = json!({"t":"reply","id":id,"ok":false,"error":r["error"].as_str().unwrap_or(crate::settings::provider_notice::SEND_GUARD_ERROR),"errorCode":r["errorCode"],"thread":th}); + if let Some(m) = r.get("machine") { x["machine"] = m.clone(); } + return vec![x]; + } + let mut x = pl.reply.clone(); x["note"] = json!(format!("The project is made, but its first message did not go: {}", r["error"].as_str().unwrap_or("send it again"))); return vec![x] + } } } return vec![pl.reply]; } @@ -201,7 +218,12 @@ impl RpcHandler for Commands { if let Some(("post", th, text)) = pl.act.clone() { let msg = th.strip_prefix("home-").unwrap_or("").to_string(); let r = match hub.rpc_for("turn.start") { Some(h) => h.call(hub, who, &json!(0), "turn.start", &json!({"thread": th, "text": text, "msg": msg})).await.into_iter().next().unwrap_or(Value::Null), None => json!({"ok": false, "error": "no agent module is running"}) }; - if r["ok"] != true { return vec![json!({"t":"reply","id":id,"ok":false,"error":r["error"].as_str().unwrap_or("the message could not be delivered; send it again")})] } + if r["ok"] != true { + let mut x = json!({"t":"reply","id":id,"ok":false,"error":r["error"].as_str().unwrap_or("the message could not be delivered; send it again"),"thread":th}); + if let Some(c) = r.get("errorCode") { x["errorCode"] = c.clone(); } + if let Some(m) = r.get("machine") { x["machine"] = m.clone(); } + return vec![x] + } } else if let Some((kind, th, text)) = pl.act.clone() { if let Some(s) = self.agents() { match kind { "steer" => s.steer(&th, &text).await, "start_one" => s.start_one(&th, &text).await, _ => s.start_queued(&th, &text).await } } } diff --git a/native/host/src/commands/tests.rs b/native/host/src/commands/tests.rs index 040e6b63c2..5fea8c464e 100644 --- a/native/host/src/commands/tests.rs +++ b/native/host/src/commands/tests.rs @@ -692,3 +692,25 @@ async fn ask_on(h: &Arc, c: &mut crate::hub::Conn, m: &str, p: Value) -> (V assert_eq!(e[0], json!({"$":"ThreadPinned","id":"t3","pinned":true,"at":0})); assert_eq!(e[1], json!({"$":"ThreadPinned","id":"t1","pinned":false,"at":0}), "{e:?}"); let (e, _) = ask(&h, "thread.pin", json!({"thread":"t3"})).await; assert_eq!(e.len(), 1, "pinning a pinned one unpins nothing: {e:?}"); } + +#[tokio::test] async fn project_new_and_start_with_text_refuse_without_creating_folder_or_events_when_no_provider() { + let h = hub("np-proj").await; + let mut about = serde_json::Map::new(); + for (agent, _) in crate::present::keys::AGENTS { + about.insert((*agent).to_string(), json!({"cli": ""})); + } + let _guard = crate::settings::provider_notice::override_for_test(&h, true, json!({"probed": true, "about": about})); + let parent = crate::plat::tmp::dir("cmds-np-dir"); + let target = parent.join("fresh-proj"); + let (ev, r) = ask(&h, "project.new", json!({"path": target.to_string_lossy(), "empty": true, "text": "build it"})).await; + assert_eq!(r["ok"], false, "{r}"); + assert_eq!(r["errorCode"], crate::settings::provider_notice::SEND_GUARD_CODE); + assert_eq!(r["error"], crate::settings::provider_notice::SEND_GUARD_ERROR); + assert!(ev.is_empty(), "refused project.new must log zero events: {ev:?}"); + assert!(!target.exists(), "refused project.new must create no folder on disk"); + + let (ev2, r2) = ask(&h, "project.start", json!({"project": "p1", "msg": "start-1", "text": "hello"})).await; + assert_eq!(r2["ok"], false, "{r2}"); + assert_eq!(r2["errorCode"], crate::settings::provider_notice::SEND_GUARD_CODE); + assert!(ev2.is_empty(), "refused project.start must log zero events: {ev2:?}"); +} diff --git a/native/host/src/data/ext.rs b/native/host/src/data/ext.rs index d1c798c1f3..1c0a6360c7 100644 --- a/native/host/src/data/ext.rs +++ b/native/host/src/data/ext.rs @@ -655,16 +655,35 @@ pub fn wants_value(v: &Value) -> bool { matches!(s(v, "t"), "plot" | "shot" | "v async fn composer_run(hub: &Arc, c: &mut Conn, p: &Value) -> Result { use crate::session::composer::{btw_answer, intent_edit, word_of, Word, BTW_EMPTY}; let (th, text) = (s(p, "thread"), s(p, "text")); - if !known_thread(&*hub.model().await, th) { return Err(err("unknown thread")) } + if !known_any(hub, &*hub.model().await, th) { return Err(err("unknown thread")) } match word_of(text) { None => Err(err("not a command of the composer")), Some(Word::Btw(q)) if q.is_empty() => Err(err(BTW_EMPTY)), Some(Word::Btw(q)) => { + if machines::is_far(th) { + let r = rpc(hub, c, "thread.btw", json!({"thread": th, "q": q})).await?; + let a = btw_answer(r["result"]["btw"].as_str().unwrap_or("")); + let (h, client, thread, asked, ans) = (hub.clone(), c.client, th.to_string(), q.clone(), a.clone()); + tokio::spawn(async move { + tokio::time::sleep(std::time::Duration::from_millis(50)).await; + h.push(client, json!({"t":"d","k":"btw","thread":thread,"q":asked,"a":ans})); + }); + return Ok(json!({"kind":"btw","q":q,"a":a})); + } + if let Some(why) = crate::settings::provider_notice::send_guard(hub).await { + return Err(super::no_provider_err(why)); + } let (h, client, thread, asked) = (hub.clone(), c.client, th.to_string(), q.clone()); tokio::spawn(async move { // the model may take a minute: this socket keeps answering meanwhile - let who = crate::api::Caller { gen: String::new(), client: 0 }; + // Fresh non-attached client id so thread.btw keeps client > 0 checks without taking the attached desktop reply path. + let who = crate::api::Caller { gen: String::new(), client: h.fresh_client() }; let r = match h.rpc_for("thread.btw") { Some(x) => x.call(&h, &who, &json!(0), "thread.btw", &json!({"thread":thread,"q":asked})).await.into_iter().next().unwrap_or(Value::Null), None => Value::Null }; - h.push(client, json!({"t":"d","k":"btw","thread":thread,"q":asked,"a":btw_answer(r["result"]["btw"].as_str().unwrap_or(""))})); + let a = if r["ok"] == true { + btw_answer(r["result"]["btw"].as_str().unwrap_or("")) + } else { + r["error"].as_str().filter(|e| !e.is_empty()).map(str::to_string).unwrap_or_else(|| btw_answer("")) + }; + h.push(client, json!({"t":"d","k":"btw","thread":thread,"q":asked,"a":a})); }); Ok(json!({"kind":"btw","q":q})) } @@ -686,6 +705,7 @@ async fn composer_run(hub: &Arc, c: &mut Conn, p: &Value) -> Result { let r = hub.request_here(c, &json!({"id":0,"m":"project.new","p":{"path":path,"empty":true,"text":first}})).await.into_iter().find(|v| v["t"] == "reply").unwrap_or(Value::Null); if r["ok"] == true { return Ok(json!({"kind":"made","thread":r["thread"],"note":r["note"].as_str().unwrap_or("")})) } + if r.get("errorCode").is_some() { return Err(super::err_from_rpc(&r)) } let why = r["error"].as_str().unwrap_or("The project could not be made.").to_string(); match r["result"]["exists"].as_str() { Some(d) if p["exists"] == true => Ok(json!({"kind":"exists","path":d,"error":why})), _ => Err(err(why)) } } diff --git a/native/host/src/data/mod.rs b/native/host/src/data/mod.rs index 63d2dc2f6e..18c63da773 100644 --- a/native/host/src/data/mod.rs +++ b/native/host/src/data/mod.rs @@ -34,6 +34,37 @@ fn ms(at: u64) -> u64 { if at < 100_000_000_000 { at * 1000 } else { at } } fn clip(s: &str, n: usize) -> String { let t: String = s.chars().take(n).collect(); t.replace('\n', " ") } fn s<'a>(v: &'a Value, k: &str) -> &'a str { v.get(k).and_then(Value::as_str).unwrap_or("") } fn err(e: T) -> Value { json!(e.to_string()) } +pub(crate) fn no_provider_err(why: &str) -> Value { + json!({"message": why, "errorCode": crate::settings::provider_notice::SEND_GUARD_CODE}) +} +pub(crate) fn err_from_rpc(r: &Value) -> Value { + let msg = r["error"].as_str().map(str::to_string).unwrap_or_else(|| r["error"].to_string()); + if r.get("errorCode").is_some() || r.get("machine").is_some() || r.get("thread").is_some() { + let mut obj = json!({"message": msg}); + if let Some(c) = r.get("errorCode") { obj["errorCode"] = c.clone(); } + if let Some(m) = r.get("machine") { obj["machine"] = m.clone(); } + if let Some(t) = r.get("thread") { obj["thread"] = t.clone(); } + obj + } else { + json!(msg) + } +} +fn err_reply(id: Value, e: Value) -> Value { + if e.is_object() + && e.get("code").is_none() + && e.get("key").is_none() + && (e.get("errorCode").is_some() || e.get("machine").is_some() || e.get("thread").is_some()) + { + if let Some(msg) = e.get("message").and_then(Value::as_str) { + let mut out = json!({"t":"reply","id":id,"ok":false,"error":msg}); + for k in ["errorCode", "machine", "thread"] { + if let Some(v) = e.get(k) { out[k] = v.clone(); } + } + return out; + } + } + json!({"t":"reply","id":id,"ok":false,"error":e}) +} // ---- plain CBOR (no key dictionary: the app's decoder knows nothing of the hub's) ---- fn head(out: &mut Vec, major: u8, n: u64) { @@ -412,7 +443,7 @@ async fn rpc(hub: &Arc, c: &mut Conn, m: &str, p: Value) -> Result r, None => hub.request_here(c, &json!({"id":0,"m":m,"p":p})).await.into_iter().find(|v| v["t"] == "reply").ok_or_else(|| err("no answer"))?, }; - if r["ok"] == true { Ok(r) } else { Err(r["error"].clone().as_str().map(|e| json!(e)).unwrap_or(r["error"].clone())) } + if r["ok"] == true { Ok(r) } else { Err(err_from_rpc(&r)) } } fn safe_id(x: &str) -> bool { !x.is_empty() && x.len() <= 64 && x.chars().all(|c| c.is_ascii_alphanumeric() || "-_.:".contains(c)) } static SENT: Mutex, VecDeque)>> = Mutex::new(None); @@ -612,8 +643,16 @@ async fn call(hub: &Arc, c: &mut Conn, m: &str, p: &Value, is_browser: bool "thread.create" => { let project = s(p, "project"); if project.is_empty() { return Err(err("project")) } if project == crate::sidebar::SCRATCH { return Err(err(SCRATCH_CLOSED)) } + let has_text = !s(p, "text").trim().is_empty(); + let far_proj = machines::is_far(project); + if has_text && !far_proj { + if let Some(why) = crate::settings::provider_notice::send_guard(hub).await { + return Err(no_provider_err(why)); + } + } // like the desktop's +: the env follows the thread.env setting (auto: a worktree in a git project) unless the phone names one let mut q = json!({"project":project}); + if has_text && far_proj { q["preflightSend"] = json!(true); } if !s(p, "env").is_empty() { if !matches!(s(p, "env"), "auto" | "worktree" | "local") { return Err(err("env: auto, worktree or local")) } q["env"] = p["env"].clone() } for k in ["title", "provider", "model"] { if !s(p, k).is_empty() { q[k] = p[k].clone() } } let r = rpc(hub, c, "thread.create", q).await?; @@ -624,7 +663,21 @@ async fn call(hub: &Arc, c: &mut Conn, m: &str, p: &Value, is_browser: bool if !s(p, "effort").is_empty() { rpc(hub, c, "thread.effort", json!({"thread":id,"effort":s(p, "effort")})).await?; } if !s(p, "speed").is_empty() { rpc(hub, c, "thread.speed", json!({"thread":id,"speed":s(p, "speed")})).await?; } // (a thread just made on a linked machine is not in the mirror yet: its first message goes straight there) - if !s(p, "text").is_empty() { if far { rpc(hub, c, "turn.start", json!({"thread":id,"text":s(p, "text"),"msg":format!("m{}-{}", now_ms(), hub.fresh_client())})).await?; } else { send_message(hub, c, &id, s(p, "text"), "", &Value::Null, &Value::Null, &Value::Null).await?; } } + if has_text { + let sent = if far { + rpc(hub, c, "turn.start", json!({"thread":id,"text":s(p, "text"),"msg":format!("m{}-{}", now_ms(), hub.fresh_client())})).await.map(|_| ()) + } else { + send_message(hub, c, &id, s(p, "text"), "", &Value::Null, &Value::Null, &Value::Null).await.map(|_| ()) + }; + if let Err(mut e) = sent { + if !e.is_object() { + let msg = e.as_str().map(str::to_string).unwrap_or_else(|| e.to_string()); + e = json!({"message": msg}); + } + e["thread"] = json!(id); + return Err(e); + } + } let g = hub.model().await; let asks = open_ask_counts(hub); if far { return Ok(json!({"thread":far_made(hub, &g, &id, project, s(p, "title"))})) } thread_json(hub, &g, &id, &asks).map(|t| json!({"thread":t})).ok_or_else(|| err("no thread was made")) @@ -895,7 +948,7 @@ async fn handle_for(hub: &Arc, c: &mut Conn, subs: &mut Subs, v: &Value, is "shell.sync" => open::shell_sync(hub, c, subs, &p, is_browser).await, _ => match term::call(hub, c.client, &mut subs.terms, m, &p).await { Some(r) => r, None => call(hub, c, m, &p, is_browser).await }, }; - match res { Ok(r) => json!({"t":"reply","id":id,"ok":true,"result":r}), Err(e) => json!({"t":"reply","id":id,"ok":false,"error":e}) } + match res { Ok(r) => json!({"t":"reply","id":id,"ok":true,"result":r}), Err(e) => err_reply(id, e) } } /// A request that waits on another machine (its thread or project is `~`, or a viewer read about a drawing watched there) is run off the socket's loop, @@ -1000,6 +1053,9 @@ async fn socket_with_reg( let name = NAME.get_or_init(crate::net::botnet::name).await.clone(); let theme = hub.setting("ui.theme").await.unwrap_or_default(); let locale = hub.setting("ui.lang").await.unwrap_or_default(); + // Subscribe before taking the hello snapshot so live notice/log changes during setup are never missed. + let (mut changes, mut frames) = (hub.changed.subscribe(), hub.frames.subscribe()); + let mut seen = hub.store.len(); let (hub_offer, notice, migrating) = if browser.is_some() { (String::new(), Value::Null, Value::Null) } else { @@ -1010,14 +1066,20 @@ async fn socket_with_reg( ) }; let no_provider = crate::settings::provider_notice::for_hub(&hub).await.map_or(Value::Null, |n| n.json()); + let mut no_provider_sent = no_provider.clone(); let mut hello = json!({"t":"hello","proto":PROTO,"hub":host,"name":name,"version":hub.cfg.version,"epoch":hub.epoch,"now":now_ms(),"features":FEATURES,"theme":theme,"locale":locale,"hubOffer":hub_offer,"hubBack":hub.info_now()["hub.back"].as_str().unwrap_or(""),"commands":crate::session::composer::words(),"notice":notice,"migrating":migrating,"noProvider":no_provider}); if let Some(c) = z { hello["z"] = json!(c) } // the home (feature "home", net/home.rs): where the uberbot lives, as this hub sees it; `k:"home"` pushes follow it on a lists subscription let mut home_sent = crate::net::home::now(&hub).await; hello["home"] = home_sent.clone(); tx.send(pack(&hello, json_mode)).await?; tx.arm(); // the hello went as it is: what follows is compressed (when a codec was chosen) + let no_provider_now = crate::settings::provider_notice::for_hub(&hub).await.map_or(Value::Null, |n| n.json()); + if no_provider_now != no_provider_sent { + no_provider_sent = no_provider_now.clone(); + let val = if no_provider_now.is_null() { String::new() } else { no_provider_now.to_string() }; + if !send_frame(&mut tx, &hub, browser.as_ref(), conn.client, pack(&json!({"t":"info","info":{crate::settings::provider_notice::INFO_KEY:val}}), json_mode)).await? { return Ok(()) } + } let (late_tx, mut late_rx) = tokio::sync::mpsc::unbounded_channel::(); - let (mut changes, mut frames) = (hub.changed.subscribe(), hub.frames.subscribe()); - let mut seen = hub.store.len(); let mut subs = Subs::default(); + let mut subs = Subs::default(); let mut beat = tokio::time::interval(Duration::from_millis(15000)); beat.tick().await; let mut far_beat = tokio::time::interval(Duration::from_millis(2000)); far_beat.tick().await; loop { @@ -1056,7 +1118,7 @@ async fn socket_with_reg( let mut c2 = Conn { local_view_socket: false, sent: vec![], client: conn.client, gen: conn.gen.clone(), view_id: String::new(), target: Value::Null, cbor: false, lastrev: 0 }; tokio::spawn(async move { let res = match term::far_wait(&m, &p) { true => term::far_call(&hub, c2.client, &m, &p).await, false => call(&hub, &mut c2, &m, &p, is_browser).await }; - let _ = late.send(match res { Ok(r) => json!({"t":"reply","id":id,"ok":true,"result":r}), Err(e) => json!({"t":"reply","id":id,"ok":false,"error":e}) }); + let _ = late.send(match res { Ok(r) => json!({"t":"reply","id":id,"ok":true,"result":r}), Err(e) => err_reply(id, e) }); }); continue } @@ -1075,10 +1137,20 @@ async fn socket_with_reg( if len > seen { 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\"")); 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 inv_changed { + let cur = crate::settings::provider_notice::for_hub(&hub).await.map_or(Value::Null, |n| n.json()); + if cur != no_provider_sent { + no_provider_sent = cur.clone(); + let val = if cur.is_null() { String::new() } else { cur.to_string() }; + if !send_frame(&mut tx, &hub, browser.as_ref(), conn.client, pack(&json!({"t":"info","info":{crate::settings::provider_notice::INFO_KEY:val}}), json_mode)).await? { return Ok(()) } + sent = true; + } + } } if !sent { if let Some((ref device_id, ref reg)) = browser { @@ -1110,6 +1182,9 @@ async fn socket_with_reg( }, // 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); + } 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) { diff --git a/native/host/src/data/tests.rs b/native/host/src/data/tests.rs index 3ae816b561..e4d3049676 100644 --- a/native/host/src/data/tests.rs +++ b/native/host/src/data/tests.rs @@ -1493,3 +1493,62 @@ async fn viewer_layout_over_a_socket_is_per_device_pushed_and_refuses_in_code_ke let r = ask(&mut ws, 1, "link.resolve", json!({"url":"backplane://settings/accounts","thread":""})).await; assert_eq!(r["result"], json!({"kind":"settings","page":"accounts"})); } + +fn probed_models(installed: &[&str]) -> Value { + let mut about = serde_json::Map::new(); + for (agent, _) in crate::present::keys::AGENTS { + let cli = if installed.contains(agent) { format!("/usr/bin/{agent}") } else { String::new() }; + about.insert((*agent).to_string(), json!({"cli": cli})); + } + json!({"probed": true, "about": about}) +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn data_hello_populates_no_provider_and_live_clears_over_socket() { + let (h, port) = up("np-hello").await; + let mut guard = crate::settings::provider_notice::override_for_test(&h.hub, false, probed_models(&[])); + crate::settings::provider_notice::publish(&h.hub).await; + let mut ws_cached = open(port, "&enc=json").await; + let hello_cached = next(&mut ws_cached).await; + assert!(hello_cached["noProvider"].is_null(), "cached negative probe must not populate hello.noProvider before live scan: {hello_cached}"); + drop(ws_cached); + + guard = crate::settings::provider_notice::override_for_test(&h.hub, true, probed_models(&[])); + crate::settings::provider_notice::publish(&h.hub).await; + let mut ws = open(port, "&enc=json").await; + let hello = next(&mut ws).await; + assert_eq!(hello["noProvider"]["reason"], "none_installed", "{hello}"); + assert_eq!(hello["noProvider"]["url"], "backplane://settings/accounts"); + + let _ok_guard = crate::settings::provider_notice::override_for_test(&h.hub, true, probed_models(&["claude"])); + drop(guard); + crate::settings::provider_notice::publish(&h.hub).await; + let clear = loop { + let v = next(&mut ws).await; + if v["t"] == "info" && v["info"].get(crate::settings::provider_notice::INFO_KEY).is_some() { + break v; + } + }; + assert_eq!(clear["info"][crate::settings::provider_notice::INFO_KEY], ""); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn data_composer_btw_and_thread_create_refuse_without_side_effects_when_no_provider() { + let (h, port) = up("np-guard").await; + let _guard = crate::settings::provider_notice::override_for_test(&h.hub, true, probed_models(&[])); + let mut ws = open(port, "&enc=json").await; + let _hello = next(&mut ws).await; + let n0 = h.hub.store.len(); + + let btw = ask(&mut ws, 1, "composer.run", json!({"thread":"t1","text":"/btw why"})).await; + assert_eq!(btw["ok"], false, "{btw}"); + assert_eq!(btw["errorCode"], crate::settings::provider_notice::SEND_GUARD_CODE); + assert_eq!(btw["error"], crate::settings::provider_notice::SEND_GUARD_ERROR); + + let create_with_text = ask(&mut ws, 2, "thread.create", json!({"project":"p1","text":"hello world"})).await; + assert_eq!(create_with_text["ok"], false, "{create_with_text}"); + assert_eq!(create_with_text["errorCode"], crate::settings::provider_notice::SEND_GUARD_CODE); + assert_eq!(create_with_text["error"], crate::settings::provider_notice::SEND_GUARD_ERROR); + assert_eq!(h.hub.store.len(), n0, "refused thread.create with initial prompt must leave zero ThreadCreated events"); + + let empty_create = ask(&mut ws, 3, "thread.create", json!({"project":"p1"})).await; + assert_eq!(empty_create["ok"], true, "opening an empty thread remains allowed so user sees proactive banner: {empty_create}"); +} diff --git a/native/host/src/net/homemove.rs b/native/host/src/net/homemove.rs index ff1410fa34..94279a111b 100644 --- a/native/host/src/net/homemove.rs +++ b/native/host/src/net/homemove.rs @@ -320,7 +320,7 @@ pub fn moved_thread(at: &str, thread: &str, project: Option<&str>, there: &dyn F /// The move in progress: where to, and the threads it carries (the person's messages to them are held until it is over). /// Kept in `/home-held.json` from the move's start to the last held message's delivery (as net/farsend.rs keeps far-sends.json), so a hub that /// restarts mid-move loses none of them: `recover` delivers them on the next start, to the new home when the move finished, else here. -#[derive(serde::Serialize, serde::Deserialize, Default)] +#[derive(Clone, serde::Serialize, serde::Deserialize, Default)] struct Moving { link: String, threads: HashSet, held: Vec, #[serde(skip)] path: Option } static MOVING: Mutex> = Mutex::new(None); fn held_path(home: &Path) -> PathBuf { home.join("home-held.json") } @@ -408,18 +408,75 @@ async fn has_msg(hub: &Arc, thread: &str, msg: &str) -> bool { let m = hub.model().await; m.page(&hub.store, thread, 0, 64).map(|pg| pg.rows.iter().any(|r| r.id == msg)).unwrap_or(false) } async fn deliver_held(hub: &Arc, mut m: Moving, moved: bool) { + let mut failed: Vec = vec![]; while !m.held.is_empty() { let p = m.held[0].clone(); let th = gs(&p, "thread").to_string(); let to = crate::net::far::id(&m.link, &th); - if p["via"] == "deliver" { - if moved { if let Err(e) = deliver_there(&to, &m.link, &p) { eprintln!("backplane: home move: a held delivery to {th} was not sent: {e}") } } - else if !has_msg(hub, &th, gs(&p, "msg")).await { if let Some(h) = hub.rpc_for("thread.deliver") { let _ = h.call(hub, &Caller { gen: "home".into(), client: 0 }, &json!(0), "thread.deliver", &p).await; } } - } else if moved { if let Err(e) = forward(&to, &m.link, &p) { eprintln!("backplane: home move: a held message to {th} was not sent: {e}") } } - else if !has_msg(hub, &th, gs(&p, "msg")).await { if let Some(h) = hub.rpc_for("turn.start") { let _ = h.call(hub, &Caller { gen: "home".into(), client: 1 }, &json!(0), "turn.start", &p).await; } } - m.held.remove(0); m.save(); // (the far outbox keeps what goes there from here on) + let delivered = if p["via"] == "deliver" { + if moved { + match deliver_there(&to, &m.link, &p) { + Ok(()) => true, + Err(e) => { + eprintln!("backplane: home move: a held delivery to {th} was not sent: {e}"); + false + } + } + } else if has_msg(hub, &th, gs(&p, "msg")).await { + true + } else if let Some(h) = hub.rpc_for("thread.deliver") { + let r = h.call(hub, &Caller { gen: "home".into(), client: 0 }, &json!(0), "thread.deliver", &p).await; + if r.iter().any(|v| v["ok"] == true) { + true + } else { + eprintln!("backplane: home move: a held delivery to {th} failed locally: {:?}", r.first()); + false + } + } else { + eprintln!("backplane: home move: a held delivery to {th} has no thread.deliver handler"); + false + } + } else if moved { + match forward(&to, &m.link, &p) { + Ok(()) => true, + Err(e) => { + eprintln!("backplane: home move: a held message to {th} was not sent: {e}"); + false + } + } + } else if has_msg(hub, &th, gs(&p, "msg")).await { + true + } else if let Some(h) = hub.rpc_for("turn.start") { + let r = h.call(hub, &Caller { gen: "home".into(), client: 1 }, &json!(0), "turn.start", &p).await; + if r.iter().any(|v| v["ok"] == true) { + true + } else { + eprintln!("backplane: home move: a held message to {th} failed locally: {:?}", r.first()); + false + } + } else { + eprintln!("backplane: home move: a held message to {th} has no turn.start handler"); + false + }; + let item = m.held.remove(0); + if !delivered { + failed.push(item); + } + if failed.is_empty() { + m.save(); + } else { + let mut snap = m.clone(); + snap.held = failed.iter().chain(m.held.iter()).cloned().collect(); + snap.save(); + } + } + if failed.is_empty() { + if let Some(p) = &m.path { let _ = std::fs::remove_file(p); } + } else { + m.held = failed; + m.save(); + eprintln!("backplane: home move: {} held message(s) remain saved after delivery failure", m.held.len()); } - if let Some(p) = &m.path { let _ = std::fs::remove_file(p); } } // ---- the readiness check (before a move; nothing here signs in, installs or costs a request to a provider) ---- @@ -1033,4 +1090,41 @@ mod tests { for (off, part) in [(0u64, &b"abc"[..]), (3, b"def"), (3, b"def")] { let r = serve(&hub, "L", "home.file", &json!({"root":"home","rel":"mail/x.txt","off":off,"b64":b64(part)})).await; assert_eq!(r["ok"], true, "{r}") } assert_eq!(std::fs::read(home.join("mail/x.txt")).unwrap(), b"abcdef", "the chunk sent again is written once"); } + + #[tokio::test(flavor = "multi_thread")] async fn deliver_held_keeps_failed_items_on_disk() { + use crate::api::{Caller, Fut, RpcHandler}; + struct DummyTurn(bool); + impl RpcHandler for DummyTurn { + fn methods(&self) -> &'static [&'static str] { &["turn.start"] } + fn call<'a>(&'a self, _h: &'a Arc, _w: &'a Caller, id: &'a Value, _m: &'a str, _p: &'a Value) -> Fut<'a, Vec> { + let ok = self.0; + Box::pin(async move { + vec![if ok { json!({"t":"reply","id":id,"ok":true}) } else { json!({"t":"reply","id":id,"ok":false,"error":"refused"}) }] + }) + } + } + let home = crate::plat::tmp::dir("hm-keep"); + 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 path = held_path(&home); + let held_item = json!({"thread":"t1","msg":"m1","text":"keep me"}); + let m = Moving { link: "L1".into(), threads: ["t1".to_string()].into_iter().collect(), held: vec![held_item.clone()], path: Some(path.clone()) }; + m.save(); + deliver_held(&hub, m.clone(), false).await; + let saved: Moving = serde_json::from_slice(&std::fs::read(&path).unwrap()).unwrap(); + assert_eq!(saved.held.len(), 1, "missing handler must retain held item"); + + hub.register_rpc(Arc::new(DummyTurn(false))); + deliver_held(&hub, m.clone(), false).await; + let saved2: Moving = serde_json::from_slice(&std::fs::read(&path).unwrap()).unwrap(); + assert_eq!(saved2.held.len(), 1, "failed turn.start must retain held item"); + + let home2 = crate::plat::tmp::dir("hm-drop"); + let hub2 = Hub::start(crate::hub::Cfg { home: home2.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(); + hub2.register_rpc(Arc::new(DummyTurn(true))); + let path2 = held_path(&home2); + let m2 = Moving { link: "L1".into(), threads: ["t1".to_string()].into_iter().collect(), held: vec![held_item], path: Some(path2.clone()) }; + m2.save(); + deliver_held(&hub2, m2, false).await; + assert!(!path2.exists(), "successful delivery removes held file"); + } } diff --git a/native/host/src/net/rpc.rs b/native/host/src/net/rpc.rs index b7da852117..e21cb56743 100644 --- a/native/host/src/net/rpc.rs +++ b/native/host/src/net/rpc.rs @@ -137,7 +137,8 @@ impl Parts { } else if ok { watching.lock().unwrap().remove(&client); } } let frame = if code == 200 { - far::reply_on(serde_json::from_str::(&text).unwrap_or_else(|_| json!({"t":"reply","ok":false,"error":"invalid reply from that machine","id":0})), id, l) + let r = far::reply_on(serde_json::from_str::(&text).unwrap_or_else(|_| json!({"t":"reply","ok":false,"error":"invalid reply from that machine","id":0})), id, l); + crate::settings::provider_notice::rewrite_remote_reply(r, &machine_name(&sync, l)) } else if code == 0 { err(id, "that machine is away").remove(0) } else { err(id, &format!("that machine did not take it: {}", text.chars().take(120).collect::())).remove(0) }; { let mut w = waiting.lock().unwrap(); if let Some(n) = w.get_mut(&client) { *n -= 1; if *n == 0 { w.remove(&client); } } } frame @@ -226,6 +227,15 @@ async fn send_held(sync: Arc, hub: std::sync::Weak, out: Arc(&text) + .ok() + .filter(crate::settings::provider_notice::is_local_refusal_reply) + .map(|v| crate::settings::provider_notice::rewrite_remote_reply(v, &machine_name(&sync, &item.link)).to_string()) + .unwrap_or(text) + } else { + text + }; out2.answered(&item.msg, code, &text, farsend::now_ms()); busy2.lock().unwrap().retain(|m| *m != item.msg); out2.kick.notify_one(); @@ -261,6 +271,15 @@ pub fn machines_of(sync: &FarSync) -> Vec<(String, String, String)> { rows.into_iter().zip(uniq).map(|(r, (_, label))| (r.0, label, r.2)).collect() } +fn machine_name(sync: &FarSync, link: &str) -> String { + machines_of(sync) + .into_iter() + .find(|(id, _, _)| id == link) + .map(|(_, name, _)| name) + .filter(|n| !n.is_empty()) + .unwrap_or_else(|| link.to_string()) +} + /// The bots lane's transport for `owner.mail` (a signed POST to a linked machine); only to one of the owner's own (the request carries mail text). pub struct Link { pub sync: Arc, pub hub: std::sync::Weak, pub copy: bool } impl OwnerLink for Link { diff --git a/native/host/src/present/screen.rs b/native/host/src/present/screen.rs index 9cccff23fa..391f7fdcdb 100644 --- a/native/host/src/present/screen.rs +++ b/native/host/src/present/screen.rs @@ -31,7 +31,7 @@ impl super::Screen for Recent { // a revoked device gone); opening the page reads it too (the page in the session is still the one before the press) let devpage=super::settings::page(¶ms["session"])=="devices" || (text(params,"action")=="settings-page" && text(params,"value")=="devices"); let acted; let params=if devpage && text(params,"action").starts_with("device-") { match super::settings::device_act(text(params,"action"),text(params,"value")) { Some(patch)=>{ let mut c=params.clone(); crate::session::patch::merge(&mut c["session"],&patch); c["action"]=json!(""); c["value"]=json!(""); acted=c; &acted } None=>params } } else { params }; - let withinfo; let params=if super::settings::is_open(¶ms["session"]) || shows_thread(params) || shows_swarm_models(params) || setup { let mut c=params.clone(); c["hubInfo"]=_hub.info_now(); c["hubInfo"]["client"]=params["client"].clone(); if devpage { if let Some(r)=crate::net::start::routes() { c["hubInfo"]["devices"]=r.devices(); } c["hubInfo"]["shares"]=json!(crate::files::share::listed_now()); } if setup || super::settings::page(¶ms["session"])=="machines" { if let Some(p)=crate::net::start::peering() { c["hubInfo"]["machines"]=p.page_data(); } } withinfo=c; &withinfo } else { let mut c=params.clone(); c["hubInfo"]=json!({"models":crate::settings::models::info()}); withinfo=c; &withinfo }; + let withinfo; let params=if super::settings::is_open(¶ms["session"]) || shows_thread(params) || shows_swarm_models(params) || setup { let mut c=params.clone(); c["hubInfo"]=_hub.info_now(); c["hubInfo"]["client"]=params["client"].clone(); c["hubInfo"]["modelsProbedHere"]=json!(crate::settings::models::probed_here()); if devpage { if let Some(r)=crate::net::start::routes() { c["hubInfo"]["devices"]=r.devices(); } c["hubInfo"]["shares"]=json!(crate::files::share::listed_now()); } if setup || super::settings::page(¶ms["session"])=="machines" { if let Some(p)=crate::net::start::peering() { c["hubInfo"]["machines"]=p.page_data(); } } withinfo=c; &withinfo } else { let mut c=params.clone(); c["hubInfo"]=json!({"models":crate::settings::models::info(),"modelsProbedHere":crate::settings::models::probed_here()}); withinfo=c; &withinfo }; // a 0.14 import of this hub: its card goes over any page (present/onboard.rs import_overlay) let withmig; let params=match crate::import014::last_published(&_hub.cfg.home) { Some(v) => { let mut c=params.clone(); c["importV014"]=v; withmig=c; &withmig } None => params }; let m=_hub.mirrors(); @@ -938,7 +938,7 @@ pub fn recent_unified(st: &State,far: &[(String,&State)],un: &Unified,p: &Value) let shown=json!({"projects":projects,"sidebarPages":pages,"nativeSidebar":1,"active":[],"legacy":[],"thread":shown_thread,"rooms":rooms(st,far,un,hub),"bots":bots(st,far,un,hub,opts.now),"theme":setting(st,"ui.theme"),"mouse":json!({"2d":setting(st,"mouse.2d"),"3d":setting(st,"mouse.3d"),"invert":setting(st,"mouse.invert")}),"browserStart":crate::settings::browser_start::url(setting(st,crate::settings::browser_start::KEY)), "renaming":renaming,"deleting":deleting,"bot":null,"settings":if super::settings::is_open(&session) { super::settings::view(st,&session,p.get("hubInfo").unwrap_or(&Value::Null)) }else{Value::Null},"newRoom":super::botforms::new_room(st,hub,&session).unwrap_or(Value::Null),"newBot":super::botforms::new_bot(&session).unwrap_or(Value::Null),"projectHome":null}); let mut shown=shown; - let no_provider=crate::settings::provider_notice::from_screen(p.get("hubInfo").and_then(|h|h["models"].as_str()),setting(st,"accounts.inventory")); + let no_provider=crate::settings::provider_notice::from_screen(p.get("hubInfo").and_then(|h|h["models"].as_str()), p.get("hubInfo").and_then(|h|h["modelsProbedHere"].as_bool()), setting(st,"accounts.inventory")); if !no_provider.is_null() { shown["noProvider"]=no_provider; } if !far.is_empty() { shown["machines"]=machine_switch(far,un,&mpick); } // the sections (docs/ALWAYS-ON.md section 8): Bub, Needs you, Pinned, Active, groups, Quiet; the project page; Ctrl+K's list @@ -1792,8 +1792,11 @@ mod selected_thread_tests { "hub":"h","generation":"g","epoch":"e","viewId":"v","revision":st.seq,"now":1000000,"session":{"drafts":{},"open":{}}, "window":{"remaining":0},"page":{"thread":"t1","rows":[]}}); assert!(recent(&st,&base).unwrap()["shown"].get("noProvider").is_none(), "unprobed builtin omits noProvider"); + let mut cached_only=base.clone(); + cached_only["hubInfo"]=json!({"models":json!({"probed":true,"about":{"claude":{"cli":""},"codex":{"cli":""}}}).to_string(),"modelsProbedHere":false}); + assert!(recent(&st,&cached_only).unwrap()["shown"].get("noProvider").is_none(), "cached negative probe omits noProvider until current process scans"); let mut none=base.clone(); - none["hubInfo"]=json!({"models":json!({"probed":true,"about":{"claude":{"cli":""},"codex":{"cli":""}}}).to_string()}); + none["hubInfo"]=json!({"models":json!({"probed":true,"about":{"claude":{"cli":""},"codex":{"cli":""}}}).to_string(),"modelsProbedHere":true}); let np=recent(&st,&none).unwrap()["shown"]["noProvider"].clone(); assert_eq!(np["reason"],"none_installed"); assert_eq!(np["url"],"backplane://settings/accounts"); diff --git a/native/host/src/settings/models.rs b/native/host/src/settings/models.rs index e47cc1e9b4..7318f0fd50 100644 --- a/native/host/src/settings/models.rs +++ b/native/host/src/settings/models.rs @@ -12,8 +12,12 @@ pub const CLAUDE: &[&str] = &["fable", "opus", "sonnet", "haiku"]; static LIVE: RwLock> = RwLock::new(None); /// Whether the hub detects its agents' models (the binary's start, models_probe::start): a test hub keeps the built-in value and asks no CLI. static DETECTS: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); +/// Whether this hub process has completed at least one live CLI probe (separate from `models.cache`'s persisted `"probed": true`). +static PROBED_HERE: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); pub fn live() -> bool { DETECTS.load(std::sync::atomic::Ordering::Relaxed) } pub fn set_detects() { DETECTS.store(true, std::sync::atomic::Ordering::Relaxed) } +pub fn probed_here() -> bool { PROBED_HERE.load(std::sync::atomic::Ordering::Relaxed) } +pub fn mark_probed() { PROBED_HERE.store(true, std::sync::atomic::Ordering::Relaxed) } /// The info in force becomes `info`; answers whether it changed. pub fn set_live(info: &str) -> bool { let mut g = LIVE.write().unwrap_or_else(|e| e.into_inner()); diff --git a/native/host/src/settings/models_probe.rs b/native/host/src/settings/models_probe.rs index cef1920360..26fe5efb60 100644 --- a/native/host/src/settings/models_probe.rs +++ b/native/host/src/settings/models_probe.rs @@ -260,7 +260,17 @@ pub async fn detect(home: &Path) -> Found { /// One detection: a list that differs from the one in force is cached, pushed to every client and every view is drawn again. Answers whether it changed. pub async fn refresh(hub: &Arc) -> bool { let info = info_of(&detect(&hub.cfg.home).await); - if !super::models::set_live(&info) { return false } + let first_scan = !super::models::probed_here(); + let changed = super::models::set_live(&info); + // Mark live scan completed only after updating live models so callers never combine probed_here with stale cache data. + super::models::mark_probed(); + if !changed { + if first_scan { + super::provider_notice::publish(hub).await; + hub.bump_views(); + } + return false; + } let _ = std::fs::write(hub.cfg.home.join("models.cache.part"), cache_text(&info)).and_then(|_| std::fs::rename(hub.cfg.home.join("models.cache.part"), hub.cfg.home.join("models.cache"))); hub.push_all(&json!({"t":"info","info":{"models":super::models::info(),"models.all":super::models::all()}})); super::provider_notice::publish(hub).await; @@ -292,9 +302,8 @@ pub fn refresh_soon(hub: &Arc) { pub fn start(hub: Arc) { let cached = std::fs::read_to_string(hub.cfg.home.join("models.cache")).ok().as_deref().and_then(cache_read); if let Some(i) = &cached { + // Warm the picker cache at startup, but keep negative notices/send guards quiet until this process's live scan completes. super::models::set_live(i); - let h = hub.clone(); - tokio::spawn(async move { super::provider_notice::publish(&h).await; }); } if crate::copy::on() && std::env::var("BACKPLANE_AGENTS").map_or(true, |d| d.is_empty()) { return } super::models::set_detects(); diff --git a/native/host/src/settings/provider_notice.rs b/native/host/src/settings/provider_notice.rs index 82c867b2cf..f169f347f5 100644 --- a/native/host/src/settings/provider_notice.rs +++ b/native/host/src/settings/provider_notice.rs @@ -12,6 +12,42 @@ pub const TEXT_NONE_INSTALLED: &str = "Connect Claude, Codex, Antigravity, or an pub const TEXT_SIGNED_OUT: &str = "Sign in to Claude, Codex, or another provider in Settings → Accounts to start chatting."; pub const BUTTON: &str = "Open Settings → Accounts"; pub const SEND_GUARD_ERROR: &str = "No AI provider connected yet. Open Settings → Accounts to connect Claude, Codex, Antigravity, or another provider."; +pub const SEND_GUARD_CODE: &str = "no_provider"; +pub const SEND_GUARD_REMOTE_CODE: &str = "no_provider_remote"; + +/// Refusal copy for a send routed to a linked machine that has zero providers connected. +pub fn remote_send_guard_error(machine: &str) -> String { + let who = if machine.trim().is_empty() { "that machine" } else { machine.trim() }; + format!( + "No AI provider connected on {who}. Open Settings → Accounts on {who} to connect Claude, Codex, Antigravity, or another provider." + ) +} + +/// RPC reply frame for a local send-guard refusal, preserving string `error` plus structured `errorCode`. +pub fn rpc_error_reply(id: &Value, why: &str) -> Value { + json!({"t": "reply", "id": id, "ok": false, "error": why, "errorCode": SEND_GUARD_CODE}) +} + +/// True when a reply frame is a local zero-provider refusal from a hub. +pub fn is_local_refusal_reply(frame: &Value) -> bool { + frame["ok"] == false + && (frame["errorCode"].as_str() == Some(SEND_GUARD_CODE) + || frame["error"].as_str() == Some(SEND_GUARD_ERROR)) +} + +/// Rewrites a forwarded destination-hub zero-provider refusal so it names `machine` instead of directing the user to local Settings. +pub fn rewrite_remote_reply(mut frame: Value, machine: &str) -> Value { + if is_local_refusal_reply(&frame) { + if let Some(o) = frame.as_object_mut() { + o.insert("error".into(), json!(remote_send_guard_error(machine))); + o.insert("errorCode".into(), json!(SEND_GUARD_REMOTE_CODE)); + if !machine.trim().is_empty() { + o.insert("machine".into(), json!(machine.trim())); + } + } + } + frame +} const NON_ACCOUNT_PROVIDERS: &[&str] = &["grok", "muse", "antigravity", "opencode", "pi", "omp"]; @@ -87,7 +123,10 @@ pub fn check(models: &Value, inventory: &str) -> Option { } /// Pure JSON value for presenter `shown["noProvider"]` (Null when a provider is usable or detection has not run). -pub fn from_screen(models_raw: Option<&str>, inventory: &str) -> Value { +pub fn from_screen(models_raw: Option<&str>, probed_here: Option, inventory: &str) -> Value { + if probed_here == Some(false) { + return Value::Null; + } let models = models_raw .and_then(|s| serde_json::from_str::(s).ok()) .unwrap_or(Value::Null); @@ -102,8 +141,58 @@ pub fn guard_for(models: &Value, inventory: &str, client: u64, retry: bool, has_ check(models, inventory).map(|_| SEND_GUARD_ERROR) } +#[cfg(test)] +static TEST_MODELS: std::sync::LazyLock>> = + std::sync::LazyLock::new(Default::default); +#[cfg(test)] +static TEST_SEQ: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1); + +#[cfg(test)] +pub struct TestOverride { + key: usize, + seq: u64, +} + +#[cfg(test)] +impl Drop for TestOverride { + fn drop(&mut self) { + if let Ok(mut g) = TEST_MODELS.lock() { + if g.get(&self.key).is_some_and(|(s, _, _)| *s == self.seq) { + g.remove(&self.key); + } + } + } +} + +/// Per-hub test override for `(probed_here, models)` without mutating global `models::LIVE` or `PROBED_HERE`. +#[cfg(test)] +pub fn override_for_test(hub: &Arc, probed_here: bool, models: Value) -> TestOverride { + let key = Arc::as_ptr(hub) as usize; + let seq = TEST_SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + TEST_MODELS.lock().unwrap().insert(key, (seq, probed_here, models)); + TestOverride { key, seq } +} + pub async fn for_hub(hub: &Arc) -> Option { - let models: Value = serde_json::from_str(&super::models::info()).unwrap_or(Value::Null); + #[cfg(test)] + let test_override = TEST_MODELS + .lock() + .unwrap() + .get(&(Arc::as_ptr(hub) as usize)) + .map(|(_, probed, models)| (*probed, models.clone())); + #[cfg(not(test))] + let test_override: Option<(bool, Value)> = None; + + let (probed_here, models) = match test_override { + Some(v) => v, + None => ( + super::models::probed_here(), + serde_json::from_str::(&super::models::info()).unwrap_or(Value::Null), + ), + }; + if !probed_here { + return None; + } let inventory = hub.setting("accounts.inventory").await.unwrap_or_default(); check(&models, &inventory) } @@ -135,7 +224,8 @@ mod tests { let builtin: Value = serde_json::from_str(&crate::settings::models::builtin()).unwrap(); assert_eq!(check(&builtin, ""), None); assert_eq!(check(&Value::Null, ""), None); - assert_eq!(from_screen(None, ""), Value::Null); + assert_eq!(from_screen(None, None, ""), Value::Null); + assert_eq!(from_screen(Some(&probed_with(&[]).to_string()), Some(false), ""), Value::Null); } #[test] @@ -147,7 +237,7 @@ mod tests { assert_eq!(n.text, TEXT_NONE_INSTALLED); assert_eq!(n.button, BUTTON); assert_eq!(n.url, ACCOUNTS_URL); - assert_eq!(from_screen(Some(&m.to_string()), ""), n.json()); + assert_eq!(from_screen(Some(&m.to_string()), Some(true), ""), n.json()); } #[test] @@ -230,4 +320,52 @@ mod tests { let ok = probed_with(&["grok"]); assert_eq!(guard_for(&ok, "", 1, false, true), None); } + + #[test] + fn remote_rewrite_tags_and_names_destination_machine_without_changing_other_errors() { + let local_reply = rpc_error_reply(&json!(7), SEND_GUARD_ERROR); + assert_eq!(local_reply["errorCode"], SEND_GUARD_CODE); + assert!(is_local_refusal_reply(&local_reply)); + + let rewritten = rewrite_remote_reply(local_reply, "boat-hub"); + assert_eq!(rewritten["ok"], false); + assert_eq!(rewritten["errorCode"], SEND_GUARD_REMOTE_CODE); + assert_eq!(rewritten["machine"], "boat-hub"); + assert_eq!( + rewritten["error"].as_str().unwrap(), + "No AI provider connected on boat-hub. Open Settings → Accounts on boat-hub to connect Claude, Codex, Antigravity, or another provider." + ); + assert!(!rewritten["error"].as_str().unwrap().starts_with("No AI provider connected yet.")); + + let other = json!({"t":"reply","id":7,"ok":false,"error":"permission denied"}); + assert!(!is_local_refusal_reply(&other)); + assert_eq!(rewrite_remote_reply(other.clone(), "boat-hub"), other); + } + + #[tokio::test] + async fn per_hub_override_gates_notice_on_current_process_scan() { + let dir = crate::plat::tmp::dir("pn-override"); + let hub = Hub::start( + crate::hub::Cfg { + home: dir.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 _cached = override_for_test(&hub, false, probed_with(&[])); + assert_eq!(for_hub(&hub).await, None, "cached negative probe must not emit notice before live scan"); + assert_eq!(send_guard(&hub).await, None); + + let _scanned = override_for_test(&hub, true, probed_with(&[])); + let notice = for_hub(&hub).await.expect("live scan with zero providers emits notice"); + assert_eq!(notice.reason, "none_installed"); + assert_eq!(send_guard(&hub).await, Some(SEND_GUARD_ERROR)); + } } diff --git a/web/build.ts b/web/build.ts index bea9b209c8..536ae7b414 100644 --- a/web/build.ts +++ b/web/build.ts @@ -111,6 +111,7 @@ function collectI18nKeys(tsFiles: string[]): string[] { "provider.notice.text.signedout", "provider.notice.button", "provider.notice.senderr", + "provider.notice.senderr.remote", ]); const re = /\bt\(\s*["']([a-zA-Z0-9_.-]+)["']/g; for (const f of tsFiles) { diff --git a/web/dist/assets/app.js b/web/dist/assets/app.js index 7d7634624e..b23c6bef6f 100644 --- a/web/dist/assets/app.js +++ b/web/dist/assets/app.js @@ -1,15 +1,15 @@ -function Wt(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 In(e){return e==="done"||e==="failed"||e==="cancelled"}function Rn(e,t){if(!e||e.id!==t.id)return!0;let n=In(e.state),i=In(t.state);if(n!==i)return i;return(t.ended??0)>=(e.ended??0)}function jn(e){if(e.state!=="done")return!1;if(typeof e.hold==="boolean")return!e.hold;return(e.notes??[]).length===0}var gt={en:{"agy.signout":"Sign out","android.hub.machines.approve":"Approve","android.load.earlier":"load earlier","approval.dismiss":"Dismiss","approval.implement":"Implement","ask.plan":"Proposed plan","bots.rooms":"Rooms","bots.tab.browser":"Browser","common.cancel":"Cancel","common.close":"Close","common.copy":"Copy","common.delete":"Delete","common.refresh":"Refresh","common.remove":"Remove","common.save":"Save","composer.placeholder":"Ask anything: @bot, >thread, %project, #room, $skill, /btw","composer.send":"Send","composer.stop":"Stop","gpui.acct.connected":"Connected","gpui.acct.not.connected":"Not connected","gpui.acct.sign.in.expired":"Sign-in expired","gpui.ask.plan.ready":"Ready for review","gpui.ask.plan.revise":"Revise","gpui.ask.plan.reviseph":"What should change in the plan?","gpui.ask.plan.sendrev":"Send revision","gpui.b.in.reply.to":"↩ In reply to: {quote}","gpui.b.replying.to":"↩ Replying to: {line}","gpui.bots.recall.off":"Off","gpui.bots.recall.on":"On","gpui.c.term.collapse":"Collapse","gpui.c.term.expand":"Expand","gpui.commands":"Commands","gpui.e.open.folder":"Open folder","gpui.filter.projects.and.threads":"Filter projects and threads","gpui.fold.or.unfold.the.sidebar":"Fold or unfold the sidebar","gpui.follow.paused":"Following paused","gpui.follow.wait":"Following: waiting for the agent's next edit","gpui.gerbers":"Gerbers","gpui.improvements":"Improvements","gpui.jump.to.a.thread.run":"Jump to a thread, run a command or find what was said","gpui.mgmt.bom.dnp":"DNP","gpui.mgmt.bom.nompn":"no MPN","gpui.mgmt.checks.all":"All","gpui.mgmt.checks.fix":"Fix with agent","gpui.mgmt.checks.run":"Run","gpui.mgmt.close":"Close the panel","gpui.mgmt.fab.apply":"Apply","gpui.mgmt.fab.changed":"Changed since you last looked","gpui.mgmt.fab.derived":"* worked out from the fab's page (a mil in mm, a ring from a diameter). Dimmed: the rigid board's value, where this board's page says nothing else. A date opens the page it was read from.","gpui.mgmt.fab.extra":"Costs more","gpui.mgmt.fab.findings":"Findings","gpui.mgmt.fab.free":"Base price","gpui.mgmt.fab.judge":"Datasheets","gpui.mgmt.fab.limit":"Limit","gpui.mgmt.fab.readcol":"Read","gpui.mgmt.fab.refresh":"Refresh","gpui.mgmt.fab.reviewbtn":"Review","gpui.mgmt.fab.seen":"Seen","gpui.mgmt.fab.thefab":"The fab","gpui.mgmt.fab.use":"Use","gpui.mgmt.life.nopart":"No reading of this part yet.","gpui.mgmt.life.reading":"Reading its history…","gpui.mgmt.plan.addnote":"Add note","gpui.mgmt.plan.all":"Approve all","gpui.mgmt.plan.before":"Plan before routing","gpui.mgmt.plan.compact":"Compact","gpui.mgmt.plan.done":"done","gpui.mgmt.plan.drawn":"The plan's corridors and planes are drawn on the board while this panel is open. Close it to hide them.","gpui.mgmt.plan.edited":"Edited","gpui.mgmt.plan.elsewhere":"A routing plan for {board} awaits your approval","gpui.mgmt.plan.emptysub":"Layers, corridors, and planes appear here once a plan is proposed.","gpui.mgmt.plan.expand":"Expand","gpui.mgmt.plan.fit":"Fit","gpui.mgmt.plan.grid.all":"All layers","gpui.mgmt.plan.grid.pair":"Side by side","gpui.mgmt.plan.grid.single":"Single","gpui.mgmt.plan.hide":"Hide done","gpui.mgmt.plan.hint":"Drag waypoints to steer · Click + on edge to insert · Right-click vertex to remove","gpui.mgmt.plan.keysnote":"On this KiCad version, approve from this panel: in plan view KiCad's A, R and W keys aren't the plan's yet (A opens Add Footprint). Update KiCad.","gpui.mgmt.plan.layer":"Approve layer","gpui.mgmt.plan.layer.short":"Layer","gpui.mgmt.plan.lock":"Lock","gpui.mgmt.plan.locked":"Locked","gpui.mgmt.plan.noboard":"No routing plan for this board.","gpui.mgmt.plan.noitems":"No corridors or planes on this layer","gpui.mgmt.plan.note.placeholder":"Steering note for router…","gpui.mgmt.plan.nothing":"Nothing awaits your approval","gpui.mgmt.plan.offwords":"Agents route as you ask. Turn it on to have them propose a routing plan first and route only what you approve here.","gpui.mgmt.plan.onwords":"Before routing a board with 4 or more copper layers or more than 60 nets, the agent proposes corridors and plane regions here. It routes only what you approve.","gpui.mgmt.plan.reading":"Reading the routing plan…","gpui.mgmt.plan.reference":"over {layer}","gpui.mgmt.plan.refused":"KiCad refused","gpui.mgmt.plan.reject":"Reject","gpui.mgmt.plan.rejectlayer":"Reject layer","gpui.mgmt.plan.reqplain":"Approval requested","gpui.mgmt.plan.requested":"Approval requested: {what}","gpui.mgmt.plan.saved":"saved plan","gpui.mgmt.plan.show":"Show done","gpui.mgmt.plan.st.approved":"Approved","gpui.mgmt.plan.st.awaiting":"Awaiting review","gpui.mgmt.plan.st.blocked":"Blocked","gpui.mgmt.plan.st.empty":"Empty","gpui.mgmt.plan.st.partial":"Partial","gpui.mgmt.plan.st.rejected":"Rejected","gpui.mgmt.plan.st.routed":"Routed","gpui.mgmt.plan.st.routing":"Routing","gpui.mgmt.plan.st.verified":"Verified","gpui.mgmt.plan.stackup.short":"Stackup","gpui.mgmt.plan.stop":"Stop routing","gpui.mgmt.plan.sync":"Link zoom","gpui.mgmt.plan.tab":"Plan","gpui.mgmt.plan.unlock":"Unlock","gpui.mgmt.plan.verify":"Verify","gpui.mgmt.plan.view.canvas":"Canvas","gpui.mgmt.plan.view.list":"List","gpui.mgmt.plan.view.split":"Split","gpui.mgmt.plan.width":"Width","gpui.next.thread":"Next thread","gpui.nothing.matches":"Nothing matches","gpui.planmode.bar.always":"Plan mode — explores and proposes a plan before editing","gpui.planmode.bar.executing":"Building the approved plan","gpui.planmode.bar.once":"Plan mode (1 turn) — explores and proposes a plan before editing","gpui.planmode.bar.pending":"Proposed plan awaits review below","gpui.planmode.bar.planning":"Planning — drafting a plan before edits","gpui.planmode.chip.building":"Building","gpui.planmode.chip.once":"Plan · 1t","gpui.planmode.scope.always":"Always","gpui.planmode.scope.once":"1 turn","gpui.planmode.tip":"Plan before acting (1 turn, always, or off)","gpui.planmode.top.executing":"Building plan","gpui.planmode.top.once":"Plan (1 turn)","gpui.planmode.top.pending":"Review plan","gpui.planmode.top.planning":"Planning","gpui.previous.thread":"Previous thread","gpui.rail.no.board":"No board in this project","gpui.rail.no.mech":"No mechanical parts in this project","gpui.rail.no.schematic":"No schematic in this project","gpui.rail.split.needs.both":"Split needs a board and a schematic","home.away":"Home ({name}) is away","home.away.queued":"Home ({name}) is away · {n} queued","home.away.since":"Home ({name}) is away since {time}","home.away.since.queued":"Home ({name}) is away since {time} · {n} queued","home.machine":"Home machine","home.move.failed":"Home move failed","home.move.failed.note":"Home move failed: {note}","home.move.here":"Make this machine the home","home.moving":"Moving home to {to}…","home.moving.step":"Moving home to {to}: {step}","hub.back.crash":"Backplane is back after it stopped unexpectedly","hub.restarting":"Restarting Backplane…","hub.restarting.build":"Restarting Backplane… (new build {build})","hub.stopped":"Backplane stopped","ios.hub.address.field":"Hub address","menu.pin":"Pin","menu.settle":"Settle","menu.unpin":"Unpin","model.col.agent":"Agent","notify.settled":"Settled","palette.archive":"Archive thread","palette.command.placeholder":"Type a command or a thread","palette.diff":"Diff: what this thread changed","palette.newthread":"New thread","palette.settings":"Settings","palette.terminal":"Terminal","palette.unarchive":"Unarchive thread","phone.unsettle":"Unsettle","provider.notice.button":"Open Settings → Accounts","provider.notice.head":"No AI provider connected","provider.notice.senderr":"No AI provider connected yet. Open Settings → Accounts to connect Claude, Codex, Antigravity, or another provider.","provider.notice.text.none":"Connect Claude, Codex, Antigravity, or another provider to start chatting.","provider.notice.text.signedout":"Sign in to Claude, Codex, or another provider in Settings → Accounts to start chatting.","reply.action":"Reply","reply.cancel":"Cancel reply","reply.to":"In reply to:","secret.you":"You","settings.lang":"Language","sheet.rename":"Rename thread","sidebar.add.project":"Add project","sidebar.search.projects":"Search projects","thread.context.base":"Backplane","thread.context.copied":"Prompt copied.","thread.context.copy":"Copy prompt","thread.context.disable":"Disable","thread.context.enable":"Enable","thread.context.index":"Available skills index","thread.context.injected.label":"Injected project instructions","thread.context.instructions":"Instructions","thread.context.mcp":"Project MCPs","thread.context.native.note":"Backplane’s launch prompt. Native files are loaded by the provider.","thread.context.none.instructions":"No project instructions found.","thread.context.none.mcp":"No project MCP configurations found.","thread.context.reading":"Reading thread context…","thread.context.size":"{bytes} B · ≈{tokens} tokens","thread.context.skills":"Skills","thread.context.system":"System Prompt","thread.context.title":"Context & Prompt","thread.context.trust":"Trust and enable","thread.new":"New thread","tools.pinned":"Pinned","tools.retry":"Retry","tour.title.bots":"Bots","viewer.board":"Board","viewer.diff":"Diff","viewer.files":"Files","viewer.mech":"Mech","viewer.review":"Review","viewer.schematic":"Schematic","viewer.solid":"3D","web.chat.answer.btn":"Answer","web.chat.answer.placeholder":"Type answer…","web.chat.answered":"Answered: {answer}","web.chat.choose":"Choose a project thread on the left to begin.","web.chat.empty":"No messages yet. Type below to start a turn.","web.chat.finished":"Finished {time}","web.chat.finished.dur":"Finished {time} · {dur}","web.chat.loading":"Loading messages…","web.chat.review.mode":"Review mode","web.chat.streaming":"Streaming…","web.clone.add.dir":"Add {dir}","web.clone.back":"Back","web.clone.change.folder":"Change folder","web.clone.cloned":"Cloned {repo} into {dest}","web.clone.cloning":"Cloning {repo} into {dest}","web.clone.copied":"Copied","web.clone.first":"First message: {text}","web.clone.folder.name":"Folder name","web.clone.go":"Clone","web.clone.loading":"Loading…","web.clone.no.folders":"No folders here","web.clone.open.project":"Open the project","web.clone.open.thread":"Open the thread","web.clone.private":"private","web.clone.repo.placeholder":"https or ssh URL, or owner/repo","web.clone.retry":"Try again","web.clone.same":"Already cloned there: it is added as it is.","web.clone.signin":"Sign in to GitHub","web.clone.signin.done":"Signed in to GitHub","web.clone.signin.enter":"Enter this code on GitHub:","web.clone.signin.wait":"Starting GitHub sign-in…","web.clone.start.thread":"Start a thread","web.clone.stopped":"Stopped cloning {repo}","web.clone.tab":"Clone from git","web.clone.up":"Up","web.clone.use.dir":"Use {dir}","web.composer.attach":"Attach image","web.composer.maximages":"At most {max} images per message.","web.composer.unsupported":"Unsupported image type: {type}","web.composer.voice":"Voice dictation","web.logout.failed":"Could not confirm sign-out. Try again.","web.pair.approve.in":"Approve on desktop or paired phone · expires in {time}","web.pair.approved":"Approved. Opening Backplane…","web.pair.cancelled":"Cancelled.","web.pair.code":"Comparison code","web.pair.denied":"Pairing request was denied.","web.pair.expired":"Pairing code expired. Request a new code to try again.","web.pair.failed":"Pairing request failed ({status})","web.pair.name":"Browser name","web.pair.nocode":"Hub did not return a comparison code.","web.pair.ratelimited":"Too many pairing attempts. Wait a moment and try again.","web.pair.request":"Request pairing","web.pair.requesting":"Requesting pairing code…","web.pair.subtitle":"Pair this browser with your hub. Approve the 6-digit code in Backplane › Settings › Devices.","web.pair.unreachable":"Could not reach the hub. Check your tailnet connection.","web.plan.awaiting":"{n} awaiting approval","web.plan.net.one":"1 net","web.plan.nets":"{n} nets","web.settings.providers":"AI providers","web.settings.providers.browser":"Connect a provider in the Backplane desktop or mobile app under Settings → Accounts."},es:{"agy.signout":"Cerrar sesión","android.hub.machines.approve":"Aprobar","android.load.earlier":"cargar anteriores","approval.dismiss":"Descartar","approval.implement":"Implementar","ask.plan":"Plan propuesto","bots.rooms":"Salas","bots.tab.browser":"Navegador","common.cancel":"Cancelar","common.close":"Cerrar","common.copy":"Copiar","common.delete":"Eliminar","common.refresh":"Actualizar","common.remove":"Quitar","common.save":"Guardar","composer.placeholder":"Pregunta lo que sea: @bot, >hilo, %proyecto, #sala, $skill, /btw","composer.send":"Enviar","composer.stop":"Detener","gpui.acct.connected":"Conectado","gpui.acct.not.connected":"No conectado","gpui.acct.sign.in.expired":"Sesión caducada","gpui.ask.plan.ready":"Listo para revisar","gpui.ask.plan.revise":"Revisar","gpui.ask.plan.reviseph":"¿Qué debería cambiar en el plan?","gpui.ask.plan.sendrev":"Enviar revisión","gpui.b.in.reply.to":"↩ En respuesta a: {quote}","gpui.b.replying.to":"↩ Respondiendo a: {line}","gpui.bots.recall.off":"Desactivado","gpui.bots.recall.on":"Activado","gpui.c.term.collapse":"Contraer","gpui.c.term.expand":"Expandir","gpui.commands":"Comandos","gpui.e.open.folder":"Abrir carpeta","gpui.filter.projects.and.threads":"Filtrar proyectos e hilos","gpui.fold.or.unfold.the.sidebar":"Plegar o desplegar la barra lateral","gpui.follow.paused":"Seguimiento en pausa","gpui.follow.wait":"Siguiendo: esperando la próxima edición del agente","gpui.gerbers":"Gerbers","gpui.improvements":"Mejoras","gpui.jump.to.a.thread.run":"Saltar a un hilo, ejecutar un comando o buscar lo dicho","gpui.mgmt.bom.dnp":"DNP","gpui.mgmt.bom.nompn":"sin MPN","gpui.mgmt.checks.all":"Todas","gpui.mgmt.checks.fix":"Corregir con agente","gpui.mgmt.checks.run":"Ejecutar","gpui.mgmt.close":"Cerrar el panel","gpui.mgmt.fab.apply":"Aplicar","gpui.mgmt.fab.changed":"Cambió desde la última vez que miraste","gpui.mgmt.fab.derived":"* calculado desde la página del fabricante (un mil en mm, un anillo desde un diámetro). Atenuado: el valor de la placa rígida, cuando la página de esta placa no dice otra cosa. Una fecha abre la página de la que se leyó.","gpui.mgmt.fab.extra":"Cuesta más","gpui.mgmt.fab.findings":"Hallazgos","gpui.mgmt.fab.free":"Precio base","gpui.mgmt.fab.judge":"Hojas de datos","gpui.mgmt.fab.limit":"Límite","gpui.mgmt.fab.readcol":"Leído","gpui.mgmt.fab.refresh":"Actualizar","gpui.mgmt.fab.reviewbtn":"Revisar","gpui.mgmt.fab.seen":"Visto","gpui.mgmt.fab.thefab":"El fabricante","gpui.mgmt.fab.use":"Usar","gpui.mgmt.life.nopart":"Sin lectura de esta pieza aún.","gpui.mgmt.life.reading":"Leyendo su historial…","gpui.mgmt.plan.addnote":"Añadir nota","gpui.mgmt.plan.all":"Aprobar todo","gpui.mgmt.plan.before":"Planificar antes de rutear","gpui.mgmt.plan.compact":"Compacto","gpui.mgmt.plan.done":"hecho","gpui.mgmt.plan.drawn":"Los corredores y planos del plan se dibujan en la placa mientras este panel está abierto. Ciérralo para ocultarlos.","gpui.mgmt.plan.edited":"Editado","gpui.mgmt.plan.elsewhere":"Un plan de ruteo para {board} espera tu aprobación","gpui.mgmt.plan.emptysub":"Las capas, corredores y planos aparecerán aquí cuando se proponga un plan.","gpui.mgmt.plan.expand":"Expandir","gpui.mgmt.plan.fit":"Ajustar","gpui.mgmt.plan.grid.all":"Todas las capas","gpui.mgmt.plan.grid.pair":"Lado a lado","gpui.mgmt.plan.grid.single":"Única","gpui.mgmt.plan.hide":"Ocultar hechos","gpui.mgmt.plan.hint":"Arrastra vértices para guiar · Clic en + del borde para insertar · Clic derecho en vértice para quitar","gpui.mgmt.plan.keysnote":"En esta versión de KiCad, aprueba desde este panel: en la vista de plan las teclas A, R y W de KiCad aún no son del plan (A abre Añadir Huella). Actualiza KiCad.","gpui.mgmt.plan.layer":"Aprobar capa","gpui.mgmt.plan.layer.short":"Capa","gpui.mgmt.plan.lock":"Bloquear","gpui.mgmt.plan.locked":"Bloqueado","gpui.mgmt.plan.noboard":"No hay plan de ruteo para esta placa.","gpui.mgmt.plan.noitems":"Sin corredores ni planos en esta capa","gpui.mgmt.plan.note.placeholder":"Nota de guiado para el router…","gpui.mgmt.plan.nothing":"Nada espera tu aprobación","gpui.mgmt.plan.offwords":"Los agentes rutean como les pidas. Actívalo para que primero propongan un plan de ruteo y ruteen solo lo que apruebes aquí.","gpui.mgmt.plan.onwords":"Antes de rutear una placa con 4 o más capas de cobre o más de 60 redes, el agente propone aquí corredores y regiones de plano. Solo rutea lo que apruebes.","gpui.mgmt.plan.reading":"Leyendo el plan de ruteo…","gpui.mgmt.plan.reference":"sobre {layer}","gpui.mgmt.plan.refused":"KiCad lo rechazó","gpui.mgmt.plan.reject":"Rechazar","gpui.mgmt.plan.rejectlayer":"Rechazar capa","gpui.mgmt.plan.reqplain":"Aprobación solicitada","gpui.mgmt.plan.requested":"Aprobación solicitada: {what}","gpui.mgmt.plan.saved":"plan guardado","gpui.mgmt.plan.show":"Mostrar hechos","gpui.mgmt.plan.st.approved":"Aprobado","gpui.mgmt.plan.st.awaiting":"Esperando revisión","gpui.mgmt.plan.st.blocked":"Bloqueado","gpui.mgmt.plan.st.empty":"Vacío","gpui.mgmt.plan.st.partial":"Parcial","gpui.mgmt.plan.st.rejected":"Rechazado","gpui.mgmt.plan.st.routed":"Ruteado","gpui.mgmt.plan.st.routing":"Ruteando","gpui.mgmt.plan.st.verified":"Verificado","gpui.mgmt.plan.stackup.short":"Apilamiento","gpui.mgmt.plan.stop":"Detener ruteo","gpui.mgmt.plan.sync":"Vincular zoom","gpui.mgmt.plan.tab":"Plan","gpui.mgmt.plan.unlock":"Desbloquear","gpui.mgmt.plan.verify":"Verificar","gpui.mgmt.plan.view.canvas":"Lienzo","gpui.mgmt.plan.view.list":"Lista","gpui.mgmt.plan.view.split":"Dividido","gpui.mgmt.plan.width":"Ancho","gpui.next.thread":"Hilo siguiente","gpui.nothing.matches":"Nada coincide","gpui.planmode.bar.always":"Modo plan — explora y propone un plan antes de editar","gpui.planmode.bar.executing":"Ejecutando el plan aprobado","gpui.planmode.bar.once":"Modo plan (1 turno) — explora y propone un plan antes de editar","gpui.planmode.bar.pending":"El plan propuesto espera revisión abajo","gpui.planmode.bar.planning":"Planificando — redactando un plan antes de editar","gpui.planmode.chip.building":"Ejecutando","gpui.planmode.chip.once":"Plan · 1t","gpui.planmode.scope.always":"Siempre","gpui.planmode.scope.once":"1 turno","gpui.planmode.tip":"Planificar antes de actuar (1 turno, siempre u off)","gpui.planmode.top.executing":"Ejecutando plan","gpui.planmode.top.once":"Plan (1 turno)","gpui.planmode.top.pending":"Revisar plan","gpui.planmode.top.planning":"Planificando","gpui.previous.thread":"Hilo anterior","gpui.rail.no.board":"Este proyecto no tiene placa","gpui.rail.no.mech":"Este proyecto no tiene piezas mecánicas","gpui.rail.no.schematic":"Este proyecto no tiene esquema","gpui.rail.split.needs.both":"La vista dividida requiere una placa y un esquema","home.away":"El inicio ({name}) no está disponible","home.away.queued":"El inicio ({name}) no está disponible · {n} en cola","home.away.since":"El inicio ({name}) no está disponible desde las {time}","home.away.since.queued":"El inicio ({name}) no está disponible desde las {time} · {n} en cola","home.machine":"Máquina de inicio","home.move.failed":"No se pudo mover el inicio","home.move.failed.note":"No se pudo mover el inicio: {note}","home.move.here":"Hacer de esta máquina el inicio","home.moving":"Moviendo el inicio a {to}…","home.moving.step":"Moviendo el inicio a {to}: {step}","hub.back.crash":"Backplane volvió tras detenerse de forma inesperada","hub.restarting":"Reiniciando Backplane…","hub.restarting.build":"Reiniciando Backplane… (nueva compilación {build})","hub.stopped":"Backplane se detuvo","ios.hub.address.field":"Dirección del hub","menu.pin":"Fijar","menu.settle":"Cerrar","menu.unpin":"Desfijar","model.col.agent":"Agente","notify.settled":"Cerrado","palette.archive":"Archivar hilo","palette.command.placeholder":"Escribe un comando o un hilo","palette.diff":"Diff: qué cambió este hilo","palette.newthread":"Nuevo hilo","palette.settings":"Ajustes","palette.terminal":"Terminal","palette.unarchive":"Desarchivar hilo","phone.unsettle":"Reabrir","provider.notice.button":"Abrir Configuración → Cuentas","provider.notice.head":"No hay ningún proveedor de IA conectado","provider.notice.senderr":"Aún no hay ningún proveedor de IA conectado. Abre Configuración → Cuentas para conectar Claude, Codex, Antigravity u otro proveedor.","provider.notice.text.none":"Conecta Claude, Codex, Antigravity u otro proveedor para empezar a chatear.","provider.notice.text.signedout":"Inicia sesión en Claude, Codex u otro proveedor en Configuración → Cuentas para empezar a chatear.","reply.action":"Responder","reply.cancel":"Cancelar respuesta","reply.to":"En respuesta a:","secret.you":"Tú","settings.lang":"Idioma","sheet.rename":"Renombrar hilo","sidebar.add.project":"Añadir proyecto","sidebar.search.projects":"Buscar proyectos","thread.context.base":"Backplane","thread.context.copied":"Se copiaron las instrucciones.","thread.context.copy":"Copiar instrucciones","thread.context.disable":"Desactivar","thread.context.enable":"Activar","thread.context.index":"Índice de habilidades disponibles","thread.context.injected.label":"Instrucciones del proyecto añadidas","thread.context.instructions":"Instrucciones","thread.context.mcp":"MCP del proyecto","thread.context.native.note":"Instrucciones de inicio de Backplane. El proveedor carga los archivos nativos.","thread.context.none.instructions":"No se encontraron instrucciones del proyecto.","thread.context.none.mcp":"No se encontraron configuraciones MCP del proyecto.","thread.context.reading":"Leyendo el contexto del hilo…","thread.context.size":"{bytes} B · ≈{tokens} tokens","thread.context.skills":"Habilidades","thread.context.system":"Instrucciones del sistema","thread.context.title":"Contexto e instrucciones","thread.context.trust":"Confiar y activar","thread.new":"Nuevo hilo","tools.pinned":"Fijado","tools.retry":"Reintentar","tour.title.bots":"Bots","viewer.board":"Placa","viewer.diff":"Diff","viewer.files":"Archivos","viewer.mech":"Mech","viewer.review":"Revisión","viewer.schematic":"Esquemático","viewer.solid":"3D","web.chat.answer.btn":"Responder","web.chat.answer.placeholder":"Escribe una respuesta…","web.chat.answered":"Respondido: {answer}","web.chat.choose":"Elige un hilo de proyecto a la izquierda para empezar.","web.chat.empty":"Aún no hay mensajes. Escribe abajo para iniciar un turno.","web.chat.finished":"Terminado {time}","web.chat.finished.dur":"Terminado {time} · {dur}","web.chat.loading":"Cargando mensajes…","web.chat.review.mode":"Modo de revisión","web.chat.streaming":"Transmitiendo…","web.clone.add.dir":"Añadir {dir}","web.clone.back":"Atrás","web.clone.change.folder":"Cambiar carpeta","web.clone.cloned":"{repo} clonado en {dest}","web.clone.cloning":"Clonando {repo} en {dest}","web.clone.copied":"Copiado","web.clone.first":"Primer mensaje: {text}","web.clone.folder.name":"Nombre de la carpeta","web.clone.go":"Clonar","web.clone.loading":"Cargando…","web.clone.no.folders":"No hay carpetas aquí","web.clone.open.project":"Abrir el proyecto","web.clone.open.thread":"Abrir el hilo","web.clone.private":"privado","web.clone.repo.placeholder":"URL https o ssh, o propietario/repositorio","web.clone.retry":"Reintentar","web.clone.same":"Ya está clonado ahí: se añade tal cual.","web.clone.signin":"Iniciar sesión en GitHub","web.clone.signin.done":"Sesión iniciada en GitHub","web.clone.signin.enter":"Introduce este código en GitHub:","web.clone.signin.wait":"Iniciando sesión en GitHub…","web.clone.start.thread":"Empezar un hilo","web.clone.stopped":"Se detuvo la clonación de {repo}","web.clone.tab":"Clonar desde git","web.clone.up":"Subir","web.clone.use.dir":"Usar {dir}","web.composer.attach":"Adjuntar imagen","web.composer.maximages":"Como máximo {max} imágenes por mensaje.","web.composer.unsupported":"Tipo de imagen no compatible: {type}","web.composer.voice":"Dictado por voz","web.logout.failed":"No se pudo confirmar el cierre de sesión. Inténtalo de nuevo.","web.pair.approve.in":"Aprueba en el escritorio o en un teléfono vinculado · caduca en {time}","web.pair.approved":"Aprobado. Abriendo Backplane…","web.pair.cancelled":"Cancelado.","web.pair.code":"Código de comparación","web.pair.denied":"Se rechazó la solicitud de vinculación.","web.pair.expired":"El código de vinculación caducó. Solicita uno nuevo para intentarlo otra vez.","web.pair.failed":"Falló la solicitud de vinculación ({status})","web.pair.name":"Nombre del navegador","web.pair.nocode":"El hub no devolvió un código de comparación.","web.pair.ratelimited":"Demasiados intentos de vinculación. Espera un momento e inténtalo de nuevo.","web.pair.request":"Solicitar vinculación","web.pair.requesting":"Solicitando código de vinculación…","web.pair.subtitle":"Vincula este navegador con tu hub. Aprueba el código de 6 dígitos en Backplane › Ajustes › Dispositivos.","web.pair.unreachable":"No se pudo conectar con el hub. Comprueba tu conexión de tailnet.","web.plan.awaiting":"{n} esperando aprobación","web.plan.net.one":"1 red","web.plan.nets":"{n} redes","web.settings.providers":"Proveedores de IA","web.settings.providers.browser":"Conecta un proveedor en la aplicación de escritorio o móvil de Backplane en Configuración → Cuentas."},ja:{"agy.signout":"サインアウト","android.hub.machines.approve":"承認","android.load.earlier":"以前のメッセージを読み込む","approval.dismiss":"閉じる","approval.implement":"実装","ask.plan":"提案されたプラン","bots.rooms":"ルーム","bots.tab.browser":"ブラウザ","common.cancel":"キャンセル","common.close":"閉じる","common.copy":"コピー","common.delete":"削除","common.refresh":"更新","common.remove":"削除","common.save":"保存","composer.placeholder":"何でも質問:@bot、>thread、%project、#room、$skill、/btw","composer.send":"送信","composer.stop":"停止","gpui.acct.connected":"接続済み","gpui.acct.not.connected":"未接続","gpui.acct.sign.in.expired":"サインインの期限切れ","gpui.ask.plan.ready":"確認待ち","gpui.ask.plan.revise":"修正","gpui.ask.plan.reviseph":"計画のどこを変更しますか?","gpui.ask.plan.sendrev":"修正を送る","gpui.b.in.reply.to":"↩ 返信先:{quote}","gpui.b.replying.to":"↩ 返信中:{line}","gpui.bots.recall.off":"オフ","gpui.bots.recall.on":"オン","gpui.c.term.collapse":"折りたたむ","gpui.c.term.expand":"展開","gpui.commands":"コマンド","gpui.e.open.folder":"フォルダを開く","gpui.filter.projects.and.threads":"プロジェクトとスレッドを絞り込む","gpui.fold.or.unfold.the.sidebar":"サイドバーを折りたたむ/開く","gpui.follow.paused":"追従を一時停止中","gpui.follow.wait":"追従中: エージェントの次の編集を待っています","gpui.gerbers":"ガーバー","gpui.improvements":"改善","gpui.jump.to.a.thread.run":"スレッドへ移動、コマンドを実行、または発言を検索","gpui.mgmt.bom.dnp":"実装しない","gpui.mgmt.bom.nompn":"MPNなし","gpui.mgmt.checks.all":"すべて","gpui.mgmt.checks.fix":"エージェントに直してもらう","gpui.mgmt.checks.run":"実行","gpui.mgmt.close":"パネルを閉じる","gpui.mgmt.fab.apply":"適用","gpui.mgmt.fab.changed":"前回見てから変わったところ","gpui.mgmt.fab.derived":"* 製造元のページから計算した値です(milをmmに、径からランドを)。薄い色の項目はリジッド基板の値です(この基板のページに記載がないもの)。日付を押すと読んだページが開きます。","gpui.mgmt.fab.extra":"追加料金","gpui.mgmt.fab.findings":"指摘","gpui.mgmt.fab.free":"基本料金","gpui.mgmt.fab.judge":"データシート","gpui.mgmt.fab.limit":"項目","gpui.mgmt.fab.readcol":"読んだ日","gpui.mgmt.fab.refresh":"再読み込み","gpui.mgmt.fab.reviewbtn":"レビュー","gpui.mgmt.fab.seen":"確認済み","gpui.mgmt.fab.thefab":"製造元","gpui.mgmt.fab.use":"使う","gpui.mgmt.life.nopart":"この部品の記録はまだありません。","gpui.mgmt.life.reading":"履歴を読んでいます…","gpui.mgmt.plan.addnote":"メモを追加","gpui.mgmt.plan.all":"すべて承認","gpui.mgmt.plan.before":"配線前に計画する","gpui.mgmt.plan.compact":"標準","gpui.mgmt.plan.done":"完了","gpui.mgmt.plan.drawn":"計画の配線経路とプレーンは、このパネルを開いている間だけ基板上に表示されます。閉じると消えます。","gpui.mgmt.plan.edited":"編集済み","gpui.mgmt.plan.elsewhere":"{board}の配線計画が承認を待っています","gpui.mgmt.plan.emptysub":"計画が提案されると、レイヤー・コリドー・ベタ領域がここに表示されます。","gpui.mgmt.plan.expand":"拡大","gpui.mgmt.plan.fit":"全体表示","gpui.mgmt.plan.grid.all":"全レイヤー","gpui.mgmt.plan.grid.pair":"並べて表示","gpui.mgmt.plan.grid.single":"単一","gpui.mgmt.plan.hide":"完了を隠す","gpui.mgmt.plan.hint":"頂点をドラッグして誘導 · 辺の + をクリックで追加 · 頂点を右クリックで削除","gpui.mgmt.plan.keysnote":"このバージョンのKiCadでは、このパネルから承認してください。プランビューでのKiCadのA・R・Wキーはまだ計画のものではありません(Aはフットプリントの追加を開きます)。KiCadを更新してください。","gpui.mgmt.plan.layer":"層を承認","gpui.mgmt.plan.layer.short":"レイヤー","gpui.mgmt.plan.lock":"ロック","gpui.mgmt.plan.locked":"ロック中","gpui.mgmt.plan.noboard":"この基板の配線計画はありません。","gpui.mgmt.plan.noitems":"このレイヤーにコリドーまたはプレーンがありません","gpui.mgmt.plan.note.placeholder":"ルーターへの指示メモ…","gpui.mgmt.plan.nothing":"承認待ちはありません","gpui.mgmt.plan.offwords":"エージェントは指示どおりに配線します。オンにすると、まず配線計画を提案し、ここで承認したものだけを配線します。","gpui.mgmt.plan.onwords":"銅箔層が4層以上、またはネットが60本を超える基板では、配線の前にエージェントがここで配線経路とプレーン領域を提案します。承認したものだけを配線します。","gpui.mgmt.plan.reading":"配線計画を読んでいます…","gpui.mgmt.plan.reference":"基準 {layer}","gpui.mgmt.plan.refused":"KiCad が拒否しました","gpui.mgmt.plan.reject":"却下","gpui.mgmt.plan.rejectlayer":"レイヤーを却下","gpui.mgmt.plan.reqplain":"承認が求められています","gpui.mgmt.plan.requested":"承認が求められています: {what}","gpui.mgmt.plan.saved":"保存された計画","gpui.mgmt.plan.show":"完了を表示","gpui.mgmt.plan.st.approved":"承認済み","gpui.mgmt.plan.st.awaiting":"承認待ち","gpui.mgmt.plan.st.blocked":"ブロック","gpui.mgmt.plan.st.empty":"空","gpui.mgmt.plan.st.partial":"一部完了","gpui.mgmt.plan.st.rejected":"却下","gpui.mgmt.plan.st.routed":"配線済み","gpui.mgmt.plan.st.routing":"配線中","gpui.mgmt.plan.st.verified":"検証済み","gpui.mgmt.plan.stackup.short":"スタックアップ","gpui.mgmt.plan.stop":"配線を止める","gpui.mgmt.plan.sync":"ズーム連動","gpui.mgmt.plan.tab":"計画","gpui.mgmt.plan.unlock":"ロック解除","gpui.mgmt.plan.verify":"検証","gpui.mgmt.plan.view.canvas":"キャンバス","gpui.mgmt.plan.view.list":"リスト","gpui.mgmt.plan.view.split":"分割","gpui.mgmt.plan.width":"幅","gpui.next.thread":"次のスレッド","gpui.nothing.matches":"一致するものはありません","gpui.planmode.bar.always":"計画モード — 編集前に調査して計画を提案します","gpui.planmode.bar.executing":"承認された計画を実行しています","gpui.planmode.bar.once":"計画モード (1回) — 編集前に調査して計画を提案します","gpui.planmode.bar.pending":"提案された計画が下のレビューを待っています","gpui.planmode.bar.planning":"計画中 — 編集前の計画を作成しています","gpui.planmode.chip.building":"実行中","gpui.planmode.chip.once":"計画 · 1回","gpui.planmode.scope.always":"常時","gpui.planmode.scope.once":"1回","gpui.planmode.tip":"実行前に計画を作成 (1回・常時・オフ)","gpui.planmode.top.executing":"計画を実行中","gpui.planmode.top.once":"計画 (1回)","gpui.planmode.top.pending":"計画を確認","gpui.planmode.top.planning":"計画中","gpui.previous.thread":"前のスレッド","gpui.rail.no.board":"このプロジェクトには基板がありません","gpui.rail.no.mech":"このプロジェクトには機械部品がありません","gpui.rail.no.schematic":"このプロジェクトには回路図がありません","gpui.rail.split.needs.both":"分割表示には基板と回路図が必要です","home.away":"ホーム({name})はオフラインです","home.away.queued":"ホーム({name})はオフラインです · {n} 件待機中","home.away.since":"ホーム({name})は {time} からオフラインです","home.away.since.queued":"ホーム({name})は {time} からオフラインです · {n} 件待機中","home.machine":"ホームマシン","home.move.failed":"ホームの移動に失敗しました","home.move.failed.note":"ホームの移動に失敗しました: {note}","home.move.here":"このマシンをホームにする","home.moving":"ホームを {to} へ移動中…","home.moving.step":"ホームを {to} へ移動中: {step}","hub.back.crash":"予期せず停止したBackplaneが戻りました","hub.restarting":"Backplaneを再起動しています…","hub.restarting.build":"Backplaneを再起動しています…(新しいビルド {build})","hub.stopped":"Backplaneは停止しました","ios.hub.address.field":"ハブのアドレス","menu.pin":"ピン留め","menu.settle":"完了","menu.unpin":"ピン留めを解除","model.col.agent":"エージェント","notify.settled":"完了","palette.archive":"スレッドをアーカイブ","palette.command.placeholder":"コマンドまたはスレッドを入力","palette.diff":"差分:このスレッドの変更","palette.newthread":"新しいスレッド","palette.settings":"設定","palette.terminal":"ターミナル","palette.unarchive":"スレッドのアーカイブを解除","phone.unsettle":"未完了に戻す","provider.notice.button":"設定 → アカウントを開く","provider.notice.head":"AI プロバイダーが接続されていません","provider.notice.senderr":"AI プロバイダーがまだ接続されていません。設定 → アカウントを開いて、Claude、Codex、Antigravity などのプロバイダーを接続してください。","provider.notice.text.none":"チャットを始めるには、Claude、Codex、Antigravity などのプロバイダーを接続してください。","provider.notice.text.signedout":"チャットを始めるには、設定 → アカウントで Claude、Codex などのプロバイダーにサインインしてください。","reply.action":"返信","reply.cancel":"返信をやめる","reply.to":"返信先:","secret.you":"あなた","settings.lang":"言語","sheet.rename":"スレッド名を変更","sidebar.add.project":"プロジェクトを追加","sidebar.search.projects":"プロジェクトを検索","thread.context.base":"Backplane","thread.context.copied":"プロンプトをコピーしました。","thread.context.copy":"プロンプトをコピー","thread.context.disable":"無効にする","thread.context.enable":"有効にする","thread.context.index":"利用可能なスキルの一覧","thread.context.injected.label":"追加されたプロジェクトの指示","thread.context.instructions":"指示","thread.context.mcp":"プロジェクトの MCP","thread.context.native.note":"Backplane が起動時に渡すプロンプトです。ネイティブファイルはプロバイダーが読み込みます。","thread.context.none.instructions":"プロジェクトの指示が見つかりません。","thread.context.none.mcp":"プロジェクトの MCP 設定が見つかりません。","thread.context.reading":"スレッドのコンテキストを読み込み中…","thread.context.size":"{bytes} B・約{tokens}トークン","thread.context.skills":"スキル","thread.context.system":"システムプロンプト","thread.context.title":"コンテキストとプロンプト","thread.context.trust":"承認して有効にする","thread.new":"新しいスレッド","tools.pinned":"固定中","tools.retry":"再試行","tour.title.bots":"ボット","viewer.board":"基板","viewer.diff":"差分","viewer.files":"ファイル","viewer.mech":"Mech","viewer.review":"レビュー","viewer.schematic":"回路図","viewer.solid":"3D","web.chat.answer.btn":"回答","web.chat.answer.placeholder":"回答を入力…","web.chat.answered":"回答済み: {answer}","web.chat.choose":"左側からプロジェクトのスレッドを選んで開始してください。","web.chat.empty":"まだメッセージはありません。下に入力して開始してください。","web.chat.finished":"完了 {time}","web.chat.finished.dur":"完了 {time} · {dur}","web.chat.loading":"メッセージを読み込んでいます…","web.chat.review.mode":"レビューモード","web.chat.streaming":"受信中…","web.clone.add.dir":"{dir} を追加","web.clone.back":"戻る","web.clone.change.folder":"フォルダを変更","web.clone.cloned":"{repo} を {dest} にクローンしました","web.clone.cloning":"{repo} を {dest} にクローン中","web.clone.copied":"コピーしました","web.clone.first":"最初のメッセージ: {text}","web.clone.folder.name":"フォルダ名","web.clone.go":"クローン","web.clone.loading":"読み込み中…","web.clone.no.folders":"フォルダがありません","web.clone.open.project":"プロジェクトを開く","web.clone.open.thread":"スレッドを開く","web.clone.private":"非公開","web.clone.repo.placeholder":"https / ssh の URL、または owner/repo","web.clone.retry":"もう一度","web.clone.same":"すでにそこにクローンされています: そのまま追加します。","web.clone.signin":"GitHub にサインイン","web.clone.signin.done":"GitHub にサインインしました","web.clone.signin.enter":"このコードを GitHub に入力してください:","web.clone.signin.wait":"GitHub のサインインを開始しています…","web.clone.start.thread":"スレッドを開始","web.clone.stopped":"{repo} のクローンを中止しました","web.clone.tab":"git からクローン","web.clone.up":"上へ","web.clone.use.dir":"{dir} を使う","web.composer.attach":"画像を添付","web.composer.maximages":"1 件のメッセージに添付できる画像は最大 {max} 枚です。","web.composer.unsupported":"未対応の画像形式です: {type}","web.composer.voice":"音声入力","web.logout.failed":"サインアウトを確認できませんでした。もう一度お試しください。","web.pair.approve.in":"デスクトップまたはペアリング済みの端末で承認してください · 有効期限 {time}","web.pair.approved":"承認されました。Backplane を開いています…","web.pair.cancelled":"キャンセルしました。","web.pair.code":"確認コード","web.pair.denied":"ペアリングのリクエストが拒否されました。","web.pair.expired":"ペアリングコードの有効期限が切れました。新しいコードをリクエストしてください。","web.pair.failed":"ペアリングのリクエストに失敗しました ({status})","web.pair.name":"ブラウザー名","web.pair.nocode":"ハブから確認コードが返されませんでした。","web.pair.ratelimited":"ペアリングの試行回数が多すぎます。しばらく待ってからやり直してください。","web.pair.request":"ペアリングをリクエスト","web.pair.requesting":"ペアリングコードをリクエストしています…","web.pair.subtitle":"このブラウザーをハブとペアリングします。Backplane › 設定 › デバイス で 6 桁のコードを承認してください。","web.pair.unreachable":"ハブに接続できませんでした。tailnet の接続を確認してください。","web.plan.awaiting":"{n} 件が承認待ち","web.plan.net.one":"1 ネット","web.plan.nets":"{n} ネット","web.settings.providers":"AI プロバイダー","web.settings.providers.browser":"Backplane のデスクトップまたはモバイルアプリの設定 → アカウントからプロバイダーを接続してください。"}};function Hn(e,t){if(!t)return e;return e.replace(/\{([a-zA-Z0-9_.-]+)\}/g,(n,i)=>Object.prototype.hasOwnProperty.call(t,i)?String(t[i]):n)}var ft=hs(),_t=new Set,qt=new Map;for(let[e,t]of Object.entries(gt.en||{}))if(typeof t==="string"&&!qt.has(t))qt.set(t,e);function hs(){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 Dn(){if(typeof document<"u"&&document.documentElement)document.documentElement.lang=ft}Dn();function Tt(e){return _t.add(e),()=>{_t.delete(e)}}function Fn(e){if(!e)return!1;let t=e.toLowerCase(),n=t.startsWith("ja")?"ja":t.startsWith("es")?"es":t.startsWith("en")?"en":"";if(!n)return!1;let i=n!==ft;if(ft=n,Dn(),i)for(let s of _t)s(ft);return i}function b(e,t,n){let s=(gt[ft]||gt.en||{})[e]??gt.en?.[e]??t??e;return Hn(s,n)}function pe(e){if(!e)return"";let t=qt.get(e);if(!t)return e;return b(t,e)}function J(e,t="",n=""){let i=document.createElement(e);if(t)i.className=t;if(n)i.textContent=n;return i}function Fe(e,t="",n){let i=J("button",t,e);if(i.type="button",n)i.addEventListener("click",n);return i}function bs(e){let t=e.replace(/[\\/]+$/,"");if(!t)return e||"/";let n=t.split(/[\\/]/);return n[n.length-1]||t}function gs(e,t){let n=e.includes("\\")&&!e.includes("/")?"\\":"/";return e.endsWith(n)?e+t:e+n+t}class Kt{hub;actionLabel;action;root;pathInput;upBtn;listEl;errEl;actBtn;path="";parent=null;gen=0;busy=!1;constructor(e,t,n,i=[]){this.hub=e;this.actionLabel=t;this.action=n;this.root=J("div","bp-fb"),this.root.setAttribute("data-testid","folder-browser");let s=J("div","bp-fb-head");this.upBtn=Fe("↑","bp-btn-ghost bp-fb-up",()=>{if(this.parent)this.go(this.parent)}),this.upBtn.title=b("web.clone.up","Up"),this.upBtn.setAttribute("aria-label",b("web.clone.up","Up")),this.pathInput=J("input","bp-input bp-fb-path"),this.pathInput.spellcheck=!1,this.pathInput.setAttribute("data-testid","folder-path"),this.pathInput.addEventListener("keydown",(a)=>{if(a.key==="Enter"){a.preventDefault();let o=this.pathInput.value.trim();if(o)this.go(o)}}),s.append(this.upBtn,this.pathInput),this.listEl=J("div","bp-fb-list"),this.errEl=J("div","bp-ap-err bp-hidden");let r=J("div","bp-ap-foot");this.actBtn=Fe("","primary",()=>{this.run()}),this.actBtn.setAttribute("data-testid","folder-act"),r.append(...i,this.actBtn),this.root.append(s,this.listEl,this.errEl,r)}currentPath(){return this.path}async go(e){let t=++this.gen;this.setError(""),this.listEl.replaceChildren(J("div","bp-fb-empty",b("web.clone.loading","Loading…")));try{let n=await this.hub.rpc("dirs.list",{path:e});if(t!==this.gen)return;this.path=n.path,this.parent=n.parent??null,this.render(n.dirs??[])}catch(n){if(t!==this.gen)return;this.setError(pe(n instanceof Error?n.message:String(n))),this.render(null)}}refreshLocale(){this.upBtn.title=b("web.clone.up","Up"),this.updateAct()}render(e){if(this.pathInput.value=this.path,this.upBtn.disabled=!this.parent,this.updateAct(),e===null){this.listEl.replaceChildren();return}if(e.length===0){this.listEl.replaceChildren(J("div","bp-fb-empty",b("web.clone.no.folders","No folders here")));return}let t=document.createDocumentFragment();for(let n of e){let i=Fe("","bp-fb-row",()=>{this.go(gs(this.path,n))});i.append(J("span","bp-fb-icon","▸"),J("span","bp-fb-name",n)),t.appendChild(i)}this.listEl.replaceChildren(t),this.listEl.scrollTop=0}updateAct(){this.actBtn.textContent=this.path?this.actionLabel(bs(this.path)):this.actionLabel("…"),this.actBtn.disabled=!this.path||this.busy}async run(){if(!this.path||this.busy)return;this.busy=!0,this.updateAct(),this.setError("");try{await this.action(this.path)}catch(e){this.setError(pe(e instanceof Error?e.message:String(e)))}finally{this.busy=!1,this.updateAct()}}setError(e){this.errEl.textContent=e,this.errEl.classList.toggle("bp-hidden",!e)}}class zt{container;host;backdrop=null;bodyEl=null;tabsEl=null;mode="folder";repoText="";repoValue="";firstText="";wantThread=!0;userParent="";nameText="";nameTouched=!1;dest=null;destGen=0;destPending=!1;destTimer=null;repos=null;reposGen=0;reposTimer=null;showSuggest=!1;suggestIdx=-1;startErr="";starting=!1;picking=!1;jobId="";job=null;specs=new Map;signin=null;copied=!1;repoInput=null;suggestEl=null;destEl=null;signinEl=null;cloneBtn=null;jobEl=null;constructor(e,t){this.container=e;this.host=t}isOpen(){return this.backdrop!==null}open(e={}){let t=this.host.hub.hasFeature("clone"),n=!e.repo&&Boolean(this.jobId)&&(!this.job||this.job.state==="running"||this.job.state==="done");if(!this.backdrop)this.build();if(!n)this.jobId="",this.job=null,this.resetForm();if(e.repo!==void 0||e.text!==void 0)this.repoText=(e.repo??"").trim(),this.repoValue="",this.firstText=(e.text??"").trim();if(this.mode=t&&(e.mode==="clone"||n)?"clone":"folder",this.render(),n){if(this.job)this.maybeGo(this.job);this.reconcile()}else if(this.mode==="clone"&&this.repoText)this.askDest()}reconcile(){let e=this.jobId;if(!e)return;this.host.hub.rpc("clone.status",{id:e}).then((t)=>this.apply(t)).catch(()=>{})}close(){if(this.reposTimer!==null)window.clearTimeout(this.reposTimer);if(this.destTimer!==null)window.clearTimeout(this.destTimer);this.reposTimer=null,this.destTimer=null,this.backdrop?.remove(),this.backdrop=null,this.bodyEl=null,this.tabsEl=null}escape(){if(this.picking){this.picking=!1,this.render();return}if(this.showSuggest){this.showSuggest=!1,this.renderSuggest();return}this.close()}refreshLocale(){if(this.backdrop)this.render()}handleFrame(e){if(e.k==="clone"){let t=e.clone;if(t)this.apply(t)}else if(e.k==="clone.repos"){if(this.isOpen()&&this.mode==="clone"&&!this.jobId)this.askRepos(0)}else if(e.k==="clone.signin"){if(!this.signin)return;let t=this.signin.state;if(this.signin=e.signin??null,this.signin?.state==="cancelled")this.signin=null;if(t!=="done"&&this.signin?.state==="done")this.askRepos(0);this.renderSignin()}}build(){let e=J("div","bp-modal-backdrop");e.setAttribute("data-testid","add-project");let t=J("div","bp-modal bp-ap"),n=J("div","bp-modal-head"),i=J("h2","",b("sidebar.add.project","Add project")),s=Fe("×","icon",()=>this.close());s.title=b("common.close","Close"),s.setAttribute("aria-label",b("common.close","Close")),n.append(i,s),this.tabsEl=J("div","bp-ap-tabs"),this.bodyEl=J("div","bp-modal-body bp-ap-body"),t.append(n,this.tabsEl,this.bodyEl),e.appendChild(t),e.addEventListener("mousedown",(r)=>{if(r.target===e)this.close()}),this.container.appendChild(e),this.backdrop=e}resetForm(){this.repoText="",this.repoValue="",this.firstText="",this.wantThread=!0,this.userParent="",this.nameText="",this.nameTouched=!1,this.dest=null,this.destPending=!1,this.repos=null,this.showSuggest=!1,this.suggestIdx=-1,this.startErr="",this.starting=!1,this.picking=!1,this.signin=null,this.copied=!1}render(){if(!this.bodyEl||!this.tabsEl||!this.backdrop)return;let e=this.backdrop.querySelector(".bp-modal-head h2");if(e)e.textContent=b("sidebar.add.project","Add project");if(this.renderTabs(),this.repoInput=null,this.suggestEl=null,this.destEl=null,this.signinEl=null,this.cloneBtn=null,this.jobEl=null,this.mode==="folder")this.renderFolder();else if(this.jobId&&this.job)this.renderJobView();else if(this.picking)this.renderPickParent();else this.renderCloneForm()}renderTabs(){if(!this.tabsEl)return;if(!this.host.hub.hasFeature("clone")){this.tabsEl.classList.add("bp-hidden");return}this.tabsEl.classList.remove("bp-hidden");let e=(t,n)=>{let i=Fe(n,"bp-ap-tab"+(this.mode===t?" on":""),()=>{if(this.mode===t)return;if(this.mode=t,this.render(),t==="clone"&&!this.jobId&&this.repos===null)this.askRepos(0)});return i.setAttribute("data-testid",`ap-tab-${t}`),i.setAttribute("aria-pressed",String(this.mode===t)),i};this.tabsEl.replaceChildren(e("folder",b("gpui.e.open.folder","Open folder")),e("clone",b("web.clone.tab","Clone from git")))}renderFolder(){let e=new Kt(this.host.hub,(t)=>b("web.clone.add.dir","Add {dir}",{dir:t}),async(t)=>{let n=await this.host.hub.rpc("project.add",{path:t},30000);if(this.close(),n.project)this.host.onProjectAdded(n.project)});this.bodyEl.replaceChildren(e.root),e.go("")}renderCloneForm(){let e=this.bodyEl,t=J("div","bp-ap-form"),n=J("div","bp-ap-repo"),i=J("input","bp-input");i.type="text",i.spellcheck=!1,i.autocomplete="off",i.placeholder=b("web.clone.repo.placeholder","https or ssh URL, or owner/repo"),i.setAttribute("aria-label",b("web.clone.repo.placeholder","https or ssh URL, or owner/repo")),i.setAttribute("data-testid","clone-repo"),i.value=this.repoText,i.addEventListener("input",()=>{if(this.repoText=i.value,this.repoValue="",this.showSuggest=!0,this.suggestIdx=-1,this.startErr="",!this.nameTouched)this.nameText="";this.askRepos(200),this.askDest(250)}),i.addEventListener("focus",()=>{if(this.showSuggest=!0,this.repos===null)this.askRepos(0);else this.renderSuggest()}),i.addEventListener("blur",()=>{window.setTimeout(()=>{if(document.activeElement!==i)this.showSuggest=!1,this.renderSuggest()},120)}),i.addEventListener("keydown",(u)=>this.repoKey(u)),this.repoInput=i,this.suggestEl=J("div","bp-ap-suggest bp-hidden"),this.suggestEl.setAttribute("data-testid","clone-suggest"),n.append(i,this.suggestEl),this.signinEl=J("div","bp-ap-signin bp-hidden"),this.signinEl.setAttribute("data-testid","clone-signin"),this.destEl=J("div","bp-ap-dest"),this.destEl.setAttribute("data-testid","clone-dest");let s=J("label","bp-ap-check"),r=J("input");r.type="checkbox",r.checked=this.wantThread,r.setAttribute("data-testid","clone-thread"),r.addEventListener("change",()=>{this.wantThread=r.checked}),s.append(r,J("span","",b("web.clone.start.thread","Start a thread")));let a=[n,this.signinEl,this.destEl,s];if(this.firstText)a.push(J("div","bp-ap-first bp-dim",b("web.clone.first","First message: {text}",{text:this.firstText})));let o=J("div","bp-ap-err"+(this.startErr?"":" bp-hidden"),this.startErr);o.setAttribute("data-testid","clone-start-error");let c=J("div","bp-ap-foot");this.cloneBtn=Fe(b("web.clone.go","Clone"),"primary",()=>{this.startClone()}),this.cloneBtn.setAttribute("data-testid","clone-go"),c.append(this.cloneBtn),a.push(o,c),t.append(...a),e.replaceChildren(t),this.renderSuggest(),this.renderSignin(),this.renderDest(),window.setTimeout(()=>{if(this.repoInput===i&&!this.repoText)i.focus()},0)}repoKey(e){let t=this.repos?.repos??[],n=this.showSuggest&&t.length>0;if(e.key==="ArrowDown"&&n)e.preventDefault(),this.suggestIdx=Math.min(t.length-1,this.suggestIdx+1),this.renderSuggest();else if(e.key==="ArrowUp"&&n)e.preventDefault(),this.suggestIdx=Math.max(-1,this.suggestIdx-1),this.renderSuggest();else if(e.key==="Enter"){e.preventDefault();let i=n&&this.suggestIdx>=0?t[this.suggestIdx]:void 0;if(i)this.pickRepo(i);else if(this.canStart())this.startClone()}}pickRepo(e){if(this.repoText=e.name,this.repoValue=e.value,this.showSuggest=!1,this.suggestIdx=-1,this.startErr="",!this.nameTouched)this.nameText="";if(this.repoInput)this.repoInput.value=e.name;this.renderSuggest(),this.askDest()}repoArg(){return this.repoValue||this.repoText.trim()}askRepos(e){if(this.reposTimer!==null)window.clearTimeout(this.reposTimer);this.reposTimer=window.setTimeout(()=>{this.reposTimer=null;let t=++this.reposGen,n=this.repoValue?"":this.repoText.trim();this.host.hub.rpc("clone.repos",{q:n,limit:12},30000).then((i)=>{if(t!==this.reposGen)return;this.repos=i,this.renderSuggest(),this.renderSignin()}).catch(()=>{if(t!==this.reposGen)return;this.repos={repos:[],state:"error",hint:"Couldn't list your GitHub repositories."},this.renderSuggest()})},e)}renderSuggest(){let e=this.suggestEl;if(!e)return;let t=this.repos,n=t?.repos??[],i=[];if(this.showSuggest&&!this.repoValue){if(n.forEach((s,r)=>{let a=Fe("","bp-ap-sug"+(r===this.suggestIdx?" active":""));a.setAttribute("data-testid","clone-suggestion"),a.addEventListener("mousedown",(c)=>c.preventDefault()),a.addEventListener("click",()=>this.pickRepo(s));let o=J("div","bp-ap-sug-top");if(o.append(J("span","bp-ap-sug-name",s.name)),s.private)o.append(J("span","bp-ap-tag",b("web.clone.private","private")));if(a.append(o),s.description)a.append(J("div","bp-ap-sug-desc",s.description));i.push(a)}),n.length===0&&t){if(t.loading)i.push(J("div","bp-ap-sug-note",b("web.clone.loading","Loading…")));else if(t.hint){let s=J("div","bp-ap-sug-note");if(s.append(J("span","",pe(t.hint))),t.state==="signedout"){let r=Fe(b("web.clone.signin","Sign in to GitHub"),"bp-btn-line",()=>{this.startSignin()});r.addEventListener("mousedown",(a)=>a.preventDefault()),r.setAttribute("data-testid","clone-signin-btn"),s.append(r)}i.push(s)}}}e.replaceChildren(...i),e.classList.toggle("bp-hidden",i.length===0)}askDest(e=0){if(this.destTimer!==null)window.clearTimeout(this.destTimer);this.destPending=!0,this.updateCloneBtn(),this.destTimer=window.setTimeout(()=>{this.destTimer=null;let t=++this.destGen,n=this.repoArg();if(!n){this.dest=null,this.destPending=!1,this.renderDest();return}let i={repo:n};if(this.userParent)i.parent=this.userParent;if(this.nameTouched&&this.nameText.trim())i.name=this.nameText.trim();else if(this.userParent)i.name="";this.host.hub.rpc("clone.dest",i).then((s)=>{if(t!==this.destGen)return;if(this.dest=s,this.destPending=!1,!this.nameTouched&&s.folder)this.nameText=s.folder;this.renderDest()}).catch((s)=>{if(t!==this.destGen)return;this.dest={ok:!1,error:s instanceof Error?s.message:String(s)},this.destPending=!1,this.renderDest()})},e)}renderDest(){let e=this.destEl;if(!e)return;let t=this.dest,n=[];if(t&&!t.repo){if(t.error&&this.repoText.trim())n.push(this.errLine(pe(t.error)))}else if(t){let a=J("div","bp-ap-where"),o=J("span","bp-ap-dest-path",t.destShown||t.dest||t.defaultParentShown||"");o.setAttribute("data-testid","clone-dest-shown");let c=Fe(b("web.clone.change.folder","Change folder"),"bp-btn-line",()=>{this.picking=!0,this.render()});c.setAttribute("data-testid","clone-change-folder"),a.append(o,c),n.push(a);let u=J("label","bp-ap-name");u.append(J("span","bp-ap-lbl",b("web.clone.folder.name","Folder name")));let l=J("input","bp-input");if(l.type="text",l.spellcheck=!1,l.value=this.nameText,l.setAttribute("data-testid","clone-name"),l.addEventListener("input",()=>{this.nameText=l.value,this.nameTouched=l.value.trim()!=="",this.startErr="",this.askDest(250)}),l.addEventListener("keydown",(p)=>{if(p.key==="Enter"&&this.canStart())p.preventDefault(),this.startClone()}),u.append(l),n.push(u),!t.ok&&t.error)n.push(this.errLine(pe(t.error)));else if(t.same)n.push(J("div","bp-ap-note bp-dim",b("web.clone.same","Already cloned there: it is added as it is.")))}let i=document.activeElement,s=i&&e.contains(i)&&i.getAttribute("data-testid")==="clone-name",r=s?i.selectionStart:null;if(e.replaceChildren(...n),e.classList.toggle("bp-hidden",n.length===0),s){let a=e.querySelector('[data-testid="clone-name"]');if(a){if(a.focus(),r!==null)a.setSelectionRange(r,r)}}this.updateCloneBtn()}errLine(e){let t=J("div","bp-ap-err",e);return t.setAttribute("data-testid","clone-dest-error"),t}canStart(){return Boolean(this.dest?.ok&&this.dest.repo&&!this.destPending&&!this.starting&&this.repoArg())}updateCloneBtn(){if(this.cloneBtn)this.cloneBtn.disabled=!this.canStart()}renderPickParent(){let e=this.dest?.parent||this.userParent||this.dest?.defaultParent||"",t=Fe(b("web.clone.back","Back"),"bp-btn-line",()=>{this.picking=!1,this.render()}),n=new Kt(this.host.hub,(i)=>b("web.clone.use.dir","Use {dir}",{dir:i}),async(i)=>{this.userParent=i,this.picking=!1,this.render(),this.askDest()},[t]);this.bodyEl.replaceChildren(n.root),n.go(e)}async startClone(){if(!this.canStart()||!this.dest)return;this.starting=!0,this.startErr="",this.updateCloneBtn();let e={repo:this.repoArg(),thread:this.wantThread,text:this.firstText},t=Wt();this.jobId=t,this.job=null,this.specs.set(t,e);try{let n=await this.host.hub.rpc("clone.start",{id:t,repo:e.repo,parent:this.dest.parent??"",name:this.dest.folder??this.nameText.trim(),thread:e.thread,text:e.text});this.starting=!1,this.apply(n)}catch(n){this.starting=!1;let i=pe(n instanceof Error?n.message:String(n));if(this.jobId===t&&!this.job){let s=await this.host.hub.rpc("clone.status",{id:t}).catch(()=>null);if(s&&s.id===t){this.apply(s);return}}if(this.jobId===t&&!this.job){if(this.jobId="",this.startErr=i,this.mode==="clone")this.render()}}}async retry(e,t){let n=this.specs.get(e.id)??{repo:e.origin||e.repo||"",thread:!0,text:""},i=Wt(),s=this.jobId;this.jobId=i,this.specs.set(i,n),t.disabled=!0;try{let r=await this.host.hub.rpc("clone.start",{id:i,repo:n.repo,dest:e.dest??"",thread:n.thread,text:n.text});this.apply(r)}catch(r){let a=pe(r instanceof Error?r.message:String(r));if(this.jobId!==i)return;if(!this.job||this.job.id!==i){let o=await this.host.hub.rpc("clone.status",{id:i}).catch(()=>null);if(o&&o.id===i){this.apply(o);return}}if(this.jobId===i&&(!this.job||this.job.id!==i))this.jobId=s,t.disabled=!1,this.showJobError(a)}}apply(e){if(!e||e.id!==this.jobId)return;if(!Rn(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&&jn(e))this.goTo(e)}renderJobView(){this.jobEl=J("div","bp-ap-job"),this.jobEl.setAttribute("data-testid","clone-job"),this.signinEl=J("div","bp-ap-signin bp-hidden"),this.signinEl.setAttribute("data-testid","clone-signin"),this.bodyEl.replaceChildren(this.jobEl,this.signinEl),this.renderJob(),this.renderSignin()}renderJob(){let e=this.jobEl,t=this.job;if(!e||!t)return;let n=t.destShown||t.dest||"",i=t.repo||"",s=t.state==="done"?b("web.clone.cloned","Cloned {repo} into {dest}",{repo:i,dest:n}):t.state==="cancelled"?b("web.clone.stopped","Stopped cloning {repo}",{repo:i}):b("web.clone.cloning","Cloning {repo} into {dest}",{repo:i,dest:n}),r=[J("div","bp-ap-job-title",s)];if(t.state==="running"){let a=J("div","bp-ap-phase",pe(t.phase||""));a.setAttribute("data-testid","clone-phase");let o=J("div","bp-ap-bar"+(typeof t.pct==="number"?"":" indeterminate")),c=J("div","bp-ap-bar-fill");if(typeof t.pct==="number")c.style.width=`${Math.max(0,Math.min(100,t.pct))}%`;if(o.appendChild(c),o.setAttribute("role","progressbar"),typeof t.pct==="number")o.setAttribute("aria-valuenow",String(t.pct));if(r.push(a,o),t.detail)r.push(J("div","bp-ap-detail bp-dim",t.detail));let u=J("div","bp-ap-foot"),l=Fe(b("common.cancel","Cancel"),"bp-btn-line",()=>{this.host.hub.rpc("clone.cancel",{id:t.id}).then((p)=>this.apply(p)).catch(()=>{})});l.setAttribute("data-testid","clone-cancel"),u.append(l),r.push(u)}else if(t.state==="failed"||t.state==="cancelled"){if(t.state==="failed"&&t.error){let u=J("div","bp-ap-err",pe(t.error));u.setAttribute("data-testid","clone-error"),r.push(u)}let a=J("div","bp-ap-foot"),o=Fe(b("web.clone.back","Back"),"bp-btn-line",()=>{this.jobId="",this.job=null,this.signin=null,this.render(),this.askDest()});if(a.append(o),t.signin){let u=Fe(b("web.clone.signin","Sign in to GitHub"),"bp-btn-line",()=>{this.startSignin()});u.setAttribute("data-testid","clone-signin-btn"),a.append(u)}let c=Fe(b("web.clone.retry","Try again"),"primary",()=>{this.retry(t,c)});c.setAttribute("data-testid","clone-retry"),a.append(c),r.push(a)}else if(t.state==="done"){let a=t.notes??[];if(a.length>0){let l=J("ul","bp-ap-notes");l.setAttribute("data-testid","clone-notes");for(let p of a)l.appendChild(J("li","",pe(p)));r.push(l)}let o=J("div","bp-ap-foot"),c=t.thread?b("web.clone.open.thread","Open the thread"):b("web.clone.open.project","Open the project"),u=Fe(c,"primary",()=>this.goTo(t));u.setAttribute("data-testid","clone-open"),o.append(u),r.push(o)}e.replaceChildren(...r)}showJobError(e){if(!this.jobEl)return;this.jobEl.querySelector(".bp-ap-job-err")?.remove();let t=J("div","bp-ap-err bp-ap-job-err",e);this.jobEl.appendChild(t)}goTo(e){this.jobId="",this.job=null,this.close(),this.host.onCloneDone(e)}async startSignin(){this.signin={state:"starting"},this.copied=!1,this.renderSignin();try{let e=await this.host.hub.rpc("clone.signin",{restart:!0},30000);if(!this.signin||this.signin.state==="starting")this.signin=e}catch(e){this.signin={state:"failed",error:e instanceof Error?e.message:String(e)}}if(this.signin?.state==="done")this.askRepos(0);this.renderSignin()}renderSignin(){let e=this.signinEl;if(!e)return;let t=this.signin,n=[];if(t&&t.state){if(t.state==="starting"||t.state==="waiting"&&!t.code)n.push(J("div","bp-dim",b("web.clone.signin.wait","Starting GitHub sign-in…")));else if(t.state==="waiting"){n.push(J("div","",b("web.clone.signin.enter","Enter this code on GitHub:")));let i=J("div","bp-ap-code-row"),s=J("span","bp-ap-code",t.code||"");s.setAttribute("data-testid","clone-signin-code");let r=Fe(this.copied?b("web.clone.copied","Copied"):b("common.copy","Copy"),"bp-btn-line",()=>{navigator.clipboard?.writeText(t.code||"").then(()=>{this.copied=!0,this.renderSignin()}).catch(()=>{})});if(i.append(s,r),n.push(i),t.url){let a=J("a","bp-ap-link",t.url);a.href=t.url,a.target="_blank",a.rel="noopener noreferrer",a.setAttribute("data-testid","clone-signin-url"),n.push(a)}}else if(t.state==="done")n.push(J("div","bp-ok",b("web.clone.signin.done","Signed in to GitHub")));else if(t.state==="failed")n.push(J("div","bp-ap-err",pe(t.error||"")))}e.replaceChildren(...n),e.classList.toggle("bp-hidden",n.length===0)}}function fs(e){try{let t=new URL(e,window.location.origin);if(t.protocol==="https:"||t.protocol==="http:")return t.href}catch{}return null}function vt(e,t){let n=/(`[^`]+`|\*\*[^*]+\*\*|\*[^*]+\*|\[([^\]]+)\]\(([^)]+)\))/g,i=0,s;while((s=n.exec(t))!==null){if(s.index>i)e.appendChild(document.createTextNode(t.slice(i,s.index)));let r=s[0];if(r.startsWith("`")&&r.endsWith("`")){let a=document.createElement("code");a.className="bp-code-inline",a.textContent=r.slice(1,-1),e.appendChild(a)}else if(r.startsWith("**")&&r.endsWith("**")){let a=document.createElement("strong");a.textContent=r.slice(2,-2),e.appendChild(a)}else if(r.startsWith("*")&&r.endsWith("*")){let a=document.createElement("em");a.textContent=r.slice(1,-1),e.appendChild(a)}else if(r.startsWith("[")){let a=s[2]??"",o=fs(s[3]??"");if(o){let c=document.createElement("a");c.href=o,c.target="_blank",c.rel="noopener noreferrer",c.textContent=a,e.appendChild(c)}else e.appendChild(document.createTextNode(a))}i=n.lastIndex}if(i=(e.ended??0)}function Hn(e){if(e.state!=="done")return!1;if(typeof e.hold==="boolean")return!e.hold;return(e.notes??[]).length===0}var gt={en:{"agy.signout":"Sign out","android.hub.machines.approve":"Approve","android.load.earlier":"load earlier","approval.dismiss":"Dismiss","approval.implement":"Implement","ask.plan":"Proposed plan","bots.rooms":"Rooms","bots.tab.browser":"Browser","common.cancel":"Cancel","common.close":"Close","common.copy":"Copy","common.delete":"Delete","common.refresh":"Refresh","common.remove":"Remove","common.save":"Save","composer.placeholder":"Ask anything: @bot, >thread, %project, #room, $skill, /btw","composer.send":"Send","composer.stop":"Stop","gpui.acct.connected":"Connected","gpui.acct.not.connected":"Not connected","gpui.acct.sign.in.expired":"Sign-in expired","gpui.ask.plan.ready":"Ready for review","gpui.ask.plan.revise":"Revise","gpui.ask.plan.reviseph":"What should change in the plan?","gpui.ask.plan.sendrev":"Send revision","gpui.b.in.reply.to":"↩ In reply to: {quote}","gpui.b.replying.to":"↩ Replying to: {line}","gpui.bots.recall.off":"Off","gpui.bots.recall.on":"On","gpui.c.term.collapse":"Collapse","gpui.c.term.expand":"Expand","gpui.commands":"Commands","gpui.e.open.folder":"Open folder","gpui.filter.projects.and.threads":"Filter projects and threads","gpui.fold.or.unfold.the.sidebar":"Fold or unfold the sidebar","gpui.follow.paused":"Following paused","gpui.follow.wait":"Following: waiting for the agent's next edit","gpui.gerbers":"Gerbers","gpui.improvements":"Improvements","gpui.jump.to.a.thread.run":"Jump to a thread, run a command or find what was said","gpui.mgmt.bom.dnp":"DNP","gpui.mgmt.bom.nompn":"no MPN","gpui.mgmt.checks.all":"All","gpui.mgmt.checks.fix":"Fix with agent","gpui.mgmt.checks.run":"Run","gpui.mgmt.close":"Close the panel","gpui.mgmt.fab.apply":"Apply","gpui.mgmt.fab.changed":"Changed since you last looked","gpui.mgmt.fab.derived":"* worked out from the fab's page (a mil in mm, a ring from a diameter). Dimmed: the rigid board's value, where this board's page says nothing else. A date opens the page it was read from.","gpui.mgmt.fab.extra":"Costs more","gpui.mgmt.fab.findings":"Findings","gpui.mgmt.fab.free":"Base price","gpui.mgmt.fab.judge":"Datasheets","gpui.mgmt.fab.limit":"Limit","gpui.mgmt.fab.readcol":"Read","gpui.mgmt.fab.refresh":"Refresh","gpui.mgmt.fab.reviewbtn":"Review","gpui.mgmt.fab.seen":"Seen","gpui.mgmt.fab.thefab":"The fab","gpui.mgmt.fab.use":"Use","gpui.mgmt.life.nopart":"No reading of this part yet.","gpui.mgmt.life.reading":"Reading its history…","gpui.mgmt.plan.addnote":"Add note","gpui.mgmt.plan.all":"Approve all","gpui.mgmt.plan.before":"Plan before routing","gpui.mgmt.plan.compact":"Compact","gpui.mgmt.plan.done":"done","gpui.mgmt.plan.drawn":"The plan's corridors and planes are drawn on the board while this panel is open. Close it to hide them.","gpui.mgmt.plan.edited":"Edited","gpui.mgmt.plan.elsewhere":"A routing plan for {board} awaits your approval","gpui.mgmt.plan.emptysub":"Layers, corridors, and planes appear here once a plan is proposed.","gpui.mgmt.plan.expand":"Expand","gpui.mgmt.plan.fit":"Fit","gpui.mgmt.plan.grid.all":"All layers","gpui.mgmt.plan.grid.pair":"Side by side","gpui.mgmt.plan.grid.single":"Single","gpui.mgmt.plan.hide":"Hide done","gpui.mgmt.plan.hint":"Drag waypoints to steer · Click + on edge to insert · Right-click vertex to remove","gpui.mgmt.plan.keysnote":"On this KiCad version, approve from this panel: in plan view KiCad's A, R and W keys aren't the plan's yet (A opens Add Footprint). Update KiCad.","gpui.mgmt.plan.layer":"Approve layer","gpui.mgmt.plan.layer.short":"Layer","gpui.mgmt.plan.lock":"Lock","gpui.mgmt.plan.locked":"Locked","gpui.mgmt.plan.noboard":"No routing plan for this board.","gpui.mgmt.plan.noitems":"No corridors or planes on this layer","gpui.mgmt.plan.note.placeholder":"Steering note for router…","gpui.mgmt.plan.nothing":"Nothing awaits your approval","gpui.mgmt.plan.offwords":"Agents route as you ask. Turn it on to have them propose a routing plan first and route only what you approve here.","gpui.mgmt.plan.onwords":"Before routing a board with 4 or more copper layers or more than 60 nets, the agent proposes corridors and plane regions here. It routes only what you approve.","gpui.mgmt.plan.reading":"Reading the routing plan…","gpui.mgmt.plan.reference":"over {layer}","gpui.mgmt.plan.refused":"KiCad refused","gpui.mgmt.plan.reject":"Reject","gpui.mgmt.plan.rejectlayer":"Reject layer","gpui.mgmt.plan.reqplain":"Approval requested","gpui.mgmt.plan.requested":"Approval requested: {what}","gpui.mgmt.plan.saved":"saved plan","gpui.mgmt.plan.show":"Show done","gpui.mgmt.plan.st.approved":"Approved","gpui.mgmt.plan.st.awaiting":"Awaiting review","gpui.mgmt.plan.st.blocked":"Blocked","gpui.mgmt.plan.st.empty":"Empty","gpui.mgmt.plan.st.partial":"Partial","gpui.mgmt.plan.st.rejected":"Rejected","gpui.mgmt.plan.st.routed":"Routed","gpui.mgmt.plan.st.routing":"Routing","gpui.mgmt.plan.st.verified":"Verified","gpui.mgmt.plan.stackup.short":"Stackup","gpui.mgmt.plan.stop":"Stop routing","gpui.mgmt.plan.sync":"Link zoom","gpui.mgmt.plan.tab":"Plan","gpui.mgmt.plan.unlock":"Unlock","gpui.mgmt.plan.verify":"Verify","gpui.mgmt.plan.view.canvas":"Canvas","gpui.mgmt.plan.view.list":"List","gpui.mgmt.plan.view.split":"Split","gpui.mgmt.plan.width":"Width","gpui.next.thread":"Next thread","gpui.nothing.matches":"Nothing matches","gpui.planmode.bar.always":"Plan mode — explores and proposes a plan before editing","gpui.planmode.bar.executing":"Building the approved plan","gpui.planmode.bar.once":"Plan mode (1 turn) — explores and proposes a plan before editing","gpui.planmode.bar.pending":"Proposed plan awaits review below","gpui.planmode.bar.planning":"Planning — drafting a plan before edits","gpui.planmode.chip.building":"Building","gpui.planmode.chip.once":"Plan · 1t","gpui.planmode.scope.always":"Always","gpui.planmode.scope.once":"1 turn","gpui.planmode.tip":"Plan before acting (1 turn, always, or off)","gpui.planmode.top.executing":"Building plan","gpui.planmode.top.once":"Plan (1 turn)","gpui.planmode.top.pending":"Review plan","gpui.planmode.top.planning":"Planning","gpui.previous.thread":"Previous thread","gpui.rail.no.board":"No board in this project","gpui.rail.no.mech":"No mechanical parts in this project","gpui.rail.no.schematic":"No schematic in this project","gpui.rail.split.needs.both":"Split needs a board and a schematic","home.away":"Home ({name}) is away","home.away.queued":"Home ({name}) is away · {n} queued","home.away.since":"Home ({name}) is away since {time}","home.away.since.queued":"Home ({name}) is away since {time} · {n} queued","home.machine":"Home machine","home.move.failed":"Home move failed","home.move.failed.note":"Home move failed: {note}","home.move.here":"Make this machine the home","home.moving":"Moving home to {to}…","home.moving.step":"Moving home to {to}: {step}","hub.back.crash":"Backplane is back after it stopped unexpectedly","hub.restarting":"Restarting Backplane…","hub.restarting.build":"Restarting Backplane… (new build {build})","hub.stopped":"Backplane stopped","ios.hub.address.field":"Hub address","menu.pin":"Pin","menu.settle":"Settle","menu.unpin":"Unpin","model.col.agent":"Agent","notify.settled":"Settled","palette.archive":"Archive thread","palette.command.placeholder":"Type a command or a thread","palette.diff":"Diff: what this thread changed","palette.newthread":"New thread","palette.settings":"Settings","palette.terminal":"Terminal","palette.unarchive":"Unarchive thread","phone.unsettle":"Unsettle","provider.notice.button":"Open Settings → Accounts","provider.notice.head":"No AI provider connected","provider.notice.senderr":"No AI provider connected yet. Open Settings → Accounts to connect Claude, Codex, Antigravity, or another provider.","provider.notice.senderr.remote":"No AI provider connected on {machine}. Open Settings → Accounts on {machine} to connect Claude, Codex, Antigravity, or another provider.","provider.notice.text.none":"Connect Claude, Codex, Antigravity, or another provider to start chatting.","provider.notice.text.signedout":"Sign in to Claude, Codex, or another provider in Settings → Accounts to start chatting.","reply.action":"Reply","reply.cancel":"Cancel reply","reply.to":"In reply to:","secret.you":"You","settings.lang":"Language","sheet.rename":"Rename thread","sidebar.add.project":"Add project","sidebar.search.projects":"Search projects","thread.context.base":"Backplane","thread.context.copied":"Prompt copied.","thread.context.copy":"Copy prompt","thread.context.disable":"Disable","thread.context.enable":"Enable","thread.context.index":"Available skills index","thread.context.injected.label":"Injected project instructions","thread.context.instructions":"Instructions","thread.context.mcp":"Project MCPs","thread.context.native.note":"Backplane’s launch prompt. Native files are loaded by the provider.","thread.context.none.instructions":"No project instructions found.","thread.context.none.mcp":"No project MCP configurations found.","thread.context.reading":"Reading thread context…","thread.context.size":"{bytes} B · ≈{tokens} tokens","thread.context.skills":"Skills","thread.context.system":"System Prompt","thread.context.title":"Context & Prompt","thread.context.trust":"Trust and enable","thread.new":"New thread","tools.pinned":"Pinned","tools.retry":"Retry","tour.title.bots":"Bots","viewer.board":"Board","viewer.diff":"Diff","viewer.files":"Files","viewer.mech":"Mech","viewer.review":"Review","viewer.schematic":"Schematic","viewer.solid":"3D","web.chat.answer.btn":"Answer","web.chat.answer.placeholder":"Type answer…","web.chat.answered":"Answered: {answer}","web.chat.choose":"Choose a project thread on the left to begin.","web.chat.empty":"No messages yet. Type below to start a turn.","web.chat.finished":"Finished {time}","web.chat.finished.dur":"Finished {time} · {dur}","web.chat.loading":"Loading messages…","web.chat.review.mode":"Review mode","web.chat.streaming":"Streaming…","web.clone.add.dir":"Add {dir}","web.clone.back":"Back","web.clone.change.folder":"Change folder","web.clone.cloned":"Cloned {repo} into {dest}","web.clone.cloning":"Cloning {repo} into {dest}","web.clone.copied":"Copied","web.clone.first":"First message: {text}","web.clone.folder.name":"Folder name","web.clone.go":"Clone","web.clone.loading":"Loading…","web.clone.no.folders":"No folders here","web.clone.open.project":"Open the project","web.clone.open.thread":"Open the thread","web.clone.private":"private","web.clone.repo.placeholder":"https or ssh URL, or owner/repo","web.clone.retry":"Try again","web.clone.same":"Already cloned there: it is added as it is.","web.clone.signin":"Sign in to GitHub","web.clone.signin.done":"Signed in to GitHub","web.clone.signin.enter":"Enter this code on GitHub:","web.clone.signin.wait":"Starting GitHub sign-in…","web.clone.start.thread":"Start a thread","web.clone.stopped":"Stopped cloning {repo}","web.clone.tab":"Clone from git","web.clone.up":"Up","web.clone.use.dir":"Use {dir}","web.composer.attach":"Attach image","web.composer.maximages":"At most {max} images per message.","web.composer.unsupported":"Unsupported image type: {type}","web.composer.voice":"Voice dictation","web.logout.failed":"Could not confirm sign-out. Try again.","web.pair.approve.in":"Approve on desktop or paired phone · expires in {time}","web.pair.approved":"Approved. Opening Backplane…","web.pair.cancelled":"Cancelled.","web.pair.code":"Comparison code","web.pair.denied":"Pairing request was denied.","web.pair.expired":"Pairing code expired. Request a new code to try again.","web.pair.failed":"Pairing request failed ({status})","web.pair.name":"Browser name","web.pair.nocode":"Hub did not return a comparison code.","web.pair.ratelimited":"Too many pairing attempts. Wait a moment and try again.","web.pair.request":"Request pairing","web.pair.requesting":"Requesting pairing code…","web.pair.subtitle":"Pair this browser with your hub. Approve the 6-digit code in Backplane › Settings › Devices.","web.pair.unreachable":"Could not reach the hub. Check your tailnet connection.","web.plan.awaiting":"{n} awaiting approval","web.plan.net.one":"1 net","web.plan.nets":"{n} nets","web.settings.providers":"AI providers","web.settings.providers.browser":"Connect a provider in the Backplane desktop or mobile app under Settings → Accounts."},es:{"agy.signout":"Cerrar sesión","android.hub.machines.approve":"Aprobar","android.load.earlier":"cargar anteriores","approval.dismiss":"Descartar","approval.implement":"Implementar","ask.plan":"Plan propuesto","bots.rooms":"Salas","bots.tab.browser":"Navegador","common.cancel":"Cancelar","common.close":"Cerrar","common.copy":"Copiar","common.delete":"Eliminar","common.refresh":"Actualizar","common.remove":"Quitar","common.save":"Guardar","composer.placeholder":"Pregunta lo que sea: @bot, >hilo, %proyecto, #sala, $skill, /btw","composer.send":"Enviar","composer.stop":"Detener","gpui.acct.connected":"Conectado","gpui.acct.not.connected":"No conectado","gpui.acct.sign.in.expired":"Sesión caducada","gpui.ask.plan.ready":"Listo para revisar","gpui.ask.plan.revise":"Revisar","gpui.ask.plan.reviseph":"¿Qué debería cambiar en el plan?","gpui.ask.plan.sendrev":"Enviar revisión","gpui.b.in.reply.to":"↩ En respuesta a: {quote}","gpui.b.replying.to":"↩ Respondiendo a: {line}","gpui.bots.recall.off":"Desactivado","gpui.bots.recall.on":"Activado","gpui.c.term.collapse":"Contraer","gpui.c.term.expand":"Expandir","gpui.commands":"Comandos","gpui.e.open.folder":"Abrir carpeta","gpui.filter.projects.and.threads":"Filtrar proyectos e hilos","gpui.fold.or.unfold.the.sidebar":"Plegar o desplegar la barra lateral","gpui.follow.paused":"Seguimiento en pausa","gpui.follow.wait":"Siguiendo: esperando la próxima edición del agente","gpui.gerbers":"Gerbers","gpui.improvements":"Mejoras","gpui.jump.to.a.thread.run":"Saltar a un hilo, ejecutar un comando o buscar lo dicho","gpui.mgmt.bom.dnp":"DNP","gpui.mgmt.bom.nompn":"sin MPN","gpui.mgmt.checks.all":"Todas","gpui.mgmt.checks.fix":"Corregir con agente","gpui.mgmt.checks.run":"Ejecutar","gpui.mgmt.close":"Cerrar el panel","gpui.mgmt.fab.apply":"Aplicar","gpui.mgmt.fab.changed":"Cambió desde la última vez que miraste","gpui.mgmt.fab.derived":"* calculado desde la página del fabricante (un mil en mm, un anillo desde un diámetro). Atenuado: el valor de la placa rígida, cuando la página de esta placa no dice otra cosa. Una fecha abre la página de la que se leyó.","gpui.mgmt.fab.extra":"Cuesta más","gpui.mgmt.fab.findings":"Hallazgos","gpui.mgmt.fab.free":"Precio base","gpui.mgmt.fab.judge":"Hojas de datos","gpui.mgmt.fab.limit":"Límite","gpui.mgmt.fab.readcol":"Leído","gpui.mgmt.fab.refresh":"Actualizar","gpui.mgmt.fab.reviewbtn":"Revisar","gpui.mgmt.fab.seen":"Visto","gpui.mgmt.fab.thefab":"El fabricante","gpui.mgmt.fab.use":"Usar","gpui.mgmt.life.nopart":"Sin lectura de esta pieza aún.","gpui.mgmt.life.reading":"Leyendo su historial…","gpui.mgmt.plan.addnote":"Añadir nota","gpui.mgmt.plan.all":"Aprobar todo","gpui.mgmt.plan.before":"Planificar antes de rutear","gpui.mgmt.plan.compact":"Compacto","gpui.mgmt.plan.done":"hecho","gpui.mgmt.plan.drawn":"Los corredores y planos del plan se dibujan en la placa mientras este panel está abierto. Ciérralo para ocultarlos.","gpui.mgmt.plan.edited":"Editado","gpui.mgmt.plan.elsewhere":"Un plan de ruteo para {board} espera tu aprobación","gpui.mgmt.plan.emptysub":"Las capas, corredores y planos aparecerán aquí cuando se proponga un plan.","gpui.mgmt.plan.expand":"Expandir","gpui.mgmt.plan.fit":"Ajustar","gpui.mgmt.plan.grid.all":"Todas las capas","gpui.mgmt.plan.grid.pair":"Lado a lado","gpui.mgmt.plan.grid.single":"Única","gpui.mgmt.plan.hide":"Ocultar hechos","gpui.mgmt.plan.hint":"Arrastra vértices para guiar · Clic en + del borde para insertar · Clic derecho en vértice para quitar","gpui.mgmt.plan.keysnote":"En esta versión de KiCad, aprueba desde este panel: en la vista de plan las teclas A, R y W de KiCad aún no son del plan (A abre Añadir Huella). Actualiza KiCad.","gpui.mgmt.plan.layer":"Aprobar capa","gpui.mgmt.plan.layer.short":"Capa","gpui.mgmt.plan.lock":"Bloquear","gpui.mgmt.plan.locked":"Bloqueado","gpui.mgmt.plan.noboard":"No hay plan de ruteo para esta placa.","gpui.mgmt.plan.noitems":"Sin corredores ni planos en esta capa","gpui.mgmt.plan.note.placeholder":"Nota de guiado para el router…","gpui.mgmt.plan.nothing":"Nada espera tu aprobación","gpui.mgmt.plan.offwords":"Los agentes rutean como les pidas. Actívalo para que primero propongan un plan de ruteo y ruteen solo lo que apruebes aquí.","gpui.mgmt.plan.onwords":"Antes de rutear una placa con 4 o más capas de cobre o más de 60 redes, el agente propone aquí corredores y regiones de plano. Solo rutea lo que apruebes.","gpui.mgmt.plan.reading":"Leyendo el plan de ruteo…","gpui.mgmt.plan.reference":"sobre {layer}","gpui.mgmt.plan.refused":"KiCad lo rechazó","gpui.mgmt.plan.reject":"Rechazar","gpui.mgmt.plan.rejectlayer":"Rechazar capa","gpui.mgmt.plan.reqplain":"Aprobación solicitada","gpui.mgmt.plan.requested":"Aprobación solicitada: {what}","gpui.mgmt.plan.saved":"plan guardado","gpui.mgmt.plan.show":"Mostrar hechos","gpui.mgmt.plan.st.approved":"Aprobado","gpui.mgmt.plan.st.awaiting":"Esperando revisión","gpui.mgmt.plan.st.blocked":"Bloqueado","gpui.mgmt.plan.st.empty":"Vacío","gpui.mgmt.plan.st.partial":"Parcial","gpui.mgmt.plan.st.rejected":"Rechazado","gpui.mgmt.plan.st.routed":"Ruteado","gpui.mgmt.plan.st.routing":"Ruteando","gpui.mgmt.plan.st.verified":"Verificado","gpui.mgmt.plan.stackup.short":"Apilamiento","gpui.mgmt.plan.stop":"Detener ruteo","gpui.mgmt.plan.sync":"Vincular zoom","gpui.mgmt.plan.tab":"Plan","gpui.mgmt.plan.unlock":"Desbloquear","gpui.mgmt.plan.verify":"Verificar","gpui.mgmt.plan.view.canvas":"Lienzo","gpui.mgmt.plan.view.list":"Lista","gpui.mgmt.plan.view.split":"Dividido","gpui.mgmt.plan.width":"Ancho","gpui.next.thread":"Hilo siguiente","gpui.nothing.matches":"Nada coincide","gpui.planmode.bar.always":"Modo plan — explora y propone un plan antes de editar","gpui.planmode.bar.executing":"Ejecutando el plan aprobado","gpui.planmode.bar.once":"Modo plan (1 turno) — explora y propone un plan antes de editar","gpui.planmode.bar.pending":"El plan propuesto espera revisión abajo","gpui.planmode.bar.planning":"Planificando — redactando un plan antes de editar","gpui.planmode.chip.building":"Ejecutando","gpui.planmode.chip.once":"Plan · 1t","gpui.planmode.scope.always":"Siempre","gpui.planmode.scope.once":"1 turno","gpui.planmode.tip":"Planificar antes de actuar (1 turno, siempre u off)","gpui.planmode.top.executing":"Ejecutando plan","gpui.planmode.top.once":"Plan (1 turno)","gpui.planmode.top.pending":"Revisar plan","gpui.planmode.top.planning":"Planificando","gpui.previous.thread":"Hilo anterior","gpui.rail.no.board":"Este proyecto no tiene placa","gpui.rail.no.mech":"Este proyecto no tiene piezas mecánicas","gpui.rail.no.schematic":"Este proyecto no tiene esquema","gpui.rail.split.needs.both":"La vista dividida requiere una placa y un esquema","home.away":"El inicio ({name}) no está disponible","home.away.queued":"El inicio ({name}) no está disponible · {n} en cola","home.away.since":"El inicio ({name}) no está disponible desde las {time}","home.away.since.queued":"El inicio ({name}) no está disponible desde las {time} · {n} en cola","home.machine":"Máquina de inicio","home.move.failed":"No se pudo mover el inicio","home.move.failed.note":"No se pudo mover el inicio: {note}","home.move.here":"Hacer de esta máquina el inicio","home.moving":"Moviendo el inicio a {to}…","home.moving.step":"Moviendo el inicio a {to}: {step}","hub.back.crash":"Backplane volvió tras detenerse de forma inesperada","hub.restarting":"Reiniciando Backplane…","hub.restarting.build":"Reiniciando Backplane… (nueva compilación {build})","hub.stopped":"Backplane se detuvo","ios.hub.address.field":"Dirección del hub","menu.pin":"Fijar","menu.settle":"Cerrar","menu.unpin":"Desfijar","model.col.agent":"Agente","notify.settled":"Cerrado","palette.archive":"Archivar hilo","palette.command.placeholder":"Escribe un comando o un hilo","palette.diff":"Diff: qué cambió este hilo","palette.newthread":"Nuevo hilo","palette.settings":"Ajustes","palette.terminal":"Terminal","palette.unarchive":"Desarchivar hilo","phone.unsettle":"Reabrir","provider.notice.button":"Abrir Configuración → Cuentas","provider.notice.head":"No hay ningún proveedor de IA conectado","provider.notice.senderr":"Aún no hay ningún proveedor de IA conectado. Abre Configuración → Cuentas para conectar Claude, Codex, Antigravity u otro proveedor.","provider.notice.senderr.remote":"No hay ningún proveedor de IA conectado en {machine}. Abre Configuración → Cuentas en {machine} para conectar Claude, Codex, Antigravity u otro proveedor.","provider.notice.text.none":"Conecta Claude, Codex, Antigravity u otro proveedor para empezar a chatear.","provider.notice.text.signedout":"Inicia sesión en Claude, Codex u otro proveedor en Configuración → Cuentas para empezar a chatear.","reply.action":"Responder","reply.cancel":"Cancelar respuesta","reply.to":"En respuesta a:","secret.you":"Tú","settings.lang":"Idioma","sheet.rename":"Renombrar hilo","sidebar.add.project":"Añadir proyecto","sidebar.search.projects":"Buscar proyectos","thread.context.base":"Backplane","thread.context.copied":"Se copiaron las instrucciones.","thread.context.copy":"Copiar instrucciones","thread.context.disable":"Desactivar","thread.context.enable":"Activar","thread.context.index":"Índice de habilidades disponibles","thread.context.injected.label":"Instrucciones del proyecto añadidas","thread.context.instructions":"Instrucciones","thread.context.mcp":"MCP del proyecto","thread.context.native.note":"Instrucciones de inicio de Backplane. El proveedor carga los archivos nativos.","thread.context.none.instructions":"No se encontraron instrucciones del proyecto.","thread.context.none.mcp":"No se encontraron configuraciones MCP del proyecto.","thread.context.reading":"Leyendo el contexto del hilo…","thread.context.size":"{bytes} B · ≈{tokens} tokens","thread.context.skills":"Habilidades","thread.context.system":"Instrucciones del sistema","thread.context.title":"Contexto e instrucciones","thread.context.trust":"Confiar y activar","thread.new":"Nuevo hilo","tools.pinned":"Fijado","tools.retry":"Reintentar","tour.title.bots":"Bots","viewer.board":"Placa","viewer.diff":"Diff","viewer.files":"Archivos","viewer.mech":"Mech","viewer.review":"Revisión","viewer.schematic":"Esquemático","viewer.solid":"3D","web.chat.answer.btn":"Responder","web.chat.answer.placeholder":"Escribe una respuesta…","web.chat.answered":"Respondido: {answer}","web.chat.choose":"Elige un hilo de proyecto a la izquierda para empezar.","web.chat.empty":"Aún no hay mensajes. Escribe abajo para iniciar un turno.","web.chat.finished":"Terminado {time}","web.chat.finished.dur":"Terminado {time} · {dur}","web.chat.loading":"Cargando mensajes…","web.chat.review.mode":"Modo de revisión","web.chat.streaming":"Transmitiendo…","web.clone.add.dir":"Añadir {dir}","web.clone.back":"Atrás","web.clone.change.folder":"Cambiar carpeta","web.clone.cloned":"{repo} clonado en {dest}","web.clone.cloning":"Clonando {repo} en {dest}","web.clone.copied":"Copiado","web.clone.first":"Primer mensaje: {text}","web.clone.folder.name":"Nombre de la carpeta","web.clone.go":"Clonar","web.clone.loading":"Cargando…","web.clone.no.folders":"No hay carpetas aquí","web.clone.open.project":"Abrir el proyecto","web.clone.open.thread":"Abrir el hilo","web.clone.private":"privado","web.clone.repo.placeholder":"URL https o ssh, o propietario/repositorio","web.clone.retry":"Reintentar","web.clone.same":"Ya está clonado ahí: se añade tal cual.","web.clone.signin":"Iniciar sesión en GitHub","web.clone.signin.done":"Sesión iniciada en GitHub","web.clone.signin.enter":"Introduce este código en GitHub:","web.clone.signin.wait":"Iniciando sesión en GitHub…","web.clone.start.thread":"Empezar un hilo","web.clone.stopped":"Se detuvo la clonación de {repo}","web.clone.tab":"Clonar desde git","web.clone.up":"Subir","web.clone.use.dir":"Usar {dir}","web.composer.attach":"Adjuntar imagen","web.composer.maximages":"Como máximo {max} imágenes por mensaje.","web.composer.unsupported":"Tipo de imagen no compatible: {type}","web.composer.voice":"Dictado por voz","web.logout.failed":"No se pudo confirmar el cierre de sesión. Inténtalo de nuevo.","web.pair.approve.in":"Aprueba en el escritorio o en un teléfono vinculado · caduca en {time}","web.pair.approved":"Aprobado. Abriendo Backplane…","web.pair.cancelled":"Cancelado.","web.pair.code":"Código de comparación","web.pair.denied":"Se rechazó la solicitud de vinculación.","web.pair.expired":"El código de vinculación caducó. Solicita uno nuevo para intentarlo otra vez.","web.pair.failed":"Falló la solicitud de vinculación ({status})","web.pair.name":"Nombre del navegador","web.pair.nocode":"El hub no devolvió un código de comparación.","web.pair.ratelimited":"Demasiados intentos de vinculación. Espera un momento e inténtalo de nuevo.","web.pair.request":"Solicitar vinculación","web.pair.requesting":"Solicitando código de vinculación…","web.pair.subtitle":"Vincula este navegador con tu hub. Aprueba el código de 6 dígitos en Backplane › Ajustes › Dispositivos.","web.pair.unreachable":"No se pudo conectar con el hub. Comprueba tu conexión de tailnet.","web.plan.awaiting":"{n} esperando aprobación","web.plan.net.one":"1 red","web.plan.nets":"{n} redes","web.settings.providers":"Proveedores de IA","web.settings.providers.browser":"Conecta un proveedor en la aplicación de escritorio o móvil de Backplane en Configuración → Cuentas."},ja:{"agy.signout":"サインアウト","android.hub.machines.approve":"承認","android.load.earlier":"以前のメッセージを読み込む","approval.dismiss":"閉じる","approval.implement":"実装","ask.plan":"提案されたプラン","bots.rooms":"ルーム","bots.tab.browser":"ブラウザ","common.cancel":"キャンセル","common.close":"閉じる","common.copy":"コピー","common.delete":"削除","common.refresh":"更新","common.remove":"削除","common.save":"保存","composer.placeholder":"何でも質問:@bot、>thread、%project、#room、$skill、/btw","composer.send":"送信","composer.stop":"停止","gpui.acct.connected":"接続済み","gpui.acct.not.connected":"未接続","gpui.acct.sign.in.expired":"サインインの期限切れ","gpui.ask.plan.ready":"確認待ち","gpui.ask.plan.revise":"修正","gpui.ask.plan.reviseph":"計画のどこを変更しますか?","gpui.ask.plan.sendrev":"修正を送る","gpui.b.in.reply.to":"↩ 返信先:{quote}","gpui.b.replying.to":"↩ 返信中:{line}","gpui.bots.recall.off":"オフ","gpui.bots.recall.on":"オン","gpui.c.term.collapse":"折りたたむ","gpui.c.term.expand":"展開","gpui.commands":"コマンド","gpui.e.open.folder":"フォルダを開く","gpui.filter.projects.and.threads":"プロジェクトとスレッドを絞り込む","gpui.fold.or.unfold.the.sidebar":"サイドバーを折りたたむ/開く","gpui.follow.paused":"追従を一時停止中","gpui.follow.wait":"追従中: エージェントの次の編集を待っています","gpui.gerbers":"ガーバー","gpui.improvements":"改善","gpui.jump.to.a.thread.run":"スレッドへ移動、コマンドを実行、または発言を検索","gpui.mgmt.bom.dnp":"実装しない","gpui.mgmt.bom.nompn":"MPNなし","gpui.mgmt.checks.all":"すべて","gpui.mgmt.checks.fix":"エージェントに直してもらう","gpui.mgmt.checks.run":"実行","gpui.mgmt.close":"パネルを閉じる","gpui.mgmt.fab.apply":"適用","gpui.mgmt.fab.changed":"前回見てから変わったところ","gpui.mgmt.fab.derived":"* 製造元のページから計算した値です(milをmmに、径からランドを)。薄い色の項目はリジッド基板の値です(この基板のページに記載がないもの)。日付を押すと読んだページが開きます。","gpui.mgmt.fab.extra":"追加料金","gpui.mgmt.fab.findings":"指摘","gpui.mgmt.fab.free":"基本料金","gpui.mgmt.fab.judge":"データシート","gpui.mgmt.fab.limit":"項目","gpui.mgmt.fab.readcol":"読んだ日","gpui.mgmt.fab.refresh":"再読み込み","gpui.mgmt.fab.reviewbtn":"レビュー","gpui.mgmt.fab.seen":"確認済み","gpui.mgmt.fab.thefab":"製造元","gpui.mgmt.fab.use":"使う","gpui.mgmt.life.nopart":"この部品の記録はまだありません。","gpui.mgmt.life.reading":"履歴を読んでいます…","gpui.mgmt.plan.addnote":"メモを追加","gpui.mgmt.plan.all":"すべて承認","gpui.mgmt.plan.before":"配線前に計画する","gpui.mgmt.plan.compact":"標準","gpui.mgmt.plan.done":"完了","gpui.mgmt.plan.drawn":"計画の配線経路とプレーンは、このパネルを開いている間だけ基板上に表示されます。閉じると消えます。","gpui.mgmt.plan.edited":"編集済み","gpui.mgmt.plan.elsewhere":"{board}の配線計画が承認を待っています","gpui.mgmt.plan.emptysub":"計画が提案されると、レイヤー・コリドー・ベタ領域がここに表示されます。","gpui.mgmt.plan.expand":"拡大","gpui.mgmt.plan.fit":"全体表示","gpui.mgmt.plan.grid.all":"全レイヤー","gpui.mgmt.plan.grid.pair":"並べて表示","gpui.mgmt.plan.grid.single":"単一","gpui.mgmt.plan.hide":"完了を隠す","gpui.mgmt.plan.hint":"頂点をドラッグして誘導 · 辺の + をクリックで追加 · 頂点を右クリックで削除","gpui.mgmt.plan.keysnote":"このバージョンのKiCadでは、このパネルから承認してください。プランビューでのKiCadのA・R・Wキーはまだ計画のものではありません(Aはフットプリントの追加を開きます)。KiCadを更新してください。","gpui.mgmt.plan.layer":"層を承認","gpui.mgmt.plan.layer.short":"レイヤー","gpui.mgmt.plan.lock":"ロック","gpui.mgmt.plan.locked":"ロック中","gpui.mgmt.plan.noboard":"この基板の配線計画はありません。","gpui.mgmt.plan.noitems":"このレイヤーにコリドーまたはプレーンがありません","gpui.mgmt.plan.note.placeholder":"ルーターへの指示メモ…","gpui.mgmt.plan.nothing":"承認待ちはありません","gpui.mgmt.plan.offwords":"エージェントは指示どおりに配線します。オンにすると、まず配線計画を提案し、ここで承認したものだけを配線します。","gpui.mgmt.plan.onwords":"銅箔層が4層以上、またはネットが60本を超える基板では、配線の前にエージェントがここで配線経路とプレーン領域を提案します。承認したものだけを配線します。","gpui.mgmt.plan.reading":"配線計画を読んでいます…","gpui.mgmt.plan.reference":"基準 {layer}","gpui.mgmt.plan.refused":"KiCad が拒否しました","gpui.mgmt.plan.reject":"却下","gpui.mgmt.plan.rejectlayer":"レイヤーを却下","gpui.mgmt.plan.reqplain":"承認が求められています","gpui.mgmt.plan.requested":"承認が求められています: {what}","gpui.mgmt.plan.saved":"保存された計画","gpui.mgmt.plan.show":"完了を表示","gpui.mgmt.plan.st.approved":"承認済み","gpui.mgmt.plan.st.awaiting":"承認待ち","gpui.mgmt.plan.st.blocked":"ブロック","gpui.mgmt.plan.st.empty":"空","gpui.mgmt.plan.st.partial":"一部完了","gpui.mgmt.plan.st.rejected":"却下","gpui.mgmt.plan.st.routed":"配線済み","gpui.mgmt.plan.st.routing":"配線中","gpui.mgmt.plan.st.verified":"検証済み","gpui.mgmt.plan.stackup.short":"スタックアップ","gpui.mgmt.plan.stop":"配線を止める","gpui.mgmt.plan.sync":"ズーム連動","gpui.mgmt.plan.tab":"計画","gpui.mgmt.plan.unlock":"ロック解除","gpui.mgmt.plan.verify":"検証","gpui.mgmt.plan.view.canvas":"キャンバス","gpui.mgmt.plan.view.list":"リスト","gpui.mgmt.plan.view.split":"分割","gpui.mgmt.plan.width":"幅","gpui.next.thread":"次のスレッド","gpui.nothing.matches":"一致するものはありません","gpui.planmode.bar.always":"計画モード — 編集前に調査して計画を提案します","gpui.planmode.bar.executing":"承認された計画を実行しています","gpui.planmode.bar.once":"計画モード (1回) — 編集前に調査して計画を提案します","gpui.planmode.bar.pending":"提案された計画が下のレビューを待っています","gpui.planmode.bar.planning":"計画中 — 編集前の計画を作成しています","gpui.planmode.chip.building":"実行中","gpui.planmode.chip.once":"計画 · 1回","gpui.planmode.scope.always":"常時","gpui.planmode.scope.once":"1回","gpui.planmode.tip":"実行前に計画を作成 (1回・常時・オフ)","gpui.planmode.top.executing":"計画を実行中","gpui.planmode.top.once":"計画 (1回)","gpui.planmode.top.pending":"計画を確認","gpui.planmode.top.planning":"計画中","gpui.previous.thread":"前のスレッド","gpui.rail.no.board":"このプロジェクトには基板がありません","gpui.rail.no.mech":"このプロジェクトには機械部品がありません","gpui.rail.no.schematic":"このプロジェクトには回路図がありません","gpui.rail.split.needs.both":"分割表示には基板と回路図が必要です","home.away":"ホーム({name})はオフラインです","home.away.queued":"ホーム({name})はオフラインです · {n} 件待機中","home.away.since":"ホーム({name})は {time} からオフラインです","home.away.since.queued":"ホーム({name})は {time} からオフラインです · {n} 件待機中","home.machine":"ホームマシン","home.move.failed":"ホームの移動に失敗しました","home.move.failed.note":"ホームの移動に失敗しました: {note}","home.move.here":"このマシンをホームにする","home.moving":"ホームを {to} へ移動中…","home.moving.step":"ホームを {to} へ移動中: {step}","hub.back.crash":"予期せず停止したBackplaneが戻りました","hub.restarting":"Backplaneを再起動しています…","hub.restarting.build":"Backplaneを再起動しています…(新しいビルド {build})","hub.stopped":"Backplaneは停止しました","ios.hub.address.field":"ハブのアドレス","menu.pin":"ピン留め","menu.settle":"完了","menu.unpin":"ピン留めを解除","model.col.agent":"エージェント","notify.settled":"完了","palette.archive":"スレッドをアーカイブ","palette.command.placeholder":"コマンドまたはスレッドを入力","palette.diff":"差分:このスレッドの変更","palette.newthread":"新しいスレッド","palette.settings":"設定","palette.terminal":"ターミナル","palette.unarchive":"スレッドのアーカイブを解除","phone.unsettle":"未完了に戻す","provider.notice.button":"設定 → アカウントを開く","provider.notice.head":"AI プロバイダーが接続されていません","provider.notice.senderr":"AI プロバイダーがまだ接続されていません。設定 → アカウントを開いて、Claude、Codex、Antigravity などのプロバイダーを接続してください。","provider.notice.senderr.remote":"{machine} に AI プロバイダーが接続されていません。{machine} で設定 → アカウントを開いて、Claude、Codex、Antigravity などのプロバイダーを接続してください。","provider.notice.text.none":"チャットを始めるには、Claude、Codex、Antigravity などのプロバイダーを接続してください。","provider.notice.text.signedout":"チャットを始めるには、設定 → アカウントで Claude、Codex などのプロバイダーにサインインしてください。","reply.action":"返信","reply.cancel":"返信をやめる","reply.to":"返信先:","secret.you":"あなた","settings.lang":"言語","sheet.rename":"スレッド名を変更","sidebar.add.project":"プロジェクトを追加","sidebar.search.projects":"プロジェクトを検索","thread.context.base":"Backplane","thread.context.copied":"プロンプトをコピーしました。","thread.context.copy":"プロンプトをコピー","thread.context.disable":"無効にする","thread.context.enable":"有効にする","thread.context.index":"利用可能なスキルの一覧","thread.context.injected.label":"追加されたプロジェクトの指示","thread.context.instructions":"指示","thread.context.mcp":"プロジェクトの MCP","thread.context.native.note":"Backplane が起動時に渡すプロンプトです。ネイティブファイルはプロバイダーが読み込みます。","thread.context.none.instructions":"プロジェクトの指示が見つかりません。","thread.context.none.mcp":"プロジェクトの MCP 設定が見つかりません。","thread.context.reading":"スレッドのコンテキストを読み込み中…","thread.context.size":"{bytes} B・約{tokens}トークン","thread.context.skills":"スキル","thread.context.system":"システムプロンプト","thread.context.title":"コンテキストとプロンプト","thread.context.trust":"承認して有効にする","thread.new":"新しいスレッド","tools.pinned":"固定中","tools.retry":"再試行","tour.title.bots":"ボット","viewer.board":"基板","viewer.diff":"差分","viewer.files":"ファイル","viewer.mech":"Mech","viewer.review":"レビュー","viewer.schematic":"回路図","viewer.solid":"3D","web.chat.answer.btn":"回答","web.chat.answer.placeholder":"回答を入力…","web.chat.answered":"回答済み: {answer}","web.chat.choose":"左側からプロジェクトのスレッドを選んで開始してください。","web.chat.empty":"まだメッセージはありません。下に入力して開始してください。","web.chat.finished":"完了 {time}","web.chat.finished.dur":"完了 {time} · {dur}","web.chat.loading":"メッセージを読み込んでいます…","web.chat.review.mode":"レビューモード","web.chat.streaming":"受信中…","web.clone.add.dir":"{dir} を追加","web.clone.back":"戻る","web.clone.change.folder":"フォルダを変更","web.clone.cloned":"{repo} を {dest} にクローンしました","web.clone.cloning":"{repo} を {dest} にクローン中","web.clone.copied":"コピーしました","web.clone.first":"最初のメッセージ: {text}","web.clone.folder.name":"フォルダ名","web.clone.go":"クローン","web.clone.loading":"読み込み中…","web.clone.no.folders":"フォルダがありません","web.clone.open.project":"プロジェクトを開く","web.clone.open.thread":"スレッドを開く","web.clone.private":"非公開","web.clone.repo.placeholder":"https / ssh の URL、または owner/repo","web.clone.retry":"もう一度","web.clone.same":"すでにそこにクローンされています: そのまま追加します。","web.clone.signin":"GitHub にサインイン","web.clone.signin.done":"GitHub にサインインしました","web.clone.signin.enter":"このコードを GitHub に入力してください:","web.clone.signin.wait":"GitHub のサインインを開始しています…","web.clone.start.thread":"スレッドを開始","web.clone.stopped":"{repo} のクローンを中止しました","web.clone.tab":"git からクローン","web.clone.up":"上へ","web.clone.use.dir":"{dir} を使う","web.composer.attach":"画像を添付","web.composer.maximages":"1 件のメッセージに添付できる画像は最大 {max} 枚です。","web.composer.unsupported":"未対応の画像形式です: {type}","web.composer.voice":"音声入力","web.logout.failed":"サインアウトを確認できませんでした。もう一度お試しください。","web.pair.approve.in":"デスクトップまたはペアリング済みの端末で承認してください · 有効期限 {time}","web.pair.approved":"承認されました。Backplane を開いています…","web.pair.cancelled":"キャンセルしました。","web.pair.code":"確認コード","web.pair.denied":"ペアリングのリクエストが拒否されました。","web.pair.expired":"ペアリングコードの有効期限が切れました。新しいコードをリクエストしてください。","web.pair.failed":"ペアリングのリクエストに失敗しました ({status})","web.pair.name":"ブラウザー名","web.pair.nocode":"ハブから確認コードが返されませんでした。","web.pair.ratelimited":"ペアリングの試行回数が多すぎます。しばらく待ってからやり直してください。","web.pair.request":"ペアリングをリクエスト","web.pair.requesting":"ペアリングコードをリクエストしています…","web.pair.subtitle":"このブラウザーをハブとペアリングします。Backplane › 設定 › デバイス で 6 桁のコードを承認してください。","web.pair.unreachable":"ハブに接続できませんでした。tailnet の接続を確認してください。","web.plan.awaiting":"{n} 件が承認待ち","web.plan.net.one":"1 ネット","web.plan.nets":"{n} ネット","web.settings.providers":"AI プロバイダー","web.settings.providers.browser":"Backplane のデスクトップまたはモバイルアプリの設定 → アカウントからプロバイダーを接続してください。"}};function Dn(e,t){if(!t)return e;return e.replace(/\{([a-zA-Z0-9_.-]+)\}/g,(n,i)=>Object.prototype.hasOwnProperty.call(t,i)?String(t[i]):n)}var ft=bs(),qt=new Set,Kt=new Map;for(let[e,t]of Object.entries(gt.en||{}))if(typeof t==="string"&&!Kt.has(t))Kt.set(t,e);function bs(){let e=typeof navigator<"u"&&navigator.language?navigator.language.toLowerCase():"en";if(e.startsWith("ja"))return"ja";if(e.startsWith("es"))return"es";return"en"}function Fn(){if(typeof document<"u"&&document.documentElement)document.documentElement.lang=ft}Fn();function Bt(e){return qt.add(e),()=>{qt.delete(e)}}function $n(e){if(!e)return!1;let t=e.toLowerCase(),n=t.startsWith("ja")?"ja":t.startsWith("es")?"es":t.startsWith("en")?"en":"";if(!n)return!1;let i=n!==ft;if(ft=n,Fn(),i)for(let s of qt)s(ft);return i}function b(e,t,n){let s=(gt[ft]||gt.en||{})[e]??gt.en?.[e]??t??e;return Dn(s,n)}function pe(e){if(!e)return"";let t=Kt.get(e);if(!t)return e;return b(t,e)}function J(e,t="",n=""){let i=document.createElement(e);if(t)i.className=t;if(n)i.textContent=n;return i}function Fe(e,t="",n){let i=J("button",t,e);if(i.type="button",n)i.addEventListener("click",n);return i}function gs(e){let t=e.replace(/[\\/]+$/,"");if(!t)return e||"/";let n=t.split(/[\\/]/);return n[n.length-1]||t}function fs(e,t){let n=e.includes("\\")&&!e.includes("/")?"\\":"/";return e.endsWith(n)?e+t:e+n+t}class zt{hub;actionLabel;action;root;pathInput;upBtn;listEl;errEl;actBtn;path="";parent=null;gen=0;busy=!1;constructor(e,t,n,i=[]){this.hub=e;this.actionLabel=t;this.action=n;this.root=J("div","bp-fb"),this.root.setAttribute("data-testid","folder-browser");let s=J("div","bp-fb-head");this.upBtn=Fe("↑","bp-btn-ghost bp-fb-up",()=>{if(this.parent)this.go(this.parent)}),this.upBtn.title=b("web.clone.up","Up"),this.upBtn.setAttribute("aria-label",b("web.clone.up","Up")),this.pathInput=J("input","bp-input bp-fb-path"),this.pathInput.spellcheck=!1,this.pathInput.setAttribute("data-testid","folder-path"),this.pathInput.addEventListener("keydown",(a)=>{if(a.key==="Enter"){a.preventDefault();let o=this.pathInput.value.trim();if(o)this.go(o)}}),s.append(this.upBtn,this.pathInput),this.listEl=J("div","bp-fb-list"),this.errEl=J("div","bp-ap-err bp-hidden");let r=J("div","bp-ap-foot");this.actBtn=Fe("","primary",()=>{this.run()}),this.actBtn.setAttribute("data-testid","folder-act"),r.append(...i,this.actBtn),this.root.append(s,this.listEl,this.errEl,r)}currentPath(){return this.path}async go(e){let t=++this.gen;this.setError(""),this.listEl.replaceChildren(J("div","bp-fb-empty",b("web.clone.loading","Loading…")));try{let n=await this.hub.rpc("dirs.list",{path:e});if(t!==this.gen)return;this.path=n.path,this.parent=n.parent??null,this.render(n.dirs??[])}catch(n){if(t!==this.gen)return;this.setError(pe(n instanceof Error?n.message:String(n))),this.render(null)}}refreshLocale(){this.upBtn.title=b("web.clone.up","Up"),this.updateAct()}render(e){if(this.pathInput.value=this.path,this.upBtn.disabled=!this.parent,this.updateAct(),e===null){this.listEl.replaceChildren();return}if(e.length===0){this.listEl.replaceChildren(J("div","bp-fb-empty",b("web.clone.no.folders","No folders here")));return}let t=document.createDocumentFragment();for(let n of e){let i=Fe("","bp-fb-row",()=>{this.go(fs(this.path,n))});i.append(J("span","bp-fb-icon","▸"),J("span","bp-fb-name",n)),t.appendChild(i)}this.listEl.replaceChildren(t),this.listEl.scrollTop=0}updateAct(){this.actBtn.textContent=this.path?this.actionLabel(gs(this.path)):this.actionLabel("…"),this.actBtn.disabled=!this.path||this.busy}async run(){if(!this.path||this.busy)return;this.busy=!0,this.updateAct(),this.setError("");try{await this.action(this.path)}catch(e){this.setError(pe(e instanceof Error?e.message:String(e)))}finally{this.busy=!1,this.updateAct()}}setError(e){this.errEl.textContent=e,this.errEl.classList.toggle("bp-hidden",!e)}}class Jt{container;host;backdrop=null;bodyEl=null;tabsEl=null;mode="folder";repoText="";repoValue="";firstText="";wantThread=!0;userParent="";nameText="";nameTouched=!1;dest=null;destGen=0;destPending=!1;destTimer=null;repos=null;reposGen=0;reposTimer=null;showSuggest=!1;suggestIdx=-1;startErr="";starting=!1;picking=!1;jobId="";job=null;specs=new Map;signin=null;copied=!1;repoInput=null;suggestEl=null;destEl=null;signinEl=null;cloneBtn=null;jobEl=null;constructor(e,t){this.container=e;this.host=t}isOpen(){return this.backdrop!==null}open(e={}){let t=this.host.hub.hasFeature("clone"),n=!e.repo&&Boolean(this.jobId)&&(!this.job||this.job.state==="running"||this.job.state==="done");if(!this.backdrop)this.build();if(!n)this.jobId="",this.job=null,this.resetForm();if(e.repo!==void 0||e.text!==void 0)this.repoText=(e.repo??"").trim(),this.repoValue="",this.firstText=(e.text??"").trim();if(this.mode=t&&(e.mode==="clone"||n)?"clone":"folder",this.render(),n){if(this.job)this.maybeGo(this.job);this.reconcile()}else if(this.mode==="clone"&&this.repoText)this.askDest()}reconcile(){let e=this.jobId;if(!e)return;this.host.hub.rpc("clone.status",{id:e}).then((t)=>this.apply(t)).catch(()=>{})}close(){if(this.reposTimer!==null)window.clearTimeout(this.reposTimer);if(this.destTimer!==null)window.clearTimeout(this.destTimer);this.reposTimer=null,this.destTimer=null,this.backdrop?.remove(),this.backdrop=null,this.bodyEl=null,this.tabsEl=null}escape(){if(this.picking){this.picking=!1,this.render();return}if(this.showSuggest){this.showSuggest=!1,this.renderSuggest();return}this.close()}refreshLocale(){if(this.backdrop)this.render()}handleFrame(e){if(e.k==="clone"){let t=e.clone;if(t)this.apply(t)}else if(e.k==="clone.repos"){if(this.isOpen()&&this.mode==="clone"&&!this.jobId)this.askRepos(0)}else if(e.k==="clone.signin"){if(!this.signin)return;let t=this.signin.state;if(this.signin=e.signin??null,this.signin?.state==="cancelled")this.signin=null;if(t!=="done"&&this.signin?.state==="done")this.askRepos(0);this.renderSignin()}}build(){let e=J("div","bp-modal-backdrop");e.setAttribute("data-testid","add-project");let t=J("div","bp-modal bp-ap"),n=J("div","bp-modal-head"),i=J("h2","",b("sidebar.add.project","Add project")),s=Fe("×","icon",()=>this.close());s.title=b("common.close","Close"),s.setAttribute("aria-label",b("common.close","Close")),n.append(i,s),this.tabsEl=J("div","bp-ap-tabs"),this.bodyEl=J("div","bp-modal-body bp-ap-body"),t.append(n,this.tabsEl,this.bodyEl),e.appendChild(t),e.addEventListener("mousedown",(r)=>{if(r.target===e)this.close()}),this.container.appendChild(e),this.backdrop=e}resetForm(){this.repoText="",this.repoValue="",this.firstText="",this.wantThread=!0,this.userParent="",this.nameText="",this.nameTouched=!1,this.dest=null,this.destPending=!1,this.repos=null,this.showSuggest=!1,this.suggestIdx=-1,this.startErr="",this.starting=!1,this.picking=!1,this.signin=null,this.copied=!1}render(){if(!this.bodyEl||!this.tabsEl||!this.backdrop)return;let e=this.backdrop.querySelector(".bp-modal-head h2");if(e)e.textContent=b("sidebar.add.project","Add project");if(this.renderTabs(),this.repoInput=null,this.suggestEl=null,this.destEl=null,this.signinEl=null,this.cloneBtn=null,this.jobEl=null,this.mode==="folder")this.renderFolder();else if(this.jobId&&this.job)this.renderJobView();else if(this.picking)this.renderPickParent();else this.renderCloneForm()}renderTabs(){if(!this.tabsEl)return;if(!this.host.hub.hasFeature("clone")){this.tabsEl.classList.add("bp-hidden");return}this.tabsEl.classList.remove("bp-hidden");let e=(t,n)=>{let i=Fe(n,"bp-ap-tab"+(this.mode===t?" on":""),()=>{if(this.mode===t)return;if(this.mode=t,this.render(),t==="clone"&&!this.jobId&&this.repos===null)this.askRepos(0)});return i.setAttribute("data-testid",`ap-tab-${t}`),i.setAttribute("aria-pressed",String(this.mode===t)),i};this.tabsEl.replaceChildren(e("folder",b("gpui.e.open.folder","Open folder")),e("clone",b("web.clone.tab","Clone from git")))}renderFolder(){let e=new zt(this.host.hub,(t)=>b("web.clone.add.dir","Add {dir}",{dir:t}),async(t)=>{let n=await this.host.hub.rpc("project.add",{path:t},30000);if(this.close(),n.project)this.host.onProjectAdded(n.project)});this.bodyEl.replaceChildren(e.root),e.go("")}renderCloneForm(){let e=this.bodyEl,t=J("div","bp-ap-form"),n=J("div","bp-ap-repo"),i=J("input","bp-input");i.type="text",i.spellcheck=!1,i.autocomplete="off",i.placeholder=b("web.clone.repo.placeholder","https or ssh URL, or owner/repo"),i.setAttribute("aria-label",b("web.clone.repo.placeholder","https or ssh URL, or owner/repo")),i.setAttribute("data-testid","clone-repo"),i.value=this.repoText,i.addEventListener("input",()=>{if(this.repoText=i.value,this.repoValue="",this.showSuggest=!0,this.suggestIdx=-1,this.startErr="",!this.nameTouched)this.nameText="";this.askRepos(200),this.askDest(250)}),i.addEventListener("focus",()=>{if(this.showSuggest=!0,this.repos===null)this.askRepos(0);else this.renderSuggest()}),i.addEventListener("blur",()=>{window.setTimeout(()=>{if(document.activeElement!==i)this.showSuggest=!1,this.renderSuggest()},120)}),i.addEventListener("keydown",(u)=>this.repoKey(u)),this.repoInput=i,this.suggestEl=J("div","bp-ap-suggest bp-hidden"),this.suggestEl.setAttribute("data-testid","clone-suggest"),n.append(i,this.suggestEl),this.signinEl=J("div","bp-ap-signin bp-hidden"),this.signinEl.setAttribute("data-testid","clone-signin"),this.destEl=J("div","bp-ap-dest"),this.destEl.setAttribute("data-testid","clone-dest");let s=J("label","bp-ap-check"),r=J("input");r.type="checkbox",r.checked=this.wantThread,r.setAttribute("data-testid","clone-thread"),r.addEventListener("change",()=>{this.wantThread=r.checked}),s.append(r,J("span","",b("web.clone.start.thread","Start a thread")));let a=[n,this.signinEl,this.destEl,s];if(this.firstText)a.push(J("div","bp-ap-first bp-dim",b("web.clone.first","First message: {text}",{text:this.firstText})));let o=J("div","bp-ap-err"+(this.startErr?"":" bp-hidden"),this.startErr);o.setAttribute("data-testid","clone-start-error");let c=J("div","bp-ap-foot");this.cloneBtn=Fe(b("web.clone.go","Clone"),"primary",()=>{this.startClone()}),this.cloneBtn.setAttribute("data-testid","clone-go"),c.append(this.cloneBtn),a.push(o,c),t.append(...a),e.replaceChildren(t),this.renderSuggest(),this.renderSignin(),this.renderDest(),window.setTimeout(()=>{if(this.repoInput===i&&!this.repoText)i.focus()},0)}repoKey(e){let t=this.repos?.repos??[],n=this.showSuggest&&t.length>0;if(e.key==="ArrowDown"&&n)e.preventDefault(),this.suggestIdx=Math.min(t.length-1,this.suggestIdx+1),this.renderSuggest();else if(e.key==="ArrowUp"&&n)e.preventDefault(),this.suggestIdx=Math.max(-1,this.suggestIdx-1),this.renderSuggest();else if(e.key==="Enter"){e.preventDefault();let i=n&&this.suggestIdx>=0?t[this.suggestIdx]:void 0;if(i)this.pickRepo(i);else if(this.canStart())this.startClone()}}pickRepo(e){if(this.repoText=e.name,this.repoValue=e.value,this.showSuggest=!1,this.suggestIdx=-1,this.startErr="",!this.nameTouched)this.nameText="";if(this.repoInput)this.repoInput.value=e.name;this.renderSuggest(),this.askDest()}repoArg(){return this.repoValue||this.repoText.trim()}askRepos(e){if(this.reposTimer!==null)window.clearTimeout(this.reposTimer);this.reposTimer=window.setTimeout(()=>{this.reposTimer=null;let t=++this.reposGen,n=this.repoValue?"":this.repoText.trim();this.host.hub.rpc("clone.repos",{q:n,limit:12},30000).then((i)=>{if(t!==this.reposGen)return;this.repos=i,this.renderSuggest(),this.renderSignin()}).catch(()=>{if(t!==this.reposGen)return;this.repos={repos:[],state:"error",hint:"Couldn't list your GitHub repositories."},this.renderSuggest()})},e)}renderSuggest(){let e=this.suggestEl;if(!e)return;let t=this.repos,n=t?.repos??[],i=[];if(this.showSuggest&&!this.repoValue){if(n.forEach((s,r)=>{let a=Fe("","bp-ap-sug"+(r===this.suggestIdx?" active":""));a.setAttribute("data-testid","clone-suggestion"),a.addEventListener("mousedown",(c)=>c.preventDefault()),a.addEventListener("click",()=>this.pickRepo(s));let o=J("div","bp-ap-sug-top");if(o.append(J("span","bp-ap-sug-name",s.name)),s.private)o.append(J("span","bp-ap-tag",b("web.clone.private","private")));if(a.append(o),s.description)a.append(J("div","bp-ap-sug-desc",s.description));i.push(a)}),n.length===0&&t){if(t.loading)i.push(J("div","bp-ap-sug-note",b("web.clone.loading","Loading…")));else if(t.hint){let s=J("div","bp-ap-sug-note");if(s.append(J("span","",pe(t.hint))),t.state==="signedout"){let r=Fe(b("web.clone.signin","Sign in to GitHub"),"bp-btn-line",()=>{this.startSignin()});r.addEventListener("mousedown",(a)=>a.preventDefault()),r.setAttribute("data-testid","clone-signin-btn"),s.append(r)}i.push(s)}}}e.replaceChildren(...i),e.classList.toggle("bp-hidden",i.length===0)}askDest(e=0){if(this.destTimer!==null)window.clearTimeout(this.destTimer);this.destPending=!0,this.updateCloneBtn(),this.destTimer=window.setTimeout(()=>{this.destTimer=null;let t=++this.destGen,n=this.repoArg();if(!n){this.dest=null,this.destPending=!1,this.renderDest();return}let i={repo:n};if(this.userParent)i.parent=this.userParent;if(this.nameTouched&&this.nameText.trim())i.name=this.nameText.trim();else if(this.userParent)i.name="";this.host.hub.rpc("clone.dest",i).then((s)=>{if(t!==this.destGen)return;if(this.dest=s,this.destPending=!1,!this.nameTouched&&s.folder)this.nameText=s.folder;this.renderDest()}).catch((s)=>{if(t!==this.destGen)return;this.dest={ok:!1,error:s instanceof Error?s.message:String(s)},this.destPending=!1,this.renderDest()})},e)}renderDest(){let e=this.destEl;if(!e)return;let t=this.dest,n=[];if(t&&!t.repo){if(t.error&&this.repoText.trim())n.push(this.errLine(pe(t.error)))}else if(t){let a=J("div","bp-ap-where"),o=J("span","bp-ap-dest-path",t.destShown||t.dest||t.defaultParentShown||"");o.setAttribute("data-testid","clone-dest-shown");let c=Fe(b("web.clone.change.folder","Change folder"),"bp-btn-line",()=>{this.picking=!0,this.render()});c.setAttribute("data-testid","clone-change-folder"),a.append(o,c),n.push(a);let u=J("label","bp-ap-name");u.append(J("span","bp-ap-lbl",b("web.clone.folder.name","Folder name")));let l=J("input","bp-input");if(l.type="text",l.spellcheck=!1,l.value=this.nameText,l.setAttribute("data-testid","clone-name"),l.addEventListener("input",()=>{this.nameText=l.value,this.nameTouched=l.value.trim()!=="",this.startErr="",this.askDest(250)}),l.addEventListener("keydown",(p)=>{if(p.key==="Enter"&&this.canStart())p.preventDefault(),this.startClone()}),u.append(l),n.push(u),!t.ok&&t.error)n.push(this.errLine(pe(t.error)));else if(t.same)n.push(J("div","bp-ap-note bp-dim",b("web.clone.same","Already cloned there: it is added as it is.")))}let i=document.activeElement,s=i&&e.contains(i)&&i.getAttribute("data-testid")==="clone-name",r=s?i.selectionStart:null;if(e.replaceChildren(...n),e.classList.toggle("bp-hidden",n.length===0),s){let a=e.querySelector('[data-testid="clone-name"]');if(a){if(a.focus(),r!==null)a.setSelectionRange(r,r)}}this.updateCloneBtn()}errLine(e){let t=J("div","bp-ap-err",e);return t.setAttribute("data-testid","clone-dest-error"),t}canStart(){return Boolean(this.dest?.ok&&this.dest.repo&&!this.destPending&&!this.starting&&this.repoArg())}updateCloneBtn(){if(this.cloneBtn)this.cloneBtn.disabled=!this.canStart()}renderPickParent(){let e=this.dest?.parent||this.userParent||this.dest?.defaultParent||"",t=Fe(b("web.clone.back","Back"),"bp-btn-line",()=>{this.picking=!1,this.render()}),n=new zt(this.host.hub,(i)=>b("web.clone.use.dir","Use {dir}",{dir:i}),async(i)=>{this.userParent=i,this.picking=!1,this.render(),this.askDest()},[t]);this.bodyEl.replaceChildren(n.root),n.go(e)}async startClone(){if(!this.canStart()||!this.dest)return;this.starting=!0,this.startErr="",this.updateCloneBtn();let e={repo:this.repoArg(),thread:this.wantThread,text:this.firstText},t=_t();this.jobId=t,this.job=null,this.specs.set(t,e);try{let n=await this.host.hub.rpc("clone.start",{id:t,repo:e.repo,parent:this.dest.parent??"",name:this.dest.folder??this.nameText.trim(),thread:e.thread,text:e.text});this.starting=!1,this.apply(n)}catch(n){this.starting=!1;let i=pe(n instanceof Error?n.message:String(n));if(this.jobId===t&&!this.job){let s=await this.host.hub.rpc("clone.status",{id:t}).catch(()=>null);if(s&&s.id===t){this.apply(s);return}}if(this.jobId===t&&!this.job){if(this.jobId="",this.startErr=i,this.mode==="clone")this.render()}}}async retry(e,t){let n=this.specs.get(e.id)??{repo:e.origin||e.repo||"",thread:!0,text:""},i=_t(),s=this.jobId;this.jobId=i,this.specs.set(i,n),t.disabled=!0;try{let r=await this.host.hub.rpc("clone.start",{id:i,repo:n.repo,dest:e.dest??"",thread:n.thread,text:n.text});this.apply(r)}catch(r){let a=pe(r instanceof Error?r.message:String(r));if(this.jobId!==i)return;if(!this.job||this.job.id!==i){let o=await this.host.hub.rpc("clone.status",{id:i}).catch(()=>null);if(o&&o.id===i){this.apply(o);return}}if(this.jobId===i&&(!this.job||this.job.id!==i))this.jobId=s,t.disabled=!1,this.showJobError(a)}}apply(e){if(!e||e.id!==this.jobId)return;if(!jn(this.job,e))return;if(this.job=e,this.copied=!1,this.isOpen()&&this.mode==="clone")if(this.jobEl&&this.jobEl.isConnected)this.renderJob();else this.render();this.maybeGo(e)}maybeGo(e){if(this.isOpen()&&e.id===this.jobId&&Hn(e))this.goTo(e)}renderJobView(){this.jobEl=J("div","bp-ap-job"),this.jobEl.setAttribute("data-testid","clone-job"),this.signinEl=J("div","bp-ap-signin bp-hidden"),this.signinEl.setAttribute("data-testid","clone-signin"),this.bodyEl.replaceChildren(this.jobEl,this.signinEl),this.renderJob(),this.renderSignin()}renderJob(){let e=this.jobEl,t=this.job;if(!e||!t)return;let n=t.destShown||t.dest||"",i=t.repo||"",s=t.state==="done"?b("web.clone.cloned","Cloned {repo} into {dest}",{repo:i,dest:n}):t.state==="cancelled"?b("web.clone.stopped","Stopped cloning {repo}",{repo:i}):b("web.clone.cloning","Cloning {repo} into {dest}",{repo:i,dest:n}),r=[J("div","bp-ap-job-title",s)];if(t.state==="running"){let a=J("div","bp-ap-phase",pe(t.phase||""));a.setAttribute("data-testid","clone-phase");let o=J("div","bp-ap-bar"+(typeof t.pct==="number"?"":" indeterminate")),c=J("div","bp-ap-bar-fill");if(typeof t.pct==="number")c.style.width=`${Math.max(0,Math.min(100,t.pct))}%`;if(o.appendChild(c),o.setAttribute("role","progressbar"),typeof t.pct==="number")o.setAttribute("aria-valuenow",String(t.pct));if(r.push(a,o),t.detail)r.push(J("div","bp-ap-detail bp-dim",t.detail));let u=J("div","bp-ap-foot"),l=Fe(b("common.cancel","Cancel"),"bp-btn-line",()=>{this.host.hub.rpc("clone.cancel",{id:t.id}).then((p)=>this.apply(p)).catch(()=>{})});l.setAttribute("data-testid","clone-cancel"),u.append(l),r.push(u)}else if(t.state==="failed"||t.state==="cancelled"){if(t.state==="failed"&&t.error){let u=J("div","bp-ap-err",pe(t.error));u.setAttribute("data-testid","clone-error"),r.push(u)}let a=J("div","bp-ap-foot"),o=Fe(b("web.clone.back","Back"),"bp-btn-line",()=>{this.jobId="",this.job=null,this.signin=null,this.render(),this.askDest()});if(a.append(o),t.signin){let u=Fe(b("web.clone.signin","Sign in to GitHub"),"bp-btn-line",()=>{this.startSignin()});u.setAttribute("data-testid","clone-signin-btn"),a.append(u)}let c=Fe(b("web.clone.retry","Try again"),"primary",()=>{this.retry(t,c)});c.setAttribute("data-testid","clone-retry"),a.append(c),r.push(a)}else if(t.state==="done"){let a=t.notes??[];if(a.length>0){let l=J("ul","bp-ap-notes");l.setAttribute("data-testid","clone-notes");for(let p of a)l.appendChild(J("li","",pe(p)));r.push(l)}let o=J("div","bp-ap-foot"),c=t.thread?b("web.clone.open.thread","Open the thread"):b("web.clone.open.project","Open the project"),u=Fe(c,"primary",()=>this.goTo(t));u.setAttribute("data-testid","clone-open"),o.append(u),r.push(o)}e.replaceChildren(...r)}showJobError(e){if(!this.jobEl)return;this.jobEl.querySelector(".bp-ap-job-err")?.remove();let t=J("div","bp-ap-err bp-ap-job-err",e);this.jobEl.appendChild(t)}goTo(e){this.jobId="",this.job=null,this.close(),this.host.onCloneDone(e)}async startSignin(){this.signin={state:"starting"},this.copied=!1,this.renderSignin();try{let e=await this.host.hub.rpc("clone.signin",{restart:!0},30000);if(!this.signin||this.signin.state==="starting")this.signin=e}catch(e){this.signin={state:"failed",error:e instanceof Error?e.message:String(e)}}if(this.signin?.state==="done")this.askRepos(0);this.renderSignin()}renderSignin(){let e=this.signinEl;if(!e)return;let t=this.signin,n=[];if(t&&t.state){if(t.state==="starting"||t.state==="waiting"&&!t.code)n.push(J("div","bp-dim",b("web.clone.signin.wait","Starting GitHub sign-in…")));else if(t.state==="waiting"){n.push(J("div","",b("web.clone.signin.enter","Enter this code on GitHub:")));let i=J("div","bp-ap-code-row"),s=J("span","bp-ap-code",t.code||"");s.setAttribute("data-testid","clone-signin-code");let r=Fe(this.copied?b("web.clone.copied","Copied"):b("common.copy","Copy"),"bp-btn-line",()=>{navigator.clipboard?.writeText(t.code||"").then(()=>{this.copied=!0,this.renderSignin()}).catch(()=>{})});if(i.append(s,r),n.push(i),t.url){let a=J("a","bp-ap-link",t.url);a.href=t.url,a.target="_blank",a.rel="noopener noreferrer",a.setAttribute("data-testid","clone-signin-url"),n.push(a)}}else if(t.state==="done")n.push(J("div","bp-ok",b("web.clone.signin.done","Signed in to GitHub")));else if(t.state==="failed")n.push(J("div","bp-ap-err",pe(t.error||"")))}e.replaceChildren(...n),e.classList.toggle("bp-hidden",n.length===0)}}function vs(e){try{let t=new URL(e,window.location.origin);if(t.protocol==="https:"||t.protocol==="http:")return t.href}catch{}return null}function vt(e,t){let n=/(`[^`]+`|\*\*[^*]+\*\*|\*[^*]+\*|\[([^\]]+)\]\(([^)]+)\))/g,i=0,s;while((s=n.exec(t))!==null){if(s.index>i)e.appendChild(document.createTextNode(t.slice(i,s.index)));let r=s[0];if(r.startsWith("`")&&r.endsWith("`")){let a=document.createElement("code");a.className="bp-code-inline",a.textContent=r.slice(1,-1),e.appendChild(a)}else if(r.startsWith("**")&&r.endsWith("**")){let a=document.createElement("strong");a.textContent=r.slice(2,-2),e.appendChild(a)}else if(r.startsWith("*")&&r.endsWith("*")){let a=document.createElement("em");a.textContent=r.slice(1,-1),e.appendChild(a)}else if(r.startsWith("[")){let a=s[2]??"",o=vs(s[3]??"");if(o){let c=document.createElement("a");c.href=o,c.target="_blank",c.rel="noopener noreferrer",c.textContent=a,e.appendChild(c)}else e.appendChild(document.createTextNode(a))}i=n.lastIndex}if(i{navigator.clipboard?.writeText(l).then(()=>{y.textContent="✓",window.setTimeout(()=>{y.textContent=m},1200)}).catch(()=>{})}),d.append(g,y);let h=document.createElement("pre"),f=document.createElement("code");f.textContent=l,h.appendChild(f),p.append(d,h),t.appendChild(p);continue}if(!s.trim()){i++;continue}let r=/^(#{1,4})\s+(.+)$/.exec(s);if(r){let c=document.createElement(`h${Math.min(4,r[1].length+1)}`);c.className="bp-md-h",vt(c,r[2]),t.appendChild(c),i++;continue}if(s.startsWith("> ")){let c=document.createElement("blockquote");c.className="bp-md-quote";let u=[];while(i "))u.push(n[i].slice(2)),i++;vt(c,u.join(` -`)),t.appendChild(c);continue}if(/^\s*[-*]\s+/.test(s)){let c=document.createElement("ul");c.className="bp-md-list";while(i ")&&!/^\s*[-*]\s+/.test(n[i])&&!/^\s*\d+\.\s+/.test(n[i]))a.push(n[i]),i++;let o=document.createElement("p");o.className="bp-md-p";for(let c=0;c0)o.appendChild(document.createElement("br"));vt(o,a[c])}t.appendChild(o)}return t}var $n="http://www.w3.org/2000/svg";function wt(e){let t=document.createElementNS($n,"svg");t.setAttribute("viewBox","0 0 24 24"),t.setAttribute("width","12"),t.setAttribute("height","12"),t.setAttribute("fill","none"),t.setAttribute("stroke","currentColor"),t.setAttribute("stroke-width","1.8"),t.setAttribute("aria-hidden","true");for(let n of e){let i=document.createElementNS($n,"path");i.setAttribute("d",n),t.appendChild(i)}return t}function Yt(e){return e<10000000000?e*1000:e}function vs(e){if(!e)return"";return new Date(Yt(e)).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",hour12:!1})}function ys(e){if(!Number.isFinite(e)||e<=0||e>3600000)return"";let t=Math.max(1,Math.round(e/1000));if(t<60)return`${t}s`;let n=Math.floor(t/60),i=t%60;return i>0?`${n}m ${i}s`:`${n}m`}function Jt(e){if(e.agentOnly)return!0;if(e.kind==="note"){let t=(e.text||"").trim();if(t.startsWith("Made this folder a git repository")||t.startsWith("Backplane: snapshot")||t.includes("snapshot of existing work before first use"))return!0}return!1}class Xt{bannerEl;scrollEl;listEl;olderBtn;cb;thread=null;entries=[];hasMore=!1;loadingOlder=!1;review=null;unanswered=null;noProvider=null;btwNote=null;liveNodes=new Map;imageCache=new Map;pinnedToBottom=!0;planExpanded=new Set;planRevisingId="";planReviseDrafts=new Map;constructor(e,t){if(this.cb=t,this.bannerEl=document.createElement("div"),this.bannerEl.className="bp-thread-banners",this.scrollEl=document.createElement("div"),this.scrollEl.className="bp-timeline-scroll",this.scrollEl.setAttribute("data-testid","timeline"),this.olderBtn=document.createElement("button"),this.olderBtn.type="button",this.olderBtn.className="bp-older-btn bp-hidden",this.olderBtn.textContent=b("android.load.earlier","Load earlier"),this.olderBtn.setAttribute("data-testid","load-older-btn"),this.olderBtn.addEventListener("click",()=>{if(!this.loadingOlder&&this.hasMore)this.loadingOlder=!0,this.cb.onLoadOlder()}),this.scrollEl.addEventListener("scroll",()=>{if(this.pinnedToBottom=this.isNearBottom(),this.hasMore&&!this.loadingOlder&&this.scrollEl.scrollTop<48)this.loadingOlder=!0,this.cb.onLoadOlder()}),typeof ResizeObserver<"u"){let n=0;new ResizeObserver(()=>{let s=this.scrollEl.clientHeight;if(n>0&&s!==n&&this.pinnedToBottom)this.scrollToBottom();n=s}).observe(this.scrollEl)}this.listEl=document.createElement("div"),this.listEl.className="bp-timeline-list",this.scrollEl.append(this.olderBtn,this.listEl),e.append(this.bannerEl,this.scrollEl)}setLoading(e){this.thread=e,this.entries=[],this.hasMore=!1,this.loadingOlder=!1,this.review=null,this.unanswered=null,this.btwNote=null,this.liveNodes.clear(),this.planExpanded.clear(),this.planRevisingId="",this.planReviseDrafts.clear(),this.renderBanners(),this.olderBtn.classList.add("bp-hidden");let t=document.createElement("div");t.className="bp-empty-state",t.textContent=b("web.chat.loading","Loading messages…"),this.listEl.replaceChildren(t)}setError(e,t,n){this.thread=e,this.entries=[],this.hasMore=!1,this.loadingOlder=!1,this.review=null,this.unanswered=null,this.btwNote=null,this.liveNodes.clear(),this.planExpanded.clear(),this.planRevisingId="",this.planReviseDrafts.clear(),this.renderBanners(),this.olderBtn.classList.add("bp-hidden");let i=document.createElement("div");i.className="bp-empty-state";let s=document.createElement("div");s.className="bp-bad",s.textContent=t;let r=document.createElement("button");r.type="button",r.textContent=b("tools.retry","Retry"),r.addEventListener("click",n),i.append(s,r),this.listEl.replaceChildren(i)}getEntries(){return this.entries.slice()}refreshLocale(){let e=this.scrollEl.scrollTop;if(this.olderBtn.textContent=b("android.load.earlier","Load earlier"),this.renderBanners(),this.thread&&this.entries.length>0)this.renderEntries(!1);this.scrollEl.scrollTop=e}setThread(e,t,n,i,s){if((this.thread?.id??"")!==(e?.id??""))this.planExpanded.clear(),this.planRevisingId="",this.planReviseDrafts.clear();this.thread=e,this.entries=t.filter((r)=>!Jt(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)=>!Jt(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(Jt(e))return;let t=this.isNearBottom()||e.kind==="user"&&Boolean(e.clientId),n=this.entries.findIndex((i)=>i.id===e.id);if(n<0&&e.clientId)n=this.entries.findIndex((i)=>i.clientId&&i.clientId===e.clientId);if(n>=0)this.entries[n]=e;else this.entries.push(e);this.renderEntries(t)}goTo(e){let t=this.scrollEl.querySelector(`[data-entry-id="${CSS.escape(e)}"]`);if(!t)return!1;return t.scrollIntoView({block:"center",behavior:"smooth"}),t.classList.remove("bp-entry-flash"),t.offsetWidth,t.classList.add("bp-entry-flash"),window.setTimeout(()=>t.classList.remove("bp-entry-flash"),1200),!0}removeEntry(e){let t=this.entries.filter((n)=>n.id!==e);if(t.length!==this.entries.length)this.entries=t,this.renderEntries(!1)}appendLiveText(e,t,n){let i=this.isNearBottom(),s=this.entries.find((a)=>a.id===e);if(!s){s={id:e,kind:"assistant",text:t,at:n,live:!0},this.entries.push(s),this.renderEntries(i);return}s.text+=t,s.live=!0;let r=this.liveNodes.get(e);if(r){if(r.replaceChildren(yt(s.text)),i)this.scrollToBottom()}else this.renderEntries(i)}isNearBottom(){let e=this.scrollEl;return e.scrollHeight-e.scrollTop-e.clientHeight<80}scrollToBottom(){this.pinnedToBottom=!0,this.scrollEl.scrollTop=this.scrollEl.scrollHeight}renderBanners(){let e=document.createDocumentFragment();if(this.noProvider&&!this.thread?.id.includes("~")){let t=document.createElement("div");t.className="bp-banner bp-no-provider",t.setAttribute("data-testid","no-provider-banner");let n=document.createElement("div");n.className="bp-no-provider-body";let i=document.createElement("strong");if(i.textContent=pe(this.noProvider.head),n.appendChild(i),this.noProvider.text){let a=document.createElement("span");a.className="bp-dim",a.textContent=pe(this.noProvider.text),n.appendChild(a)}let s=document.createElement("div");s.className="bp-banner-actions";let r=document.createElement("button");r.type="button",r.className="primary",r.setAttribute("data-testid","no-provider-accounts-btn"),r.textContent=pe(this.noProvider.button),r.addEventListener("click",()=>this.cb.onOpenAccounts?.()),s.appendChild(r),t.append(n,s),e.appendChild(t)}if(this.review&&(this.review.text||this.review.button)){let t=document.createElement("div");t.className="bp-banner bp-review-bar",t.setAttribute("data-testid","review-bar");let n=document.createElement("span");if(n.textContent=this.review.text||b("web.chat.review.mode","Review mode"),t.appendChild(n),this.review.button){let i=document.createElement("button");i.type="button",i.textContent=this.review.button,i.addEventListener("click",()=>this.cb.onToggleReview(!(this.review?.on??!0))),t.appendChild(i)}e.appendChild(t)}if(this.unanswered&&(this.unanswered.head||this.unanswered.text)){let t=document.createElement("div");t.className="bp-banner bp-unanswered",t.setAttribute("data-testid","unanswered-notice");let n=document.createElement("div");if(n.className="bp-unanswered-body",this.unanswered.head){let i=document.createElement("strong");i.textContent=this.unanswered.head,n.appendChild(i)}if(this.unanswered.text){let i=document.createElement("span");i.textContent=this.unanswered.text,n.appendChild(i)}if(t.appendChild(n),this.unanswered.buttons?.length){let i=document.createElement("div");i.className="bp-banner-actions";for(let s of this.unanswered.buttons){let r=document.createElement("button");if(r.type="button",s.primary)r.className="primary";r.textContent=s.label,r.addEventListener("click",()=>this.cb.onUnansweredAction(s.action,s.value)),i.appendChild(r)}t.appendChild(i)}e.appendChild(t)}if(this.btwNote){let t=document.createElement("div");t.className="bp-banner bp-btw-banner";let n=document.createElement("div"),i=document.createElement("div");i.className="bp-dim",i.textContent=`/btw ${this.btwNote.q}`;let s=document.createElement("div");s.appendChild(yt(this.btwNote.a)),n.append(i,s);let r=document.createElement("button");r.type="button",r.className="icon",r.textContent="×",r.addEventListener("click",()=>{this.btwNote=null,this.renderBanners()}),t.append(n,r),e.appendChild(t)}this.bannerEl.replaceChildren(e)}makeEntryActions(e,t,n){let i=document.createElement("div");i.className="bp-entry-foot"+(t?" user":"");let s=document.createElement("button");s.type="button",s.className="bp-entry-act";let r=b("common.copy","Copy"),a=document.createElement("span");a.textContent=r,s.append(wt(["M9 9h11v11H9z","M5 15H4a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1h10a1 1 0 0 1 1 1v1"]),a),s.addEventListener("click",()=>{navigator.clipboard?.writeText(e.text||"").then(()=>{a.textContent="✓",window.setTimeout(()=>{a.textContent=r},1000)}).catch(()=>{})});let o=document.createElement("button");o.type="button",o.className="bp-entry-act";let c=document.createElement("span");c.textContent=b("reply.action","Reply"),o.append(wt(["M9 17l-5-5 5-5","M20 18v-2a4 4 0 0 0-4-4H4"]),c),o.addEventListener("click",()=>this.cb.onReplyEntry(e));let u=!e.live&&!e.id.startsWith("local-")&&!e.id.startsWith("live:"),l=document.createElement("span");l.className="bp-entry-time";let p=vs(e.at);if(t)l.textContent=p,i.append(s,...u?[o]:[],l);else{let d=n&&e.at?ys(Yt(e.at)-Yt(n)):"",g=p?d?b("web.chat.finished.dur","Finished {time} · {dur}",{time:p,dur:d}):b("web.chat.finished","Finished {time}",{time:p}):"";l.textContent=e.live?b("web.chat.streaming","Streaming…"):g,i.append(l,s,...u?[o]:[])}return i}closePlanRevise(){let e=this.planRevisingId;if(!e)return!1;this.planRevisingId="";let t=this.scrollEl.scrollTop;return this.renderEntries(!1),this.scrollEl.scrollTop=t,this.listEl.querySelector(`[data-testid="ask-${CSS.escape(e)}"] [data-testid="plan-revise"]`)?.focus(),!0}renderEntries(e){let t=null,n=typeof document<"u"?document.activeElement:null;if(n instanceof HTMLTextAreaElement&&n.classList.contains("bp-plan-revise-input")&&this.listEl.contains(n)&&this.planRevisingId)this.planReviseDrafts.set(this.planRevisingId,n.value),t={askId:this.planRevisingId,start:n.selectionStart,end:n.selectionEnd,dir:n.selectionDirection};this.olderBtn.classList.toggle("bp-hidden",!this.hasMore),this.liveNodes.clear();let i=document.createDocumentFragment();if(!this.thread){let r=document.createElement("div");r.className="bp-empty-state",r.textContent=b("web.chat.choose","Choose a project thread on the left to begin."),i.appendChild(r),this.listEl.replaceChildren(i);return}if(this.entries.length===0){let r=document.createElement("div");r.className="bp-empty-state",r.textContent=b("web.chat.empty","No messages yet. Type below to start a turn."),i.appendChild(r),this.listEl.replaceChildren(i);return}let s=0;for(let r of this.entries){if(r.kind==="user"&&r.at)s=r.at;let a=document.createElement("article");if(a.className=`bp-entry bp-entry-${r.kind}`+(r.live?" is-live":""),a.setAttribute("data-entry-id",r.id),r.kind==="tool"&&r.tool){let l=document.createElement("div");l.className=`bp-tool-pill bp-tool-${r.tool.state||"done"}`;let p=document.createElement("span");if(p.className="bp-tool-name",p.textContent=r.tool.name,l.appendChild(p),r.tool.summary){let d=document.createElement("span");d.className="bp-tool-summary",d.textContent=r.tool.summary,l.appendChild(d)}a.appendChild(l),i.appendChild(a);continue}if(r.kind==="ask"&&r.ask){let l=r.ask;if(l.kind==="plan"){a.appendChild(this.renderPlanAsk(l)),i.appendChild(a);continue}let p=document.createElement("div");p.className="bp-ask-card",p.setAttribute("data-testid",`ask-${l.id}`);let d=document.createElement("div");if(d.className="bp-ask-q",d.textContent=l.question,p.appendChild(d),l.state==="open"){let g=document.createElement("div");if(g.className="bp-ask-opts",l.options&&l.options.length>0)for(let y of l.options){let m=document.createElement("button");m.type="button",m.textContent=y.label,m.addEventListener("click",()=>this.cb.onAnswerAsk(l.id,y.id)),g.appendChild(m)}else{let y=document.createElement("input");y.type="text",y.className="bp-input",y.placeholder=b("web.chat.answer.placeholder","Type answer…");let m=document.createElement("button");m.type="button",m.className="primary",m.textContent=b("web.chat.answer.btn","Answer"),m.addEventListener("click",()=>{if(y.value.trim())this.cb.onAnswerAsk(l.id,y.value.trim())}),g.append(y,m)}p.appendChild(g)}else{let g=document.createElement("div");g.className="bp-ask-answered",g.textContent=b("web.chat.answered","Answered: {answer}",{answer:l.answered??""}),p.appendChild(g)}a.appendChild(p),i.appendChild(a);continue}let o=Boolean(r.text&&r.text.trim().length>0),c=Boolean(r.images&&r.images.length>0),u=Boolean(r.attachments&&r.attachments.length>0);if(!o&&!c&&!u&&!r.live)continue;if(r.replyTo?.quote){let l=document.createElement("div");l.className="bp-reply-quote",l.textContent=b("gpui.b.in.reply.to","↩ In reply to: {quote}",{quote:r.replyTo.quote});let p=r.replyTo.id;l.setAttribute("role","button"),l.tabIndex=0,l.setAttribute("data-testid","entry-reply-quote");let d=()=>{if(this.cb.onGoToEntry)this.cb.onGoToEntry(p);else this.goTo(p)};l.addEventListener("click",d),l.addEventListener("keydown",(g)=>{if(g.key==="Enter"||g.key===" ")g.preventDefault(),d()}),a.appendChild(l)}if(o||r.live){let l=document.createElement("div");if(l.className="bp-entry-body",r.kind==="user")l.textContent=r.text;else l.appendChild(yt(r.text||""));if(r.live)this.liveNodes.set(r.id,l);a.appendChild(l)}if(u&&r.attachments){let l=document.createElement("div");l.className="bp-entry-images";for(let p of r.attachments)if(p.previewUrl){let d=document.createElement("img");d.className="bp-reply-img",d.src=p.previewUrl,d.alt=p.name||"attachment",l.appendChild(d)}else if(p.path||p.name){let d=document.createElement("span");d.className="bp-tool-pill",d.textContent=p.name||p.path||"image",l.appendChild(d)}if(l.childElementCount>0)a.appendChild(l)}if(r.images&&r.images.length>0){let l=document.createElement("div");l.className="bp-entry-images";for(let p of r.images){let d=document.createElement("img");d.className="bp-reply-img",d.alt=p;let g=`${r.id}|${p}`,y=this.imageCache.get(g);if(y)d.src=y;else this.cb.onLoadImage(r.id,p).then((m)=>{if(!m)return;let h=m.url??(m.mime&&m.data?`data:${m.mime};base64,${m.data}`:"");if(!h)return;this.imageCache.set(g,h),d.src=h});l.appendChild(d)}a.appendChild(l)}a.appendChild(this.makeEntryActions(r,r.kind==="user",r.kind==="assistant"?s:void 0)),i.appendChild(a)}if(this.listEl.replaceChildren(i),t&&this.planRevisingId===t.askId){let r=this.listEl.querySelector(`[data-testid="ask-${CSS.escape(t.askId)}"] .bp-plan-revise-input`);if(r){if(r.focus({preventScroll:!0}),t.start!==null&&t.end!==null)r.setSelectionRange(t.start,t.end,t.dir??void 0)}}if(e&&!t)this.scrollToBottom()}renderPlanAsk(e){let t=this.planExpanded.has(e.id),n=e.state==="open"&&this.planRevisingId===e.id,i=document.createElement("div");i.className="bp-ask-card bp-ask-plan",i.setAttribute("data-testid",`ask-${e.id}`);let s=document.createElement("div");s.className="bp-plan-head";let r=wt(["M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z","M14 2v6h6","M16 13H8","M16 17H8","M10 9H8"]);r.classList.add("bp-plan-head-ic");let a=document.createElement("span");if(a.className="bp-plan-title",a.textContent=!e.head||e.head==="Proposed plan"?b("ask.plan","Proposed plan"):pe(e.head),s.append(r,a),e.state==="open"){let l=document.createElement("span");l.className="bp-plan-badge",l.textContent=b("gpui.ask.plan.ready","Ready for review"),s.appendChild(l)}let o=document.createElement("span");if(o.className="bp-mgmt-flex1",s.appendChild(o),e.question){let l=document.createElement("button");l.type="button",l.className="bp-plan-head-btn";let p=b("common.copy","Copy"),d=document.createElement("span");d.textContent=p,l.append(wt(["M9 9h11v11H9z","M5 15H4a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1h10a1 1 0 0 1 1 1v1"]),d),l.addEventListener("click",()=>{navigator.clipboard?.writeText(e.question).then(()=>{l.classList.add("copied"),d.textContent=b("web.clone.copied","Copied"),window.setTimeout(()=>{l.classList.remove("copied"),d.textContent=p},1200)}).catch(()=>{})}),s.appendChild(l)}let c=document.createElement("button");c.type="button",c.className="bp-plan-head-btn",c.setAttribute("data-testid","plan-expand"),c.textContent=t?b("gpui.c.term.collapse","Collapse"):b("gpui.c.term.expand","Expand"),c.addEventListener("click",()=>{if(this.planExpanded.has(e.id))this.planExpanded.delete(e.id);else this.planExpanded.add(e.id);let l=this.scrollEl.scrollTop;this.renderEntries(!1),this.scrollEl.scrollTop=l}),s.appendChild(c),i.appendChild(s);let u=document.createElement("div");if(u.className="bp-plan-body"+(t?" is-expanded":""),u.setAttribute("data-testid","plan-body"),u.appendChild(yt(e.question||"")),i.appendChild(u),e.state==="open"){let l=document.createElement("div");l.className="bp-plan-actions";let p=e.options?.find((m)=>m.id==="implement"||m.id.endsWith("|implement")),d=document.createElement("button");if(d.type="button",d.className="primary",d.setAttribute("data-testid","plan-implement"),d.textContent=p?.label&&p.label!=="Implement"?pe(p.label):b("approval.implement","Implement"),d.addEventListener("click",()=>{this.planRevisingId="",this.planReviseDrafts.delete(e.id),this.cb.onAnswerAsk(e.id,p?.id??"implement")}),l.appendChild(d),e.revise!==!1){let m=document.createElement("button");m.type="button",m.className="bp-plan-revise-btn"+(n?" active":""),m.setAttribute("data-testid","plan-revise"),m.append(wt(["M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7","M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"]),document.createTextNode(b("gpui.ask.plan.revise","Revise"))),m.addEventListener("click",()=>{let h=this.planRevisingId!==e.id;this.planRevisingId=h?e.id:"";let f=this.scrollEl.scrollTop;if(this.renderEntries(!1),this.scrollEl.scrollTop=f,h)this.listEl.querySelector(`[data-testid="ask-${CSS.escape(e.id)}"] .bp-plan-revise-input`)?.focus()}),l.appendChild(m)}let g=e.options?.find((m)=>m.id==="dismiss"||m.id.endsWith("|dismiss")),y=document.createElement("button");if(y.type="button",y.className="bp-plan-dismiss-btn",y.setAttribute("data-testid","plan-dismiss"),y.textContent=g?.label&&g.label!=="Dismiss"?pe(g.label):b("approval.dismiss","Dismiss"),y.addEventListener("click",()=>{this.planRevisingId="",this.planReviseDrafts.delete(e.id),this.cb.onAnswerAsk(e.id,g?.id??"dismiss")}),l.appendChild(y),i.appendChild(l),n){let m=document.createElement("div");m.className="bp-plan-revise",m.setAttribute("data-testid","plan-revise-drawer");let h=document.createElement("textarea");h.rows=2,h.className="bp-input bp-plan-revise-input",h.placeholder=b("gpui.ask.plan.reviseph","What should change in the plan?"),h.value=this.planReviseDrafts.get(e.id)??"";let f=document.createElement("button");f.type="button",f.className="bp-plan-revise-send",f.setAttribute("data-testid","plan-revise-send"),f.textContent=b("gpui.ask.plan.sendrev","Send revision"),f.disabled=h.value.trim().length===0;let w=()=>{let M=h.value.trim();if(!M)return;this.planRevisingId="",this.planReviseDrafts.delete(e.id),this.cb.onAnswerAsk(e.id,`revise:${M}`)},C=()=>{this.closePlanRevise()};m.addEventListener("keydown",(M)=>{if(M.key==="Escape")M.preventDefault(),M.stopPropagation(),C()}),h.addEventListener("input",()=>{this.planReviseDrafts.set(e.id,h.value),f.disabled=h.value.trim().length===0}),h.addEventListener("keydown",(M)=>{if(M.key==="Enter"&&!M.shiftKey)M.preventDefault(),w()}),f.addEventListener("click",w);let A=document.createElement("button");A.type="button",A.className="bp-btn-ghost",A.textContent=b("common.cancel","Cancel"),A.addEventListener("click",C),m.append(h,f,A),i.appendChild(m)}}else{let l=document.createElement("div");l.className="bp-ask-answered",l.textContent=b("web.chat.answered","Answered: {answer}",{answer:e.answered??""}),i.appendChild(l)}return i}}var Gn="http://www.w3.org/2000/svg",On=4,Vn=new Set(["image/png","image/jpeg","image/webp","image/gif"]);function Bt(e){let t=document.createElementNS(Gn,"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(Gn,"path");i.setAttribute("d",n),t.appendChild(i)}return t}function Zt(){return Bt(["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 Un(){return Bt(["M6 4l14 8-14 8z"])}function ws(e){let t=(e||"").toLowerCase();if(t.includes("claude")||t.includes("anthropic"))return{glyph:"A",color:"#d97706",title:"Claude"};if(t.includes("codex")||t.includes("openai"))return{glyph:"O",color:"#10b981",title:"Codex"};if(t.includes("gemini")||t.includes("antigravity"))return{glyph:"G",color:"#3b82f6",title:"Gemini"};if(t.includes("grok"))return{glyph:"X",color:"#94a3b8",title:"Grok"};return{glyph:"●",color:"var(--accent)",title:e||"Model"}}class Qt{popupEl;attachStripEl;planBarEl;fileInput;textarea;memoryEl;memoryFill;memoryText;providerMarkEl;modelTextEl;ctxEl;planChipBtn;planChipIconHost;planChipLbl;attachBtn;voiceBtn;sendBtn;stopBtn;errorEl;replyEl;cb;commands=[];popupMode="none";filteredSlash=[];mentionItems=[];popupIdx=0;enabled=!1;attachments=[];planMode=null;constructor(e,t){this.cb=t;let n=document.createElement("div");n.className="bp-composer",n.setAttribute("data-testid","composer");let i=document.createElement("div");i.className="bp-composer-inner",this.popupEl=document.createElement("div"),this.popupEl.className="bp-composer-popup bp-hidden",this.popupEl.setAttribute("data-testid","slash-menu"),this.errorEl=document.createElement("div"),this.errorEl.className="bp-composer-err bp-hidden",this.replyEl=document.createElement("div"),this.replyEl.className="bp-reply-strip bp-hidden",this.replyEl.setAttribute("data-testid","composer-reply"),this.attachStripEl=document.createElement("div"),this.attachStripEl.className="bp-attach-strip bp-hidden",this.attachStripEl.setAttribute("data-testid","composer-attachments"),this.planBarEl=document.createElement("div"),this.planBarEl.className="bp-plan-bar bp-hidden",this.planBarEl.setAttribute("data-testid","composer-plan-bar"),this.fileInput=document.createElement("input"),this.fileInput.type="file",this.fileInput.accept="image/png,image/jpeg,image/webp,image/gif",this.fileInput.multiple=!0,this.fileInput.className="bp-hidden",this.fileInput.setAttribute("data-testid","composer-file-input"),this.fileInput.addEventListener("change",()=>{if(this.fileInput.files)this.addFiles(Array.from(this.fileInput.files));this.fileInput.value=""}),this.textarea=document.createElement("textarea"),this.textarea.className="bp-composer-input",this.textarea.rows=2,this.textarea.placeholder=b("composer.placeholder","Ask anything: @bot, >thread, %project, #room, $skill, /btw"),this.textarea.setAttribute("data-testid","composer-input");let s=document.createElement("div");s.className="bp-composer-bar";let r=document.createElement("div");r.className="bp-composer-model",this.providerMarkEl=document.createElement("span"),this.providerMarkEl.className="bp-provider-mark",this.providerMarkEl.textContent="●",this.modelTextEl=document.createElement("span"),this.modelTextEl.className="bp-model-text",this.modelTextEl.textContent="default",this.ctxEl=document.createElement("span"),this.ctxEl.className="bp-ctx-pct bp-hidden",this.ctxEl.setAttribute("data-testid","composer-ctx"),r.append(this.providerMarkEl,this.modelTextEl,this.ctxEl),this.planChipBtn=document.createElement("button"),this.planChipBtn.type="button",this.planChipBtn.className="bp-plan-chip bp-hidden",this.planChipBtn.setAttribute("data-testid","composer-plan-chip"),this.planChipBtn.setAttribute("aria-pressed","false"),this.planChipIconHost=document.createElement("span"),this.planChipIconHost.className="bp-plan-chip-ic",this.planChipIconHost.appendChild(Zt()),this.planChipLbl=document.createElement("span"),this.planChipLbl.textContent=b("gpui.mgmt.plan.tab","Plan"),this.planChipBtn.append(this.planChipIconHost,this.planChipLbl),this.planChipBtn.addEventListener("click",()=>this.cb.onCyclePlanMode?.()),this.memoryEl=document.createElement("div"),this.memoryEl.className="bp-composer-memory bp-hidden",this.memoryEl.setAttribute("data-testid","composer-memory");let a=document.createElement("div");a.className="bp-memory-meter",this.memoryFill=document.createElement("div"),this.memoryFill.className="bp-memory-fill",a.appendChild(this.memoryFill),this.memoryText=document.createElement("span"),this.memoryEl.append(a,this.memoryText);let o=document.createElement("div");o.className="bp-composer-btns",this.attachBtn=document.createElement("button"),this.attachBtn.type="button",this.attachBtn.className="icon bp-composer-tool",this.attachBtn.title=b("web.composer.attach","Attach image"),this.attachBtn.setAttribute("aria-label",b("web.composer.attach","Attach image")),this.attachBtn.setAttribute("data-testid","composer-attach"),this.attachBtn.appendChild(Bt(["M21.44 11.05l-9.19 9.19a6 6 0 0 1-8.49-8.49l9.19-9.19a4 4 0 0 1 5.66 5.66l-9.2 9.19a2 2 0 0 1-2.83-2.83l8.49-8.48"])),this.attachBtn.addEventListener("click",()=>this.fileInput.click()),this.voiceBtn=document.createElement("button"),this.voiceBtn.type="button",this.voiceBtn.className="icon bp-composer-tool",this.voiceBtn.title=b("web.composer.voice","Voice dictation"),this.voiceBtn.setAttribute("aria-label",b("web.composer.voice","Voice dictation")),this.voiceBtn.setAttribute("data-testid","composer-voice"),this.voiceBtn.appendChild(Bt(["M12 1a3 3 0 0 0-3 3v8a3 3 0 0 0 6 0V4a3 3 0 0 0-3-3z","M19 10v2a7 7 0 0 1-14 0v-2","M12 19v4","M8 23h8"])),this.voiceBtn.addEventListener("click",()=>this.cb.onToggleVoice?.()),this.stopBtn=document.createElement("button"),this.stopBtn.type="button",this.stopBtn.className="primary stop bp-hidden",this.stopBtn.textContent=b("composer.stop","Stop"),this.stopBtn.setAttribute("data-testid","composer-stop"),this.stopBtn.addEventListener("click",()=>this.cb.onInterrupt()),this.sendBtn=document.createElement("button"),this.sendBtn.type="button",this.sendBtn.className="primary bp-send-btn",this.sendBtn.textContent=b("composer.send","Send"),this.sendBtn.setAttribute("data-testid","composer-send"),this.sendBtn.addEventListener("click",()=>this.submit()),o.append(this.attachBtn,this.voiceBtn,this.stopBtn,this.sendBtn),s.append(r,this.planChipBtn,this.memoryEl,o),i.append(this.popupEl,this.errorEl,this.replyEl,this.attachStripEl,this.planBarEl,this.fileInput,this.textarea,s),n.appendChild(i),e.appendChild(n),this.textarea.addEventListener("paste",(c)=>{let u=c.clipboardData?.items;if(!u)return;let l=[];for(let p=0;p0)c.preventDefault(),this.addFiles(l)}),this.textarea.addEventListener("input",()=>{this.autoGrow(),this.clearError(),this.updatePopups()}),this.textarea.addEventListener("keydown",(c)=>{if(this.popupMode!=="none"){let u=this.popupMode==="slash"?this.filteredSlash.length:this.mentionItems.length;if(c.key==="ArrowDown"){c.preventDefault(),this.popupIdx=(this.popupIdx+1)%Math.max(1,u),this.renderPopup();return}if(c.key==="ArrowUp"){c.preventDefault(),this.popupIdx=(this.popupIdx-1+Math.max(1,u))%Math.max(1,u),this.renderPopup();return}if(c.key==="Tab"||c.key==="Enter"&&!c.shiftKey&&this.shouldCompleteOnEnter()){c.preventDefault(),this.applyPopupChoice(this.popupIdx);return}if(c.key==="Escape"){c.preventDefault(),this.closePopup();return}}if(c.key==="Tab"&&c.shiftKey&&this.planMode!==null){c.preventDefault(),this.cb.onCyclePlanMode?.();return}if(c.key==="Enter"&&!c.shiftKey)c.preventDefault(),this.submit()})}setCommands(e){this.commands=e.map((t)=>({...t,word:t.word.replace(/^\//,"")}))}setModelChip(e,t,n){let i=ws(t);if(this.providerMarkEl.textContent=i.glyph,this.providerMarkEl.style.color=i.color,this.providerMarkEl.title=i.title,this.modelTextEl.textContent=e||"default",typeof n==="number"&&Number.isFinite(n)&&n>=0)this.ctxEl.textContent=`ctx ${Math.round(n)}%`,this.ctxEl.classList.remove("bp-hidden");else this.ctxEl.textContent="",this.ctxEl.classList.add("bp-hidden")}setFeatures(e,t){this.attachBtn.classList.toggle("bp-hidden",!e),this.voiceBtn.classList.toggle("bp-hidden",!t)}setVoiceRecording(e){this.voiceBtn.classList.toggle("recording",e),this.voiceBtn.setAttribute("aria-pressed",e?"true":"false")}setVoiceLevel(e){this.voiceBtn.setAttribute("data-level",String(e))}getDraft(){return this.textarea.value}getCaret(){return this.textarea.selectionStart??this.textarea.value.length}setMemory(e){if(this.memoryEl.classList.toggle("bp-hidden",!e),!e)return;let t=e.total??0,n=t>0?Math.min(1,(e.done??0)/t):1;this.memoryFill.style.width=`${Math.round(n*100)}%`,this.memoryFill.dataset.state=e.state??"",this.memoryText.textContent=e.line??"",this.memoryEl.title=[e.status,e.lines,e.viewLine].filter(Boolean).join(` -`)}setPlanMode(e){if(this.planMode=e,this.textarea.classList.remove("is-plan","is-plan-exec"),this.sendBtn.classList.remove("is-plan","is-plan-exec"),this.planChipBtn.classList.remove("is-plan","is-exec"),this.planBarEl.classList.remove("is-exec"),!e){this.planChipBtn.classList.add("bp-hidden"),this.planChipBtn.setAttribute("aria-pressed","false"),this.planBarEl.classList.add("bp-hidden"),this.planBarEl.replaceChildren(),this.sendBtn.textContent=b("composer.send","Send");return}let t=e.phase,n=t!=="off",i=t==="armed"||t==="planning"||t==="pending",s=t==="executing";this.planChipBtn.classList.remove("bp-hidden"),this.planChipBtn.classList.toggle("is-plan",i),this.planChipBtn.classList.toggle("is-exec",s),this.planChipBtn.setAttribute("aria-pressed",n?"true":"false");let r=`${b("gpui.planmode.tip","Plan before acting (1 turn, always, or off)")} · Shift+Tab`;if(this.planChipBtn.title=r,this.planChipBtn.setAttribute("aria-label",r),this.planChipIconHost.replaceChildren(s?Un():Zt()),this.planChipLbl.textContent=s?b("gpui.planmode.chip.building","Building"):t==="pending"?b("gpui.mgmt.fab.reviewbtn","Review"):i&&e.once?b("gpui.planmode.chip.once","Plan · 1t"):b("gpui.mgmt.plan.tab","Plan"),this.textarea.classList.toggle("is-plan",i),this.textarea.classList.toggle("is-plan-exec",s),this.sendBtn.classList.toggle("is-plan",i),this.sendBtn.classList.toggle("is-plan-exec",s),this.sendBtn.textContent=i?b("gpui.mgmt.plan.tab","Plan"):b("composer.send","Send"),!n){this.planBarEl.classList.add("bp-hidden"),this.planBarEl.replaceChildren();return}this.planBarEl.classList.remove("bp-hidden"),this.planBarEl.classList.toggle("is-exec",s);let a=document.createElement("span");a.className="bp-plan-bar-ic",a.appendChild(s?Un():Zt());let o=document.createElement("span");o.className="bp-plan-bar-text",o.textContent=t==="armed"&&e.once?b("gpui.planmode.bar.once","Plan mode (1 turn) — explores and proposes a plan before editing"):t==="armed"?b("gpui.planmode.bar.always","Plan mode — explores and proposes a plan before editing"):t==="planning"?b("gpui.planmode.bar.planning","Planning — drafting a plan before edits"):t==="pending"?b("gpui.planmode.bar.pending","Proposed plan awaits review below"):b("gpui.planmode.bar.executing","Building the approved plan");let c=[a,o];if(t==="armed"||t==="planning"){let u=document.createElement("div");u.className="bp-plan-scopes";let l=(p,d,g,y)=>{let m=document.createElement("button");return m.type="button",m.className="bp-plan-scope-btn"+(d?" active":""),m.textContent=p,m.disabled=!this.enabled,m.setAttribute("data-testid",y),m.addEventListener("click",()=>this.cb.onSetPlanMode?.(g)),m};u.append(l(b("gpui.planmode.scope.once","1 turn"),e.once,"once","plan-scope-once"),l(b("gpui.planmode.scope.always","Always"),!e.once,"always","plan-scope-always"),l(b("gpui.bots.recall.off","Off"),!1,"off","plan-scope-off")),c.push(u)}this.planBarEl.replaceChildren(...c)}setState(e,t){this.enabled=e,this.textarea.disabled=!e,this.sendBtn.disabled=!e,this.attachBtn.disabled=!e,this.voiceBtn.disabled=!e,this.planChipBtn.disabled=!e,this.planBarEl.querySelectorAll(".bp-plan-scope-btn").forEach((n)=>{n.disabled=!e}),this.stopBtn.classList.toggle("bp-hidden",!t)}setDraft(e){this.textarea.value=e,this.autoGrow(),this.textarea.focus()}setReply(e,t,n){if(!e){this.replyEl.replaceChildren(),this.replyEl.classList.add("bp-hidden");return}let i=document.createElement("button");i.type="button",i.className="bp-reply-strip-body",i.setAttribute("data-testid","composer-reply-go");let s=document.createElement("span");s.className="bp-reply-strip-who",s.textContent=e.who;let r=document.createElement("span");if(r.className="bp-reply-strip-line",r.textContent=b("gpui.b.replying.to","↩ Replying to: {line}",{line:e.line}),i.append(s,r),t)i.addEventListener("click",t);let a=document.createElement("button");a.type="button",a.className="icon bp-reply-strip-drop",a.textContent="×";let o=b("reply.cancel","Cancel reply");if(a.title=o,a.setAttribute("aria-label",o),a.setAttribute("data-testid","composer-reply-drop"),n)a.addEventListener("click",n);this.replyEl.replaceChildren(i,a),this.replyEl.classList.remove("bp-hidden"),this.textarea.focus()}prependDraft(e){let t=this.textarea.value;this.textarea.value=t?`${e} +`)),t.appendChild(c);continue}if(/^\s*[-*]\s+/.test(s)){let c=document.createElement("ul");c.className="bp-md-list";while(i ")&&!/^\s*[-*]\s+/.test(n[i])&&!/^\s*\d+\.\s+/.test(n[i]))a.push(n[i]),i++;let o=document.createElement("p");o.className="bp-md-p";for(let c=0;c0)o.appendChild(document.createElement("br"));vt(o,a[c])}t.appendChild(o)}return t}var Gn="http://www.w3.org/2000/svg";function wt(e){let t=document.createElementNS(Gn,"svg");t.setAttribute("viewBox","0 0 24 24"),t.setAttribute("width","12"),t.setAttribute("height","12"),t.setAttribute("fill","none"),t.setAttribute("stroke","currentColor"),t.setAttribute("stroke-width","1.8"),t.setAttribute("aria-hidden","true");for(let n of e){let i=document.createElementNS(Gn,"path");i.setAttribute("d",n),t.appendChild(i)}return t}function Xt(e){return e<10000000000?e*1000:e}function ys(e){if(!e)return"";return new Date(Xt(e)).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",hour12:!1})}function ws(e){if(!Number.isFinite(e)||e<=0||e>3600000)return"";let t=Math.max(1,Math.round(e/1000));if(t<60)return`${t}s`;let n=Math.floor(t/60),i=t%60;return i>0?`${n}m ${i}s`:`${n}m`}function Yt(e){if(e.agentOnly)return!0;if(e.kind==="note"){let t=(e.text||"").trim();if(t.startsWith("Made this folder a git repository")||t.startsWith("Backplane: snapshot")||t.includes("snapshot of existing work before first use"))return!0}return!1}class Zt{bannerEl;scrollEl;listEl;olderBtn;cb;thread=null;entries=[];hasMore=!1;loadingOlder=!1;review=null;unanswered=null;noProvider=null;btwNote=null;liveNodes=new Map;imageCache=new Map;pinnedToBottom=!0;planExpanded=new Set;planRevisingId="";planReviseDrafts=new Map;constructor(e,t){if(this.cb=t,this.bannerEl=document.createElement("div"),this.bannerEl.className="bp-thread-banners",this.scrollEl=document.createElement("div"),this.scrollEl.className="bp-timeline-scroll",this.scrollEl.setAttribute("data-testid","timeline"),this.olderBtn=document.createElement("button"),this.olderBtn.type="button",this.olderBtn.className="bp-older-btn bp-hidden",this.olderBtn.textContent=b("android.load.earlier","Load earlier"),this.olderBtn.setAttribute("data-testid","load-older-btn"),this.olderBtn.addEventListener("click",()=>{if(!this.loadingOlder&&this.hasMore)this.loadingOlder=!0,this.cb.onLoadOlder()}),this.scrollEl.addEventListener("scroll",()=>{if(this.pinnedToBottom=this.isNearBottom(),this.hasMore&&!this.loadingOlder&&this.scrollEl.scrollTop<48)this.loadingOlder=!0,this.cb.onLoadOlder()}),typeof ResizeObserver<"u"){let n=0;new ResizeObserver(()=>{let s=this.scrollEl.clientHeight;if(n>0&&s!==n&&this.pinnedToBottom)this.scrollToBottom();n=s}).observe(this.scrollEl)}this.listEl=document.createElement("div"),this.listEl.className="bp-timeline-list",this.scrollEl.append(this.olderBtn,this.listEl),e.append(this.bannerEl,this.scrollEl)}setLoading(e){this.thread=e,this.entries=[],this.hasMore=!1,this.loadingOlder=!1,this.review=null,this.unanswered=null,this.btwNote=null,this.liveNodes.clear(),this.planExpanded.clear(),this.planRevisingId="",this.planReviseDrafts.clear(),this.renderBanners(),this.olderBtn.classList.add("bp-hidden");let t=document.createElement("div");t.className="bp-empty-state",t.textContent=b("web.chat.loading","Loading messages…"),this.listEl.replaceChildren(t)}setError(e,t,n){this.thread=e,this.entries=[],this.hasMore=!1,this.loadingOlder=!1,this.review=null,this.unanswered=null,this.btwNote=null,this.liveNodes.clear(),this.planExpanded.clear(),this.planRevisingId="",this.planReviseDrafts.clear(),this.renderBanners(),this.olderBtn.classList.add("bp-hidden");let i=document.createElement("div");i.className="bp-empty-state";let s=document.createElement("div");s.className="bp-bad",s.textContent=t;let r=document.createElement("button");r.type="button",r.textContent=b("tools.retry","Retry"),r.addEventListener("click",n),i.append(s,r),this.listEl.replaceChildren(i)}getEntries(){return this.entries.slice()}refreshLocale(){let e=this.scrollEl.scrollTop;if(this.olderBtn.textContent=b("android.load.earlier","Load earlier"),this.renderBanners(),this.thread&&this.entries.length>0)this.renderEntries(!1);this.scrollEl.scrollTop=e}setThread(e,t,n,i,s){if((this.thread?.id??"")!==(e?.id??""))this.planExpanded.clear(),this.planRevisingId="",this.planReviseDrafts.clear();this.thread=e,this.entries=t.filter((r)=>!Yt(r)),this.hasMore=n,this.loadingOlder=!1,this.review=i,this.unanswered=s,this.btwNote=null,this.renderBanners(),this.renderEntries(!0)}updateThreadMeta(e){if(!this.thread||this.thread.id!==e.id)return;this.thread=e}setReview(e){this.review=e,this.renderBanners()}setUnanswered(e){this.unanswered=e,this.renderBanners()}setNoProvider(e){this.noProvider=e,this.renderBanners()}showBtw(e,t){this.btwNote={q:e,a:t},this.renderBanners()}prependEntries(e,t){this.loadingOlder=!1;let n=this.scrollEl.scrollHeight,i=new Set(this.entries.map((r)=>r.id)),s=e.filter((r)=>!Yt(r)&&!i.has(r.id));this.entries=[...s,...this.entries],this.hasMore=t,this.renderEntries(!1),this.scrollEl.scrollTop+=this.scrollEl.scrollHeight-n}clearLoadingOlder(){this.loadingOlder=!1}upsertEntry(e){if(Yt(e))return;let t=this.isNearBottom()||e.kind==="user"&&Boolean(e.clientId),n=this.entries.findIndex((i)=>i.id===e.id);if(n<0&&e.clientId)n=this.entries.findIndex((i)=>i.clientId&&i.clientId===e.clientId);if(n>=0)this.entries[n]=e;else this.entries.push(e);this.renderEntries(t)}goTo(e){let t=this.scrollEl.querySelector(`[data-entry-id="${CSS.escape(e)}"]`);if(!t)return!1;return t.scrollIntoView({block:"center",behavior:"smooth"}),t.classList.remove("bp-entry-flash"),t.offsetWidth,t.classList.add("bp-entry-flash"),window.setTimeout(()=>t.classList.remove("bp-entry-flash"),1200),!0}removeEntry(e){let t=this.entries.filter((n)=>n.id!==e);if(t.length!==this.entries.length)this.entries=t,this.renderEntries(!1)}appendLiveText(e,t,n){let i=this.isNearBottom(),s=this.entries.find((a)=>a.id===e);if(!s){s={id:e,kind:"assistant",text:t,at:n,live:!0},this.entries.push(s),this.renderEntries(i);return}s.text+=t,s.live=!0;let r=this.liveNodes.get(e);if(r){if(r.replaceChildren(yt(s.text)),i)this.scrollToBottom()}else this.renderEntries(i)}isNearBottom(){let e=this.scrollEl;return e.scrollHeight-e.scrollTop-e.clientHeight<80}scrollToBottom(){this.pinnedToBottom=!0,this.scrollEl.scrollTop=this.scrollEl.scrollHeight}renderBanners(){let e=document.createDocumentFragment();if(this.noProvider&&!this.thread?.id.includes("~")){let t=document.createElement("div");t.className="bp-banner bp-no-provider",t.setAttribute("data-testid","no-provider-banner");let n=document.createElement("div");n.className="bp-no-provider-body";let i=document.createElement("strong");if(i.textContent=pe(this.noProvider.head),n.appendChild(i),this.noProvider.text){let a=document.createElement("span");a.className="bp-dim",a.textContent=pe(this.noProvider.text),n.appendChild(a)}let s=document.createElement("div");s.className="bp-banner-actions";let r=document.createElement("button");r.type="button",r.className="primary",r.setAttribute("data-testid","no-provider-accounts-btn"),r.textContent=pe(this.noProvider.button),r.addEventListener("click",()=>this.cb.onOpenAccounts?.()),s.appendChild(r),t.append(n,s),e.appendChild(t)}if(this.review&&(this.review.text||this.review.button)){let t=document.createElement("div");t.className="bp-banner bp-review-bar",t.setAttribute("data-testid","review-bar");let n=document.createElement("span");if(n.textContent=this.review.text||b("web.chat.review.mode","Review mode"),t.appendChild(n),this.review.button){let i=document.createElement("button");i.type="button",i.textContent=this.review.button,i.addEventListener("click",()=>this.cb.onToggleReview(!(this.review?.on??!0))),t.appendChild(i)}e.appendChild(t)}if(this.unanswered&&(this.unanswered.head||this.unanswered.text)){let t=document.createElement("div");t.className="bp-banner bp-unanswered",t.setAttribute("data-testid","unanswered-notice");let n=document.createElement("div");if(n.className="bp-unanswered-body",this.unanswered.head){let i=document.createElement("strong");i.textContent=this.unanswered.head,n.appendChild(i)}if(this.unanswered.text){let i=document.createElement("span");i.textContent=this.unanswered.text,n.appendChild(i)}if(t.appendChild(n),this.unanswered.buttons?.length){let i=document.createElement("div");i.className="bp-banner-actions";for(let s of this.unanswered.buttons){let r=document.createElement("button");if(r.type="button",s.primary)r.className="primary";r.textContent=s.label,r.addEventListener("click",()=>this.cb.onUnansweredAction(s.action,s.value)),i.appendChild(r)}t.appendChild(i)}e.appendChild(t)}if(this.btwNote){let t=document.createElement("div");t.className="bp-banner bp-btw-banner";let n=document.createElement("div"),i=document.createElement("div");i.className="bp-dim",i.textContent=`/btw ${this.btwNote.q}`;let s=document.createElement("div");s.appendChild(yt(this.btwNote.a)),n.append(i,s);let r=document.createElement("button");r.type="button",r.className="icon",r.textContent="×",r.addEventListener("click",()=>{this.btwNote=null,this.renderBanners()}),t.append(n,r),e.appendChild(t)}this.bannerEl.replaceChildren(e)}makeEntryActions(e,t,n){let i=document.createElement("div");i.className="bp-entry-foot"+(t?" user":"");let s=document.createElement("button");s.type="button",s.className="bp-entry-act";let r=b("common.copy","Copy"),a=document.createElement("span");a.textContent=r,s.append(wt(["M9 9h11v11H9z","M5 15H4a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1h10a1 1 0 0 1 1 1v1"]),a),s.addEventListener("click",()=>{navigator.clipboard?.writeText(e.text||"").then(()=>{a.textContent="✓",window.setTimeout(()=>{a.textContent=r},1000)}).catch(()=>{})});let o=document.createElement("button");o.type="button",o.className="bp-entry-act";let c=document.createElement("span");c.textContent=b("reply.action","Reply"),o.append(wt(["M9 17l-5-5 5-5","M20 18v-2a4 4 0 0 0-4-4H4"]),c),o.addEventListener("click",()=>this.cb.onReplyEntry(e));let u=!e.live&&!e.id.startsWith("local-")&&!e.id.startsWith("live:"),l=document.createElement("span");l.className="bp-entry-time";let p=ys(e.at);if(t)l.textContent=p,i.append(s,...u?[o]:[],l);else{let d=n&&e.at?ws(Xt(e.at)-Xt(n)):"",g=p?d?b("web.chat.finished.dur","Finished {time} · {dur}",{time:p,dur:d}):b("web.chat.finished","Finished {time}",{time:p}):"";l.textContent=e.live?b("web.chat.streaming","Streaming…"):g,i.append(l,s,...u?[o]:[])}return i}closePlanRevise(){let e=this.planRevisingId;if(!e)return!1;this.planRevisingId="";let t=this.scrollEl.scrollTop;return this.renderEntries(!1),this.scrollEl.scrollTop=t,this.listEl.querySelector(`[data-testid="ask-${CSS.escape(e)}"] [data-testid="plan-revise"]`)?.focus(),!0}renderEntries(e){let t=null,n=typeof document<"u"?document.activeElement:null;if(n instanceof HTMLTextAreaElement&&n.classList.contains("bp-plan-revise-input")&&this.listEl.contains(n)&&this.planRevisingId)this.planReviseDrafts.set(this.planRevisingId,n.value),t={askId:this.planRevisingId,start:n.selectionStart,end:n.selectionEnd,dir:n.selectionDirection};this.olderBtn.classList.toggle("bp-hidden",!this.hasMore),this.liveNodes.clear();let i=document.createDocumentFragment();if(!this.thread){let r=document.createElement("div");r.className="bp-empty-state",r.textContent=b("web.chat.choose","Choose a project thread on the left to begin."),i.appendChild(r),this.listEl.replaceChildren(i);return}if(this.entries.length===0){let r=document.createElement("div");r.className="bp-empty-state",r.textContent=b("web.chat.empty","No messages yet. Type below to start a turn."),i.appendChild(r),this.listEl.replaceChildren(i);return}let s=0;for(let r of this.entries){if(r.kind==="user"&&r.at)s=r.at;let a=document.createElement("article");if(a.className=`bp-entry bp-entry-${r.kind}`+(r.live?" is-live":""),a.setAttribute("data-entry-id",r.id),r.kind==="tool"&&r.tool){let l=document.createElement("div");l.className=`bp-tool-pill bp-tool-${r.tool.state||"done"}`;let p=document.createElement("span");if(p.className="bp-tool-name",p.textContent=r.tool.name,l.appendChild(p),r.tool.summary){let d=document.createElement("span");d.className="bp-tool-summary",d.textContent=r.tool.summary,l.appendChild(d)}a.appendChild(l),i.appendChild(a);continue}if(r.kind==="ask"&&r.ask){let l=r.ask;if(l.kind==="plan"){a.appendChild(this.renderPlanAsk(l)),i.appendChild(a);continue}let p=document.createElement("div");p.className="bp-ask-card",p.setAttribute("data-testid",`ask-${l.id}`);let d=document.createElement("div");if(d.className="bp-ask-q",d.textContent=l.question,p.appendChild(d),l.state==="open"){let g=document.createElement("div");if(g.className="bp-ask-opts",l.options&&l.options.length>0)for(let y of l.options){let m=document.createElement("button");m.type="button",m.textContent=y.label,m.addEventListener("click",()=>this.cb.onAnswerAsk(l.id,y.id)),g.appendChild(m)}else{let y=document.createElement("input");y.type="text",y.className="bp-input",y.placeholder=b("web.chat.answer.placeholder","Type answer…");let m=document.createElement("button");m.type="button",m.className="primary",m.textContent=b("web.chat.answer.btn","Answer"),m.addEventListener("click",()=>{if(y.value.trim())this.cb.onAnswerAsk(l.id,y.value.trim())}),g.append(y,m)}p.appendChild(g)}else{let g=document.createElement("div");g.className="bp-ask-answered",g.textContent=b("web.chat.answered","Answered: {answer}",{answer:l.answered??""}),p.appendChild(g)}a.appendChild(p),i.appendChild(a);continue}let o=Boolean(r.text&&r.text.trim().length>0),c=Boolean(r.images&&r.images.length>0),u=Boolean(r.attachments&&r.attachments.length>0);if(!o&&!c&&!u&&!r.live)continue;if(r.replyTo?.quote){let l=document.createElement("div");l.className="bp-reply-quote",l.textContent=b("gpui.b.in.reply.to","↩ In reply to: {quote}",{quote:r.replyTo.quote});let p=r.replyTo.id;l.setAttribute("role","button"),l.tabIndex=0,l.setAttribute("data-testid","entry-reply-quote");let d=()=>{if(this.cb.onGoToEntry)this.cb.onGoToEntry(p);else this.goTo(p)};l.addEventListener("click",d),l.addEventListener("keydown",(g)=>{if(g.key==="Enter"||g.key===" ")g.preventDefault(),d()}),a.appendChild(l)}if(o||r.live){let l=document.createElement("div");if(l.className="bp-entry-body",r.kind==="user")l.textContent=r.text;else l.appendChild(yt(r.text||""));if(r.live)this.liveNodes.set(r.id,l);a.appendChild(l)}if(u&&r.attachments){let l=document.createElement("div");l.className="bp-entry-images";for(let p of r.attachments)if(p.previewUrl){let d=document.createElement("img");d.className="bp-reply-img",d.src=p.previewUrl,d.alt=p.name||"attachment",l.appendChild(d)}else if(p.path||p.name){let d=document.createElement("span");d.className="bp-tool-pill",d.textContent=p.name||p.path||"image",l.appendChild(d)}if(l.childElementCount>0)a.appendChild(l)}if(r.images&&r.images.length>0){let l=document.createElement("div");l.className="bp-entry-images";for(let p of r.images){let d=document.createElement("img");d.className="bp-reply-img",d.alt=p;let g=`${r.id}|${p}`,y=this.imageCache.get(g);if(y)d.src=y;else this.cb.onLoadImage(r.id,p).then((m)=>{if(!m)return;let h=m.url??(m.mime&&m.data?`data:${m.mime};base64,${m.data}`:"");if(!h)return;this.imageCache.set(g,h),d.src=h});l.appendChild(d)}a.appendChild(l)}a.appendChild(this.makeEntryActions(r,r.kind==="user",r.kind==="assistant"?s:void 0)),i.appendChild(a)}if(this.listEl.replaceChildren(i),t&&this.planRevisingId===t.askId){let r=this.listEl.querySelector(`[data-testid="ask-${CSS.escape(t.askId)}"] .bp-plan-revise-input`);if(r){if(r.focus({preventScroll:!0}),t.start!==null&&t.end!==null)r.setSelectionRange(t.start,t.end,t.dir??void 0)}}if(e&&!t)this.scrollToBottom()}renderPlanAsk(e){let t=this.planExpanded.has(e.id),n=e.state==="open"&&this.planRevisingId===e.id,i=document.createElement("div");i.className="bp-ask-card bp-ask-plan",i.setAttribute("data-testid",`ask-${e.id}`);let s=document.createElement("div");s.className="bp-plan-head";let r=wt(["M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z","M14 2v6h6","M16 13H8","M16 17H8","M10 9H8"]);r.classList.add("bp-plan-head-ic");let a=document.createElement("span");if(a.className="bp-plan-title",a.textContent=!e.head||e.head==="Proposed plan"?b("ask.plan","Proposed plan"):pe(e.head),s.append(r,a),e.state==="open"){let l=document.createElement("span");l.className="bp-plan-badge",l.textContent=b("gpui.ask.plan.ready","Ready for review"),s.appendChild(l)}let o=document.createElement("span");if(o.className="bp-mgmt-flex1",s.appendChild(o),e.question){let l=document.createElement("button");l.type="button",l.className="bp-plan-head-btn";let p=b("common.copy","Copy"),d=document.createElement("span");d.textContent=p,l.append(wt(["M9 9h11v11H9z","M5 15H4a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1h10a1 1 0 0 1 1 1v1"]),d),l.addEventListener("click",()=>{navigator.clipboard?.writeText(e.question).then(()=>{l.classList.add("copied"),d.textContent=b("web.clone.copied","Copied"),window.setTimeout(()=>{l.classList.remove("copied"),d.textContent=p},1200)}).catch(()=>{})}),s.appendChild(l)}let c=document.createElement("button");c.type="button",c.className="bp-plan-head-btn",c.setAttribute("data-testid","plan-expand"),c.textContent=t?b("gpui.c.term.collapse","Collapse"):b("gpui.c.term.expand","Expand"),c.addEventListener("click",()=>{if(this.planExpanded.has(e.id))this.planExpanded.delete(e.id);else this.planExpanded.add(e.id);let l=this.scrollEl.scrollTop;this.renderEntries(!1),this.scrollEl.scrollTop=l}),s.appendChild(c),i.appendChild(s);let u=document.createElement("div");if(u.className="bp-plan-body"+(t?" is-expanded":""),u.setAttribute("data-testid","plan-body"),u.appendChild(yt(e.question||"")),i.appendChild(u),e.state==="open"){let l=document.createElement("div");l.className="bp-plan-actions";let p=e.options?.find((m)=>m.id==="implement"||m.id.endsWith("|implement")),d=document.createElement("button");if(d.type="button",d.className="primary",d.setAttribute("data-testid","plan-implement"),d.textContent=p?.label&&p.label!=="Implement"?pe(p.label):b("approval.implement","Implement"),d.addEventListener("click",()=>{this.planRevisingId="",this.planReviseDrafts.delete(e.id),this.cb.onAnswerAsk(e.id,p?.id??"implement")}),l.appendChild(d),e.revise!==!1){let m=document.createElement("button");m.type="button",m.className="bp-plan-revise-btn"+(n?" active":""),m.setAttribute("data-testid","plan-revise"),m.append(wt(["M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7","M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"]),document.createTextNode(b("gpui.ask.plan.revise","Revise"))),m.addEventListener("click",()=>{let h=this.planRevisingId!==e.id;this.planRevisingId=h?e.id:"";let f=this.scrollEl.scrollTop;if(this.renderEntries(!1),this.scrollEl.scrollTop=f,h)this.listEl.querySelector(`[data-testid="ask-${CSS.escape(e.id)}"] .bp-plan-revise-input`)?.focus()}),l.appendChild(m)}let g=e.options?.find((m)=>m.id==="dismiss"||m.id.endsWith("|dismiss")),y=document.createElement("button");if(y.type="button",y.className="bp-plan-dismiss-btn",y.setAttribute("data-testid","plan-dismiss"),y.textContent=g?.label&&g.label!=="Dismiss"?pe(g.label):b("approval.dismiss","Dismiss"),y.addEventListener("click",()=>{this.planRevisingId="",this.planReviseDrafts.delete(e.id),this.cb.onAnswerAsk(e.id,g?.id??"dismiss")}),l.appendChild(y),i.appendChild(l),n){let m=document.createElement("div");m.className="bp-plan-revise",m.setAttribute("data-testid","plan-revise-drawer");let h=document.createElement("textarea");h.rows=2,h.className="bp-input bp-plan-revise-input",h.placeholder=b("gpui.ask.plan.reviseph","What should change in the plan?"),h.value=this.planReviseDrafts.get(e.id)??"";let f=document.createElement("button");f.type="button",f.className="bp-plan-revise-send",f.setAttribute("data-testid","plan-revise-send"),f.textContent=b("gpui.ask.plan.sendrev","Send revision"),f.disabled=h.value.trim().length===0;let w=()=>{let M=h.value.trim();if(!M)return;this.planRevisingId="",this.planReviseDrafts.delete(e.id),this.cb.onAnswerAsk(e.id,`revise:${M}`)},C=()=>{this.closePlanRevise()};m.addEventListener("keydown",(M)=>{if(M.key==="Escape")M.preventDefault(),M.stopPropagation(),C()}),h.addEventListener("input",()=>{this.planReviseDrafts.set(e.id,h.value),f.disabled=h.value.trim().length===0}),h.addEventListener("keydown",(M)=>{if(M.key==="Enter"&&!M.shiftKey)M.preventDefault(),w()}),f.addEventListener("click",w);let A=document.createElement("button");A.type="button",A.className="bp-btn-ghost",A.textContent=b("common.cancel","Cancel"),A.addEventListener("click",C),m.append(h,f,A),i.appendChild(m)}}else{let l=document.createElement("div");l.className="bp-ask-answered",l.textContent=b("web.chat.answered","Answered: {answer}",{answer:e.answered??""}),i.appendChild(l)}return i}}var On="http://www.w3.org/2000/svg",Vn=4,Un=new Set(["image/png","image/jpeg","image/webp","image/gif"]);function It(e){let t=document.createElementNS(On,"svg");t.setAttribute("viewBox","0 0 24 24"),t.setAttribute("width","15"),t.setAttribute("height","15"),t.setAttribute("fill","none"),t.setAttribute("stroke","currentColor"),t.setAttribute("stroke-width","1.8"),t.setAttribute("aria-hidden","true");for(let n of e){let i=document.createElementNS(On,"path");i.setAttribute("d",n),t.appendChild(i)}return t}function Qt(){return It(["M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z","M14 2v6h6","M16 13H8","M16 17H8","M10 9H8"])}function Wn(){return It(["M6 4l14 8-14 8z"])}function Es(e){let t=(e||"").toLowerCase();if(t.includes("claude")||t.includes("anthropic"))return{glyph:"A",color:"#d97706",title:"Claude"};if(t.includes("codex")||t.includes("openai"))return{glyph:"O",color:"#10b981",title:"Codex"};if(t.includes("gemini")||t.includes("antigravity"))return{glyph:"G",color:"#3b82f6",title:"Gemini"};if(t.includes("grok"))return{glyph:"X",color:"#94a3b8",title:"Grok"};return{glyph:"●",color:"var(--accent)",title:e||"Model"}}class en{popupEl;attachStripEl;planBarEl;fileInput;textarea;memoryEl;memoryFill;memoryText;providerMarkEl;modelTextEl;ctxEl;planChipBtn;planChipIconHost;planChipLbl;attachBtn;voiceBtn;sendBtn;stopBtn;errorEl;replyEl;cb;commands=[];popupMode="none";filteredSlash=[];mentionItems=[];popupIdx=0;enabled=!1;attachments=[];planMode=null;constructor(e,t){this.cb=t;let n=document.createElement("div");n.className="bp-composer",n.setAttribute("data-testid","composer");let i=document.createElement("div");i.className="bp-composer-inner",this.popupEl=document.createElement("div"),this.popupEl.className="bp-composer-popup bp-hidden",this.popupEl.setAttribute("data-testid","slash-menu"),this.errorEl=document.createElement("div"),this.errorEl.className="bp-composer-err bp-hidden",this.replyEl=document.createElement("div"),this.replyEl.className="bp-reply-strip bp-hidden",this.replyEl.setAttribute("data-testid","composer-reply"),this.attachStripEl=document.createElement("div"),this.attachStripEl.className="bp-attach-strip bp-hidden",this.attachStripEl.setAttribute("data-testid","composer-attachments"),this.planBarEl=document.createElement("div"),this.planBarEl.className="bp-plan-bar bp-hidden",this.planBarEl.setAttribute("data-testid","composer-plan-bar"),this.fileInput=document.createElement("input"),this.fileInput.type="file",this.fileInput.accept="image/png,image/jpeg,image/webp,image/gif",this.fileInput.multiple=!0,this.fileInput.className="bp-hidden",this.fileInput.setAttribute("data-testid","composer-file-input"),this.fileInput.addEventListener("change",()=>{if(this.fileInput.files)this.addFiles(Array.from(this.fileInput.files));this.fileInput.value=""}),this.textarea=document.createElement("textarea"),this.textarea.className="bp-composer-input",this.textarea.rows=2,this.textarea.placeholder=b("composer.placeholder","Ask anything: @bot, >thread, %project, #room, $skill, /btw"),this.textarea.setAttribute("data-testid","composer-input");let s=document.createElement("div");s.className="bp-composer-bar";let r=document.createElement("div");r.className="bp-composer-model",this.providerMarkEl=document.createElement("span"),this.providerMarkEl.className="bp-provider-mark",this.providerMarkEl.textContent="●",this.modelTextEl=document.createElement("span"),this.modelTextEl.className="bp-model-text",this.modelTextEl.textContent="default",this.ctxEl=document.createElement("span"),this.ctxEl.className="bp-ctx-pct bp-hidden",this.ctxEl.setAttribute("data-testid","composer-ctx"),r.append(this.providerMarkEl,this.modelTextEl,this.ctxEl),this.planChipBtn=document.createElement("button"),this.planChipBtn.type="button",this.planChipBtn.className="bp-plan-chip bp-hidden",this.planChipBtn.setAttribute("data-testid","composer-plan-chip"),this.planChipBtn.setAttribute("aria-pressed","false"),this.planChipIconHost=document.createElement("span"),this.planChipIconHost.className="bp-plan-chip-ic",this.planChipIconHost.appendChild(Qt()),this.planChipLbl=document.createElement("span"),this.planChipLbl.textContent=b("gpui.mgmt.plan.tab","Plan"),this.planChipBtn.append(this.planChipIconHost,this.planChipLbl),this.planChipBtn.addEventListener("click",()=>this.cb.onCyclePlanMode?.()),this.memoryEl=document.createElement("div"),this.memoryEl.className="bp-composer-memory bp-hidden",this.memoryEl.setAttribute("data-testid","composer-memory");let a=document.createElement("div");a.className="bp-memory-meter",this.memoryFill=document.createElement("div"),this.memoryFill.className="bp-memory-fill",a.appendChild(this.memoryFill),this.memoryText=document.createElement("span"),this.memoryEl.append(a,this.memoryText);let o=document.createElement("div");o.className="bp-composer-btns",this.attachBtn=document.createElement("button"),this.attachBtn.type="button",this.attachBtn.className="icon bp-composer-tool",this.attachBtn.title=b("web.composer.attach","Attach image"),this.attachBtn.setAttribute("aria-label",b("web.composer.attach","Attach image")),this.attachBtn.setAttribute("data-testid","composer-attach"),this.attachBtn.appendChild(It(["M21.44 11.05l-9.19 9.19a6 6 0 0 1-8.49-8.49l9.19-9.19a4 4 0 0 1 5.66 5.66l-9.2 9.19a2 2 0 0 1-2.83-2.83l8.49-8.48"])),this.attachBtn.addEventListener("click",()=>this.fileInput.click()),this.voiceBtn=document.createElement("button"),this.voiceBtn.type="button",this.voiceBtn.className="icon bp-composer-tool",this.voiceBtn.title=b("web.composer.voice","Voice dictation"),this.voiceBtn.setAttribute("aria-label",b("web.composer.voice","Voice dictation")),this.voiceBtn.setAttribute("data-testid","composer-voice"),this.voiceBtn.appendChild(It(["M12 1a3 3 0 0 0-3 3v8a3 3 0 0 0 6 0V4a3 3 0 0 0-3-3z","M19 10v2a7 7 0 0 1-14 0v-2","M12 19v4","M8 23h8"])),this.voiceBtn.addEventListener("click",()=>this.cb.onToggleVoice?.()),this.stopBtn=document.createElement("button"),this.stopBtn.type="button",this.stopBtn.className="primary stop bp-hidden",this.stopBtn.textContent=b("composer.stop","Stop"),this.stopBtn.setAttribute("data-testid","composer-stop"),this.stopBtn.addEventListener("click",()=>this.cb.onInterrupt()),this.sendBtn=document.createElement("button"),this.sendBtn.type="button",this.sendBtn.className="primary bp-send-btn",this.sendBtn.textContent=b("composer.send","Send"),this.sendBtn.setAttribute("data-testid","composer-send"),this.sendBtn.addEventListener("click",()=>this.submit()),o.append(this.attachBtn,this.voiceBtn,this.stopBtn,this.sendBtn),s.append(r,this.planChipBtn,this.memoryEl,o),i.append(this.popupEl,this.errorEl,this.replyEl,this.attachStripEl,this.planBarEl,this.fileInput,this.textarea,s),n.appendChild(i),e.appendChild(n),this.textarea.addEventListener("paste",(c)=>{let u=c.clipboardData?.items;if(!u)return;let l=[];for(let p=0;p0)c.preventDefault(),this.addFiles(l)}),this.textarea.addEventListener("input",()=>{this.autoGrow(),this.clearError(),this.updatePopups()}),this.textarea.addEventListener("keydown",(c)=>{if(this.popupMode!=="none"){let u=this.popupMode==="slash"?this.filteredSlash.length:this.mentionItems.length;if(c.key==="ArrowDown"){c.preventDefault(),this.popupIdx=(this.popupIdx+1)%Math.max(1,u),this.renderPopup();return}if(c.key==="ArrowUp"){c.preventDefault(),this.popupIdx=(this.popupIdx-1+Math.max(1,u))%Math.max(1,u),this.renderPopup();return}if(c.key==="Tab"||c.key==="Enter"&&!c.shiftKey&&this.shouldCompleteOnEnter()){c.preventDefault(),this.applyPopupChoice(this.popupIdx);return}if(c.key==="Escape"){c.preventDefault(),this.closePopup();return}}if(c.key==="Tab"&&c.shiftKey&&this.planMode!==null){c.preventDefault(),this.cb.onCyclePlanMode?.();return}if(c.key==="Enter"&&!c.shiftKey)c.preventDefault(),this.submit()})}setCommands(e){this.commands=e.map((t)=>({...t,word:t.word.replace(/^\//,"")}))}setModelChip(e,t,n){let i=Es(t);if(this.providerMarkEl.textContent=i.glyph,this.providerMarkEl.style.color=i.color,this.providerMarkEl.title=i.title,this.modelTextEl.textContent=e||"default",typeof n==="number"&&Number.isFinite(n)&&n>=0)this.ctxEl.textContent=`ctx ${Math.round(n)}%`,this.ctxEl.classList.remove("bp-hidden");else this.ctxEl.textContent="",this.ctxEl.classList.add("bp-hidden")}setFeatures(e,t){this.attachBtn.classList.toggle("bp-hidden",!e),this.voiceBtn.classList.toggle("bp-hidden",!t)}setVoiceRecording(e){this.voiceBtn.classList.toggle("recording",e),this.voiceBtn.setAttribute("aria-pressed",e?"true":"false")}setVoiceLevel(e){this.voiceBtn.setAttribute("data-level",String(e))}getDraft(){return this.textarea.value}getCaret(){return this.textarea.selectionStart??this.textarea.value.length}setMemory(e){if(this.memoryEl.classList.toggle("bp-hidden",!e),!e)return;let t=e.total??0,n=t>0?Math.min(1,(e.done??0)/t):1;this.memoryFill.style.width=`${Math.round(n*100)}%`,this.memoryFill.dataset.state=e.state??"",this.memoryText.textContent=e.line??"",this.memoryEl.title=[e.status,e.lines,e.viewLine].filter(Boolean).join(` +`)}setPlanMode(e){if(this.planMode=e,this.textarea.classList.remove("is-plan","is-plan-exec"),this.sendBtn.classList.remove("is-plan","is-plan-exec"),this.planChipBtn.classList.remove("is-plan","is-exec"),this.planBarEl.classList.remove("is-exec"),!e){this.planChipBtn.classList.add("bp-hidden"),this.planChipBtn.setAttribute("aria-pressed","false"),this.planBarEl.classList.add("bp-hidden"),this.planBarEl.replaceChildren(),this.sendBtn.textContent=b("composer.send","Send");return}let t=e.phase,n=t!=="off",i=t==="armed"||t==="planning"||t==="pending",s=t==="executing";this.planChipBtn.classList.remove("bp-hidden"),this.planChipBtn.classList.toggle("is-plan",i),this.planChipBtn.classList.toggle("is-exec",s),this.planChipBtn.setAttribute("aria-pressed",n?"true":"false");let r=`${b("gpui.planmode.tip","Plan before acting (1 turn, always, or off)")} · Shift+Tab`;if(this.planChipBtn.title=r,this.planChipBtn.setAttribute("aria-label",r),this.planChipIconHost.replaceChildren(s?Wn():Qt()),this.planChipLbl.textContent=s?b("gpui.planmode.chip.building","Building"):t==="pending"?b("gpui.mgmt.fab.reviewbtn","Review"):i&&e.once?b("gpui.planmode.chip.once","Plan · 1t"):b("gpui.mgmt.plan.tab","Plan"),this.textarea.classList.toggle("is-plan",i),this.textarea.classList.toggle("is-plan-exec",s),this.sendBtn.classList.toggle("is-plan",i),this.sendBtn.classList.toggle("is-plan-exec",s),this.sendBtn.textContent=i?b("gpui.mgmt.plan.tab","Plan"):b("composer.send","Send"),!n){this.planBarEl.classList.add("bp-hidden"),this.planBarEl.replaceChildren();return}this.planBarEl.classList.remove("bp-hidden"),this.planBarEl.classList.toggle("is-exec",s);let a=document.createElement("span");a.className="bp-plan-bar-ic",a.appendChild(s?Wn():Qt());let o=document.createElement("span");o.className="bp-plan-bar-text",o.textContent=t==="armed"&&e.once?b("gpui.planmode.bar.once","Plan mode (1 turn) — explores and proposes a plan before editing"):t==="armed"?b("gpui.planmode.bar.always","Plan mode — explores and proposes a plan before editing"):t==="planning"?b("gpui.planmode.bar.planning","Planning — drafting a plan before edits"):t==="pending"?b("gpui.planmode.bar.pending","Proposed plan awaits review below"):b("gpui.planmode.bar.executing","Building the approved plan");let c=[a,o];if(t==="armed"||t==="planning"){let u=document.createElement("div");u.className="bp-plan-scopes";let l=(p,d,g,y)=>{let m=document.createElement("button");return m.type="button",m.className="bp-plan-scope-btn"+(d?" active":""),m.textContent=p,m.disabled=!this.enabled,m.setAttribute("data-testid",y),m.addEventListener("click",()=>this.cb.onSetPlanMode?.(g)),m};u.append(l(b("gpui.planmode.scope.once","1 turn"),e.once,"once","plan-scope-once"),l(b("gpui.planmode.scope.always","Always"),!e.once,"always","plan-scope-always"),l(b("gpui.bots.recall.off","Off"),!1,"off","plan-scope-off")),c.push(u)}this.planBarEl.replaceChildren(...c)}setState(e,t){this.enabled=e,this.textarea.disabled=!e,this.sendBtn.disabled=!e,this.attachBtn.disabled=!e,this.voiceBtn.disabled=!e,this.planChipBtn.disabled=!e,this.planBarEl.querySelectorAll(".bp-plan-scope-btn").forEach((n)=>{n.disabled=!e}),this.stopBtn.classList.toggle("bp-hidden",!t)}setDraft(e){this.textarea.value=e,this.autoGrow(),this.textarea.focus()}setReply(e,t,n){if(!e){this.replyEl.replaceChildren(),this.replyEl.classList.add("bp-hidden");return}let i=document.createElement("button");i.type="button",i.className="bp-reply-strip-body",i.setAttribute("data-testid","composer-reply-go");let s=document.createElement("span");s.className="bp-reply-strip-who",s.textContent=e.who;let r=document.createElement("span");if(r.className="bp-reply-strip-line",r.textContent=b("gpui.b.replying.to","↩ Replying to: {line}",{line:e.line}),i.append(s,r),t)i.addEventListener("click",t);let a=document.createElement("button");a.type="button",a.className="icon bp-reply-strip-drop",a.textContent="×";let o=b("reply.cancel","Cancel reply");if(a.title=o,a.setAttribute("aria-label",o),a.setAttribute("data-testid","composer-reply-drop"),n)a.addEventListener("click",n);this.replyEl.replaceChildren(i,a),this.replyEl.classList.remove("bp-hidden"),this.textarea.focus()}prependDraft(e){let t=this.textarea.value;this.textarea.value=t?`${e} ${t}`:e,this.autoGrow(),this.textarea.focus()}showError(e,t){let n=document.createElement("span");if(n.textContent=pe(e),t){let i=document.createElement("button");i.type="button",i.className="bp-composer-err-act",i.setAttribute("data-testid","composer-err-accounts"),i.textContent=t.label,i.addEventListener("click",t.onClick),this.errorEl.replaceChildren(n,i)}else this.errorEl.replaceChildren(n);this.errorEl.classList.remove("bp-hidden")}clearError(){this.errorEl.replaceChildren(),this.errorEl.classList.add("bp-hidden")}focus(){this.textarea.focus()}refreshLocale(){this.textarea.placeholder=b("composer.placeholder","Ask anything: @bot, >thread, %project, #room, $skill, /btw"),this.attachBtn.title=b("web.composer.attach","Attach image"),this.attachBtn.setAttribute("aria-label",b("web.composer.attach","Attach image")),this.voiceBtn.title=b("web.composer.voice","Voice dictation"),this.voiceBtn.setAttribute("aria-label",b("web.composer.voice","Voice dictation")),this.sendBtn.textContent=b("composer.send","Send"),this.stopBtn.textContent=b("composer.stop","Stop"),this.setPlanMode(this.planMode)}autoGrow(){this.textarea.style.height="auto",this.textarea.style.height=`${Math.min(180,Math.max(54,this.textarea.scrollHeight))}px`}shouldCompleteOnEnter(){if(this.popupMode==="mention")return!0;if(this.popupMode==="slash"){let e=this.textarea.value;return e.startsWith("/")&&!e.includes(" ")}return!1}updatePopups(){let e=this.textarea.value;if(e.startsWith("/")&&!e.includes(" ")&&!e.includes(` -`)){let n=e.slice(1).toLowerCase();if(this.filteredSlash=this.commands.filter((i)=>i.word.toLowerCase().startsWith(n)),this.filteredSlash.length>0){this.popupMode="slash",this.popupIdx=Math.min(this.popupIdx,this.filteredSlash.length-1),this.renderPopup();return}}let t=/(?:^|\s)([@>%#])([a-zA-Z0-9._-]{1,32})$/.exec(e.slice(0,this.textarea.selectionStart));if(t){let n=t[1],i=t[2];this.cb.onQueryMentions(i,n).then((s)=>{if(s.length>0)this.mentionItems=s,this.popupMode="mention",this.popupIdx=0,this.renderPopup();else if(this.popupMode==="mention")this.closePopup()});return}this.closePopup()}closePopup(){this.popupMode="none",this.popupEl.classList.add("bp-hidden"),this.popupEl.replaceChildren()}renderPopup(){let e=document.createDocumentFragment();if(this.popupMode==="slash")this.filteredSlash.forEach((t,n)=>{let i=document.createElement("button");i.type="button",i.className="bp-popup-row"+(n===this.popupIdx?" active":""),i.setAttribute("data-testid",`slash-item-${t.word}`);let s=document.createElement("span");s.className="bp-popup-name",s.textContent=`/${t.word}`;let r=document.createElement("span");r.className="bp-popup-desc",r.textContent=t.desc||t.label,i.append(s,r),i.addEventListener("mousedown",(a)=>{a.preventDefault(),this.applyPopupChoice(n)}),e.appendChild(i)});else if(this.popupMode==="mention")this.mentionItems.forEach((t,n)=>{let i=document.createElement("button");i.type="button",i.className="bp-popup-row"+(n===this.popupIdx?" active":"");let s=document.createElement("span");s.className="bp-popup-name",s.textContent=t.word||`${t.sigil}${t.label}`;let r=document.createElement("span");r.className="bp-popup-desc",r.textContent=t.detail||t.label,i.append(s,r),i.addEventListener("mousedown",(a)=>{a.preventDefault(),this.applyPopupChoice(n)}),e.appendChild(i)});this.popupEl.replaceChildren(e),this.popupEl.classList.remove("bp-hidden")}applyPopupChoice(e){if(this.popupMode==="slash"){let t=this.filteredSlash[e];if(t)this.textarea.value=`/${t.word} `,this.autoGrow(),this.textarea.focus();this.closePopup()}else if(this.popupMode==="mention"){let t=this.mentionItems[e];if(t){let n=this.textarea.selectionStart,i=this.textarea.value.slice(0,n),s=this.textarea.value.slice(n),r=i.replace(/([@>%#][a-zA-Z0-9._-]{1,32})$/,`${t.word} `);this.textarea.value=r+s,this.textarea.selectionStart=this.textarea.selectionEnd=r.length,this.textarea.focus()}this.closePopup()}}async addFiles(e){this.clearError();for(let t of e){if(!Vn.has(t.type)){this.showError(b("web.composer.unsupported","Unsupported image type: {type}",{type:t.type||t.name}));continue}if(this.attachments.length>=On){this.showError(b("web.composer.maximages","At most {max} images per message.",{max:On}));break}let n=await new Promise((s,r)=>{let a=new FileReader;a.onload=()=>s(String(a.result||"")),a.onerror=()=>r(Error("read failed")),a.readAsDataURL(t)}).catch(()=>""),i=n.indexOf(",");if(i<0)continue;this.attachments.push({name:t.name||`image-${this.attachments.length+1}.png`,mime:t.type,data:n.slice(i+1),previewUrl:n})}this.renderAttachments()}renderAttachments(){if(this.attachments.length===0){this.attachStripEl.classList.add("bp-hidden"),this.attachStripEl.replaceChildren();return}let e=document.createDocumentFragment();this.attachments.forEach((t,n)=>{let i=document.createElement("div");i.className="bp-attach-chip";let s=document.createElement("img");s.src=t.previewUrl,s.alt=t.name,s.className="bp-attach-thumb";let r=document.createElement("button");r.type="button",r.className="icon bp-attach-rm",r.textContent="×",r.title=b("common.remove","Remove"),r.addEventListener("click",()=>{this.attachments.splice(n,1),this.renderAttachments()}),i.append(s,r),e.appendChild(i)}),this.attachStripEl.replaceChildren(e),this.attachStripEl.classList.remove("bp-hidden")}submit(){if(!this.enabled)return;let e=this.textarea.value.trim();if(!e&&this.attachments.length===0)return;if(this.closePopup(),this.clearError(),e.startsWith("/")&&this.attachments.length===0){let n=e.slice(1).split(/\s+/)[0]?.toLowerCase()??"";if(this.commands.some((i)=>i.word.toLowerCase()===n)){this.textarea.value="",this.autoGrow(),this.cb.onRunCommand(e);return}}let t=this.attachments.map(({name:n,mime:i,data:s})=>({name:n,mime:i,data:s}));this.attachments=[],this.renderAttachments(),this.textarea.value="",this.autoGrow(),this.cb.onSend(e,t)}}async function Wn(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 Es=new Set(["bom","checks","life","plan","fab"]);function It(e){if(!e||!Array.isArray(e.panels))return[];return e.panels.filter((t)=>t&&typeof t.id==="string"&&Es.has(t.id))}function Yn(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 Rt(e,t=22){let n=e.join(", ");if(n.length<=t)return n;let i="";for(let s=0;s0?` +${o}`.length:0)>t)return i?`${i} +${e.length-s}`:`${e[0]} +${e.length-1}`;i=a}return i}function at(e){if(!Number.isFinite(e)||e<0)return"?";if(e<1000)return String(Math.round(e));if(e<1e6){let n=e/1000;return n<10?`${n.toFixed(1).replace(/\.0$/,"")}k`:`${Math.round(n)}k`}let t=e/1e6;return t<10?`${t.toFixed(1).replace(/\.0$/,"")}M`:`${Math.round(t)}M`}function ot(e){if(!Number.isFinite(e))return"";if(e>=1)return`$${e.toFixed(2)}`;let t=e.toFixed(4).replace(/0+$/,"");return(t.split(".")[1]??"").length<2?`$${e.toFixed(2)}`:`$${t}`}var xs=new Set(["0201","0402","0603","0805","1206","1210","1812","2010","2512"]),Cs=new Set(["QFN","DFN","SOT","SOIC","SOP","SSOP","TSSOP","MSOP","QFP","LQFP","TQFP","BGA","WLCSP","SOD","TO","SON","LGA"]);function Xn(e){if(!e)return"";let t=e.indexOf(":"),i=(t>=0?e.slice(t+1):e).split("_");for(let a of i)if(xs.has(a))return a;let s=i[0]??"",r=s.replace(/[^a-zA-Z].*$/,"").toUpperCase();if(Cs.has(r)){let a=s.split("-");if(a.length>=2&&/^\d+$/.test(a[1]))return`${a[0]}-${a[1]}`;return a[0]}return i.slice(0,2).join("_")}function Zn(e){let t=e?.status??"";if(!t)return null;let n=typeof e?.stock==="number"?e.stock:-1;if(t==="checking")return{text:"…",tone:"faint"};if(t==="unknown")return{text:"?",tone:"faint"};if(t==="out")return{text:`out ${at(Math.max(n,0))}`,tone:"bad"};if(t==="low")return{text:`low ${at(n)}`,tone:"warn"};return{text:at(n),tone:"ok"}}function Qn(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 ei(e,t){if(!t)return e;return e.filter((n)=>n.source===t)}function tn(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 jt(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 ti(e){return e.state==="routed"||e.state==="verified"}function ni(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 ii(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 si(e){let t=e.done??0,n=e.approved??0,i=e.awaiting??0,s=e.blocked??0,r=0;if(typeof e.total!=="number"){for(let a of e.layers??[])for(let o of a.items??[])if(o.state==="routed"||o.state==="verified")t+=1;else if(o.state==="routing")r+=1;else if(o.state==="approved")n+=1}else if(e.routing)r=Math.max(0,e.total-(t+n+i+s));return[{count:t,tone:"ok"},{count:r,tone:"accent"},{count:n,tone:"input"},{count:i,tone:"warn"},{count:s,tone:"bad"}]}function ri(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 ai(e){return e==="extra"?"costs-more limits":"base-price limits"}function nn(e,t){return e.watchGen===t.watchGen&&e.editGen===t.editGen&&e.project!==""&&e.project===t.project&&e.editId!==""&&e.editId===t.editId}function oi(e){return{project:e.project,refs:e.refs.slice(),field:e.field,value:e.was}}function sn(e,t){return e.watchGen===t.watchGen&&e.project!==""&&e.project===t.project&&e.threadId!==""&&e.threadId===t.threadId&&e.threadGen===t.threadGen}var _n=["#f59e0b","#38bdf8","#c084fc","#2dd4bf","#ef4444","#a3e635","#f97316","#ec4899"],qn=["#14b8a6","#f59e0b","#c084fc","#22c55e","#38bdf8","#ef4444","#e879f9","#84cc16"];function li(e){let t=2166136261;for(let n=0;n>>0;return t}function Et(e,t=""){let n=t.trim().toLowerCase();if(n&&n!=="#5a7a9a"&&n!=="#8a8a8a")return t;let i=e.toUpperCase();if(i.includes("3V3A")||i.includes("AVDD")||i.includes("VDDA"))return"#38bdf8";if(i.includes("1V8")||i.includes("1.8V"))return"#c084fc";if(i.includes("2V5")||i.includes("2.5V"))return"#a3e635";if(i.includes("3V3")||i.includes("3.3V")||i.includes("VCC"))return"#f59e0b";if(i.includes("5V")||i.startsWith("+5"))return"#ef4444";if(i.includes("12V")||i.includes("24V"))return"#f97316";if(i.includes("VBAT")||i.includes("VIN"))return"#ec4899";if(i.includes("GND"))return"#2dd4bf";return _n[li(i)%_n.length]}function lt(e,t=""){let n=t.trim().toLowerCase();if(n&&n!=="#8a8a8a")return t;return qn[li(e)%qn.length]}function ci(e,t,n,i=14){let s=Math.max(1,Math.abs(e[2]-e[0])),r=Math.max(1,Math.abs(e[3]-e[1])),a=Math.max(20,t-i*2),o=Math.max(20,n-i*2),c=Math.max(0.05,Math.min(200,Math.min(a/s,o/r)));return{cx:(e[0]+e[2])*0.5,cy:(e[1]+e[3])*0.5,scale:c,fitted:c,touched:!1}}function Ve(e,t,n,i,s){return[i*0.5+(t-e.cx)*e.scale,s*0.5+(n-e.cy)*e.scale]}function Ht(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 di(e,t,n){let i=Math.max(0.0001,e.scale);return{...e,cx:e.cx-t/i,cy:e.cy-n/i,touched:!0}}function pi(e,t,n,i,s,r){let a=Math.max(0.02,e.fitted*0.35),o=Math.max(40,e.fitted*24),c=Math.max(a,Math.min(o,e.scale*t)),[u,l]=Ht(e,n,i,s,r);return{...e,cx:u-(n-s*0.5)/c,cy:l-(i-r*0.5)/c,scale:c,touched:!0}}function mi(e,t,n,i){let s=e.map((a)=>[a[0],a[1]]);if(s.length===0)return[n];let r=i&&t+1>=s.length?s.length:Math.min(t+1,s.length);return s.splice(r,0,[n[0],n[1]]),s}function rn(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 ks(e,t,n,i,s,r){let a=s-n,o=r-i,c=a*a+o*o;if(c<0.000001)return(e-n)*(e-n)+(t-i)*(t-i);let u=Math.max(0,Math.min(1,((e-n)*a+(t-i)*o)/c)),l=n+u*a,p=i+u*o;return(e-l)*(e-l)+(t-p)*(t-p)}function Kn(e,t,n){if(n.length<3)return!1;let i=!1;for(let s=0,r=n.length-1;st!==u>t&&e<(c-a)*(t-o)/(u-o+0.000000000001)+a)i=!i}return i}function an(e,t){return Math.max(5,Math.min(32,e*t))}function Dt(e,t,n,i,s,r,a,o,c){if(i){for(let d of e){if(d.layer!==n||d.id!==i||d.locked)continue;let g=d.path??[];for(let y=0;y=3)for(let y=0;y=0;d--){let g=t[d];if(g.layer!==n)continue;let y=g.outline??[];if(!Kn(l,p,y))continue;if(!(g.holes??[]).some((h)=>Kn(l,p,h)))return{kind:"region",id:g.id}}return null}function ct(e){let t=null,n=null,i=[];for(let r of e){if(!r.layer)continue;i.push(r.layer);let a=r.items??[],o=a.filter((u)=>u.kind==="corridor").length,c=a.filter((u)=>u.kind==="plane").length;if((o>0||r.role==="signal")&&(!t||o>t.count))t={count:o,layer:r.layer};if((c>0||r.role==="power"||r.role==="plane")&&(!n||c>n.count))n={count:c,layer:r.layer}}let s=[];if(t)s.push(t.layer);if(n&&!s.includes(n.layer))s.push(n.layer);for(let r of i){if(s.length>=2)break;if(!s.includes(r))s.push(r)}return s}function zn(e,t){if(!e||e.length===0)return null;if(e.length===1)return e[0];let n=Math.max(0,Math.min(1,t)),i=0;for(let a=1;a=s&&o>0.000000001){let c=(s-r)/o;return[e[a-1][0]+(e[a][0]-e[a-1][0])*c,e[a-1][1]+(e[a][1]-e[a-1][1])*c]}r+=o}return e[e.length-1]}function it(e,t,n){for(let i of t??[])if(i.layer===e&&i.title)return i.title;for(let i of n??[])if(i.layer===e&&i.title)return i.title;return e}function ui(e,t,n){if(e==="split"&&n.length>0)return t.filter((i)=>n.includes(i.layer));return t}function en(e,t){return!(e[2]<=t[0]||e[0]>=t[2]||e[3]<=t[1]||e[1]>=t[3])}function Jn(e,t,n){if(n.length<3)return!1;let i=!1;for(let s=0,r=n.length-1;st!==u>t&&e<(c-a)*(t-o)/(u-o+0.000000000001)+a)i=!i}return i}function hi(e,t){if(e.length<3)return null;let n=1/0,i=1/0,s=-1/0,r=-1/0,a=0,o=0;for(let u of e)n=Math.min(n,u[0]),i=Math.min(i,u[1]),s=Math.max(s,u[0]),r=Math.max(r,u[1]),a+=u[0],o+=u[1];let c=[[(n+s)*0.5,(i+r)*0.5],[a/e.length,o/e.length]];for(let u of[0.5,0.25,0.75,0.125,0.875])for(let l of[0.5,0.25,0.75,0.125,0.875])c.push([n+(s-n)*l,i+(r-i)*u]);for(let u of c)if(Jn(u[0],u[1],e)&&!t.some((l)=>Jn(u[0],u[1],l)))return u;return null}function bi(e,t,n,i,s,r){let a=[];for(let l of e){let p=l.nets??0,d=l.path??[];if(p<=0||d.length<2)continue;let g=0;for(let y=1;y{let d=l.sel||l.hov?1:0,g=p.sel||p.hov?1:0;if(g!==d)return g-d;if(p.nets!==l.nets)return p.nets-l.nets;return l.b.id.localeCompare(p.b.id)});let o=[],c=[],u=(l,p,d,g,y)=>[l-d*0.5-y,p-g*0.5-y,l+d*0.5+y,p+g*0.5+y];for(let l of a){let p=l.b.name||"",d=String(l.nets),g=p?`${p} · ${l.nets}`:d,y=(l.sel||l.hov||l.pxLen>=95)&&p?[g,d]:[d],m=null,h=(w,C)=>Math.max(C*0.5+3,Math.min(Math.max(C*0.5+3,n-C*0.5-3),w)),f=(w,C)=>Math.max(C*0.5+3,Math.min(Math.max(C*0.5+3,i-C*0.5-3),w));e:for(let w of y){let C=Math.max(16,w.length*5.9+10),A=15;for(let M of[0.5,0.35,0.65,0.22,0.78]){let S=zn(l.pts,M);if(!S)continue;let[T,B]=Ve(t,S[0],S[1],n,i),R=h(T,C),O=f(B,15),H=u(R,O,C,15,2);if(!o.some((ae)=>en(H,ae))){m={id:l.b.id,text:w,cx:R,cy:O,pw:C,ph:15,col:l.col,sel:l.sel};break e}}}if(!m){let w=zn(l.pts,0.5);if(w){let[C,A]=Ve(t,w[0],w[1],n,i),M=Math.max(16,d.length*6.5+8),S=15,T=h(C,M);for(let B of[-18,18]){let R=f(A+B,15);if(!o.some((O)=>en(u(T,R,M,15,2),O))){m={id:l.b.id,text:d,cx:T,cy:R,pw:M,ph:15,col:l.col,sel:l.sel};break}}}}if(m)o.push(u(m.cx,m.cy,m.pw,m.ph,2)),c.push(m)}return c}function gi(e,t,n,i,s,r=[]){let a=new Set(s),o=[];for(let l of e){if(!l.r||!l.b||l.b.length!==4)continue;let[p,d]=Ve(t,l.b[0],l.b[1],n,i),[g,y]=Ve(t,l.b[2],l.b[3],n,i),m=Math.abs(g-p),h=Math.abs(y-d);if(m<13||h<9)continue;let f=(p+g)*0.5,w=(d+y)*0.5;if(f<8||f>n-8||w<8||w>i-8)continue;o.push({text:l.r,cx:f,cy:w,bw:l.r.length*5.8+4,bh:11,score:m*h+(a.has(l.r)?1e4:0)})}o.sort((l,p)=>p.score-l.score);let c=[...r],u=[];for(let l of o){let p=[l.cx-l.bw*0.5,l.cy-l.bh*0.5,l.cx+l.bw*0.5,l.cy+l.bh*0.5];if(!c.some((g)=>en(p,g)))c.push(p),u.push({text:l.text,cx:l.cx,cy:l.cy})}return u}function fi(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 Ft(e,t){if(!t||t.length===0)return e;let n=new Map;for(let r of e)if(r.layer)n.set(r.layer,r);let i=[],s=new Set;for(let r of t){if(!r.layer)continue;s.add(r.layer);let a=n.get(r.layer);if(a)i.push(a);else i.push({layer:r.layer,index:r.index,title:r.title||`L${r.index} · ${r.layer}`,subtitle:r.subtitle||"",role:r.role,status:"proposed",done:0,approved:0,total:0,items:[]})}for(let r of e)if(r.layer&&!s.has(r.layer))i.push(r);return i}function vi(e,t,n,i,s,r,a,o){return e===t&&n===i&&s===r&&(o===void 0||a>=o)}var yi="#111917",As="#16201d",Ls="rgba(212, 224, 219, 0.92)",Ss="rgba(61, 80, 73, 0.72)",Ps="rgba(82, 107, 97, 0.85)";var wi="#f59e0b",Ns="#eef5f2",Ei="#ef4444";function st(e,t){let n=e.trim().replace(/^#/,"");if(n.length===6){let i=parseInt(n.slice(0,2),16),s=parseInt(n.slice(2,4),16),r=parseInt(n.slice(4,6),16);if(!Number.isNaN(i)&&!Number.isNaN(s)&&!Number.isNaN(r))return`rgba(${i}, ${s}, ${r}, ${t})`}return`rgba(20, 184, 166, ${t})`}function Ms(e,t,n){let i=0.14,s=0.45,r=0.85,a=!1;switch(e){case"approved":case"routing":i=0.16,s=0.51,r=0.91;break;case"edited":i=0.2,s=0.56,r=0.95;break;case"routed":case"verified":i=0.08,s=0.26,r=0.59;break;case"rejected":case"failed":i=0.05,s=0.13,r=0.27;break;case"blocked":i=0.18,s=0.48,r=0.88,a=!0;break}if(t)i=Math.min(0.35,i+0.1),s=Math.min(0.71,s+0.12),r=1;else if(n)i=Math.min(0.28,i+0.06),s=Math.min(0.63,s+0.07);return{glow:i,body:s,core:r,bad:a}}function Ts(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 Bs(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 on{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=Ft(e.layers,e.copperLayers);if(t.length===0)return[];if(e.gridMode==="all")return t;if(e.gridMode==="single"){let s=e.shownLayers.find((a)=>t.some((o)=>o.layer===a))??ct(t)[0]??t[0]?.layer,r=t.find((a)=>a.layer===s);return r?[r]:[]}let n=e.shownLayers.length>0&&e.shownLayers.every((s)=>t.some((r)=>r.layer===s))?e.shownLayers.slice(0,2):ct(t),i=[];for(let s of n){let r=t.find((a)=>a.layer===s);if(r)i.push(r)}return i.length>0?i:t.slice(0,2)}update(e,t){this.state=e;let n=this.visibleLayers(e);this.root.classList.toggle("two-cols",t&&n.length>1);let i=n.map((s)=>s.layer).join("|");if(i!==this.renderedLayerKey){this.renderedLayerKey=i;for(let s of this.cards.values())s.ro.disconnect();this.cards.clear(),this.root.replaceChildren();for(let s of n){let r=this.buildCard(s);this.cards.set(s.layer,r),this.root.appendChild(r.el)}}else for(let s of n){let r=this.cards.get(s.layer);if(r)this.syncCardHeaderAndLegend(r,s)}this.scheduleDraw()}effectiveBbox(e){let t=e.bbox;if(!t||t.length!==4||Math.abs(t[2]-t[0])<0.5||Math.abs(t[3]-t[1])<0.5)return[0,0,100,70];return t}getCam(e,t,n){let i=this.state,s=i?.syncZoom?this.sharedCam:this.layerCams.get(e)??null;if(s&&s.touched)return s;return ci(i?this.effectiveBbox(i.board):[0,0,100,70],t,n,14)}setCam(e,t){if(this.state?.syncZoom)this.sharedCam=t;else this.layerCams.set(e,t)}buildCard(e){let t=document.createElement("section");t.className="bp-plan-card",t.setAttribute("data-testid",`mgmt-plan-card-${e.layer}`);let n=document.createElement("div");n.className="bp-plan-card-head";let i=document.createElement("div");i.className="bp-plan-card-head-top";let s=document.createElement("span"),r=e.role==="power"||(e.items?.length??0)>0&&(e.items??[]).every((w)=>w.kind==="plane");s.className="bp-plan-card-bar "+(r?"pwr":"sig");let a=document.createElement("span");a.className="bp-plan-card-title";let o=document.createElement("span");o.className="bp-plan-status-badge";let c=document.createElement("button");c.type="button",c.className="bp-mgmt-btn bp-plan-mini-btn",c.textContent="✓",c.title=b("gpui.mgmt.plan.layer","Approve layer"),c.addEventListener("click",(w)=>{w.stopPropagation(),this.cb.onApproveLayer(e.layer,!0)});let u=document.createElement("button");u.type="button",u.className="bp-mgmt-btn bp-plan-mini-btn",u.textContent="✗",u.title=b("gpui.mgmt.plan.rejectlayer","Reject layer"),u.addEventListener("click",(w)=>{w.stopPropagation(),this.cb.onApproveLayer(e.layer,!1)}),i.append(s,a,o,c,u);let l=document.createElement("div");l.className="bp-plan-card-sub",n.append(i,l);let p=document.createElement("div");p.className="bp-plan-card-canvas-wrap";let d=document.createElement("canvas");d.className="bp-plan-card-canvas",d.setAttribute("data-testid",`mgmt-plan-canvas-${e.layer}`);let g=document.createElement("div");g.className="bp-plan-hover-hud bp-hidden",p.append(d,g);let y=document.createElement("div");y.className="bp-plan-legend bp-hidden",t.append(n,p,y);let m=d.getContext("2d"),h=new ResizeObserver(()=>this.scheduleDraw());h.observe(p),this.attachPointerListeners(d,e.layer);let f={layer:e.layer,el:t,canvas:d,ctx:m,legendEl:y,okBtn:c,noBtn:u,statusEl:o,titleEl:a,subtitleEl:l,hoverHudEl:g,ro:h};return this.syncCardHeaderAndLegend(f,e),f}syncCardHeaderAndLegend(e,t){e.titleEl.textContent=it(t.layer,this.state?.copperLayers,this.state?.layers)||t.title||t.layer;let n=t.subtitle||t.stackup||"";e.subtitleEl.textContent=n,e.subtitleEl.classList.toggle("bp-hidden",!n);let i=t.items??[],s=Bs(t);e.statusEl.className=`bp-plan-card-status tone-${s.tone==="warn"?"dim":s.tone}`,e.statusEl.textContent=i.length>0?b(s.key,s.label):"",e.statusEl.classList.toggle("bp-hidden",i.length===0);let r=i.some((o)=>o.state==="proposed"||o.state==="edited");if(e.okBtn)e.okBtn.classList.toggle("bp-hidden",!r);if(e.noBtn)e.noBtn.classList.toggle("bp-hidden",!r);let a=(this.state?.regions??[]).filter((o)=>o.layer===t.layer);if(a.length===0)e.legendEl.classList.add("bp-hidden"),e.legendEl.replaceChildren();else{e.legendEl.classList.remove("bp-hidden");let o=document.createDocumentFragment();for(let c of a){let u=document.createElement("button");u.type="button";let l=this.state?.selectedId===c.id;u.className="bp-plan-legend-chip"+(l?" active":"");let p=document.createElement("span");p.className="bp-plan-legend-sw",p.style.background=Et(c.net||c.id,c.color||"");let d=document.createElement("span");d.textContent=c.net||c.id,u.append(p,d),u.addEventListener("click",()=>{this.cb.onSelect(c.id),this.cb.onFocusItem(c.id)}),o.appendChild(u)}e.legendEl.replaceChildren(o)}}attachPointerListeners(e,t){e.addEventListener("contextmenu",(i)=>i.preventDefault()),e.addEventListener("dblclick",()=>this.fitAll()),e.addEventListener("pointerdown",(i)=>{let s=this.state;if(!s)return;this.root.focus({preventScroll:!0});let r=e.getBoundingClientRect(),a=i.clientX-r.left,o=i.clientY-r.top,c=Math.max(1,r.width),u=Math.max(1,r.height),l=this.getCam(t,c,u),p=Dt(s.bands,s.regions,t,s.selectedId,l,c,u,a,o);if(i.button===2){if(p?.kind==="vertex"){let d=this.getItemPts(p.id,p.isPlane),g=rn(d,p.idx,p.isPlane);if(g)this.selectedVertex=null,this.cb.onCommitFields(p.id,{[p.isPlane?"outline":"path"]:g})}return}if(i.button!==0)return;if(e.setPointerCapture(i.pointerId),this.downPos={x:i.clientX,y:i.clientY},p?.kind==="vertex"){let d=this.getItemPts(p.id,p.isPlane),g=d.map((y)=>[y[0],y[1]]);this.selectedVertex={id:p.id,idx:p.idx},this.drag={layer:t,kind:"vertex",id:p.id,isPlane:p.isPlane,idx:p.idx,pts:d.map((y)=>[y[0],y[1]]),origPts:g,moved:!1},this.scheduleDraw()}else if(p?.kind==="midpoint"){let d=this.getItemPts(p.id,p.isPlane),g=d.map((h)=>[h[0],h[1]]),y=mi(d,p.segIdx,p.pos,p.isPlane),m=p.isPlane&&p.segIdx+1>=d.length?y.length-1:Math.min(p.segIdx+1,y.length-1);this.selectedVertex={id:p.id,idx:m},this.patchLocalItem(p.id,p.isPlane,y),this.drag={layer:t,kind:"vertex",id:p.id,isPlane:p.isPlane,idx:m,pts:y,origPts:g,moved:!0},this.scheduleDraw()}else this.selectedVertex=null,this.drag={layer:t,kind:"pan",lastX:a,lastY:o}}),e.addEventListener("pointermove",(i)=>{let s=this.state;if(!s)return;let r=e.getBoundingClientRect(),a=i.clientX-r.left,o=i.clientY-r.top,c=Math.max(1,r.width),u=Math.max(1,r.height);if(this.drag&&this.drag.layer===t){if(this.drag.kind==="pan"){let A=this.getCam(t,c,u);this.setCam(t,di(A,a-this.drag.lastX,o-this.drag.lastY)),this.drag.lastX=a,this.drag.lastY=o,this.scheduleDraw();return}if(this.downPos&&Math.hypot(i.clientX-this.downPos.x,i.clientY-this.downPos.y)<1.5&&!this.drag.moved)return;let m=this.getCam(t,c,u),[h,f]=Ht(m,a,o,c,u),w=[Math.round(h*1000)/1000,Math.round(f*1000)/1000];this.drag.moved=!0,this.drag.pts[this.drag.idx]=w;let C=this.drag.pts.map((A)=>[A[0],A[1]]);this.patchLocalItem(this.drag.id,this.drag.isPlane,C),this.scheduleDraw();return}let l=this.getCam(t,c,u),p=Dt(s.bands,s.regions,t,s.selectedId,l,c,u,a,o),d=this.hover?.hit?"id"in this.hover.hit?this.hover.hit.id:"":"",g=this.hover?.hit.kind??"",y=p?p.id:"";if(this.hover=p?{layer:t,hit:p}:null,e.style.cursor=p?"pointer":"crosshair",d!==y||(p?.kind??"")!==g)this.syncHoverHud(t),this.scheduleDraw()}),e.addEventListener("pointerleave",()=>{if(this.hover?.layer===t)this.hover=null,this.syncHoverHud(t),this.scheduleDraw()});let n=()=>{let i=this.drag;if(!i||i.layer!==t)return;if(this.drag=null,this.downPos=null,i.kind==="vertex"&&i.moved){let s=i.origPts.map((r)=>[r[0],r[1]]);this.patchLocalItem(i.id,i.isPlane,s)}this.cb.onDragEnd?.(),this.scheduleDraw()};e.addEventListener("pointercancel",n),e.addEventListener("lostpointercapture",n),e.addEventListener("pointerup",(i)=>{let s=this.state,r=this.drag,a=this.downPos;if(this.drag=null,this.downPos=null,e.hasPointerCapture(i.pointerId))e.releasePointerCapture(i.pointerId);if(r&&r.kind==="vertex"&&r.layer===t){if(r.moved)this.cb.onCommitFields(r.id,{[r.isPlane?"outline":"path"]:r.pts});else this.cb.onDragEnd?.(),this.scheduleDraw();return}if(s&&a&&Math.hypot(i.clientX-a.x,i.clientY-a.y)<4.5){let o=e.getBoundingClientRect(),c=i.clientX-o.left,u=i.clientY-o.top,l=Math.max(1,o.width),p=Math.max(1,o.height),d=this.getCam(t,l,p),g=Dt(s.bands,s.regions,t,s.selectedId,d,l,p,c,u);if(g&&(g.kind==="band"||g.kind==="region")){this.cb.onSelect(g.id),this.cb.onFocusItem(g.id);return}if(!g&&s.selectedId){this.cb.onSelect("");return}}this.cb.onDragEnd?.()}),e.addEventListener("wheel",(i)=>{i.preventDefault();let s=e.getBoundingClientRect(),r=i.clientX-s.left,a=i.clientY-s.top,o=Math.max(1,s.width),c=Math.max(1,s.height),u=this.getCam(t,o,c),l=Math.max(0.65,Math.min(1.55,1-i.deltaY*0.002));this.setCam(t,pi(u,l,r,a,o,c)),this.scheduleDraw()},{passive:!1})}patchLocalItem(e,t,n){let i=this.state;if(!i)return;if(t){let s=i.regions.find((r)=>r.id===e);if(s){if(s.outline=n,s.edited=!0,s.state==="proposed")s.state="edited"}}else{let s=i.bands.find((r)=>r.id===e);if(s){if(s.path=n,s.edited=!0,s.state==="proposed")s.state="edited"}}}getItemPts(e,t){let n=this.state;if(!n)return[];if(t)return(n.regions.find((i)=>i.id===e)?.outline??[]).map((i)=>[i[0],i[1]]);return(n.bands.find((i)=>i.id===e)?.path??[]).map((i)=>[i[0],i[1]])}syncHoverHud(e){let t=this.cards.get(e),n=this.state;if(!t||!n)return;if(!this.hover||this.hover.layer!==e){t.hoverHudEl.classList.add("bp-hidden"),t.hoverHudEl.textContent="";return}let i=this.hover.hit.id,s=n.bands.find((o)=>o.id===i),r=n.regions.find((o)=>o.id===i),a="";if(s)a=`${s.name||i} · ${s.nets??0}n · ${(s.width??1.5).toFixed(2)}mm`;else if(r)a=r.reference?`${r.net||i} · ${r.reference}`:r.net||i;if(!a)t.hoverHudEl.classList.add("bp-hidden");else t.hoverHudEl.classList.remove("bp-hidden"),t.hoverHudEl.textContent=a}onKeyDown(e){let t=this.state;if(!t)return;if(e.key==="0"||e.key==="Home"){e.preventDefault(),this.fitAll();return}if(e.key==="Escape"){this.selectedVertex=null,this.cb.onSelect("");return}if(!t.selectedId)return;let n=t.bands.find((a)=>a.id===t.selectedId),i=t.regions.find((a)=>a.id===t.selectedId),s=Boolean(n?.locked??i?.locked),r=e.key.toLowerCase();if(r==="a")e.preventDefault(),this.cb.onQuickApprove([t.selectedId],!0);else if(r==="r")e.preventDefault(),this.cb.onQuickApprove([t.selectedId],!1);else if(r==="l")e.preventDefault(),this.cb.onCommitFields(t.selectedId,{locked:!s});else if(r==="w"&&n&&!s){e.preventDefault();let a=e.shiftKey?-0.25:0.25,o=Math.round(Math.max(0.15,Math.min(25,(n.width??1.5)+a))*100)/100;this.cb.onCommitFields(t.selectedId,{width:o})}else if((e.key==="Delete"||e.key==="Backspace")&&!s&&this.selectedVertex?.id===t.selectedId){e.preventDefault();let a=Boolean(i),o=this.getItemPts(t.selectedId,a),c=rn(o,this.selectedVertex.idx,a);if(c)this.selectedVertex=null,this.cb.onCommitFields(t.selectedId,{[a?"outline":"path"]:c})}}scheduleDraw(){if(this.rafPending)return;this.rafPending=requestAnimationFrame(()=>{this.rafPending=0,this.drawAll()})}drawAll(){let e=this.state;if(!e)return;let t=Math.max(0.45,Math.min(1.25,Math.abs(this.effectiveBbox(e.board)[3]-this.effectiveBbox(e.board)[1])/Math.max(1,Math.abs(this.effectiveBbox(e.board)[2]-this.effectiveBbox(e.board)[0]))));for(let n of this.cards.values()){let i=n.canvas.parentElement;if(!i)continue;let s=Math.max(120,Math.round(i.clientWidth)),r=Math.max(165,Math.min(250,Math.round(s*t)));n.canvas.style.height=`${r}px`;let a=Math.max(1,window.devicePixelRatio||1),o=Math.round(s*a),c=Math.round(r*a);if(n.canvas.width!==o||n.canvas.height!==c)n.canvas.width=o,n.canvas.height=c;n.ctx.setTransform(a,0,0,a,0,0),this.drawLayer(n.ctx,n.layer,s,r,e)}}drawLayer(e,t,n,i,s){let r=this.getCam(t,n,i),a=(m,h)=>Ve(r,m,h,n,i);e.fillStyle=yi,e.fillRect(0,0,n,i);let o=(s.board.outline??[]).filter((m)=>m.length>=3);if(e.fillStyle=As,o.length>0){e.beginPath();for(let m of o){for(let h=0;hm.layer===t),u=this.hover?.layer===t?this.hover.hit:null;for(let m of c){let h=m.outline??[];if(h.length<3)continue;let f=s.selectedId===m.id,w=u?.id===m.id,C=Ts(m.state||"proposed",f,w),A=Et(m.net||m.id,m.color||"");e.beginPath();for(let S=0;SB)B=H;if(ae>R)R=ae}if(Math.abs(B-S)>=38&&Math.abs(R-T)>=18){let O=hi(h,m.holes??[]);if(O){let[H,ae]=a(O[0],O[1]);e.fillStyle=st(A,f?0.91:0.67),e.font="bold 10px ui-monospace, 'SFMono-Regular', Menlo, monospace",e.textAlign="center",e.textBaseline="middle",e.fillText(M,H,ae)}}}}if(e.strokeStyle=Ls,e.lineWidth=1.25,e.lineCap="round",e.lineJoin="round",o.length>0){e.beginPath();for(let m of o){for(let h=0;hm.layer===t),d=bi(p,r,n,i,s.selectedId,u?.id??""),g=d.map((m)=>[m.cx-m.pw*0.5-1,m.cy-m.ph*0.5-1,m.cx+m.pw*0.5+1,m.cy+m.ph*0.5+1]),y=[];for(let m of p){for(let h of m.from??[])y.push(h);for(let h of m.to??[])y.push(h)}e.fillStyle="rgba(143, 163, 155, 0.72)",e.font="9.5px ui-monospace, 'SFMono-Regular', Menlo, monospace",e.textAlign="center",e.textBaseline="middle";for(let m of gi(l,r,n,i,y,g))e.fillText(m.text,m.cx,m.cy);for(let m of p){let h=m.guides??[];if(h.length===0)continue;let f=s.selectedId===m.id||u?.id===m.id,w=lt(m.name||m.id,m.color||"");e.strokeStyle=st(w,f?0.38:0.17),e.lineWidth=f?1:0.7,e.beginPath();for(let C of h){let[A,M]=a(C[0],C[1]),[S,T]=a(C[2],C[3]);e.moveTo(A,M),e.lineTo(S,T)}e.stroke()}for(let m of p){let h=m.path??[];if(h.length<2)continue;let f=s.selectedId===m.id,w=u?.id===m.id,C=Ms(m.state||"proposed",f,w),A=lt(m.name||m.id,m.color||""),M=an(m.width??1.5,r.scale),S=()=>{e.beginPath();for(let T=0;T{let w=f?h.length:Math.max(0,h.length-1);for(let C=0;Cn.id===e))return;if(this.openPanel!==e)this.togglePanel(e)}getTabs(){return It(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=It(e);if(!this.digest||t.length===0){this.planCanvas?.destroy(),this.planCanvas=null,this.panelEl.classList.remove("bp-plan-expanded"),this.stripEl.classList.add("bp-hidden"),this.panelEl.classList.add("bp-hidden"),this.panelEl.removeAttribute("data-testid"),this.panelEl.replaceChildren(),this.stripEl.replaceChildren(),this.cb.onOpenChange?.(!1);return}this.stripEl.classList.remove("bp-hidden");let n=document.createDocumentFragment(),i=document.createElement("div");i.className="bp-mgmt-tabs";for(let a of t){let o=document.createElement("button");o.type="button";let c=this.openPanel===a.id;o.className="bp-mgmt-tab"+(c?" active":""),o.setAttribute("data-testid",`mgmt-tab-${a.id}`),o.setAttribute("aria-pressed",c?"true":"false");let u=document.createElement("span");u.textContent=pe(a.label),o.appendChild(u);let l=this.getPanelData(a.id),p=Yn(l);if(p){let d=document.createElement("span");d.className=`bp-mgmt-badge bp-tone-${p.tone}`,d.textContent=p.text,o.appendChild(d)}o.addEventListener("click",()=>this.togglePanel(a.id)),i.appendChild(o)}if(n.appendChild(i),this.openPanel){let a=document.createElement("button");a.type="button",a.className="icon bp-mgmt-close",a.textContent="×",a.title=b("gpui.mgmt.close","Close the panel"),a.setAttribute("aria-label",b("gpui.mgmt.close","Close the panel")),a.setAttribute("data-testid","mgmt-close"),a.addEventListener("click",()=>this.closePanel()),n.appendChild(a)}if(this.stripEl.replaceChildren(n),!this.openPanel){this.planCanvas?.destroy(),this.planCanvas=null,this.panelEl.classList.remove("bp-plan-expanded"),this.panelEl.classList.add("bp-hidden"),this.panelEl.removeAttribute("data-testid"),this.panelEl.replaceChildren(),this.cb.onOpenChange?.(!1);return}if(this.openPanel!=="plan")this.planCanvas?.destroy(),this.planCanvas=null,this.panelEl.classList.remove("bp-plan-expanded");else this.panelEl.classList.toggle("bp-plan-expanded",this.planExpanded);this.panelEl.classList.remove("bp-hidden"),this.panelEl.setAttribute("data-testid",`mgmt-panel-${this.openPanel}`),this.cb.onOpenChange?.(!0);let s=this.openPanel==="plan"&&this.planCanvas!==null&&document.activeElement instanceof HTMLElement&&this.panelEl.contains(document.activeElement)&&(document.activeElement===this.planCanvas.root||this.planCanvas.root.contains(document.activeElement)),r=document.createDocumentFragment();if(this.errorMsg){let a=document.createElement("div");a.className="bp-mgmt-note bp-tone-bad",a.textContent=this.errorMsg,r.appendChild(a)}switch(this.openPanel){case"bom":r.appendChild(this.renderBom());break;case"checks":r.appendChild(this.renderChecks());break;case"life":r.appendChild(this.renderLife());break;case"plan":r.appendChild(this.renderPlan());break;case"fab":r.appendChild(this.renderFab());break}if(this.panelEl.replaceChildren(r),s)this.planCanvas?.root.focus({preventScroll:!0})}renderBom(){let e=document.createElement("div");e.className="bp-mgmt-body";let t=this.getPanelData("bom");if(!t)return e.appendChild(this.makeEmpty("Reading the schematic…")),e;let n=Array.isArray(t.lines)?t.lines:[],i=document.createElement("div");i.className="bp-mgmt-head";let s=document.createElement("span");s.className="bp-dim",s.textContent=`${t.parts??0} parts · ${n.length} lines`;let r=document.createElement("span"),a=t.source==="kicad";if(r.className="bp-mgmt-pill"+(a?" accent":""),r.textContent=a?"live":"saved",i.append(s,r),(t.priced??0)>0&&(t.checking??0)===0&&typeof t.cost==="number"){let u=document.createElement("span");u.className="bp-dim",u.textContent=(t.priced??0)<(t.lookups??0)?`≥ ${ot(t.cost)}/board`:`${ot(t.cost)}/board`,i.appendChild(u)}if(t.paused){let u=document.createElement("span");u.className="bp-mgmt-faint",u.textContent="Stock check paused",i.appendChild(u)}if(e.appendChild(i),t.stock_note){let u=document.createElement("div");u.className="bp-mgmt-note bp-mgmt-faint",u.textContent=pe(t.stock_note),e.appendChild(u)}let o=this.bomEditingId?n.find((u)=>u.id===this.bomEditingId)??null:null;if(o)e.appendChild(this.renderBomEditor(o));else{let u=document.createElement("div");u.className="bp-mgmt-filter-row";let l=document.createElement("input");l.type="text",l.className="bp-mgmt-filter",l.placeholder="Filter BOM (ref, value, footprint, MPN, dnp)…",l.value=this.bomFilter,l.setAttribute("data-testid","mgmt-bom-filter"),l.addEventListener("input",()=>{this.bomFilter=l.value,this.renderBomRows(c,n)}),u.appendChild(l),e.appendChild(u)}let c=document.createElement("div");return c.className="bp-mgmt-rows",c.setAttribute("data-testid","mgmt-bom-rows"),this.renderBomRows(c,n),e.appendChild(c),e}renderBomRows(e,t){let n=Qn(t,this.bomFilter);if(n.length===0){e.replaceChildren(this.makeEmpty(t.length===0?"No parts found.":"No matching lines."));return}let i=t.some((r)=>Boolean(r.mpn)||Boolean(r.fab)),s=document.createDocumentFragment();for(let r of n){let a=Array.isArray(r.refs)?r.refs:[],o=document.createElement("div");o.className="bp-mgmt-row"+(this.bomSelectedId===r.id?" active":"")+(r.dnp?" faint":""),o.setAttribute("data-testid",`mgmt-bom-row-${r.id}`);let c=document.createElement("div");c.className="bp-mgmt-row-line";let u=document.createElement("span");if(u.className="bp-mgmt-strong bp-mgmt-flex1",u.textContent=Rt(a,24),c.appendChild(u),r.dnp){let m=document.createElement("span");m.className="bp-mgmt-pill",m.textContent=b("gpui.mgmt.bom.dnp","DNP"),c.appendChild(m)}else{let m=Zn(r.stock);if(m){let h=document.createElement("span");h.className=`bp-tone-${m.tone}`,h.textContent=m.text,c.appendChild(h)}}let l=document.createElement("button");l.type="button",l.className="bp-mgmt-btn",l.textContent="Edit",l.addEventListener("click",(m)=>{m.stopPropagation(),this.bomEditGen++,this.bomEditingId=r.id,this.bomEditDraft=r.mpn??"",this.bomEditStatus="",this.bomLastUndo=null,this.render()}),c.appendChild(l);let p=document.createElement("div");p.className="bp-mgmt-row-sub";let d=[`${r.qty??a.length}×`,r.value??"",Xn(r.footprint??"")].filter(Boolean).join(" · "),g=document.createElement("span");g.className="bp-dim",g.textContent=d;let y=document.createElement("span");if(y.className="bp-mgmt-flex1",r.mpn)y.textContent=r.mpn;else if(i&&!r.dnp)y.className+=" bp-tone-warn",y.textContent=b("gpui.mgmt.bom.nompn","no MPN");if(p.append(g,y),!r.dnp&&typeof r.stock?.price==="number"){let m=document.createElement("span");m.className="bp-dim",m.textContent=ot(r.stock.price),p.appendChild(m)}if(!r.dnp&&r.stock?.class){let m=document.createElement("span");m.className="bp-mgmt-faint",m.textContent=pe(r.stock.class),p.appendChild(m)}o.append(c,p),o.addEventListener("click",()=>{this.bomSelectedId=r.id,this.renderBomRows(e,t)}),s.appendChild(o)}e.replaceChildren(s)}renderBomEditor(e){let t=document.createElement("div");t.className="bp-mgmt-editor",t.setAttribute("data-testid","mgmt-bom-edit");let n=Array.isArray(e.refs)?e.refs:[],i=document.createElement("div");i.className="bp-mgmt-row-line";let s=document.createElement("span");s.className="bp-mgmt-strong",s.textContent=Rt(n,30);let r=document.createElement("button");r.type="button",r.className="icon",r.textContent="×",r.addEventListener("click",()=>{this.bomEditGen++,this.bomEditingId="",this.bomLastUndo=null,this.bomEditStatus="",this.render()}),i.append(s,r);let a=document.createElement("input");a.type="text",a.className="bp-mgmt-filter",a.placeholder="MPN",a.value=this.bomEditDraft,a.addEventListener("input",()=>{this.bomEditDraft=a.value});let o=()=>({watchGen:this.watchGen,editGen:this.bomEditGen,project:this.project,editId:this.bomEditingId}),c=async(d,g=!1)=>{let y=o();this.bomEditStatus="Writing…",this.render();try{let m=await this.cb.hub.rpc("mgmt.bom.edit",d);if(!nn(y,o()))return;this.bomLastUndo=!g&&(m.changed??0)>0?{project:d.project,editId:y.editId,refs:d.refs.slice(),field:d.field,was:typeof m.was==="string"?m.was:d.field==="mpn"?e.mpn??"":e.dnp?"yes":"no"}:null,this.bomEditStatus=g?"Restored":(m.changed??0)===0?"No change":m.via==="kicad"?"Updated in KiCad":"Saved to schematic"}catch(m){if(!nn(y,o()))return;this.bomEditStatus=m instanceof Error?m.message:"Could not save edit"}this.render()},u=document.createElement("div");u.className="bp-mgmt-btn-row";let l=document.createElement("button");l.type="button",l.className="primary bp-mgmt-btn",l.textContent="Save MPN",l.addEventListener("click",()=>{c({project:this.project,refs:n.slice(),field:"mpn",value:this.bomEditDraft.trim()})});let p=document.createElement("button");if(p.type="button",p.className="bp-mgmt-btn",p.textContent=e.dnp?"Clear DNP":"Mark DNP",p.addEventListener("click",()=>{c({project:this.project,refs:n.slice(),field:"dnp",value:e.dnp?"no":"yes"})}),u.append(l,p),this.bomLastUndo&&this.bomLastUndo.project===this.project&&this.bomLastUndo.editId===this.bomEditingId){let d=this.bomLastUndo,g=document.createElement("button");g.type="button",g.className="bp-mgmt-btn",g.textContent="Undo",g.addEventListener("click",()=>{c(oi(d),!0)}),u.appendChild(g)}if(t.append(i,a,u),this.bomEditStatus){let d=document.createElement("div");d.className="bp-mgmt-faint",d.textContent=this.bomEditStatus,t.appendChild(d)}return t}renderChecks(){let e=document.createElement("div");e.className="bp-mgmt-body";let t=this.getPanelData("checks");if(!t)return e.appendChild(this.makeEmpty("Reading checks…")),e;let n=Array.isArray(t.groups)?t.groups:[],i=Array.from(new Set(n.map((d)=>d.source).filter(Boolean))),s=(d)=>t.sources?.[d]?.label||d.toUpperCase(),r=(d)=>t.sources?.[d]?.judged===!0,a=document.createElement("div");a.className="bp-mgmt-head bp-mgmt-scroll-x";let o=document.createElement("button");o.type="button",o.className="bp-mgmt-btn"+(this.checksSource===""?" active":""),o.textContent=b("gpui.mgmt.checks.all","All"),o.addEventListener("click",()=>{this.checksSource="",this.render()}),a.appendChild(o);for(let d of i){let g=document.createElement("button");g.type="button",g.className="bp-mgmt-btn"+(this.checksSource===d?" active":""),g.textContent=s(d)+(r(d)?" · judged":""),g.addEventListener("click",()=>{this.checksSource=this.checksSource===d?"":d,this.render()}),a.appendChild(g)}let c=document.createElement("span");c.className="bp-mgmt-flex1";let u=document.createElement("button");if(u.type="button",u.className="bp-mgmt-btn",u.textContent=b("gpui.mgmt.checks.run","Run"),u.addEventListener("click",()=>{let d=this.watchGen,g=this.project;this.checksStatus="Running checks…",this.render(),this.cb.hub.rpc("kicad.checks.run",{project:g}).then(()=>{if(d!==this.watchGen||g!==this.project)return;this.checksStatus="",this.render()}).catch((y)=>{if(d!==this.watchGen||g!==this.project)return;this.checksStatus=y instanceof Error?y.message:"Could not run checks",this.render()})}),a.append(c,u),e.appendChild(a),this.checksStatus){let d=document.createElement("div");d.className="bp-mgmt-note bp-dim",d.textContent=this.checksStatus,e.appendChild(d)}let l=document.createElement("div");l.className="bp-mgmt-rows",l.setAttribute("data-testid","mgmt-checks-rows");let p=ei(n,this.checksSource);if(p.length===0)l.appendChild(this.makeEmpty("No check findings."));else for(let d of p){let g=d.severity==="error"?"bad":d.severity==="warning"?"warn":"faint",y=document.createElement("div");y.className="bp-mgmt-group-head";let m=document.createElement("span");m.className=`bp-mgmt-dot bp-tone-bg-${g}`;let h=document.createElement("span");h.className="bp-mgmt-flex1",h.textContent=`${s(d.source)} · ${d.rule}`;let f=document.createElement("span");f.className=`bp-tone-${g}`,f.textContent=String(d.n),y.append(m,h,f),l.appendChild(y);for(let w of d.rows??[]){let C=document.createElement("div");C.className="bp-mgmt-row"+(this.checksSelectedId===w.id?" active":"");let A=document.createElement("div");if(A.textContent=pe(w.title??""),C.appendChild(A),w.names||this.checksSelectedId===w.id){let M=document.createElement("div");M.className="bp-mgmt-row-sub";let S=document.createElement("span");if(S.className="bp-dim bp-mgmt-flex1",S.textContent=w.names??"",M.appendChild(S),this.checksSelectedId===w.id){let T=document.createElement("button");T.type="button",T.className="bp-mgmt-btn accent",T.textContent=b("gpui.mgmt.checks.fix","Fix with agent"),T.addEventListener("click",(B)=>{B.stopPropagation();let R={watchGen:this.watchGen,project:this.project,threadId:this.cb.getThreadId(),threadGen:this.cb.getThreadGen()};this.cb.hub.rpc("kicad.checks.fix",{project:R.project,id:w.id}).then((O)=>{let H={watchGen:this.watchGen,project:this.project,threadId:this.cb.getThreadId(),threadGen:this.cb.getThreadGen()};if(!sn(R,H))return;if(O.text)this.cb.onSendText(O.text),this.checksStatus="Sent to agent",this.render()}).catch((O)=>{let H={watchGen:this.watchGen,project:this.project,threadId:this.cb.getThreadId(),threadGen:this.cb.getThreadGen()};if(!sn(R,H))return;this.checksStatus=O instanceof Error?O.message:"Could not send finding",this.render()})}),M.appendChild(T)}C.appendChild(M)}C.addEventListener("click",()=>{this.checksSelectedId=w.id,this.cb.hub.rpc("kicad.checks.focus",{project:this.project,id:w.id}).catch(()=>{}),this.render()}),l.appendChild(C)}}return e.appendChild(l),e}renderLife(){let e=document.createElement("div");e.className="bp-mgmt-body";let t=this.getPanelData("life");if(!t)return e.appendChild(this.makeEmpty("Reading lifecycle…")),e;let n=document.createElement("div");n.className="bp-mgmt-head";let i=t.counts??{};for(let c of["active","nrnd","eol"]){let u=i[c]??0,l=tn(c),p=document.createElement("span");p.className=u>0?`bp-tone-${l.tone}`:"bp-mgmt-faint",p.textContent=`${l.label} ${u}`,n.appendChild(p)}if((i.unknown??0)>0){let c=document.createElement("span");c.className="bp-mgmt-faint",c.textContent=`${i.unknown} unknown`,n.appendChild(c)}if(t.since){let c=document.createElement("span");c.className="bp-mgmt-flex1";let u=document.createElement("span");u.className="bp-mgmt-faint",u.textContent=`since ${jt(t.since)} (${t.samples??0})`,n.append(c,u)}e.appendChild(n);let s=document.createElement("div");s.className="bp-mgmt-rows",s.setAttribute("data-testid","mgmt-life-rows");let r=t.bom?.cost??[],a=t.bom?.instock??[],o=t.bom?.lines??0;if(r.length===0)s.appendChild(this.makeEmpty(o===0?"No line has an MPN or fab part number to follow yet.":"No reading of the fab's stock yet: the BOM panel's lookups start it."));else{let c=r[r.length-1],u=a[a.length-1],l=document.createElement("div");l.className="bp-mgmt-note bp-dim",l.textContent=`Parts/board: ${ot(c[1])} · ${Math.round(u?.[1]??0)}/${o} lines in stock (${jt(c[0])})`,s.appendChild(l)}for(let c of t.parts??[]){let u=this.lifeSelectedKey===c.key,l=tn(c.lifecycle??"unknown"),p=document.createElement("div");p.className="bp-mgmt-row"+(u?" active":"");let d=document.createElement("div");d.className="bp-mgmt-row-line";let g=document.createElement("span");g.className="bp-mgmt-strong",g.textContent=Rt(c.refs??[],14);let y=document.createElement("span");y.className="bp-mgmt-flex1 bp-dim",y.textContent=c.mpn||c.key;let m=document.createElement("span");if(m.className=`bp-tone-${l.tone}`,m.textContent=l.label,d.append(g,y,m),typeof c.stock==="number"){let h=document.createElement("span");h.className="bp-dim",h.textContent=at(c.stock),d.appendChild(h)}if(p.appendChild(d),u){let h=document.createElement("div");if(h.className="bp-mgmt-row-sub bp-mgmt-faint",this.lifePartLoading)h.textContent=b("gpui.mgmt.life.reading","Reading its history…");else if(this.lifePartSamples&&this.lifePartSamples.length>0){let f=this.lifePartSamples[this.lifePartSamples.length-1];h.textContent=`${this.lifePartSamples.length} samples · latest ${f.at?jt(f.at):""}`+(typeof f.stock==="number"?` · stock ${at(f.stock)}`:"")+(typeof f.price==="number"?` · ${ot(f.price)}`:"")}else h.textContent=b("gpui.mgmt.life.nopart","No reading of this part yet.");p.appendChild(h)}p.addEventListener("click",()=>{if(this.lifeSelectedKey===c.key){this.lifeSelectedKey="",this.lifePartSamples=null,this.render();return}this.lifeSelectedKey=c.key,this.lifePartSamples=null,this.lifePartLoading=!0,this.render(),this.cb.hub.rpc("mgmt.life.part",{project:this.project,key:c.key}).then((h)=>{if(this.lifeSelectedKey!==c.key)return;this.lifePartLoading=!1,this.lifePartSamples=Array.isArray(h.samples)?h.samples:[],this.render()}).catch(()=>{if(this.lifeSelectedKey!==c.key)return;this.lifePartLoading=!1,this.lifePartSamples=[],this.render()})}),s.appendChild(p)}return e.appendChild(s),e}renderPlan(){let e=document.createElement("div");e.className="bp-mgmt-body";let t=this.getPanelData("plan");if(!t)return e.appendChild(this.makeEmpty(b("gpui.mgmt.plan.reading","Reading the routing plan…"))),e;let n=(E,k)=>{let j=this.watchGen,P=this.project;this.planStatus="",this.cb.hub.rpc(E,{pro:P,...k}).catch((K)=>{if(j!==this.watchGen||P!==this.project)return;this.planOptimistic.clear(),this.planStatus=K instanceof Error?K.message:b("gpui.mgmt.plan.refused","KiCad refused"),this.render()})};if(t.revision!==this.planOptimisticRev)this.planOptimisticRev=t.revision,this.planOptimistic.clear();let i=`${this.project}:${t.revision??0}`;if(t.board_trimmed&&this.planHydrateAskedKey!==i&&this.project){this.planHydrateAskedKey=i;let E=this.watchGen,k=++this.planHydrateGen,j=this.project,P=t.revision??0;this.cb.hub.rpc("plan.get",{pro:j,board:!0}).then((K)=>{let ee=fi(K);if(!ee)return;let D=typeof ee.revision==="number"?ee.revision:P;if(!vi(E,this.watchGen,k,this.planHydrateGen,j,this.project,D,this.planHydratedRev))return;this.planHydratedRev=D,this.planHydratedKey=`${j}:${D}`,this.planHydratedBoard=ee.board??null,this.planHydratedDraw=ee.draw??null,this.render()}).catch(()=>{})}let s=t.on===!0,r=document.createElement("div");r.className="bp-plan-header";let a=document.createElement("div");a.className="bp-plan-toggle";let o=document.createElement("span");o.className="bp-mgmt-strong",o.textContent=b("gpui.mgmt.plan.before","Plan before routing"),o.title=s?b("gpui.mgmt.plan.onwords","Before routing a board with 4 or more copper layers or more than 60 nets, the agent proposes corridors and plane regions here. It routes only what you approve."):b("gpui.mgmt.plan.offwords","Agents route as you ask. Turn it on to have them propose a routing plan first and route only what you approve here."),a.appendChild(o);let c=t.awaiting??0,u=t.blocked??0,l=t.done??0,p=t.total??0,d=t.revision??0,g=t.empty?[]:si(t),y=g.reduce((E,k)=>E+k.count,0);if(!t.empty){let E=ii(t),k=document.createElement("span");if(k.className=`bp-plan-status-badge tone-${E.tone}`,k.textContent=b(E.key,E.label),a.appendChild(k),d>0){let P=document.createElement("span");P.className="bp-dim",P.textContent=`v${d}`,a.appendChild(P)}let j=document.createElement("span");if(j.className="bp-plan-header-counts bp-mgmt-flex1 "+(c>0?"bp-tone-warn":u>0?"bp-tone-bad":"bp-dim"),j.textContent=p>0?`${l}/${p} ${b("gpui.mgmt.plan.done","done")}`:c>0?b("web.plan.awaiting","{n} awaiting approval",{n:c}):b("gpui.mgmt.plan.nothing","Nothing awaits your approval"),a.appendChild(j),!t.live){let P=document.createElement("span");P.className="bp-mgmt-pill",P.textContent=b("gpui.mgmt.plan.saved","saved plan"),a.appendChild(P)}}else{let E=document.createElement("span");E.className="bp-mgmt-flex1",a.appendChild(E)}let m=document.createElement("button");m.type="button",m.className="bp-mgmt-btn bp-plan-chip-btn"+(s?" active":""),m.setAttribute("data-testid","mgmt-plan-on"),m.setAttribute("aria-pressed",s?"true":"false"),m.textContent=b("gpui.bots.recall.on","On"),m.addEventListener("click",()=>n("plan.enable",{on:!0}));let h=document.createElement("button");if(h.type="button",h.className="bp-mgmt-btn bp-plan-chip-btn"+(!s?" active":""),h.setAttribute("data-testid","mgmt-plan-off"),h.setAttribute("aria-pressed",!s?"true":"false"),h.textContent=b("gpui.bots.recall.off","Off"),h.addEventListener("click",()=>n("plan.enable",{on:!1})),a.append(m,h),r.appendChild(a),y>0){let E=document.createElement("div");E.className="bp-plan-segbar";for(let k of g){if(k.count<=0)continue;let j=document.createElement("div");j.className=`bp-plan-seg bp-tone-bg-${k.tone}`,j.style.flexGrow=String(k.count),E.appendChild(j)}r.appendChild(E)}e.appendChild(r);for(let E of t.elsewhere??[]){let k=document.createElement("div");k.className="bp-plan-elsewhere";let j=document.createElement("span");j.className="bp-tone-warn bp-mgmt-flex1",j.textContent=b("gpui.mgmt.plan.elsewhere","A routing plan for {board} awaits your approval",{board:E.name||E.rel||""}),k.appendChild(j),e.appendChild(k)}if(t.empty){let E=document.createElement("div");E.className="bp-mgmt-note";let k=document.createElement("div");k.className="bp-dim",k.textContent=b("gpui.mgmt.plan.noboard","No routing plan for this board.");let j=document.createElement("div");return j.className="bp-mgmt-faint",j.textContent=b("gpui.mgmt.plan.emptysub","Layers, corridors, and planes appear here once a plan is proposed."),E.append(k,j),e.appendChild(E),e}let f=t.stackup_summary??"",w=Array.isArray(t.impedances)?t.impedances:[],C=Boolean(f)||w.length>0,A=document.createElement("div");if(A.className="bp-mgmt-head",c>0){let E=document.createElement("button");E.type="button",E.className="primary bp-mgmt-btn",E.setAttribute("data-testid","mgmt-plan-approve-all"),E.textContent=b("gpui.mgmt.plan.all","Approve all"),E.addEventListener("click",()=>n("plan.approve",{layer:"",ids:[],approve:!0})),A.appendChild(E)}if(t.routing){let E=document.createElement("button");E.type="button",E.className="bp-mgmt-btn",E.setAttribute("data-testid","mgmt-plan-stop"),E.textContent=b("gpui.mgmt.plan.stop","Stop routing"),E.addEventListener("click",()=>n("plan.stop",{})),A.appendChild(E)}if(t.live&&l>0){let E=document.createElement("button");E.type="button",E.className="bp-mgmt-btn",E.setAttribute("data-testid","mgmt-plan-verify"),E.textContent=b("gpui.mgmt.plan.verify","Verify"),E.addEventListener("click",()=>n("plan.verify",{})),A.appendChild(E)}let M=document.createElement("span");if(M.className="bp-mgmt-flex1",A.appendChild(M),C){let E=document.createElement("button");E.type="button",E.className="bp-mgmt-btn bp-plan-chip-btn"+(this.planStackupOpen?" active":""),E.setAttribute("data-testid","mgmt-plan-stackup-toggle"),E.setAttribute("aria-expanded",this.planStackupOpen?"true":"false"),E.textContent=`${b("gpui.mgmt.plan.stackup.short","Stackup")} ${this.planStackupOpen?"▾":"▸"}`,E.addEventListener("click",()=>{this.planStackupOpen=!this.planStackupOpen,this.render()}),A.appendChild(E)}let S=document.createElement("button");S.type="button",S.className="bp-mgmt-btn",S.setAttribute("data-testid","mgmt-plan-hide"),S.textContent=this.planHideDone?b("gpui.mgmt.plan.show","Show done"):b("gpui.mgmt.plan.hide","Hide done"),S.addEventListener("click",()=>{this.planHideDone=!this.planHideDone,this.render()}),A.appendChild(S),e.appendChild(A);let T=Array.isArray(t.asks)?t.asks:[];if(T.length>0){let E=T.map((ee)=>ee.what||"").filter(Boolean).join(", "),k=T[0]?.note||"",j=document.createElement("div");j.className="bp-plan-elsewhere";let P=document.createElement("div");P.className="bp-plan-ask-col";let K=document.createElement("div");if(K.className="bp-tone-warn",K.textContent=E?b("gpui.mgmt.plan.requested","Approval requested: {what}",{what:E}):b("gpui.mgmt.plan.reqplain","Approval requested"),P.appendChild(K),k){let ee=document.createElement("div");ee.className="bp-dim",ee.textContent=k,P.appendChild(ee)}j.appendChild(P),e.appendChild(j)}if(this.planStatus){let E=document.createElement("div");E.className="bp-mgmt-note bp-plan-err bp-tone-bad";let k=document.createElement("span");k.className="bp-mgmt-flex1",k.textContent=this.planStatus==="KiCad refused"?b("gpui.mgmt.plan.refused","KiCad refused"):pe(this.planStatus);let j=document.createElement("button");j.type="button",j.className="icon",j.textContent="×",j.title=b("common.close","Close"),j.addEventListener("click",()=>{this.planStatus="",this.render()}),E.append(k,j),e.appendChild(E)}if(t.keys_note){let E=document.createElement("div");E.className="bp-mgmt-note bp-dim";let k="On this KiCad version, approve from this panel: in plan view KiCad's A, R and W keys aren't the plan's yet (A opens Add Footprint). Update KiCad.";E.textContent=t.keys_note===k?b("gpui.mgmt.plan.keysnote",k):pe(t.keys_note),e.appendChild(E)}if(C&&this.planStackupOpen){let E=document.createElement("div");if(E.className="bp-plan-stackup-body",E.setAttribute("data-testid","mgmt-plan-stackup-body"),f){let k=document.createElement("div");k.className="bp-dim",k.textContent=f,E.appendChild(k)}for(let k of w){let j=document.createElement("div");j.className="bp-mgmt-faint",j.textContent=`· ${k}`,E.appendChild(j)}e.appendChild(E)}let B=(E,k,j,P)=>{let K=document.createElement("button");return K.type="button",K.className="bp-mgmt-btn bp-plan-chip-btn"+(k?" active":""),K.setAttribute("data-testid",j),K.setAttribute("aria-pressed",k?"true":"false"),K.textContent=E,K.addEventListener("click",P),K},R=document.createElement("div");if(R.className="bp-plan-viewbar",R.append(B(b("gpui.mgmt.plan.view.canvas","Canvas"),this.planViewMode==="canvas","mgmt-plan-view-canvas",()=>{this.planViewMode="canvas",this.render()}),B(b("gpui.mgmt.plan.view.split","Split"),this.planViewMode==="split","mgmt-plan-view-split",()=>{this.planViewMode="split",this.render()}),B(b("gpui.mgmt.plan.view.list","List"),this.planViewMode==="list","mgmt-plan-view-list",()=>{this.planViewMode="list",this.render()})),this.planViewMode!=="list"){let E=document.createElement("span");E.className="bp-plan-sep";let k=document.createElement("span");k.className="bp-plan-sep";let j=document.createElement("button");j.type="button",j.className="bp-mgmt-btn bp-plan-mini-btn",j.setAttribute("data-testid","mgmt-plan-fit"),j.textContent=b("gpui.mgmt.plan.fit","Fit"),j.addEventListener("click",()=>this.planCanvas?.fitAll()),R.append(E,B(b("gpui.mgmt.plan.grid.pair","Side by side"),this.planGridMode==="pair","mgmt-plan-grid-pair",()=>{this.planGridMode="pair",this.render()}),B(b("gpui.mgmt.plan.grid.all","All layers"),this.planGridMode==="all","mgmt-plan-grid-all",()=>{this.planGridMode="all",this.render()}),B(b("gpui.mgmt.plan.grid.single","Single"),this.planGridMode==="single","mgmt-plan-grid-single",()=>{this.planGridMode="single",this.render()}),k,B(b("gpui.mgmt.plan.sync","Link zoom"),this.planSyncZoom,"mgmt-plan-sync",()=>{this.planSyncZoom=!this.planSyncZoom,this.render()}),j)}let O=document.createElement("span");O.className="bp-mgmt-flex1";let H=document.createElement("button");H.type="button",H.className="bp-mgmt-btn bp-plan-mini-btn",H.setAttribute("data-testid","mgmt-plan-expand"),H.textContent=this.planExpanded?b("gpui.mgmt.plan.compact","Compact"):b("gpui.mgmt.plan.expand","Expand"),H.addEventListener("click",()=>{this.planExpanded=!this.planExpanded,this.render()}),R.append(O,H),e.appendChild(R);let ae=Boolean(this.planHydratedBoard)&&this.planHydratedKey.startsWith(`${this.project}:`)&&(this.planHydratedKey===i||this.planHydratedRev!==void 0&&this.planHydratedRev>=(t.revision??0)),ue=ae&&this.planHydratedBoard?this.planHydratedBoard:t.board??{bbox:[0,0,100,70],outline:[],parts:[]},oe=ae&&this.planHydratedDraw?this.planHydratedDraw:t.draw??{bands:[],regions:[]},we=(oe.bands??[]).map((E)=>{let k=this.planOptimistic.get(E.id);if(!k)return{...E};return{...E,...k,edited:!0,state:E.state==="proposed"?"edited":E.state}}),Le=(oe.regions??[]).map((E)=>{let k=this.planOptimistic.get(E.id);if(!k)return{...E};return{...E,...k,edited:!0,state:E.state==="proposed"?"edited":E.state}}),Ne=[],he=(t.layers??[]).map((E)=>{let k=[];for(let j of E.items??[]){let P=this.planOptimistic.get(j.id);if(!P){k.push(j);continue}let K={...j,width:typeof P.width==="number"?P.width:j.width,locked:typeof P.locked==="boolean"?P.locked:j.locked,edited:!0,state:j.state==="proposed"?"edited":j.state};if(typeof P.layer==="string"&&P.layer!==E.layer)Ne.push({target:P.layer,item:K});else k.push(K)}return{...E,items:k}});for(let E of Ne){let k=he.find((j)=>j.layer===E.target);if(k)k.items=[...k.items??[],E.item]}let be=Ft(he,t.copper_layers),I=this.planGridMode==="all"?be.map((E)=>E.layer):this.planGridMode==="single"?[this.planShownLayers.find((E)=>be.some((k)=>k.layer===E))??ct(be)[0]??be[0]?.layer??""].filter(Boolean):this.planShownLayers.length>0&&this.planShownLayers.every((E)=>be.some((k)=>k.layer===E))?this.planShownLayers.slice(0,2):ct(be);if(this.planViewMode!=="list"&&this.planGridMode!=="all"&&be.length>1){let E=document.createElement("div");E.className="bp-plan-layerbar";for(let k of be){let j=I.includes(k.layer),P=(k.items??[]).length,K=it(k.layer,t.copper_layers,be)||k.title||k.layer,ee=P>0?`${K} · ${P}`:K,D=B(ee,j,`mgmt-plan-layerpill-${k.layer}`,()=>{if(this.planGridMode==="single")this.planShownLayers=[k.layer];else if(this.planGridMode==="pair"){if(!I.includes(k.layer))this.planShownLayers=I.length>=2?[I[0],k.layer]:[...I,k.layer]}else this.planGridMode="single",this.planShownLayers=[k.layer];this.render()});if(P===0&&!j)D.classList.add("empty-layer");E.appendChild(D)}e.appendChild(E)}let le=(E,k)=>{let j=this.planOptimistic.get(E)??{};if(this.planOptimistic.set(E,{...j,...k}),typeof k.layer==="string"){if(this.planGridMode==="single")this.planShownLayers=[k.layer];else if(this.planGridMode==="pair"&&!I.includes(k.layer))this.planShownLayers=I.length>=2?[I[0],k.layer]:[...I,k.layer]}let P=typeof t.revision==="number"?t.revision:void 0;this.render(),n("plan.update",{ops:[{op:"set",id:E,fields:k}],...P!==void 0?{base:P}:{}})};if(this.planCommitFields=le,this.planSelectedId){let E="",k=null;for(let j of he){let P=(j.items??[]).find((K)=>K.id===this.planSelectedId);if(P){E=j.layer,k=P;break}}if(k){let j=it(E,t.copper_layers,be),P=document.createElement("div");P.className="bp-plan-inspector",P.setAttribute("data-testid","mgmt-plan-inspector");let K=document.createElement("div");K.className="bp-plan-ins-row";let ee=document.createElement("span");ee.className="bp-plan-ins-sw",ee.style.background=k.kind==="corridor"?lt(k.name||k.id,k.color||""):Et(k.name||k.id,k.color||"");let D=document.createElement("span");D.className="bp-mgmt-strong",D.textContent=k.name||k.id;let z=document.createElement("span");if(z.className="bp-dim",z.textContent=j,K.append(ee,D,z),k.edited||k.state==="edited"){let Y=document.createElement("span");Y.className="bp-plan-ins-pill warn",Y.textContent=b("gpui.mgmt.plan.edited","Edited"),K.appendChild(Y)}if(k.locked){let Y=document.createElement("span");Y.className="bp-plan-ins-pill",Y.textContent=b("gpui.mgmt.plan.locked","Locked"),K.appendChild(Y)}let je=document.createElement("span");je.className="bp-mgmt-flex1",K.appendChild(je);let Se=document.createElement("button");if(Se.type="button",Se.className="bp-mgmt-btn bp-plan-mini-btn",Se.setAttribute("data-testid","mgmt-plan-lock"),Se.textContent=k.locked?b("gpui.mgmt.plan.unlock","Unlock"):b("gpui.mgmt.plan.lock","Lock"),Se.addEventListener("click",()=>le(k.id,{locked:!k.locked})),K.appendChild(Se),k.state==="proposed"||k.state==="edited"){let Y=document.createElement("button");Y.type="button",Y.className="primary bp-mgmt-btn bp-plan-mini-btn",Y.textContent=b("android.hub.machines.approve","Approve"),Y.addEventListener("click",()=>n("plan.approve",{layer:"",ids:[k.id],approve:!0}));let fe=document.createElement("button");fe.type="button",fe.className="bp-mgmt-btn bp-plan-mini-btn",fe.textContent=b("gpui.mgmt.plan.reject","Reject"),fe.addEventListener("click",()=>n("plan.approve",{layer:"",ids:[k.id],approve:!1})),K.append(Y,fe)}let me=document.createElement("button");me.type="button",me.className="bp-mgmt-btn bp-plan-mini-btn",me.setAttribute("data-testid","mgmt-plan-note-toggle"),me.textContent=b("gpui.mgmt.plan.addnote","Add note"),me.addEventListener("click",()=>{this.planNoteOpen=!this.planNoteOpen,this.render()});let Me=document.createElement("button");if(Me.type="button",Me.className="icon",Me.textContent="×",Me.addEventListener("click",()=>{this.planSelectedId="",this.planNoteOpen=!1,this.planMoveLayerOpen=!1,this.render()}),K.append(me,Me),P.appendChild(K),!k.locked){let Y=document.createElement("div");if(Y.className="bp-plan-ins-row",k.kind==="corridor"){let ie=typeof k.width==="number"?k.width:1.5,ke=document.createElement("span");ke.className="bp-dim",ke.textContent=b("gpui.mgmt.plan.width","Width");let He=document.createElement("button");He.type="button",He.className="bp-mgmt-btn bp-plan-mini-btn",He.setAttribute("data-testid","mgmt-plan-w-down"),He.textContent="-",He.addEventListener("click",()=>{let Ue=Math.round(Math.max(0.15,ie-0.25)*100)/100;le(k.id,{width:Ue})});let re=document.createElement("span");re.className="bp-plan-ins-val",re.textContent=`${ie.toFixed(2)}mm`;let ge=document.createElement("button");ge.type="button",ge.className="bp-mgmt-btn bp-plan-mini-btn",ge.setAttribute("data-testid","mgmt-plan-w-up"),ge.textContent="+",ge.addEventListener("click",()=>{let Ue=Math.round(Math.min(25,ie+0.25)*100)/100;le(k.id,{width:Ue})});let _e=document.createElement("span");_e.className="bp-plan-sep",Y.append(ke,He,re,ge,_e)}let fe=(t.copper_layers??[]).length>0?(t.copper_layers??[]).map((ie)=>ie.layer):he.map((ie)=>ie.layer);if(fe.length>0){let ie=document.createElement("span");ie.className="bp-dim",ie.textContent=b("gpui.mgmt.plan.layer.short","Layer"),Y.appendChild(ie),Y.appendChild(B(`${j} ${this.planMoveLayerOpen?"▴":"▾"}`,this.planMoveLayerOpen,"mgmt-plan-move-toggle",()=>{this.planMoveLayerOpen=!this.planMoveLayerOpen,this.render()}))}if(P.appendChild(Y),this.planMoveLayerOpen&&fe.length>0){let ie=document.createElement("div");ie.className="bp-plan-ins-row";for(let ke of fe){let He=it(ke,t.copper_layers,be);ie.appendChild(B(He,ke===E,`mgmt-plan-move-${ke}`,()=>{if(this.planMoveLayerOpen=!1,ke!==E)le(k.id,{layer:ke});else this.render()}))}P.appendChild(ie)}}if(this.planNoteOpen){let Y=document.createElement("form");Y.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=b("gpui.mgmt.plan.note.placeholder","Steering note for router…");let ie=document.createElement("button");ie.type="submit",ie.className="primary bp-mgmt-btn bp-plan-mini-btn",ie.setAttribute("data-testid","mgmt-plan-note-submit"),ie.textContent=b("gpui.mgmt.plan.addnote","Add note"),Y.append(fe,ie),Y.addEventListener("submit",(ke)=>{ke.preventDefault();let He=fe.value.trim();if(!He)return;fe.value="",this.planNoteOpen=!1;let re=typeof t.revision==="number"?t.revision:void 0;this.render(),n("plan.update",{ops:[{op:"note",target:k.id,text:He}],...re!==void 0?{base:re}:{}})}),P.appendChild(Y)}if(this.planViewMode!=="list"&&!k.locked){let Y=document.createElement("div");Y.className="bp-plan-hint",Y.textContent=b("gpui.mgmt.plan.hint","Drag waypoints to steer · Click + on edge to insert · Right-click vertex to remove"),P.appendChild(Y)}e.appendChild(P)}}let ne=document.createElement("div");ne.className="bp-mgmt-rows"+(this.planViewMode==="split"?" bp-plan-split-list":""),ne.setAttribute("data-testid","mgmt-plan-rows");let X=b("gpui.mgmt.plan.done","done"),ce=ui(this.planViewMode,he,I);if(this.planViewMode==="split"&&ce.length===0){let E=document.createElement("div");E.className="bp-dim",E.style.padding="6px 8px",E.style.fontSize="11px",E.textContent=b("gpui.mgmt.plan.noitems","No corridors or planes on this layer"),ne.appendChild(E)}for(let E of ce){let k=E.items??[],j=it(E.layer,t.copper_layers,be)||E.layer;if(this.planViewMode==="split"){if(ce.length>1){let P=document.createElement("div");P.className="bp-plan-split-divider";let K=E.role==="power"||E.role==="plane",ee=document.createElement("span");ee.className="bp-plan-card-bar "+(K?"pwr":"sig");let D=document.createElement("span");D.className="bp-mgmt-strong",D.textContent=j;let z=document.createElement("span");z.className="bp-dim",z.textContent=`${E.done??0}/${k.length} ${X}`,P.append(ee,D,z),ne.appendChild(P)}}else{let P=document.createElement("div");P.className="bp-mgmt-group-head bp-plan-layer-head";let K=document.createElement("div");K.className="bp-mgmt-row-line";let ee=document.createElement("span");ee.className="bp-mgmt-strong",ee.textContent=j;let D=document.createElement("span");if(D.className="bp-dim bp-mgmt-flex1",D.textContent=`${E.role?`${E.role} · `:""}${E.done??0}/${k.length} ${X}`,K.append(ee,D),E.status!=="approved"&&k.length>0){let z=document.createElement("button");z.type="button",z.className="bp-mgmt-btn",z.textContent=b("gpui.mgmt.plan.layer","Approve layer"),z.addEventListener("click",()=>n("plan.approve",{layer:E.layer,ids:[],approve:!0}));let je=document.createElement("button");je.type="button",je.className="bp-mgmt-btn",je.textContent=b("gpui.mgmt.plan.reject","Reject"),je.addEventListener("click",()=>n("plan.approve",{layer:E.layer,ids:[],approve:!1})),K.append(z,je)}if(P.appendChild(K),E.stackup){let z=document.createElement("div");z.className="bp-plan-layer-stackup",z.textContent=E.stackup,P.appendChild(z)}ne.appendChild(P)}for(let P of k){if(this.planHideDone&&ti(P))continue;let K=this.planSelectedId===P.id,ee=document.createElement("div");ee.className="bp-mgmt-row bp-plan-row"+(K?" active":""),ee.setAttribute("data-testid",`mgmt-plan-row-${P.id}`);let D=document.createElement("div");D.className="bp-mgmt-row-line";let z=document.createElement("span");z.className=`bp-plan-swatch bp-plan-st-${P.state||"proposed"}`,z.style.setProperty("--swatch-color",P.color||"#8a8a8a");let je=document.createElement("span");je.className="bp-mgmt-flex1"+(P.state==="blocked"||P.state==="failed"?" bp-tone-bad":P.state==="edited"?" bp-tone-warn":P.state==="rejected"||P.state==="routed"||P.state==="verified"?" bp-dim":""),je.textContent=`${P.name||P.id}${P.locked?" \uD83D\uDD12":""}`;let Se=[];if(P.kind==="plane"){if(P.reference)Se.push(b("gpui.mgmt.plan.reference","over {layer}",{layer:P.reference}))}else{let Y=P.nets??0;Se.push(Y===1?b("web.plan.net.one","1 net"):b("web.plan.nets","{n} nets",{n:Y}))}if(typeof P.width==="number"&&Number.isFinite(P.width))Se.push(`${P.width.toFixed(2)}mm`);if(P.impedance)Se.push(P.impedance);let me=Se.join(" · "),Me=document.createElement("span");if(Me.className="bp-plan-mark "+(P.state==="blocked"||P.state==="failed"?"bp-tone-bad":P.state==="verified"||P.state==="routed"?"bp-tone-ok":P.state==="approved"?"bp-tone-accent":"bp-dim"),Me.textContent=ni(P),D.append(z,je,Me),P.state==="proposed"||P.state==="edited"){let Y=document.createElement("button");Y.type="button",Y.className="bp-mgmt-btn",Y.textContent="✓",Y.title=b("gpui.mgmt.plan.layer","Approve layer"),Y.addEventListener("click",(ie)=>{ie.stopPropagation(),n("plan.approve",{layer:"",ids:[P.id],approve:!0})});let fe=document.createElement("button");fe.type="button",fe.className="bp-mgmt-btn",fe.textContent="✗",fe.title=b("gpui.mgmt.plan.reject","Reject"),fe.addEventListener("click",(ie)=>{ie.stopPropagation(),n("plan.approve",{layer:"",ids:[P.id],approve:!1})}),D.append(Y,fe)}if(ee.appendChild(D),me){let Y=document.createElement("div");Y.className="bp-mgmt-row-sub bp-plan-detail bp-dim",Y.textContent=me,ee.appendChild(Y)}if(P.state==="routing"&&typeof P.total==="number"&&P.total>0){let Y=document.createElement("div");Y.className="bp-plan-microbar";let fe=document.createElement("div");fe.className="bp-plan-microbar-fill";let ie=Math.max(0,Math.min(100,Math.round((P.routed??0)/P.total*100)));fe.style.width=`${ie}%`,Y.appendChild(fe),ee.appendChild(Y)}if(P.problem_text){let Y=document.createElement("div");Y.className="bp-plan-problem",Y.textContent=P.problem_text,ee.appendChild(Y)}ee.addEventListener("click",()=>{this.planSelectedId=P.id,n("plan.focus",{id:P.id}),this.render()}),ne.appendChild(ee)}}if(this.planViewMode!=="list"){if(!this.planCanvas)this.planCanvas=new on({onSelect:(P)=>{if(this.planSelectedId=P,!P)this.planNoteOpen=!1;this.render()},onFocusItem:(P)=>{n("plan.focus",{id:P})},onDragEnd:()=>{if(this.planRenderDeferred)this.planRenderDeferred=!1,this.render()},onCommitFields:(P,K)=>{(this.planCommitFields??le)(P,K)},onApproveLayer:(P,K)=>{n("plan.approve",{layer:P,ids:[],approve:K})},onQuickApprove:(P,K)=>{n("plan.approve",{layer:"",ids:P,approve:K})}});let E=this.panelEl.parentElement?.classList.contains("bp-has-viewer")===!1,k=this.planExpanded||this.panelEl.clientWidth>=540||E;this.planCanvas.update({gridMode:this.planGridMode,syncZoom:this.planSyncZoom,shownLayers:I,selectedId:this.planSelectedId,board:ue,bands:we,regions:Le,layers:be,copperLayers:t.copper_layers},k);let j=document.createElement("div");j.className="bp-plan-canvas-scroll",j.appendChild(this.planCanvas.root),e.appendChild(j)}if(this.planViewMode!=="canvas")e.appendChild(ne);if((t.draw?.bands?.length??0)>0||(t.draw?.regions?.length??0)>0){let E=document.createElement("div");E.className="bp-plan-footer",E.textContent=b("gpui.mgmt.plan.drawn","The plan's corridors and planes are drawn on the board while this panel is open. Close it to hide them."),e.appendChild(E)}return e}renderFab(){let e=document.createElement("div");e.className="bp-mgmt-body";let t=this.getPanelData("fab");if(!t)return e.appendChild(this.makeEmpty("Reading the fab's profile…")),e;if(t.error){let w=document.createElement("div");return w.className="bp-mgmt-note bp-tone-warn",w.textContent=t.error,e.appendChild(w),e}let n=(w,C={})=>{let A=this.watchGen,M=this.project;this.fabStatus="",this.cb.hub.rpc("fab.profile",{pro:M,action:w,...C}).catch((S)=>{if(A!==this.watchGen||M!==this.project)return;this.fabStatus=S instanceof Error?S.message:"Fab action failed",this.render()})},i=document.createElement("div");i.className="bp-mgmt-head";let s=document.createElement("span");s.className="bp-mgmt-strong",s.textContent=b("gpui.mgmt.fab.thefab","The fab");let r=document.createElement("span");r.className="bp-dim bp-mgmt-flex1",r.textContent=`rev ${t.rev??0}${t.updated?` · ${t.updated}`:""}${t.board?` · ${t.board}`:""} · ${ai(t.tier??"")}`;let a=document.createElement("button");if(a.type="button",a.className="bp-mgmt-btn",a.textContent=b("gpui.mgmt.fab.refresh","Refresh"),a.addEventListener("click",()=>n("refresh")),i.append(s,r,a),e.appendChild(i),this.fabStatus){let w=document.createElement("div");w.className="bp-mgmt-note bp-tone-bad",w.textContent=this.fabStatus,e.appendChild(w)}let o=document.createElement("div");o.className="bp-mgmt-rows",o.setAttribute("data-testid","mgmt-fab-rows");let c=t.review,u=document.createElement("div");u.className="bp-mgmt-row";let l=document.createElement("div");l.className="bp-mgmt-row-line";let p=document.createElement("span"),d=(c?.counts?.error??0)>0;if(p.className="bp-mgmt-flex1 "+(d?"bp-tone-bad":"bp-dim"),p.textContent=c?.running?"Reviewing the design…":c?.at==null?"No design review yet":`${c.counts?.error??0} must-fix · ${c.counts?.warning??0} should-fix · ${c.counts?.info??0} notes${c.scope?` (${c.scope})`:""}`,l.appendChild(p),c?.at!=null){let w=document.createElement("button");w.type="button",w.className="bp-mgmt-btn",w.textContent=b("gpui.mgmt.fab.findings","Findings"),w.addEventListener("click",()=>this.togglePanel("checks")),l.appendChild(w)}if(!c?.running){let w=document.createElement("button");w.type="button",w.className="bp-mgmt-btn",w.textContent=b("gpui.mgmt.fab.reviewbtn","Review"),w.addEventListener("click",()=>n("review")),l.appendChild(w)}if(c?.judge){let w=document.createElement("button");w.type="button",w.className="bp-mgmt-btn",w.textContent=b("gpui.mgmt.fab.judge","Datasheets"),w.addEventListener("click",()=>{if(c.judge)this.cb.onSendText(c.judge)}),l.appendChild(w)}u.appendChild(l),o.appendChild(u);let g=ri(t.drc?.state??""),y=document.createElement("div");y.className="bp-mgmt-row";let m=document.createElement("div");m.className="bp-mgmt-row-line";let h=document.createElement("span");if(h.className="bp-mgmt-flex1 "+(g.button?"bp-tone-warn":"bp-dim"),h.textContent=g.text,m.appendChild(h),g.button){let w=document.createElement("button");w.type="button",w.className="bp-mgmt-btn",w.textContent=g.button,w.addEventListener("click",()=>n("drc")),m.appendChild(w)}y.appendChild(m),o.appendChild(y);for(let w of t.conflicts??[]){let C=document.createElement("div");C.className="bp-mgmt-row bp-tone-bad",C.textContent=w,o.appendChild(C)}for(let w of t.suggestions??[]){let C=document.createElement("div");C.className="bp-mgmt-row";let A=document.createElement("div");A.className="bp-mgmt-row-line";let M=document.createElement("span");M.className="bp-mgmt-flex1 bp-tone-warn",M.textContent=`${w.label||w.key}: board ${w.project??"?"} mm, fab ${w.fab??"?"} mm`;let S=document.createElement("button");S.type="button",S.className="bp-mgmt-btn",S.textContent=b("gpui.mgmt.fab.apply","Apply"),S.addEventListener("click",()=>n("apply",{key:w.key})),A.append(M,S),C.appendChild(A),o.appendChild(C)}if(t.stackup?.chosen){let w=document.createElement("div");w.className="bp-mgmt-row";let C=document.createElement("div");C.className="bp-mgmt-row-line";let A=t.stackup.by==="proposed",M=document.createElement("span");if(M.className="bp-mgmt-flex1 "+(A?"bp-tone-warn":"bp-dim"),M.textContent=`${A?"Proposed: ":""}${t.stackup.chosen}${t.stackup.outer_50_mm?` (50Ω ${t.stackup.outer_50_mm} mm)`:""}`,C.appendChild(M),A){let S=t.stackup.chosen,T=document.createElement("button");T.type="button",T.className="bp-mgmt-btn",T.textContent=b("gpui.mgmt.fab.use","Use"),T.addEventListener("click",()=>n("stackup",{id:S})),C.appendChild(T)}w.appendChild(C),o.appendChild(w)}if(Array.isArray(t.changed)&&t.changed.length>0){let w=document.createElement("div");w.className="bp-mgmt-row";let C=document.createElement("div");C.className="bp-mgmt-row-line";let A=document.createElement("span");A.className="bp-mgmt-flex1 bp-tone-warn",A.textContent=b("gpui.mgmt.fab.changed","Changed since you last looked");let M=document.createElement("button");M.type="button",M.className="bp-mgmt-btn",M.textContent=b("gpui.mgmt.fab.seen","Seen"),M.addEventListener("click",()=>n("seen")),C.append(A,M),w.appendChild(C);for(let S of t.changed.slice(0,12)){let T=document.createElement("div");T.className="bp-mgmt-faint",T.textContent=S,w.appendChild(T)}o.appendChild(w)}let f=Array.isArray(t.limits)?t.limits:[];if(f.length>0){let w=document.createElement("div");w.className="bp-mgmt-group-head";let C=document.createElement("span");C.className="bp-mgmt-flex1",C.textContent=b("gpui.mgmt.fab.limit","Limit");let A=document.createElement("span");A.className="bp-mgmt-col",A.textContent=b("gpui.mgmt.fab.free","Base price");let M=document.createElement("span");M.className="bp-mgmt-col",M.textContent=b("gpui.mgmt.fab.extra","Costs more");let S=document.createElement("span");S.className="bp-mgmt-col bp-mgmt-col-read",S.textContent=b("gpui.mgmt.fab.readcol","Read"),w.append(C,A,M,S),o.appendChild(w);for(let B of f){let R=document.createElement("div");R.className="bp-mgmt-row";let O=document.createElement("div");O.className="bp-mgmt-row-line";let H=document.createElement("span");H.className="bp-mgmt-flex1"+(B.changed?" bp-tone-warn":B.inherited?" bp-dim":""),H.textContent=`${B.changed?"• ":""}${B.label??""}`;let ae=document.createElement("span");ae.className="bp-mgmt-col",ae.textContent=B.free?.text||"—";let ue=document.createElement("span");ue.className="bp-mgmt-col bp-dim",ue.textContent=B.extra?.text||"—";let oe=B.free&&typeof B.free==="object"?B.free:B.extra,we=oe?.fetched??"",Le=Boolean(we)&&oe?.confidence!=="published",Ne=we?Le?`${we}*`:we:"—",he=oe?.source??"",be;if(he.startsWith("https://")&&we){let I=document.createElement("a");I.className="bp-mgmt-col bp-mgmt-col-read bp-mgmt-read-link",I.href=he,I.target="_blank",I.rel="noopener noreferrer",I.textContent=Ne,be=I}else{let I=document.createElement("span");I.className="bp-mgmt-col bp-mgmt-col-read bp-mgmt-faint",I.textContent=Ne,be=I}O.append(H,ae,ue,be),R.appendChild(O),o.appendChild(R)}let T=document.createElement("div");T.className="bp-mgmt-note bp-mgmt-faint",T.textContent=b("gpui.mgmt.fab.derived","* worked out from the fab's page. Dimmed: the rigid board's value. A date opens the source page."),o.appendChild(T)}return e.appendChild(o),e}makeEmpty(e){let t=document.createElement("div");return t.className="bp-mgmt-note bp-mgmt-faint",t.textContent=e,t}}var Is={trs:(e)=>e,t:(e,t)=>t},Rs=new Set(["/settle"]);function xi(e,t){let n=t.trim().toLowerCase();if(!n)return 1;let i=e.toLowerCase();if(i.startsWith(n))return 3;if(i.split(/[^a-z0-9]+/i).some((a)=>a.startsWith(n)))return 2;let r=0;for(let a=0;a0||e.status==="waiting")return{urgency:3,want:"waiting"};if(e.status==="asking")return{urgency:2,want:"question"};if(e.status==="failed"||e.state==="failed")return{urgency:1,want:"failed"};return{urgency:0,want:""}}function ki(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 Ai(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 Li(e,t=Is){let{t:n,trs:i}=t,s=[],r=new Map;for(let o of e.projects)r.set(o.id,o.title||o.id);let a=e.threads.find((o)=>o.id===e.selectedThreadId)??null;for(let o of e.railItems){if(o.state==="disabled"||o.id==="commands")continue;if(!a&&o.id!=="terminal")continue;s.push({label:i(o.label),place:o.id==="terminal"?"":"viewer",kind:"action",shortcut:o.key?o.key.toUpperCase():void 0,action:{type:"rail",id:o.id}})}if(a)s.push({label:a.pinned?n("menu.unpin","Unpin"):n("menu.pin","Pin"),place:"",kind:"action",action:{type:"thread-act",action:a.pinned?"unpin":"pin"}}),s.push({label:a.settled?n("phone.unsettle","Unsettle"):n("menu.settle","Settle"),place:"",kind:"action",action:{type:"thread-act",action:a.settled?"unsettle":"settle"}}),s.push({label:a.archived?n("palette.unarchive","Unarchive"):n("palette.archive","Archive"),place:"",kind:"action",action:{type:"thread-act",action:a.archived?"unarchive":"archive"}}),s.push({label:n("sheet.rename","Rename thread"),place:"",kind:"action",action:{type:"rename"}}),s.push({label:n("gpui.previous.thread","Previous thread"),place:"",kind:"action",action:{type:"prev-thread"}}),s.push({label:n("gpui.next.thread","Next thread"),place:"",kind:"action",action:{type:"next-thread"}});if(a)for(let o of e.commands){if(!o.word)continue;let c=Rs.has(o.word.toLowerCase());s.push({label:o.label?`${o.word} — ${o.label}`:o.word,place:o.desc||"command",kind:"command",action:{type:"command",word:o.word,runDirectly:c}})}s.push({label:n("gpui.improvements","Improvements"),place:"",kind:"action",action:{type:"improvements"}}),s.push({label:n("palette.settings","Settings"),place:"",kind:"action",action:{type:"settings"}}),s.push({label:n("gpui.fold.or.unfold.the.sidebar","Fold or unfold the sidebar"),place:"",kind:"action",action:{type:"sidebar"}});for(let o of e.projects)s.push({label:`New thread in ${o.title||o.id}`,place:"",kind:"action",action:{type:"new-thread",projectId:o.id}});for(let o of e.threads){let{urgency:c,want:u}=Ci(o);s.push({label:o.title||"Untitled thread",place:o.project?r.get(o.project)??"":"",kind:"thread",urgency:c,want:u,dotClass:ki(o),action:{type:"thread",id:o.id}})}for(let o of e.bots){if(!o.name||!o.thread)continue;s.push({label:o.name,place:"",kind:"bot",action:{type:"thread",id:o.thread}})}return s}function Si(e,t,n,i=[],s=10,r=14){let a=t.trim(),o=a.length===0,c=e.slice();if(n?.threads&&n.threads.length>0){let d=new Map;for(let y of i)d.set(y.id,y.title||y.id);let g=new Set;for(let y of c)if(y.action.type==="thread")g.add(y.action.id);for(let y of n.threads){if(!y.id||g.has(y.id))continue;g.add(y.id);let{urgency:m,want:h}=Ci(y);c.push({label:y.title||"Untitled thread",place:y.project?d.get(y.project)??"":"",kind:"thread",urgency:m,want:h,dotClass:ki(y),action:{type:"thread",id:y.id}})}}let u=[];for(let d=0;d0)u.push({score:h,index:d,item:g})}u.sort((d,g)=>{if(o){let h=(g.item.urgency??0)-(d.item.urgency??0);if(h!==0)return h}if(g.score!==d.score)return g.score-d.score;let y=d.item.kind==="thread"?0:1,m=g.item.kind==="thread"?0:1;if(y!==m)return y-m;return d.index-g.index});let l=new Set,p=[];for(let d of u){let g=`${d.item.label}\x00${d.item.place}\x00${d.item.kind}`;if(l.has(g))continue;if(l.add(g),p.push(d.item),p.length>=s)break}if(n?.messages&&n.messages.length>0&&p.length{if(a.target===t)this.close()}),s.addEventListener("input",()=>{this.query=s.value,this.activeIdx=0,this.renderList(),this.scheduleSearch()}),s.addEventListener("keydown",(a)=>{if(a.key==="Escape")a.preventDefault(),a.stopPropagation(),this.close();else if(a.key==="ArrowDown"){if(a.preventDefault(),this.listed.length>0)this.activeIdx=(this.activeIdx+1)%this.listed.length,this.renderList(!0)}else if(a.key==="ArrowUp"){if(a.preventDefault(),this.listed.length>0)this.activeIdx=(this.activeIdx-1+this.listed.length)%this.listed.length,this.renderList(!0)}else if(a.key==="Enter")a.preventDefault(),this.runAt(this.activeIdx)}),this.backdrop=t,this.inputEl=s,this.listEl=r,this.root.appendChild(t),this.renderList(),this.query.trim().length>=2)this.scheduleSearch();s.focus()}close(){if(this.searchTimer!==null)window.clearTimeout(this.searchTimer),this.searchTimer=null;if(this.searchGen++,this.backdrop)this.backdrop.remove(),this.backdrop=null,this.inputEl=null,this.listEl=null;this.prevFocus?.focus(),this.prevFocus=null}scheduleSearch(){if(this.searchTimer!==null)window.clearTimeout(this.searchTimer),this.searchTimer=null;let e=this.query.trim();if(e.length<2){this.searchHits=null,this.searchHitsQuery="";return}if(e===this.searchHitsQuery)return;let t=++this.searchGen;this.searchTimer=window.setTimeout(()=>{this.searchTimer=null,this.cb.onSearch(e).then((n)=>{if(t!==this.searchGen||!this.backdrop)return;if(this.query.trim()!==e)return;this.searchHits=n,this.searchHitsQuery=e,this.renderList()}).catch(()=>{})},180)}runAt(e){let t=this.listed[e];if(!t)return;this.close(),this.cb.onExecute(t.action)}renderList(e=!1){if(!this.listEl)return;let t=this.cb.getState(),n=Li(t,{t:b,trs:pe}),i=this.query.trim()===this.searchHitsQuery?this.searchHits:null;if(this.listed=Si(n,this.query,i,t.projects),this.activeIdx>=this.listed.length)this.activeIdx=Math.max(0,this.listed.length-1);if(this.listed.length===0){let a=document.createElement("div");a.className="bp-palette-empty",a.textContent=b("gpui.nothing.matches","Nothing matches"),this.listEl.replaceChildren(a);return}let s=document.createDocumentFragment(),r=null;for(let a=0;a0)u.appendChild(document.createTextNode(o.label.slice(0,d)));let y=document.createElement("strong");if(y.className="bp-palette-mark",y.textContent=o.label.slice(d,g),u.appendChild(y),g{if(this.activeIdx!==a)this.activeIdx=a,this.updateActiveClass()}),c.addEventListener("click",()=>this.runAt(a)),a===this.activeIdx)r=c;s.appendChild(c)}if(this.listEl.replaceChildren(s),e&&r)r.scrollIntoView({block:"nearest"})}updateActiveClass(){if(!this.listEl)return;let e=this.listEl.children;for(let t=0;tthis.onPress(e.id));return r}render(){let e=this.items.filter((a)=>a.group!=="tools"),t=this.items.filter((a)=>a.group==="tools"),n=document.createElement("div");n.className="bp-rail-pages";let i;for(let a of e){if(i!==void 0&&a.group!==i){let o=document.createElement("div");o.className="bp-rail-rule",n.appendChild(o)}i=a.group,n.appendChild(this.renderButton(a))}let s=()=>{let a=n.scrollLeft>2,o=n.scrollLeft+n.clientWidth0){let a=document.createElement("div");a.className="bp-rail-tools";for(let o of t)a.appendChild(this.renderButton(o));r.appendChild(a)}this.el.replaceChildren(r)}}var Hs=new Set(["resume","raise","retry","move","signin"]);function Ti(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 $t(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(Hs.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 Bi(e){let t=e&&typeof e==="object"?e.open:void 0;if(typeof t!=="string")return null;let n=t.indexOf(":"),i=n<0?"":t.slice(n+1);if(!i)return null;if(t.startsWith("account:"))return{kind:"account",id:i};if(t.startsWith("thread:"))return{kind:"thread",id:i};return null}class mn{backdrop;titleEl;closeBtn;bodyEl;cb;openState=!1;providersEl=null;constructor(e,t){this.cb=t,this.backdrop=document.createElement("div"),this.backdrop.className="bp-modal-backdrop bp-hidden",this.backdrop.setAttribute("data-testid","settings-modal");let n=document.createElement("div");n.className="bp-modal";let i=document.createElement("div");i.className="bp-modal-head",this.titleEl=document.createElement("h2"),this.titleEl.textContent=`${b("palette.settings","Settings")} · Devices`,this.closeBtn=document.createElement("button"),this.closeBtn.type="button",this.closeBtn.className="icon",this.closeBtn.textContent="×",this.closeBtn.setAttribute("aria-label",b("common.close","Close")),this.closeBtn.addEventListener("click",()=>this.close()),i.append(this.titleEl,this.closeBtn),this.bodyEl=document.createElement("div"),this.bodyEl.className="bp-modal-body",n.append(i,this.bodyEl),this.backdrop.appendChild(n),this.backdrop.addEventListener("click",(s)=>{if(s.target===this.backdrop)this.close()}),e.appendChild(this.backdrop)}isOpen(){return this.openState}async open(){this.openState=!0,this.backdrop.classList.remove("bp-hidden"),await this.refresh()}async openToAccounts(){await this.open(),this.providersEl?.scrollIntoView({block:"nearest"})}close(){this.openState=!1,this.backdrop.classList.add("bp-hidden")}refreshLocale(){if(this.titleEl.textContent=`${b("palette.settings","Settings")} · Devices`,this.closeBtn.setAttribute("aria-label",b("common.close","Close")),this.openState)this.refresh()}async refresh(){let e=document.createDocumentFragment();this.providersEl=null;let t=this.cb.onGetNoProvider?.()??null;if(t){let l=document.createElement("section");l.className="bp-set-section",l.setAttribute("data-testid","settings-providers");let p=document.createElement("div");p.className="bp-set-head",p.textContent=b("web.settings.providers","AI providers");let d=document.createElement("div");d.className="bp-set-row";let g=document.createElement("div");g.className="bp-set-info";let y=document.createElement("div");y.textContent=pe(t.head);let m=document.createElement("div");m.className="bp-dim",m.textContent=b("web.settings.providers.browser","Connect a provider in the Backplane desktop or mobile app under Settings → Accounts."),g.append(y,m);let h=document.createElement("div");h.className="bp-set-btns";let f=document.createElement("a");f.className="bp-link-btn primary",f.href=t.url||"backplane://settings/accounts",f.setAttribute("data-testid","settings-open-accounts"),f.textContent=pe(t.button),h.appendChild(f),d.append(g,h),l.append(p,d),this.providersEl=l,e.appendChild(l)}let n=this.cb.onGetHome?.()??null;if(n){let l=document.createElement("section");l.className="bp-set-section",l.setAttribute("data-testid","settings-home");let p=document.createElement("div");p.className="bp-set-head",p.textContent=b("home.machine","Home machine");let d=document.createElement("div");d.className="bp-set-row";let g=document.createElement("div");g.className="bp-set-info";let y=document.createElement("div"),m=n.kind==="local"?`${n.name||"This machine"} (this machine)`:n.kind==="boat"?`${n.name||"Boat"} (Boat)`:n.name||"Linked machine";y.textContent=m,g.appendChild(y);let h=document.createElement("div");if(h.className="bp-dim",n.moving?.state==="moving")h.textContent=n.moving.step?b("home.moving.step","Moving home to {to}: {step}").replace("{to}",n.moving.to).replace("{step}",n.moving.step):b("home.moving","Moving home to {to}…").replace("{to}",n.moving.to);else if(n.moving?.state==="failed")h.textContent=n.moving.note?b("home.move.failed.note","Home move failed: {note}").replace("{note}",n.moving.note):b("home.move.failed","Home move failed");else if(!n.online)h.textContent=n.queuedCount>0?b("home.away.queued","Home ({name}) is away · {n} queued").replace("{name}",n.name||"home").replace("{n}",String(n.queuedCount)):b("home.away","Home ({name}) is away").replace("{name}",n.name||"home");else h.textContent="Online";if(g.appendChild(h),d.appendChild(g),n.canMoveHere&&this.cb.onMoveHomeHere){let f=document.createElement("button");f.type="button",f.className="primary",f.textContent=b("home.move.here","Make this machine the home"),f.setAttribute("data-testid","home-move-here-btn"),f.addEventListener("click",()=>{f.disabled=!0,this.cb.onMoveHomeHere?.().finally(()=>{this.refresh()})}),d.appendChild(f)}l.append(p,d),e.appendChild(l)}let i=document.createElement("section");i.className="bp-set-section";let s=document.createElement("div");s.className="bp-set-head",s.textContent="This browser";let r=document.createElement("div");r.className="bp-set-row";let a=document.createElement("span");a.className="bp-dim",a.textContent="Sign out and revoke this browser's session cookie.";let o=document.createElement("button");o.type="button",o.className="primary stop",o.textContent=b("agy.signout","Sign out"),o.setAttribute("data-testid","logout-btn"),o.addEventListener("click",()=>{o.disabled=!0,this.cb.onLogout().catch(()=>{a.setAttribute("role","alert"),a.textContent=b("web.logout.failed","Could not confirm sign-out. Try again."),o.disabled=!1})}),r.append(a,o),i.append(s,r),e.appendChild(i);let c=document.createElement("section");c.className="bp-set-section";let u=document.createElement("div");u.className="bp-set-head",u.textContent="Paired devices",c.appendChild(u);try{let l=await this.cb.onLoadDevices();if(l.length===0){let p=document.createElement("div");p.className="bp-dim",p.textContent="No devices listed.",c.appendChild(p)}else for(let p of l){let d=document.createElement("div");d.className="bp-set-row";let g=document.createElement("div");g.className="bp-set-info";let y=document.createElement("div");if(y.textContent=p.title||p.head||"",g.appendChild(y),p.text||p.detail){let m=document.createElement("div");m.className="bp-dim",m.textContent=p.text||p.detail||"",g.appendChild(m)}if(d.appendChild(g),p.buttons?.length){let m=document.createElement("div");m.className="bp-set-btns";for(let h of p.buttons){let f=document.createElement("button");if(f.type="button",h.primary)f.className="primary";if(h.danger)f.className="primary stop";f.textContent=h.label||b("common.remove","Remove"),f.addEventListener("click",()=>{f.disabled=!0,this.cb.onDevicesAct(h.action,h.value).finally(()=>{this.refresh()})}),m.appendChild(f)}d.appendChild(m)}c.appendChild(d)}}catch(l){let p=document.createElement("div");p.className="bp-dim";let d=l instanceof Error&&l.message?l.message:"Not available from a browser";p.textContent=`${d} — manage paired devices in Backplane › Settings › Devices on desktop or a paired phone.`,c.appendChild(p)}e.appendChild(c),this.bodyEl.replaceChildren(e)}}function Ee(e,t,n){let i=document.createElement(e);if(t)i.className=t;if(n)i.textContent=n;return i}function xt(e,t,n=!1){let i=Ee("button",n?"primary":"bp-btn-ghost",e);return i.type="button",i.addEventListener("click",t),i}function un(e){return Ee("pre","bp-context-code",e)}function Ds(e){return Ee("span",`bp-context-badge ${e==="Native"||e==="Enabled"?"active":e==="Untrusted"||e==="Invalid"?"warn":""}`,pe(e))}function Gt(e,t){let n=Ee("div","bp-context-row");return n.append(Ee("strong",void 0,e),Ds(t)),n}class hn{fetchContext;dialog=Ee("dialog","bp-context");title=Ee("h2");cwd=Ee("div","bp-context-path");tabs=Ee("div","bp-context-tabs");body=Ee("div","bp-context-body");notice=Ee("p","bp-context-notice");current;thread="";requestId=0;tab=0;busy=!1;constructor(e,t){this.fetchContext=t;let n=Ee("div","bp-context-head"),i=Ee("div");i.append(this.title,this.cwd),this.title.id="bp-context-title",this.dialog.setAttribute("aria-labelledby",this.title.id),this.notice.setAttribute("role","status"),n.append(i,xt(b("common.refresh","Refresh"),()=>{this.load()}),xt(b("common.close","Close"),()=>this.dialog.close())),this.dialog.append(n,this.tabs,this.notice,this.body),this.dialog.addEventListener("close",()=>{this.requestId++}),e.append(this.dialog)}open(e){if(this.thread=e,this.tab=0,this.current=void 0,this.busy=!1,this.title.textContent=b("thread.context.title","Context & Prompt"),this.cwd.textContent="",!this.dialog.open)this.dialog.showModal();this.render(),this.load()}async load(e){if(this.busy)return;let t=++this.requestId;this.busy=!0,this.notice.textContent=b("thread.context.reading","Reading thread context…"),this.render();try{let n=await this.fetchContext(this.thread,e);if(t!==this.requestId)return;this.current=n,this.cwd.textContent=n.cwd,this.notice.textContent=""}catch(n){if(t===this.requestId)this.notice.textContent=String(n)}finally{if(t===this.requestId)this.busy=!1,this.render()}}render(){let e=[b("thread.context.instructions","Instructions"),b("thread.context.system","System Prompt"),b("thread.context.skills","Skills"),b("thread.context.mcp","Project MCPs")];this.tabs.replaceChildren(...e.map((n,i)=>{let s=xt(n,()=>{this.tab=i,this.render(),this.body.scrollTop=0,this.tabs.children[i].focus()});return s.setAttribute("aria-pressed",String(i===this.tab)),s})),this.body.replaceChildren();let t=this.current;if(!t)return;switch(this.tab){case 0:this.instructions(t.instructions);break;case 1:this.prompt(t);break;case 2:this.skills(t.skills);break;case 3:this.mcps(t.mcp);break}}instructions(e){if(!e.length)this.body.append(Ee("p","bp-dim",b("thread.context.none.instructions","No project instructions found.")));for(let t of e){let n=Ee("details","bp-context-card"),i=Ee("summary");if(i.append(Gt(t.path,t.status),Ee("small","bp-dim",b("thread.context.size","{bytes} B · ≈{tokens} tokens",{bytes:t.bytes,tokens:t.estimated_tokens}))),n.append(i,un(t.preview)),t.note)n.append(Ee("small","bp-dim",t.note));this.body.append(n)}}prompt(e){let t=Ee("div","bp-context-row"),n=xt(b("thread.context.copy","Copy prompt"),()=>{navigator.clipboard.writeText(e.prompt).then(()=>{this.notice.textContent=b("thread.context.copied","Prompt copied.")}).catch((i)=>{this.notice.textContent=String(i)})});t.append(Ee("p","bp-dim",b("thread.context.native.note","Backplane’s launch prompt. Native files are loaded by the provider.")),n),this.body.append(t);for(let[i,s]of[[b("thread.context.base","Backplane"),e.sections.base],[b("thread.context.injected.label","Injected project instructions"),e.sections.instructions],[b("thread.context.index","Available skills index"),e.sections.skills]])if(s)this.body.append(Ee("h3",void 0,i),un(s))}skills(e){for(let t of["Project","User","Bundled"]){let n=e.filter((i)=>i.scope===t);if(!n.length)continue;this.body.append(Ee("h3",void 0,pe(t)));for(let i of n){let s=Ee("article","bp-context-card");s.append(Gt(i.name,i.status),Ee("p",void 0,i.description),Ee("small","bp-context-path",[i.source,i.provider,i.model].filter(Boolean).join(" · ")),Ee("small","bp-context-path",i.path)),this.body.append(s)}}}mcps(e){if(!e.length)this.body.append(Ee("p","bp-dim",b("thread.context.none.mcp","No project MCP configurations found.")));for(let t of e){let n=Ee("article","bp-context-card");n.append(Gt(t.path,t.state));for(let s of t.servers){let r=s.url||[s.command,...s.args].map((a)=>JSON.stringify(a)).join(" ");if(n.append(Gt(s.name,s.status),un(r)),s.cwd)n.append(Ee("small","bp-context-path",s.cwd))}if(t.error)n.append(Ee("p","bp-warn",t.error));let i=t.state==="Untrusted"?"trust":t.state==="Enabled"?"disable":t.state==="Disabled"?"enable":"";if(i){let s=i==="trust"?b("thread.context.trust","Trust and enable"):i==="disable"?b("thread.context.disable","Disable"):b("thread.context.enable","Enable"),r=xt(s,()=>{this.load({action:i,path:t.path,sha256:t.sha256})},i==="trust");r.disabled=this.busy;let a=Ee("div","bp-context-actions");a.append(r),n.append(a)}this.body.append(n)}}}var Ii="http://www.w3.org/2000/svg";function Ri(){let e=document.createElementNS(Ii,"svg");e.setAttribute("viewBox","0 0 24 24"),e.setAttribute("width","14"),e.setAttribute("height","14"),e.setAttribute("fill","none"),e.setAttribute("stroke","currentColor"),e.setAttribute("stroke-width","1.75"),e.setAttribute("aria-hidden","true"),e.classList.add("bp-folder-icon");let t=document.createElementNS(Ii,"path");return t.setAttribute("d","M3 6h6l2 2h10v11H3z"),e.appendChild(t),e}function Fs(e,t,n,i){let s=e||t||n||"";if(s==="active"||s==="working"||s==="running"||s==="run")return"bp-dot-work";if(s==="finished"||s==="done")return"bp-dot-done";if(s==="waiting"||s==="asking"||s==="blocked"||s==="needs"||s==="failed"||s==="fail"||s==="cut"||s==="interrupted"||s==="limit"||s==="monitoring"||(i??0)>0)return"bp-dot-need";return"bp-dot-idle"}function ji(e){if(!e)return"";let t=e<10000000000?e*1000:e,n=Math.max(0,Math.floor((Date.now()-t)/1000));if(n<60)return"now";if(n<3600)return`${Math.floor(n/60)}m`;if(n<86400)return`${Math.floor(n/3600)}h`;return`${Math.floor(n/86400)}d`}class bn{el;hostLabel;homeBanner;filterInput;listEl;connEl;filterText="";showSettled=new Set;collapsedProjects=new Set;addShown=!1;sections=null;projects=[];threads=[];bots=[];rooms=[];selectedThreadId="";cb;needErr=new Map;needBusy=new Set;constructor(e,t){this.el=e,this.cb=t;let n=document.createElement("div");n.className="bp-side-host";let i=document.createElement("div");i.className="bp-side-host-left",this.hostLabel=document.createElement("span"),this.hostLabel.textContent="This computer";let s=document.createElement("span");s.className="bp-dim",s.textContent="›",i.append(this.hostLabel,s);let r=document.createElement("button");r.type="button",r.className="icon bp-side-collapse",r.textContent="‹",r.title="Collapse sidebar",r.setAttribute("aria-label","Collapse sidebar"),r.setAttribute("data-testid","sidebar-collapse"),r.addEventListener("click",()=>this.cb.onCollapseSidebar?.()),n.append(i,r);let a=document.createElement("div");a.className="bp-side-head",this.filterInput=document.createElement("input"),this.filterInput.type="search",this.filterInput.className="bp-input bp-side-search";let o=b("sidebar.search.projects","Search projects");this.filterInput.placeholder=o,this.filterInput.setAttribute("aria-label",o),this.filterInput.setAttribute("data-testid","sidebar-filter"),this.filterInput.addEventListener("input",()=>{this.filterText=this.filterInput.value.trim().toLowerCase(),this.render()});let c=document.createElement("button");c.type="button",c.className="icon bp-side-add",c.textContent="+",c.title=b("thread.new","New thread"),c.setAttribute("aria-label",b("thread.new","New thread")),c.setAttribute("data-testid","sidebar-new-thread"),c.addEventListener("click",()=>{let l=this.firstProjectId();if(l)this.cb.onNewThread(l)}),a.append(this.filterInput,c),this.homeBanner=document.createElement("div"),this.homeBanner.className="bp-side-home bp-hidden",this.homeBanner.setAttribute("data-testid","home-away-banner"),this.homeBanner.style.padding="6px 10px",this.homeBanner.style.fontSize="11px",this.homeBanner.style.borderBottom="1px solid var(--line, #2a2a2a)",this.listEl=document.createElement("div"),this.listEl.className="bp-side-list",this.listEl.setAttribute("data-testid","sidebar-list");let u=document.createElement("div");u.className="bp-side-footer",this.connEl=document.createElement("span"),this.connEl.className="bp-conn-status",this.connEl.textContent="Connecting…",this.connEl.setAttribute("data-testid","conn-status"),u.appendChild(this.connEl),this.el.append(n,a,this.homeBanner,this.listEl,u)}setHome(e){if(!e){this.homeBanner.classList.add("bp-hidden"),this.homeBanner.textContent="";return}let t="",n=!1;if(e.moving?.state==="moving")t=e.moving.step?b("home.moving.step","Moving home to {to}: {step}").replace("{to}",e.moving.to).replace("{step}",e.moving.step):b("home.moving","Moving home to {to}…").replace("{to}",e.moving.to);else if(e.moving?.state==="failed")t=e.moving.note?b("home.move.failed.note","Home move failed: {note}").replace("{note}",e.moving.note):b("home.move.failed","Home move failed"),n=!0;else if(!e.online){let i=e.name||"home",s="";if(e.awaySince&&e.awaySince>0){let r=new Date(e.awaySince);s=`${String(r.getHours()).padStart(2,"0")}:${String(r.getMinutes()).padStart(2,"0")}`}if(s&&e.queuedCount>0)t=b("home.away.since.queued","Home ({name}) is away since {time} · {n} queued").replace("{name}",i).replace("{time}",s).replace("{n}",String(e.queuedCount));else if(s)t=b("home.away.since","Home ({name}) is away since {time}").replace("{name}",i).replace("{time}",s);else if(e.queuedCount>0)t=b("home.away.queued","Home ({name}) is away · {n} queued").replace("{name}",i).replace("{n}",String(e.queuedCount));else t=b("home.away","Home ({name}) is away").replace("{name}",i)}if(!t)this.homeBanner.classList.add("bp-hidden"),this.homeBanner.textContent="";else this.homeBanner.textContent=t,this.homeBanner.className=n?"bp-side-home bp-bad":"bp-side-home bp-dim",this.homeBanner.classList.remove("bp-hidden")}setHostName(e){this.hostLabel.textContent=e||"This computer"}setConnStatus(e,t){this.connEl.textContent=e,this.connEl.className=`bp-conn-status ${t}`.trim()}setData(e,t,n,i){this.projects=e,this.threads=t,this.bots=n,this.rooms=i,this.render()}setSections(e,t,n){this.sections=e,this.bots=t,this.rooms=n,this.render()}setSelected(e){this.selectedThreadId=e,this.render()}focusFilter(){this.filterInput.focus()}firstProjectId(){if(this.sections){for(let e of this.sections)if(e.kind==="projects"&&e.rows.length>0){let t=e.rows[0];if(t.id&&!t.off)return t.id}}return this.projects[0]?.id??""}refreshLocale(){let e=b("sidebar.search.projects","Search projects");this.filterInput.placeholder=e,this.filterInput.setAttribute("aria-label",e),this.render()}projectsHead(e){let t=document.createElement("div");if(t.className="bp-side-section-head",!this.cb.onAddProject||this.addShown)return t.textContent=e,t;this.addShown=!0,t.classList.add("bp-side-section-row");let n=document.createElement("span");n.textContent=e;let i=document.createElement("button");i.type="button",i.className="bp-side-sec-plus bp-side-sec-btn",i.textContent="+";let s=b("sidebar.add.project","Add project");return i.title=s,i.setAttribute("aria-label",s),i.setAttribute("data-testid","sidebar-add-project"),i.addEventListener("click",(r)=>{r.stopPropagation(),this.cb.onAddProject?.()}),t.append(n,i),t}renderSectionThreadRow(e,t){let n=document.createElement("div");if(n.className="bp-thread-row"+(e.id===this.selectedThreadId?" active":"")+(e.off?" bp-dim":""),n.setAttribute("data-thread-id",e.id),n.setAttribute("data-testid",`thread-row-${e.id}`),t){let p=document.createElement("span");p.className="bp-tree-branch",p.setAttribute("aria-hidden","true"),n.appendChild(p)}let i=document.createElement("span");i.className=`bp-dot ${Fs(e.status,e.word,e.state)}`;let s=document.createElement("div");if(s.className="bp-thread-title",s.textContent=e.title||"Untitled thread",n.append(i,s),e.word==="needs"){let p=document.createElement("span");if(p.className="bp-badge-need",p.textContent=e.want==="approval"?"!":"•",e.say)p.title=e.say;n.appendChild(p)}else if(e.ago){let p=document.createElement("span");if(p.className="bp-thread-age",p.textContent=e.ago,e.pinned)p.title=b("tools.pinned","Pinned");n.appendChild(p)}let r=e.nav||e.id;if(!e.off&&r&&!r.startsWith("@room:"))n.addEventListener("click",()=>this.cb.onSelectThread(r));let a=e.kind==="swarm"?Ti(e.need):null;if(!a)return n;let o=document.createElement("div");o.className="bp-need-wrap";let c=document.createElement("div");c.className="bp-need"+(t?" nested":"")+(e.off?" bp-dim":""),c.setAttribute("data-testid",`need-${e.id}`);let u=document.createElement("span");u.className="bp-need-line",u.textContent=a.line,u.title=a.line,c.appendChild(u);for(let p of a.actions){if(!$t(p,Boolean(this.cb.hasRoomView)))continue;let d=document.createElement("button");d.type="button",d.className="bp-need-btn",d.textContent=p.label,d.setAttribute("data-testid",`need-${p.act}-${e.id}`),d.disabled=Boolean(e.off)||this.needBusy.has(e.id)||!this.cb.onNeedAct,d.addEventListener("click",(g)=>{g.stopPropagation();let y=this.cb.onNeedAct;if(!y)return;this.needErr.delete(e.id),this.needBusy.add(e.id),this.render(),y(p).catch((m)=>{this.needErr.set(e.id,m instanceof Error?m.message:String(m))}).finally(()=>{this.needBusy.delete(e.id),this.render()})}),c.appendChild(d)}o.append(n,c);let l=this.needErr.get(e.id);if(l){let p=document.createElement("div");p.className="bp-need-err"+(t?" nested":""),p.textContent=l,o.appendChild(p)}return o}renderHubSections(e,t){let n=this.sections??[],i=new Set;for(let a of n)if(a.kind==="threads")for(let o of a.rows)i.add(o.id);else if(a.kind==="projects")for(let o of a.rows)for(let c of o.threads??[])i.add(c.id);let s=this.selectedThreadId?this.threads.find((a)=>a.id===this.selectedThreadId)??null:null,r=!1;for(let a of n)if(a.kind==="projects"&&a.rows.length>0)r=!0;for(let a of n){if(a.kind==="bub")continue;if(a.kind==="threads"){let o=a.rows.filter((l)=>{if(!t)return!0;return`${l.title} ${l.project??""}`.toLowerCase().includes(t)});if(o.length===0)continue;let c=document.createElement("section");c.className="bp-side-section",c.setAttribute("data-section-id",a.id);let u=document.createElement("div");u.className="bp-side-section-head",u.textContent=a.title.toUpperCase(),c.appendChild(u);for(let l of o)c.appendChild(this.renderSectionThreadRow(l,!1));e.appendChild(c);continue}if(a.kind==="projects"){let o=a.rows.filter((l)=>{if(!t)return!0;if((l.title||l.id).toLowerCase().includes(t))return!0;if((l.threads??[]).some((p)=>p.title.toLowerCase().includes(t)))return!0;if((l.swarms??[]).some((p)=>p.title.toLowerCase().includes(t)))return!0;return!1}),c=Boolean(a.fold&&a.toggle);if(t&&o.length===0)continue;if(!c&&a.id!=="active"&&o.length===0)continue;let u=document.createElement("section");if(u.className="bp-side-section",u.setAttribute("data-section-id",a.id),c){let l=document.createElement("button");l.type="button",l.className="bp-side-section-head bp-side-section-toggle";let p=a.count??o.length,d=a.open?"▾":"▸";if(l.textContent=`${a.title.toUpperCase()} (${p}) ${d}`,a.hint)l.title=a.hint;l.addEventListener("click",()=>{if(a.toggle)this.cb.onToggleSection?.(a.toggle)}),u.appendChild(l)}else u.appendChild(this.projectsHead(a.title.toUpperCase()));if(!c||a.open||Boolean(t)){if(a.id==="active"&&!r&&!t){let l=document.createElement("div");l.className="bp-side-empty",l.textContent="No projects yet.",u.appendChild(l)}for(let l of o){let p=document.createElement("div");if(p.className="bp-proj-group"+(l.off?" bp-dim":""),p.setAttribute("data-project-id",l.id),l.nav||l.key)p.setAttribute("data-project-key",l.nav||l.key||"");let d=document.createElement("div");d.className="bp-proj-head";let g=document.createElement("button");g.type="button",g.className="bp-proj-toggle";let y=Ri();if(l.css)y.style.color=l.css;let m=document.createElement("span");if(m.className="bp-proj-name",m.textContent=l.title||l.id,g.append(y,m),l.fold==="project-fold"&&l.nav)g.addEventListener("click",()=>this.cb.onToggleProjectFold?.(l.nav));let h=document.createElement("button");if(h.type="button",h.className="icon bp-proj-add",h.title=b("thread.new","New thread"),h.textContent="+",h.setAttribute("data-testid",`new-thread-${l.id}`),l.off)h.disabled=!0;if(h.addEventListener("click",(f)=>{f.stopPropagation(),this.cb.onNewThread(l.id)}),d.append(g,h),p.appendChild(d),!l.folded||Boolean(t)){let f=Boolean(t)&&(l.title||l.id).toLowerCase().includes(t);for(let w of l.swarms??[]){if(t&&!f&&!w.title.toLowerCase().includes(t))continue;p.appendChild(this.renderSectionThreadRow(w,!0))}for(let w of l.threads??[]){if(t&&!f&&!w.title.toLowerCase().includes(t))continue;p.appendChild(this.renderSectionThreadRow(w,!0))}if(s&&s.project===l.id&&!i.has(s.id)&&(!t||f||s.title.toLowerCase().includes(t)))p.appendChild(this.renderSectionThreadRow({id:s.id,title:s.title,status:s.status,state:s.state,ago:ji(s.updatedAt),pinned:s.pinned,nav:s.id},!0))}u.appendChild(p)}}e.appendChild(u)}}}render(){this.addShown=!1;let e=document.createDocumentFragment(),t=this.filterText;if(this.sections!==null)this.renderHubSections(e,t);else{let n=new Map;for(let i of this.threads){if(i.archived||i.swarm)continue;if(t){if(!`${i.title} ${i.preview??""}`.toLowerCase().includes(t))continue}let s=n.get(i.project)??[];s.push(i),n.set(i.project,s)}if(e.appendChild(this.projectsHead("ACTIVE")),this.projects.length===0&&this.threads.length===0){let i=document.createElement("div");i.className="bp-side-empty",i.textContent="No projects yet.",e.appendChild(i)}for(let i of this.projects){let s=n.get(i.id)??[];if(t&&s.length===0&&!i.title.toLowerCase().includes(t))continue;let r=document.createElement("section");r.className="bp-proj-group",r.setAttribute("data-project-id",i.id);let a=document.createElement("div");a.className="bp-proj-head";let o=document.createElement("button");o.type="button",o.className="bp-proj-toggle";let c=this.collapsedProjects.has(i.id)&&!t,u=Ri();if(i.css)u.style.color=i.css;let l=document.createElement("span");l.className="bp-proj-name",l.textContent=i.title||i.id,o.append(u,l),o.addEventListener("click",()=>{if(this.collapsedProjects.has(i.id))this.collapsedProjects.delete(i.id);else this.collapsedProjects.add(i.id);this.render()});let p=document.createElement("button");if(p.type="button",p.className="icon bp-proj-add",p.title=b("thread.new","New thread"),p.textContent="+",p.setAttribute("data-testid",`new-thread-${i.id}`),p.addEventListener("click",(d)=>{d.stopPropagation(),this.cb.onNewThread(i.id)}),a.append(o,p),r.appendChild(a),!c)for(let d of s)r.appendChild(this.renderSectionThreadRow({id:d.id,title:d.title,status:d.status,state:d.state,ago:ji(d.updatedAt),pinned:d.pinned,nav:d.id},!0));e.appendChild(r)}}if(!t){let n=document.createElement("section");n.className="bp-proj-group bp-bots-group";let i=document.createElement("div");i.className="bp-side-section-head bp-side-section-row";let s=document.createElement("span");s.textContent=b("tour.title.bots","Bots").toUpperCase();let r=document.createElement("span");r.className="bp-side-sec-plus",r.textContent="+",r.setAttribute("aria-hidden","true"),i.append(s,r),n.appendChild(i);for(let l of this.bots){let p=document.createElement("div");p.className="bp-thread-row"+(l.thread===this.selectedThreadId?" active":"");let d=document.createElement("span");if(d.className="bp-dot bp-dot-idle",l.color)d.style.backgroundColor=l.color;let g=document.createElement("div");g.className="bp-thread-title",g.textContent=`@${l.name}`,p.append(d,g),p.addEventListener("click",()=>this.cb.onSelectBot(l)),n.appendChild(p)}e.appendChild(n);let a=document.createElement("section");a.className="bp-proj-group";let o=document.createElement("div");o.className="bp-side-section-head bp-side-section-row";let c=document.createElement("span");c.textContent=b("bots.rooms","Rooms").toUpperCase();let u=document.createElement("span");u.className="bp-side-sec-plus",u.textContent="+",u.setAttribute("aria-hidden","true"),o.append(c,u),a.appendChild(o);for(let l of this.rooms){let p=document.createElement("div");p.className="bp-thread-row";let d=document.createElement("div");d.className="bp-thread-title",d.textContent=`#${l.name}`,p.appendChild(d),a.appendChild(p)}e.appendChild(a)}this.listEl.replaceChildren(e)}}function $s(e){try{return new URL(e,window.location.origin).searchParams.get("s")||""}catch{return""}}function Ct(e){if(!e)return;for(let t of e.getTracks())try{t.stop()}catch{}}function Gs(e,t){if(t===16000){let r=new Int16Array(e.length);for(let a=0;a0?c/u:0));s[r]=l<0?l*32768:l*32767}return s}class gn{hub;cb;active=!1;starting=!1;sessionGen=0;activeGen=0;abortedGen=0;threadId="";sessionKey="";stream=null;audioCtx=null;processor=null;pendingPcm=[];postChain=Promise.resolve();stopDrain=Promise.resolve();mark=0;constructor(e,t){this.hub=e,this.cb=t}isRecording(){return this.active||this.starting}async toggle(){if(this.active||this.starting)await this.stop();else await this.start()}async start(){if(this.active||this.starting)return;let e=this.cb.getThreadId();if(!e)return;if(!navigator.mediaDevices?.getUserMedia){this.cb.showError("Microphone access is not available in this browser.");return}let t=++this.sessionGen;this.starting=!0,this.threadId=e,this.sessionKey="",this.pendingPcm=[],this.mark=this.cb.getCaret(),this.cb.setRecording(!0);let n;try{n=await navigator.mediaDevices.getUserMedia({audio:!0})}catch{if(t===this.sessionGen)this.starting=!1,this.cb.setRecording(!1),this.cb.showError("Microphone permission denied.");return}if(t!==this.sessionGen||this.cb.getThreadId()!==e){Ct(n);return}if(this.stream=n,await this.stopDrain,t!==this.sessionGen||this.cb.getThreadId()!==e){if(Ct(n),this.stream===n)this.stream=null;return}try{let i=await this.hub.rpc("voice.start",{thread:e,draft:this.cb.getDraft(),caret:this.mark});if(t!==this.sessionGen||this.cb.getThreadId()!==e){if(Ct(n),this.stream===n)this.stream=null;if(!this.active&&!this.starting)this.hub.rpc("voice.stop",{thread:e}).catch(()=>{});return}let s=i.session||(i.path?$s(i.path):"");if(!s)throw Error("Hub did not return a voice session.");this.sessionKey=s,this.activeGen=t,this.starting=!1,this.active=!0,this.startCapture(n,t)}catch(i){if(t===this.sessionGen)this.cleanupAudio(),this.starting=!1,this.active=!1,this.cb.setRecording(!1),this.cb.showError(i instanceof Error?i.message:"Could not start voice dictation.");else if(Ct(n),this.stream===n)this.stream=null}}async stop(){if(!this.active&&!this.starting)return;let e=this.activeGen,t=this.active,n=this.threadId,i=this.sessionKey;this.sessionGen++,this.starting=!1,this.active=!1,this.sessionKey="",this.cb.setRecording(!1),this.cb.setLevel(0),this.cleanupAudio();let r=this.stopDrain.then(async()=>{if(t&&i){let a=new Int16Array(this.pendingPcm);this.pendingPcm=[],this.enqueuePost(i,new Uint8Array(a.buffer),!0,e),await this.postChain}else this.pendingPcm=[];if(t&&n)await this.hub.rpc("voice.stop",{thread:n}).catch(()=>{})});this.stopDrain=r,await r}cancel(){if(!this.active&&!this.starting)return;let e=this.active,t=this.threadId;if(this.abortedGen=Math.max(this.abortedGen,this.sessionGen),this.sessionGen++,this.starting=!1,this.active=!1,this.sessionKey="",this.pendingPcm=[],this.cb.setRecording(!1),this.cb.setLevel(0),this.cleanupAudio(),e&&t&&this.hub.getState()==="connected")this.hub.rpc("voice.stop",{thread:t}).catch(()=>{})}handleFrame(e){let t=String(e.ev??""),n=String(e.thread??"");if(n&&this.cb.getThreadId()&&n!==this.cb.getThreadId())return;if(t==="draft"&&typeof e.text==="string")this.cb.setDraft(e.text),this.mark=e.text.length;else if(t==="edit"){let i=this.cb.getDraft(),s=Number(e.del??0),r=String(e.ins??""),a=Math.max(0,Math.min(i.length,this.mark)),o=Math.max(0,a-s),c=i.slice(0,o)+r+i.slice(a);this.mark=o+r.length,this.cb.setDraft(c)}else if(t==="level")this.cb.setLevel(Math.max(0,Math.min(100,Number(e.v??0))));else if(t==="view"){let i=e.view;if(i&&i.on===!1&&(this.active||this.starting))this.stop()}}startCapture(e,t){let i=new(window.AudioContext||window.webkitAudioContext),s=i.createMediaStreamSource(e),r=i.createScriptProcessor(4096,1,1);r.onaudioprocess=(a)=>{if(!this.active||t!==this.sessionGen||!this.sessionKey)return;let o=Gs(a.inputBuffer.getChannelData(0),i.sampleRate);for(let c=0;c=3200){let c=new Int16Array(this.pendingPcm.splice(0,3200));this.enqueuePost(this.sessionKey,new Uint8Array(c.buffer),!1,t)}},s.connect(r),r.connect(i.destination),this.audioCtx=i,this.processor=r}enqueuePost(e,t,n,i){this.postChain=this.postChain.then(async()=>{if(i<=this.abortedGen)return;try{let s={"Content-Type":"application/octet-stream","X-Voice-Session":e};if(n)s["X-Voice-End"]="1";let r=await fetch("/voice/in",{method:"POST",credentials:"same-origin",headers:s,body:t});if(!r.ok&&!n&&i===this.sessionGen&&this.active)this.failUpload(`Voice upload failed (${r.status}).`)}catch{if(!n&&i===this.sessionGen&&this.active)this.failUpload("Voice upload failed.")}})}failUpload(e){this.abortedGen=Math.max(this.abortedGen,this.sessionGen),this.sessionGen++,this.active=!1,this.starting=!1,this.sessionKey="",this.pendingPcm=[],this.cleanupAudio(),this.cb.setRecording(!1),this.cb.setLevel(0),this.cb.showError(e)}cleanupAudio(){if(this.processor)this.processor.disconnect(),this.processor.onaudioprocess=null,this.processor=null;if(this.audioCtx)this.audioCtx.close().catch(()=>{}),this.audioCtx=null;Ct(this.stream),this.stream=null}}var Hi=[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],Di=[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],Fi=[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],$i=[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],Os=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];function kt(e,t){let n=new Int32Array(16),i=0;for(let o=0;o0){if(n[c]++,c>i)i=c}}let s=new Int32Array(16),r=0;for(let o=1;o<=15;o++)s[o]=r,r+=n[o];let a=new Int32Array(r);for(let o=0;o0)a[s[c]++]=o}return{counts:n,symbols:a,maxBits:i}}var Vs=(()=>{let e=new Uint8Array(288);return e.fill(8,0,144),e.fill(9,144,256),e.fill(7,256,280),e.fill(8,280,288),kt(e,288)})(),Us=(()=>{let e=new Uint8Array(32);return e.fill(5),kt(e,32)})();class fn{win=new Uint8Array(32768);winPos=0;feed(e,t=16777216){let n=0,i=0,s=0,r=(p)=>{while(s=e.length)throw Error("truncated deflate frame");i|=e[n++]<>>=p,s-=p,d},a=(p)=>{let d=0,g=0,y=0;for(let m=1;m<=p.maxBits;m++){d|=r(1);let h=p.counts[m];if(d-h{let d=c+p;if(d>t)throw Error("inflated frame exceeds limit");if(d<=o.length)return;let g=o.length;while(g{u(1),o[c++]=p,this.win[this.winPos]=p,this.winPos=this.winPos+1&32767};while(n0){if(n>=e.length&&s<3)break;let p=r(1),d=r(2);if(d===0){if(i=0,s=0,n+4>e.length)throw Error("truncated stored block");let g=e[n]|e[n+1]<<8,y=e[n+2]|e[n+3]<<8;if(n+=4,(g^65535)!==y)throw Error("invalid stored block length");if(n+g>e.length)throw Error("truncated stored payload");u(g);for(let m=0;m=e.length)break}else if(d===1||d===2){let g=Vs,y=Us;if(d===2){let m=r(5)+257,h=r(5)+1,f=r(4)+4,w=new Uint8Array(19);for(let T=0;TA)throw Error("code length overflow");for(let O=0;OA)throw Error("code length overflow");S+=B}else if(T===18){let B=r(7)+11;if(S+B>A)throw Error("code length overflow");S+=B}else throw Error("invalid code length symbol")}g=kt(M,m),y=kt(M.subarray(m),h)}while(!0){let m=a(g);if(m<256)l(m);else if(m===256)break;else{let h=m-257;if(h>=Hi.length)throw Error("invalid length symbol");let f=Hi[h]+(Di[h]?r(Di[h]):0),w=a(y);if(w>=Fi.length)throw Error("invalid distance symbol");let C=Fi[w]+($i[w]?r($i[w]):0);u(f);let A=this.winPos-C&32767;for(let M=0;M{this.stateListeners.delete(e)}}onFrame(e){return this.frameListeners.add(e),()=>{this.frameListeners.delete(e)}}onBinary(e){return this.binaryListeners.add(e),()=>{this.binaryListeners.delete(e)}}rpc(e,t={},n=20000){return new Promise((i,s)=>{if(!this.ws||this.ws.readyState!==WebSocket.OPEN){s(Error("Not connected to hub"));return}let r=this.nextId++,a=window.setTimeout(()=>{this.pending.delete(r),s(Error(`RPC timeout: ${e}`))},n);this.pending.set(r,{resolve:i,reject:s,timer:a}),this.ws.send(JSON.stringify({id:r,m:e,p:t}))})}setState(e){this.state=e;for(let t of this.stateListeners)t(e,this.hello)}rejectAllPending(e){for(let[,t]of this.pending)window.clearTimeout(t.timer),t.reject(Error(e));this.pending.clear()}openSocket(){if(this.closed)return;this.inflater=null;let t=`${window.location.protocol==="https:"?"wss:":"ws:"}//${window.location.host}/ws?data=1&enc=json&z=deflate`,n=new WebSocket(t);n.binaryType="arraybuffer",this.ws=n;let i=(s)=>{let r;try{r=JSON.parse(s)}catch{return}if(r.t==="hub.restarting")this.restarting={reason:String(r.reason??""),build:String(r.build??""),text:String(r.text??""),at:Date.now()};if(r.t==="hello")this.restarting=null,this.hello=r,this.features=new Set(this.hello.features??[]),this.inflater=this.hello.z==="deflate"?new fn:null,this.reconnectDelay=500,this.setState("connected");else if(r.t==="reply"&&typeof r.id==="number"){let a=this.pending.get(r.id);if(a)if(this.pending.delete(r.id),window.clearTimeout(a.timer),r.ok)a.resolve(r.result??{});else{let o=r.error,c=typeof o==="string"?o:o&&typeof o==="object"&&("message"in o)?String(o.message):"Request failed";a.reject(Error(c))}return}for(let a of this.frameListeners)a(r)};n.addEventListener("message",(s)=>{if(s.data instanceof ArrayBuffer){if(this.inflater){let r;try{r=this.inflater.feed(new Uint8Array(s.data))}catch{n.close();return}if(r.length>0&&r[0]===123)i(this.textDecoder.decode(r));else{let a=r.buffer.slice(r.byteOffset,r.byteOffset+r.byteLength);for(let o of this.binaryListeners)o(a)}return}for(let r of this.binaryListeners)r(s.data);return}if(typeof s.data!=="string")return;i(s.data)}),n.addEventListener("close",(s)=>{if(this.ws===n)this.ws=null;if(this.rejectAllPending("Connection closed"),this.closed)return;if(s.code===4001||s.code===4401||s.code===1008){this.handleRevoked();return}this.probeSessionOrReconnect()}),n.addEventListener("error",()=>{})}async probeSessionOrReconnect(){try{let t=await fetch("/",{method:"GET",credentials:"same-origin",cache:"no-store"});if(t.status===401||t.status===403){this.handleRevoked();return}if(t.ok){if((await t.text()).includes('id="pair-root"')){this.handleRevoked();return}}}catch{}this.setState("reconnecting");let e=this.reconnectDelay;this.reconnectDelay=Math.min(8000,Math.round(this.reconnectDelay*1.6)),this.reconnectTimer=window.setTimeout(()=>{this.reconnectTimer=null,this.openSocket()},e)}handleRevoked(){this.closed=!0,this.setState("revoked"),window.location.replace("/")}}var Ws=new TextDecoder;function Gi(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 Oi(e){let t=0,n=0;function i(a){if(a<=23)return a;if(a===24){if(t>=e.length)return null;return e[t++]}if(a===25){if(t+2>e.length)return null;let o=e[t]<<8|e[t+1];return t+=2,o}if(a===26){if(t+4>e.length)return null;let o=(e[t]<<24|e[t+1]<<16|e[t+2]<<8|e[t+3])>>>0;return t+=4,o}return null}function s(a){if(n++,a>32||n>400000||t>=e.length)return null;let o=e[t++],c=o>>5,u=i(o&31);if(u===null)return null;switch(c){case 0:return u;case 1:return-1-u;case 2:{if(t+u>e.length)return null;let l=e.subarray(t,t+u);return t+=u,l}case 3:{if(t+u>e.length)return null;let l=Ws.decode(e.subarray(t,t+u));return t+=u,l}case 4:{if(u>e.length)return null;let l=Array(u);for(let p=0;p=this.b.length)return this.ok=!1,0;let n=this.b[this.i++],i=7*t;if(i>=28&&(n&240)!==0)return this.ok=!1,0;if(e=(e|(n&127)<>>0,n<128)return e}return this.ok=!1,0}nextI32(){let e=this.nextU32();return e>>>1^-(e&1)}}function Ui(e){let t=0xcbf29ce484222325n,n=0x100000001b3n,i=0xffffffffffffffffn;for(let s=0;stypeof e[m]==="number"?e[m]:h,n=t("l",0),i=t("c",0),s=t("a",255)/255,r=t("m",1),a=t("w",0),o=a/2,c=r===0&&a!==0,u=e.d instanceof Uint8Array?e.d:new Uint8Array(0),l=new Vi(u),p=[],d=[],g=0,y=0;while(l.more()){let m=l.nextU32(),h=p.length,f=1/0,w=1/0,C=-1/0,A=-1/0;if(r===2)g=g+l.nextI32()|0,y=y+l.nextI32()|0,p.push(g,y),f=C=g,w=A=y;else{let S=Math.min(l.nextU32(),1048576);for(let T=0;TC)C=g;if(yA)A=y}}let M=(p.length-h)/2;if(M>0){let S=r===2||M===1?2:r===0?0:1,T=r===0?0:o;d.push({info:m,x0:f-T,y0:w-T,x1:C+T,y1:A+T,at:h,n:M,kind:S})}}return{layer:n,color:i,alpha:s,mode:r,r:o,own:c,pts:new Float32Array(p),pieces:d}}function Wi(e,t,n){let i=(a)=>Array.isArray(a)&&a.length>=4?[Number(a[0])||0,Number(a[1])||0,Number(a[2])||0,Number(a[3])||0]:[0,0,0,0],s=Array.isArray(e.cs)?e.cs:[],r=[];for(let a=0;a=0&&o0){n.delete(o.h),n.set(o.h,c);while(n.size>1024){let u=n.keys().next().value;if(u!==void 0)n.delete(u);else break}}}}return{key:typeof e.key==="string"?e.key:"",fam:typeof e.fam==="string"?e.fam:"",base:typeof e.base==="string"?e.base:"",box:i(e.box),edge:i(e.edge),thick:typeof e.thick==="number"?e.thick:1600,note:typeof e.note==="string"?e.note:"",warn:typeof e.warn==="number"?e.warn!==0:!1,chunks:r}}function _i(e,t,n,i=!0){if(n.width<=0||n.height<=0||n.naturalWidth<=0||n.naturalHeight<=0)return null;let s=Math.min(n.width/n.naturalWidth,n.height/n.naturalHeight),r=n.naturalWidth*s,a=n.naturalHeight*s,o=n.left+(n.width-r)/2,c=i?n.top:n.top+(n.height-a)/2,u=(e-o)/r,l=(t-c)/a;if(u<0||u>1||l<0||l>1)return null;return{x:Math.max(0,Math.min(1000,Math.round(u*1000))),y:Math.max(0,Math.min(1000,Math.round(l*1000)))}}var qi=[["Enter","Enter"],["Tab","Tab"],["Bksp","Backspace"],["Esc","Escape"],["↑","ArrowUp"],["↓","ArrowDown"],["←","ArrowLeft"],["→","ArrowRight"]];function Ki(e){let t=e.trim();if(!t)return"";if(/^[a-zA-Z][a-zA-Z0-9+.-]*:/.test(t))return t;return`https://${t}`}class yn{tail=Promise.resolve();enqueue(e){let t=this.tail.then(e,e);return this.tail=t.catch(()=>{}),t}}function zi(e,t,n){let i=!0,s=!1,r=!1,a="",o=!1,c=!1,u=-1,l=null,p=new yn,d=document.createElement("div");d.className="bp-pane bp-browser-pane",d.setAttribute("data-testid","pane-browser");let g=document.createElement("div");g.className="bp-pane-bar bp-browser-nav";function y(X,ce,E){let k=document.createElement("button");if(k.type="button",k.className="bp-v-btn",k.textContent=X,k.setAttribute("data-testid",ce),E)k.title=E;return k}let m=y("←","browser-back","Back"),h=y("→","browser-forward","Forward"),f=y("↻","browser-reload","Reload"),w=document.createElement("form");w.className="bp-browser-url-form";let C=document.createElement("input");C.type="text",C.className="bp-browser-input",C.placeholder="https://…",C.autocomplete="off",C.spellcheck=!1,C.setAttribute("data-testid","browser-url");let A=y("Go","browser-go","Navigate");A.type="submit",w.append(C,A);let M=y("Take over","browser-takeover");M.classList.add("is-primary"),g.append(m,h,f,w,M);let S=document.createElement("div");S.className="bp-browser-drive-bar",S.hidden=!0;let T=document.createElement("div");T.className="bp-browser-keys-row";let B=document.createElement("input");B.type="text",B.className="bp-browser-input",B.placeholder="Type text or press Enter/Tab/Arrows…",B.autocomplete="off",B.spellcheck=!1,B.setAttribute("data-testid","browser-keys");let R=y("Send","browser-type-send");T.append(B,R);let O=document.createElement("div");O.className="bp-browser-quick-keys";for(let[X,ce]of qi){let E=y(X,`browser-key-${ce}`);E.addEventListener("click",()=>he("press",{key:ce})),O.append(E)}S.append(T,O);let H=document.createElement("div");H.className="bp-browser-err",H.setAttribute("data-testid","browser-error"),H.hidden=!0;let ae=document.createElement("div");ae.className="bp-browser-stage",ae.setAttribute("data-testid","browser-stage");let ue=document.createElement("img");ue.className="bp-browser-img",ue.alt="Hub browser screen",ue.draggable=!1,ue.hidden=!0,ue.setAttribute("data-testid","browser-frame");let oe=document.createElement("div");oe.className="bp-pane-empty",oe.setAttribute("data-testid","browser-empty"),oe.textContent="Loading browser screen…",ae.append(ue,oe);let we=document.createElement("div");we.className="bp-browser-hint",we.textContent="You have the page: click to tap, scroll to wheel, type in the key box. Hand it back when done.",we.hidden=!0,d.append(g,S,H,ae,we),e.replaceChildren(d);function Le(X){H.textContent=X,H.hidden=!X}function Ne(){S.hidden=!s,we.hidden=!s,M.textContent=s?"Hand back":"Take over",M.setAttribute("data-testid",s?"browser-handback":"browser-takeover"),M.classList.toggle("is-on",s),ue.classList.toggle("is-driving",s)}function he(X,ce={},E){p.enqueue(async()=>{if(!i)return;Le("");try{if(await t.hub.rpc("browser",{thread:n,op:X,...ce}),!i)return;E?.(),le()}catch(k){if(!i)return;Le(k instanceof Error?k.message:String(k))}})}function be(X){he("toolbar",{command:X},()=>{s=!0,Ne()})}m.addEventListener("click",()=>be("back")),h.addEventListener("click",()=>be("forward")),f.addEventListener("click",()=>be("reload")),w.addEventListener("submit",(X)=>{X.preventDefault();let ce=Ki(C.value);if(!ce)return;if(C.value=ce,!s)he("takeover",{},()=>{s=!0,Ne()});he("navigate",{url:ce},()=>{s=!0,Ne()})}),M.addEventListener("click",()=>{if(s)he("handback",{},()=>{s=!1,Ne()});else he("takeover",{},()=>{s=!0,Ne(),B.focus()})});function I(){let X=B.value;if(!X)return;B.value="",he("type",{text:X})}R.addEventListener("click",I),B.addEventListener("keydown",(X)=>{if(!s)return;if(X.key==="Enter"){if(X.preventDefault(),B.value)I();he("press",{key:"Enter"});return}if(X.key==="Tab"||X.key==="Escape"||X.key==="ArrowUp"||X.key==="ArrowDown"||X.key==="ArrowLeft"||X.key==="ArrowRight"||X.key==="Backspace"&&B.value==="")X.preventDefault(),he("press",{key:X.key})}),ue.addEventListener("click",(X)=>{if(!s||!r)return;let ce=ue.getBoundingClientRect(),E=_i(X.clientX,X.clientY,{left:ce.left,top:ce.top,width:ce.width,height:ce.height,naturalWidth:ue.naturalWidth,naturalHeight:ue.naturalHeight});if(!E)return;he("click",E)}),ue.addEventListener("wheel",(X)=>{if(!s||!r)return;X.preventDefault();let ce=Math.round(X.deltaX),E=Math.round(X.deltaY);if(ce===0&&E===0)return;he("scroll",{dx:ce,dy:E})},{passive:!1});async function le(){if(!i)return;if(o){c=!0;return}o=!0;try{do{c=!1,l=new AbortController;let X=await fetch(`/bots/${encodeURIComponent(n)}/screen.jpg`,{credentials:"same-origin",cache:"no-store",signal:l.signal});if(!i)return;if(X.ok){let ce=await X.blob();if(!i)return;let E=URL.createObjectURL(ce),k=a;if(a=E,ue.src=E,ue.hidden=!1,oe.hidden=!0,r=!0,k)URL.revokeObjectURL(k)}else if(!r)ue.hidden=!0,oe.hidden=!1,oe.textContent="No browser page yet. An agent opens one when it needs the web."}while(i&&c)}catch{if(!i)return;if(!r)ue.hidden=!0,oe.hidden=!1,oe.textContent="No browser page yet. An agent opens one when it needs the web."}finally{l=null,o=!1}}let ne=t.hub.onFrame((X)=>{if(!i)return;if(X.t==="shot"&&X.bot===n){if(typeof X.n==="number"){if(X.n===u)return;u=X.n}le()}});return le(),{destroy(){if(i=!1,ne(),l?.abort(),a)URL.revokeObjectURL(a),a=""}}}function _(e,t,n){let i=document.createElement(e);if(t)i.className=t;if(n!==void 0)i.textContent=n;return i}function Ot(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 Yi(e){let t=e.lastIndexOf(".");return t>=0?e.slice(t+1).toLowerCase():""}function qs(e){return["png","jpg","jpeg","gif","webp","svg","bmp","ico"].includes(e)}function Ji(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 Ks(e){let t=Yi(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 Xi(e,t,n,i){let s=!0,r="",a="",o=_("div","bp-pane bp-files-pane");o.setAttribute("data-testid","pane-files");let c=_("div","bp-pane-bar"),u=_("div","bp-files-crumbs"),l=_("button","bp-v-btn","Refresh");l.type="button",l.addEventListener("click",()=>void h(r)),c.append(u,l);let p=_("div","bp-files-split"),d=_("div","bp-files-list");d.setAttribute("data-testid","files-list");let g=_("div","bp-files-preview");g.setAttribute("data-testid","files-preview"),g.append(_("div","bp-pane-empty","Select a file to preview")),p.append(d,g),o.append(c,p),e.replaceChildren(o);function y(){u.replaceChildren();let f=_("button","bp-crumb-btn","project");if(f.type="button",f.addEventListener("click",()=>void h("")),u.append(f),!r)return;let w=r.split("/").filter(Boolean),C="";for(let A of w){C=C?`${C}/${A}`:A;let M=C;u.append(_("span","bp-vh-sep","/"));let S=_("button","bp-crumb-btn",A);S.type="button",S.addEventListener("click",()=>void h(M)),u.append(S)}}async function m(f,w,C){a=f,g.replaceChildren();let A=_("div","bp-files-prev-head");A.append(_("span","bp-files-prev-name",f));let M=_("div","bp-files-prev-acts"),S=Ks(w);if(S){let O=_("button","bp-v-btn is-primary",`Open in ${S}`);O.type="button",O.setAttribute("data-testid","files-open-viewer"),O.addEventListener("click",()=>i(S,f)),M.append(O)}let T=`/files/get?thread=${encodeURIComponent(n)}&path=${encodeURIComponent(f)}`,B=_("a","bp-v-btn","Download");B.href=T,B.download=w,M.append(B),A.append(M),g.append(A);let R=Yi(w);if(qs(R)){let O=_("div","bp-files-img-wrap"),H=document.createElement("img");H.className="bp-files-img",H.alt=w,H.src=T,O.append(H),g.append(O);return}if(C>524288&&!Ji(R)){g.append(_("div","bp-pane-empty",`Binary file (${Ot(C)}). Use Download to save.`));return}if(Ji(R)||C<=65536){let O=_("div","bp-pane-empty","Loading…");g.append(O);try{let H=await fetch(T,{credentials:"same-origin"});if(!s||a!==f)return;if(!H.ok){O.textContent=`Could not load file (${H.status})`;return}if((H.headers.get("content-type")||"").startsWith("image/")){O.remove();let ne=document.createElement("img");ne.className="bp-files-img",ne.alt=w,ne.src=T,g.append(ne);return}let ue=262144,oe=[],we=0,Le=!1;if(H.body){let ne=H.body.getReader();try{while(!0){let{done:X,value:ce}=await ne.read();if(X||!ce)break;if(we+ce.byteLength>ue){let E=ue-we;if(E>0)oe.push(ce.subarray(0,E)),we+=E;Le=!0,await ne.cancel();break}oe.push(ce),we+=ce.byteLength}}finally{ne.releaseLock()}}if(!s||a!==f)return;let Ne=new Uint8Array(we),he=0;for(let ne of oe)Ne.set(ne,he),he+=ne.byteLength;let be=!1;for(let ne=0;neA.dir===M.dir?A.name.localeCompare(M.name):A.dir?-1:1),d.replaceChildren(),f){let A=_("button","bp-file-row is-dir");A.type="button",A.append(_("span","bp-file-icon","↰"),_("span","bp-file-name",".."));let M=f.includes("/")?f.slice(0,f.lastIndexOf("/")):"";A.addEventListener("click",()=>void h(M)),d.append(A)}if(C.length===0){d.append(_("div","bp-pane-empty","Empty folder"));return}for(let A of C){let M=f?`${f}/${A.name}`:A.name,S=_("button","bp-file-row"+(A.dir?" is-dir":"")+(M===a?" is-sel":""));S.type="button",S.setAttribute("data-testid",`file-row-${A.name}`),S.append(_("span","bp-file-icon",A.dir?"▸":"·"),_("span","bp-file-name",A.name),_("span","bp-file-size",A.dir?"":Ot(A.size))),S.addEventListener("click",()=>{if(A.dir)h(M);else d.querySelectorAll(".bp-file-row.is-sel").forEach((T)=>T.classList.remove("is-sel")),S.classList.add("is-sel"),m(M,A.name,A.size)}),d.append(S)}}catch(w){if(!s)return;d.replaceChildren(_("div","bp-pane-empty",w instanceof Error?w.message:String(w)))}}return h(""),{destroy(){s=!1}}}function Zi(e,t,n){let i=!0,s=_("div","bp-pane bp-diff-pane");s.setAttribute("data-testid","pane-diff");let r=_("div","bp-pane-bar"),a=_("span","bp-diff-summary","Loading diff…"),o=_("button","bp-v-btn","Refresh");o.type="button",o.addEventListener("click",()=>void u()),r.append(a,o);let c=_("div","bp-diff-body");c.setAttribute("data-testid","diff-body"),s.append(r,c),e.replaceChildren(s);async function u(){a.textContent="Loading diff…",c.replaceChildren();try{let l=await t.hub.rpc("viewer.diff",{thread:n});if(!i)return;if(l?.nogit){a.textContent="Not a git repository",c.append(_("div","bp-pane-empty","This project is not a git repository."));return}let p=typeof l?.diff==="string"?l.diff:"";if(!p.trim()){a.textContent="Clean working tree",c.append(_("div","bp-pane-empty","No uncommitted changes."));return}let d=p.split(` -`),g=0,y=0,m=0,h=document.createDocumentFragment(),f=_("div","bp-diff-file");for(let w of d){if(w.startsWith("diff --git ")){if(f.childNodes.length>0)h.append(f);f=_("div","bp-diff-file"),g++;let C=w.match(/ b\/(.+)$/);f.append(_("div","bp-diff-file-head",C?C[1]:w));continue}if(w.startsWith("index ")||w.startsWith("--- ")||w.startsWith("+++ "))f.append(_("div","bp-diff-line is-meta",w));else if(w.startsWith("@@"))f.append(_("div","bp-diff-line is-hunk",w));else if(w.startsWith("+"))y++,f.append(_("div","bp-diff-line is-add",w));else if(w.startsWith("-"))m++,f.append(_("div","bp-diff-line is-del",w));else f.append(_("div","bp-diff-line",w))}if(f.childNodes.length>0)h.append(f);a.textContent=`${g||1} file${g===1?"":"s"} · +${y} -${m}`,c.append(h)}catch(l){if(!i)return;a.textContent="Diff unavailable",c.append(_("div","bp-pane-empty",l instanceof Error?l.message:String(l)))}}return u(),{destroy(){i=!1}}}function Qi(e,t,n){let i=!0,s="checks",r=_("div","bp-pane bp-review-pane");r.setAttribute("data-testid","pane-review");let a=_("div","bp-pane-bar"),o=_("div","bp-review-tabs"),c=_("button","bp-v-btn is-on","Checks"),u=_("button","bp-v-btn","BOM"),l=_("button","bp-v-btn","Comments");c.type=u.type=l.type="button",o.append(c,u,l);let p=_("button","bp-v-btn","Refresh");p.type="button",p.addEventListener("click",()=>void m()),a.append(o,p);let d=_("div","bp-review-body");d.setAttribute("data-testid","review-body"),r.append(a,d),e.replaceChildren(r);function g(h){s=h,c.classList.toggle("is-on",s==="checks"),u.classList.toggle("is-on",s==="bom"),l.classList.toggle("is-on",s==="comments"),m()}c.addEventListener("click",()=>g("checks")),u.addEventListener("click",()=>g("bom")),l.addEventListener("click",()=>g("comments"));function y(h){let f=_("div","bp-review-md"),w=h.split(` -`),C=0;while(C{T.preventDefault();let B=M.value.trim();if(!B)return;S.disabled=!0,t.hub.rpc("review.comment",{thread:n,text:B}).then(()=>{M.value="",S.disabled=!1,m()},()=>{S.disabled=!1})}),d.append(A),C.length===0){d.append(_("div","bp-pane-empty","No review comments yet."));return}for(let T of C){let B=_("div","bp-review-comment"+(T.resolved?" is-resolved":"")),R=[T.by||"review",T.file,T.layer,T.item].filter(Boolean).join(" · ");B.append(_("div","bp-review-comment-meta",R),_("div","bp-review-comment-text",T.text)),d.append(B)}return}let h=await t.hub.rpc("review.page",{thread:n,page:s});if(!i)return;let f=h?.report||{};if(d.replaceChildren(),f.line||f.gate){let w=_("div","bp-review-gate",[f.gate,f.line].filter(Boolean).join(" · "));d.append(w)}if(f.err)d.append(_("div","bp-review-err",f.err));if(Array.isArray(f.tasks)&&f.tasks.length>0){let w=_("div","bp-review-tasks");f.tasks.forEach((C,A)=>{let M=_("label","bp-review-task"),S=document.createElement("input");S.type="checkbox",S.checked=!!(C.done??C.checked);let T=typeof C.index==="number"?C.index:A;S.addEventListener("change",()=>{t.hub.rpc("review.tick",{thread:n,index:T}).then(()=>void m(),()=>{})}),M.append(S,_("span",void 0,C.text||C.label||`Item ${A+1}`)),w.append(M)}),d.append(w)}if(f.md&&f.md.trim())d.append(y(f.md));else if(!f.err&&(!f.tasks||f.tasks.length===0))d.append(_("div","bp-pane-empty",`No ${s==="bom"?"BOM":"design checks"} report available.`))}catch(h){if(!i)return;d.replaceChildren(_("div","bp-pane-empty",h instanceof Error?h.message:String(h)))}}return m(),{destroy(){i=!1}}}function es(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 wn{canvas;ctx;frame=null;masks={off:0,dim:0,lift:255};highlights=new Set;lightTheme=!1;cx=0;cy=0;scale=0.0001;fittedKey="";fitW=0;fitH=0;userMoved=!1;dirty=!1;rafId=0;pointers=new Map;dragStart=null;pinchStart=null;resizeObs;cbs;constructor(e,t={}){this.cbs=t,this.canvas=document.createElement("canvas"),this.canvas.className="bp-viewer-canvas",this.canvas.style.width="100%",this.canvas.style.height="100%",this.canvas.style.display="block",this.canvas.style.touchAction="none",e.appendChild(this.canvas);let n=this.canvas.getContext("2d");if(!n)throw Error("Canvas2D unavailable");this.ctx=n,this.resizeObs=new ResizeObserver(()=>this.scheduleDraw()),this.resizeObs.observe(this.canvas),this.canvas.addEventListener("pointerdown",this.onPointerDown),this.canvas.addEventListener("pointermove",this.onPointerMove),this.canvas.addEventListener("pointerup",this.onPointerUp),this.canvas.addEventListener("pointercancel",this.onPointerUp),this.canvas.addEventListener("wheel",this.onWheel,{passive:!1}),this.canvas.addEventListener("dblclick",this.onDblClick)}setTheme(e){if(this.lightTheme!==e)this.lightTheme=e,this.scheduleDraw()}setFrame(e){if(this.frame=e,e&&e.key!==this.fittedKey)this.fittedKey=e.key,this.fit();else this.scheduleDraw()}setLayers(e){this.masks=e,this.scheduleDraw()}setHighlights(e){this.highlights.clear();for(let[t,n]of e)this.highlights.add(`${t}:${n}`);this.scheduleDraw()}presentMask(){if(!this.frame)return 0;let e=0;for(let t of this.frame.chunks)if(t.layer<32)e=(e|1<>>0;return e>>>0}presentColors(){let e=new Map;if(!this.frame)return e;for(let t of this.frame.chunks)if(!e.has(t.layer))e.set(t.layer,t.color);return e}applyFit(e,t){if(!this.frame||e<10||t<10)return;let n=this.frame.box,i=Math.max(n[2]-n[0],1000),s=Math.max(n[3]-n[1],1000);this.cx=(n[0]+n[2])*0.5,this.cy=(n[1]+n[3])*0.5,this.scale=Math.min(e/i,t/s)*0.92,this.fitW=e,this.fitH=t,this.userMoved=!1}fit(){if(!this.frame)return;this.userMoved=!1,this.fitW=0,this.fitH=0;let e=this.canvas.getBoundingClientRect();if(e.width>=10&&e.height>=10)this.applyFit(e.width,e.height);this.scheduleDraw()}zoomToBoxMm(e){let t=e[0]*1000,n=e[1]*1000,i=e[2]*1000,s=e[3]*1000,r=Math.max(i-t,1000),a=Math.max(s-n,1000),o=this.canvas.getBoundingClientRect(),c=Math.max(o.width,200),u=Math.max(o.height,200);this.cx=(t+i)*0.5,this.cy=(n+s)*0.5,this.scale=Math.min(c/r,u/a)*0.85,this.userMoved=!0,this.scheduleDraw()}scheduleDraw(){if(this.dirty)return;this.dirty=!0,this.rafId=requestAnimationFrame(()=>{this.dirty=!1,this.rafId=0,this.draw()})}draw(){let e=this.canvas.getBoundingClientRect(),t=Math.max(1,Math.round(e.width)),n=Math.max(1,Math.round(e.height)),i=Math.min(window.devicePixelRatio||1,2),s=Math.round(t*i),r=Math.round(n*i);if(this.canvas.width!==s||this.canvas.height!==r)this.canvas.width=s,this.canvas.height=r;let a=this.ctx;a.setTransform(i,0,0,i,0,0),a.fillStyle=this.lightTheme?"#f5f4ef":"#08090b",a.fillRect(0,0,t,n);let o=this.frame;if(!o)return;if(!this.userMoved&&t>=10&&n>=10&&(Math.abs(this.fitW-t)>2||Math.abs(this.fitH-n)>2))this.applyFit(t,n);let c=t*0.5,u=n*0.5,l=this.scale,p=this.cx,d=this.cy,g=p-c/l,y=p+c/l,m=d-u/l,h=d+u/l,{off:f,dim:w,lift:C}=this.masks,A=[],M=[];for(let T=0;T>>B&1)===1)continue;if(B===C)M.push(T);else A.push(T)}let S=A.concat(M);a.lineCap="round",a.lineJoin="round";for(let T=0;T>>R.layer&1)===1,H=R.alpha*(O?0.25:1);if(H<=0.01)continue;this.drawChunk(a,R,H,g,m,y,h,p,d,l,c,u)}if(this.highlights.size>0){a.fillStyle=this.lightTheme?"rgba(245,244,239,0.72)":"rgba(8,9,11,0.72)",a.fillRect(0,0,t,n);let T=this.lightTheme?"rgba(27,29,33,0.77)":"rgba(217,221,228,0.77)";for(let B=0;Br||h.y1a)continue;if(h.n<3)continue;let f=(d[h.at]-o)*u+l,w=(d[h.at+1]-c)*u+p;e.moveTo(f,w);for(let C=1;C0)e.fill()}else if(t.mode===2){let y=Math.max(0.75,t.r*u);e.fillStyle=g,e.beginPath();let m=0;for(let h=0;hr||f.y1a)continue;let w=(d[f.at]-o)*u+l,C=(d[f.at+1]-c)*u+p;e.moveTo(w+y,C),e.arc(w,C,y,0,Math.PI*2),m++}if(m>0)e.fill()}else{e.strokeStyle=g,e.lineWidth=Math.max(1,t.r*2*u),e.beginPath();let y=0;for(let m=0;mr||h.y1a)continue;let f=(d[h.at]-o)*u+l,w=(d[h.at+1]-c)*u+p;if(h.n===1)e.moveTo(f,w),e.lineTo(f+0.01,w);else{e.moveTo(f,w);for(let C=1;C0)e.stroke()}}drawLitPieces(e,t,n,i,s,r,a,o,c,u,l,p,d){let g=t.pts,y=es(t.color,t.alpha);for(let m=0;ma||h.y1o)continue;let f=(g[h.at]-c)*l+p,w=(g[h.at+1]-u)*l+d;if(h.kind===2){let C=Math.max(1.5,t.r*l);e.fillStyle=y,e.beginPath(),e.arc(f,w,C,0,Math.PI*2),e.fill(),e.strokeStyle=i,e.lineWidth=1.5,e.stroke()}else if(h.kind===0&&h.n>=3){e.fillStyle=y,e.beginPath(),e.moveTo(f,w);for(let C=1;C=0;l--){let p=n.chunks[l];if(p.layer<32&&(u>>>p.layer&1)===1)continue;for(let d=0;dg.x1+a||rg.y1+a)continue;let y=(g.x1-g.x0+1)*(g.y1-g.y0+1);if(y{if(this.canvas.setPointerCapture(e.pointerId),this.pointers.set(e.pointerId,{x:e.clientX,y:e.clientY}),this.pointers.size===1)this.dragStart={x:e.clientX,y:e.clientY,cx:this.cx,cy:this.cy,moved:!1},this.pinchStart=null;else if(this.pointers.size===2){let[t,n]=Array.from(this.pointers.values());this.pinchStart={dist:Math.hypot(n.x-t.x,n.y-t.y)||1,midX:(t.x+n.x)*0.5,midY:(t.y+n.y)*0.5,scale:this.scale,cx:this.cx,cy:this.cy},this.dragStart=null}};onPointerMove=(e)=>{if(!this.pointers.has(e.pointerId))return;if(this.pointers.set(e.pointerId,{x:e.clientX,y:e.clientY}),this.pointers.size===2&&this.pinchStart){let[t,n]=Array.from(this.pointers.values()),i=Math.hypot(n.x-t.x,n.y-t.y)||1,s=(t.x+n.x)*0.5,r=(t.y+n.y)*0.5,a=i/this.pinchStart.dist,o=Math.max(0.0000001,Math.min(2,this.pinchStart.scale*a)),c=this.canvas.getBoundingClientRect(),u=this.pinchStart.midX-c.left-c.width*0.5,l=this.pinchStart.midY-c.top-c.height*0.5,p=s-c.left-c.width*0.5,d=r-c.top-c.height*0.5;this.scale=o,this.cx=this.pinchStart.cx+u/this.pinchStart.scale-p/o,this.cy=this.pinchStart.cy+l/this.pinchStart.scale-d/o,this.userMoved=!0,this.cbs.onUserMove?.(),this.scheduleDraw();return}if(this.dragStart&&this.pointers.size===1){let t=e.clientX-this.dragStart.x,n=e.clientY-this.dragStart.y;if(Math.hypot(t,n)>3)this.dragStart.moved=!0;if(this.dragStart.moved)this.cx=this.dragStart.cx-t/this.scale,this.cy=this.dragStart.cy-n/this.scale,this.userMoved=!0,this.cbs.onUserMove?.(),this.scheduleDraw()}};onPointerUp=(e)=>{let t=this.dragStart&&!this.dragStart.moved&&this.pointers.size===1;if(this.pointers.delete(e.pointerId),this.pointers.size<2)this.pinchStart=null;if(this.pointers.size===0)this.dragStart=null;if(t&&this.cbs.onPick){let n=this.canvas.getBoundingClientRect(),i=this.hitTest(e.clientX-n.left,e.clientY-n.top);this.cbs.onPick(i)}};onWheel=(e)=>{e.preventDefault();let t=this.canvas.getBoundingClientRect(),n=e.clientX-t.left-t.width*0.5,i=e.clientY-t.top-t.height*0.5,s=e.deltaY<0?1.16:0.8620689655172414,r=Math.max(0.0000001,Math.min(2,this.scale*s));this.cx+=n/this.scale-n/r,this.cy+=i/this.scale-i/r,this.scale=r,this.userMoved=!0,this.cbs.onUserMove?.(),this.scheduleDraw()};onDblClick=()=>{this.fit()};destroy(){if(this.rafId)cancelAnimationFrame(this.rafId);this.resizeObs.disconnect(),this.canvas.removeEventListener("pointerdown",this.onPointerDown),this.canvas.removeEventListener("pointermove",this.onPointerMove),this.canvas.removeEventListener("pointerup",this.onPointerUp),this.canvas.removeEventListener("pointercancel",this.onPointerUp),this.canvas.removeEventListener("wheel",this.onWheel),this.canvas.removeEventListener("dblclick",this.onDblClick),this.canvas.remove()}}var ts=[{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 ns(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 En(e,t,n,i){if(!e||!t||!n||!i)return!1;if(!e.startsWith(t))return!1;let s=e.slice(t.length).split(` -`),r=(s[0]||"").split("\t");if(r[0]!=="git"||r[2]!==n)return!1;let a=s[1]||r.slice(4).join("\t");if(!a)return!1;let o=a.replace(/\\/g,"/"),c=i.replace(/\\/g,"/");if(c.startsWith("/")||/^[A-Za-z]:\//.test(c))return o===c;return o===c||o.endsWith(`/${c}`)}class xn{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 zs=`#version 300 es +`)){let n=e.slice(1).toLowerCase();if(this.filteredSlash=this.commands.filter((i)=>i.word.toLowerCase().startsWith(n)),this.filteredSlash.length>0){this.popupMode="slash",this.popupIdx=Math.min(this.popupIdx,this.filteredSlash.length-1),this.renderPopup();return}}let t=/(?:^|\s)([@>%#])([a-zA-Z0-9._-]{1,32})$/.exec(e.slice(0,this.textarea.selectionStart));if(t){let n=t[1],i=t[2];this.cb.onQueryMentions(i,n).then((s)=>{if(s.length>0)this.mentionItems=s,this.popupMode="mention",this.popupIdx=0,this.renderPopup();else if(this.popupMode==="mention")this.closePopup()});return}this.closePopup()}closePopup(){this.popupMode="none",this.popupEl.classList.add("bp-hidden"),this.popupEl.replaceChildren()}renderPopup(){let e=document.createDocumentFragment();if(this.popupMode==="slash")this.filteredSlash.forEach((t,n)=>{let i=document.createElement("button");i.type="button",i.className="bp-popup-row"+(n===this.popupIdx?" active":""),i.setAttribute("data-testid",`slash-item-${t.word}`);let s=document.createElement("span");s.className="bp-popup-name",s.textContent=`/${t.word}`;let r=document.createElement("span");r.className="bp-popup-desc",r.textContent=t.desc||t.label,i.append(s,r),i.addEventListener("mousedown",(a)=>{a.preventDefault(),this.applyPopupChoice(n)}),e.appendChild(i)});else if(this.popupMode==="mention")this.mentionItems.forEach((t,n)=>{let i=document.createElement("button");i.type="button",i.className="bp-popup-row"+(n===this.popupIdx?" active":"");let s=document.createElement("span");s.className="bp-popup-name",s.textContent=t.word||`${t.sigil}${t.label}`;let r=document.createElement("span");r.className="bp-popup-desc",r.textContent=t.detail||t.label,i.append(s,r),i.addEventListener("mousedown",(a)=>{a.preventDefault(),this.applyPopupChoice(n)}),e.appendChild(i)});this.popupEl.replaceChildren(e),this.popupEl.classList.remove("bp-hidden")}applyPopupChoice(e){if(this.popupMode==="slash"){let t=this.filteredSlash[e];if(t)this.textarea.value=`/${t.word} `,this.autoGrow(),this.textarea.focus();this.closePopup()}else if(this.popupMode==="mention"){let t=this.mentionItems[e];if(t){let n=this.textarea.selectionStart,i=this.textarea.value.slice(0,n),s=this.textarea.value.slice(n),r=i.replace(/([@>%#][a-zA-Z0-9._-]{1,32})$/,`${t.word} `);this.textarea.value=r+s,this.textarea.selectionStart=this.textarea.selectionEnd=r.length,this.textarea.focus()}this.closePopup()}}async addFiles(e){this.clearError();for(let t of e){if(!Un.has(t.type)){this.showError(b("web.composer.unsupported","Unsupported image type: {type}",{type:t.type||t.name}));continue}if(this.attachments.length>=Vn){this.showError(b("web.composer.maximages","At most {max} images per message.",{max:Vn}));break}let n=await new Promise((s,r)=>{let a=new FileReader;a.onload=()=>s(String(a.result||"")),a.onerror=()=>r(Error("read failed")),a.readAsDataURL(t)}).catch(()=>""),i=n.indexOf(",");if(i<0)continue;this.attachments.push({name:t.name||`image-${this.attachments.length+1}.png`,mime:t.type,data:n.slice(i+1),previewUrl:n})}this.renderAttachments()}renderAttachments(){if(this.attachments.length===0){this.attachStripEl.classList.add("bp-hidden"),this.attachStripEl.replaceChildren();return}let e=document.createDocumentFragment();this.attachments.forEach((t,n)=>{let i=document.createElement("div");i.className="bp-attach-chip";let s=document.createElement("img");s.src=t.previewUrl,s.alt=t.name,s.className="bp-attach-thumb";let r=document.createElement("button");r.type="button",r.className="icon bp-attach-rm",r.textContent="×",r.title=b("common.remove","Remove"),r.addEventListener("click",()=>{this.attachments.splice(n,1),this.renderAttachments()}),i.append(s,r),e.appendChild(i)}),this.attachStripEl.replaceChildren(e),this.attachStripEl.classList.remove("bp-hidden")}submit(){if(!this.enabled)return;let e=this.textarea.value.trim();if(!e&&this.attachments.length===0)return;if(this.closePopup(),this.clearError(),e.startsWith("/")&&this.attachments.length===0){let n=e.slice(1).split(/\s+/)[0]?.toLowerCase()??"";if(this.commands.some((i)=>i.word.toLowerCase()===n)){this.textarea.value="",this.autoGrow(),this.cb.onRunCommand(e);return}}let t=this.attachments.map(({name:n,mime:i,data:s})=>({name:n,mime:i,data:s}));this.attachments=[],this.renderAttachments(),this.textarea.value="",this.autoGrow(),this.cb.onSend(e,t)}}async function _n(e,t=fetch){let n=await t("/auth/web/logout",{method:"POST",credentials:"same-origin",redirect:"error",headers:{"Content-Type":"application/json"},body:"{}"});if(n.status!==200||(await n.json()).state!=="revoked")throw Error("Logout was not confirmed");e()}var xs=new Set(["bom","checks","life","plan","fab"]);function Rt(e){if(!e||!Array.isArray(e.panels))return[];return e.panels.filter((t)=>t&&typeof t.id==="string"&&xs.has(t.id))}function Xn(e){let t=e?.badge?.n??0;if(!Number.isFinite(t)||t<=0)return null;return{text:t>99?"99+":String(Math.floor(t)),tone:e?.badge?.tone==="bad"?"bad":"warn"}}function jt(e,t=22){let n=e.join(", ");if(n.length<=t)return n;let i="";for(let s=0;s0?` +${o}`.length:0)>t)return i?`${i} +${e.length-s}`:`${e[0]} +${e.length-1}`;i=a}return i}function at(e){if(!Number.isFinite(e)||e<0)return"?";if(e<1000)return String(Math.round(e));if(e<1e6){let n=e/1000;return n<10?`${n.toFixed(1).replace(/\.0$/,"")}k`:`${Math.round(n)}k`}let t=e/1e6;return t<10?`${t.toFixed(1).replace(/\.0$/,"")}M`:`${Math.round(t)}M`}function ot(e){if(!Number.isFinite(e))return"";if(e>=1)return`$${e.toFixed(2)}`;let t=e.toFixed(4).replace(/0+$/,"");return(t.split(".")[1]??"").length<2?`$${e.toFixed(2)}`:`$${t}`}var Cs=new Set(["0201","0402","0603","0805","1206","1210","1812","2010","2512"]),ks=new Set(["QFN","DFN","SOT","SOIC","SOP","SSOP","TSSOP","MSOP","QFP","LQFP","TQFP","BGA","WLCSP","SOD","TO","SON","LGA"]);function Zn(e){if(!e)return"";let t=e.indexOf(":"),i=(t>=0?e.slice(t+1):e).split("_");for(let a of i)if(Cs.has(a))return a;let s=i[0]??"",r=s.replace(/[^a-zA-Z].*$/,"").toUpperCase();if(ks.has(r)){let a=s.split("-");if(a.length>=2&&/^\d+$/.test(a[1]))return`${a[0]}-${a[1]}`;return a[0]}return i.slice(0,2).join("_")}function Qn(e){let t=e?.status??"";if(!t)return null;let n=typeof e?.stock==="number"?e.stock:-1;if(t==="checking")return{text:"…",tone:"faint"};if(t==="unknown")return{text:"?",tone:"faint"};if(t==="out")return{text:`out ${at(Math.max(n,0))}`,tone:"bad"};if(t==="low")return{text:`low ${at(n)}`,tone:"warn"};return{text:at(n),tone:"ok"}}function ei(e,t){let n=t.trim().toLowerCase().split(/\s+/).filter(Boolean);if(n.length===0)return e;return e.filter((i)=>{let s=[(i.refs??[]).join(" "),i.value??"",i.footprint??"",i.mpn??"",i.fab??""].join(" ").toLowerCase();return n.every((r)=>r==="dnp"&&Boolean(i.dnp)||s.includes(r))})}function ti(e,t){if(!t)return e;return e.filter((n)=>n.source===t)}function nn(e){if(e==="active")return{label:"Active",tone:"ok"};if(e==="nrnd")return{label:"NRND",tone:"warn"};if(e==="eol")return{label:"EOL",tone:"bad"};return{label:"Unknown",tone:"faint"}}function Ht(e){if(!Number.isFinite(e)||e<=0)return"";let t=new Date(e*1000),n=t.getUTCFullYear(),i=String(t.getUTCMonth()+1).padStart(2,"0"),s=String(t.getUTCDate()).padStart(2,"0");return`${n}-${i}-${s}`}function ni(e){return e.state==="routed"||e.state==="verified"}function ii(e){switch(e.state){case"approved":return"✓";case"edited":return"✎";case"verified":return"✓✓";case"routed":return"100%";case"rejected":case"failed":return"✗";case"routing":return typeof e.routed==="number"&&typeof e.total==="number"&&e.total>0?`${e.routed}/${e.total}`:"…";case"blocked":return`⚠ ${Math.max(1,e.problems??1)}`;default:return""}}function si(e){switch(e.status){case"blocked":return{key:"gpui.mgmt.plan.st.blocked",label:"Blocked",tone:"bad"};case"routing":return{key:"gpui.mgmt.plan.st.routing",label:"Routing",tone:"accent"};case"awaiting":return{key:"gpui.mgmt.plan.st.awaiting",label:"Awaiting review",tone:"warn"};case"verified":return{key:"gpui.mgmt.plan.st.verified",label:"Verified",tone:"ok"};case"routed":return{key:"gpui.mgmt.plan.st.routed",label:"Routed",tone:"ok"};case"ready":return{key:"gpui.mgmt.plan.st.approved",label:"Approved",tone:"accent"};case"partial":return{key:"gpui.mgmt.plan.st.partial",label:"Partial",tone:"warn"};case"rejected":return{key:"gpui.mgmt.plan.st.rejected",label:"Rejected",tone:"bad"};default:if((e.blocked??0)>0)return{key:"gpui.mgmt.plan.st.blocked",label:"Blocked",tone:"bad"};if(e.routing)return{key:"gpui.mgmt.plan.st.routing",label:"Routing",tone:"accent"};if((e.awaiting??0)>0)return{key:"gpui.mgmt.plan.st.awaiting",label:"Awaiting review",tone:"warn"};return{key:"gpui.mgmt.plan.st.empty",label:"Empty",tone:"faint"}}}function ri(e){let t=e.done??0,n=e.approved??0,i=e.awaiting??0,s=e.blocked??0,r=0;if(typeof e.total!=="number"){for(let a of e.layers??[])for(let o of a.items??[])if(o.state==="routed"||o.state==="verified")t+=1;else if(o.state==="routing")r+=1;else if(o.state==="approved")n+=1}else if(e.routing)r=Math.max(0,e.total-(t+n+i+s));return[{count:t,tone:"ok"},{count:r,tone:"accent"},{count:n,tone:"input"},{count:i,tone:"warn"},{count:s,tone:"bad"}]}function ai(e){switch(e){case"current":return{text:"The fab's limits are in the DRC rules",button:null};case"stale":return{text:"The DRC rules have older fab limits",button:"Update"};case"none":return{text:"The fab's limits are not in the DRC rules",button:"Write"};default:return{text:"No KiCad project for DRC rules",button:null}}}function oi(e){return e==="extra"?"costs-more limits":"base-price limits"}function sn(e,t){return e.watchGen===t.watchGen&&e.editGen===t.editGen&&e.project!==""&&e.project===t.project&&e.editId!==""&&e.editId===t.editId}function li(e){return{project:e.project,refs:e.refs.slice(),field:e.field,value:e.was}}function rn(e,t){return e.watchGen===t.watchGen&&e.project!==""&&e.project===t.project&&e.threadId!==""&&e.threadId===t.threadId&&e.threadGen===t.threadGen}var qn=["#f59e0b","#38bdf8","#c084fc","#2dd4bf","#ef4444","#a3e635","#f97316","#ec4899"],Kn=["#14b8a6","#f59e0b","#c084fc","#22c55e","#38bdf8","#ef4444","#e879f9","#84cc16"];function ci(e){let t=2166136261;for(let n=0;n>>0;return t}function Et(e,t=""){let n=t.trim().toLowerCase();if(n&&n!=="#5a7a9a"&&n!=="#8a8a8a")return t;let i=e.toUpperCase();if(i.includes("3V3A")||i.includes("AVDD")||i.includes("VDDA"))return"#38bdf8";if(i.includes("1V8")||i.includes("1.8V"))return"#c084fc";if(i.includes("2V5")||i.includes("2.5V"))return"#a3e635";if(i.includes("3V3")||i.includes("3.3V")||i.includes("VCC"))return"#f59e0b";if(i.includes("5V")||i.startsWith("+5"))return"#ef4444";if(i.includes("12V")||i.includes("24V"))return"#f97316";if(i.includes("VBAT")||i.includes("VIN"))return"#ec4899";if(i.includes("GND"))return"#2dd4bf";return qn[ci(i)%qn.length]}function lt(e,t=""){let n=t.trim().toLowerCase();if(n&&n!=="#8a8a8a")return t;return Kn[ci(e)%Kn.length]}function di(e,t,n,i=14){let s=Math.max(1,Math.abs(e[2]-e[0])),r=Math.max(1,Math.abs(e[3]-e[1])),a=Math.max(20,t-i*2),o=Math.max(20,n-i*2),c=Math.max(0.05,Math.min(200,Math.min(a/s,o/r)));return{cx:(e[0]+e[2])*0.5,cy:(e[1]+e[3])*0.5,scale:c,fitted:c,touched:!1}}function Ve(e,t,n,i,s){return[i*0.5+(t-e.cx)*e.scale,s*0.5+(n-e.cy)*e.scale]}function Dt(e,t,n,i,s){let r=Math.max(0.0001,e.scale);return[e.cx+(t-i*0.5)/r,e.cy+(n-s*0.5)/r]}function pi(e,t,n){let i=Math.max(0.0001,e.scale);return{...e,cx:e.cx-t/i,cy:e.cy-n/i,touched:!0}}function mi(e,t,n,i,s,r){let a=Math.max(0.02,e.fitted*0.35),o=Math.max(40,e.fitted*24),c=Math.max(a,Math.min(o,e.scale*t)),[u,l]=Dt(e,n,i,s,r);return{...e,cx:u-(n-s*0.5)/c,cy:l-(i-r*0.5)/c,scale:c,touched:!0}}function ui(e,t,n,i){let s=e.map((a)=>[a[0],a[1]]);if(s.length===0)return[n];let r=i&&t+1>=s.length?s.length:Math.min(t+1,s.length);return s.splice(r,0,[n[0],n[1]]),s}function an(e,t,n){let i=n?3:2;if(e.length<=i||t<0||t>=e.length)return null;let s=e.map((r)=>[r[0],r[1]]);return s.splice(t,1),s}function As(e,t,n,i,s,r){let a=s-n,o=r-i,c=a*a+o*o;if(c<0.000001)return(e-n)*(e-n)+(t-i)*(t-i);let u=Math.max(0,Math.min(1,((e-n)*a+(t-i)*o)/c)),l=n+u*a,p=i+u*o;return(e-l)*(e-l)+(t-p)*(t-p)}function zn(e,t,n){if(n.length<3)return!1;let i=!1;for(let s=0,r=n.length-1;st!==u>t&&e<(c-a)*(t-o)/(u-o+0.000000000001)+a)i=!i}return i}function on(e,t){return Math.max(5,Math.min(32,e*t))}function Ft(e,t,n,i,s,r,a,o,c){if(i){for(let d of e){if(d.layer!==n||d.id!==i||d.locked)continue;let g=d.path??[];for(let y=0;y=3)for(let y=0;y=0;d--){let g=t[d];if(g.layer!==n)continue;let y=g.outline??[];if(!zn(l,p,y))continue;if(!(g.holes??[]).some((h)=>zn(l,p,h)))return{kind:"region",id:g.id}}return null}function ct(e){let t=null,n=null,i=[];for(let r of e){if(!r.layer)continue;i.push(r.layer);let a=r.items??[],o=a.filter((u)=>u.kind==="corridor").length,c=a.filter((u)=>u.kind==="plane").length;if((o>0||r.role==="signal")&&(!t||o>t.count))t={count:o,layer:r.layer};if((c>0||r.role==="power"||r.role==="plane")&&(!n||c>n.count))n={count:c,layer:r.layer}}let s=[];if(t)s.push(t.layer);if(n&&!s.includes(n.layer))s.push(n.layer);for(let r of i){if(s.length>=2)break;if(!s.includes(r))s.push(r)}return s}function Jn(e,t){if(!e||e.length===0)return null;if(e.length===1)return e[0];let n=Math.max(0,Math.min(1,t)),i=0;for(let a=1;a=s&&o>0.000000001){let c=(s-r)/o;return[e[a-1][0]+(e[a][0]-e[a-1][0])*c,e[a-1][1]+(e[a][1]-e[a-1][1])*c]}r+=o}return e[e.length-1]}function it(e,t,n){for(let i of t??[])if(i.layer===e&&i.title)return i.title;for(let i of n??[])if(i.layer===e&&i.title)return i.title;return e}function hi(e,t,n){if(e==="split"&&n.length>0)return t.filter((i)=>n.includes(i.layer));return t}function tn(e,t){return!(e[2]<=t[0]||e[0]>=t[2]||e[3]<=t[1]||e[1]>=t[3])}function Yn(e,t,n){if(n.length<3)return!1;let i=!1;for(let s=0,r=n.length-1;st!==u>t&&e<(c-a)*(t-o)/(u-o+0.000000000001)+a)i=!i}return i}function bi(e,t){if(e.length<3)return null;let n=1/0,i=1/0,s=-1/0,r=-1/0,a=0,o=0;for(let u of e)n=Math.min(n,u[0]),i=Math.min(i,u[1]),s=Math.max(s,u[0]),r=Math.max(r,u[1]),a+=u[0],o+=u[1];let c=[[(n+s)*0.5,(i+r)*0.5],[a/e.length,o/e.length]];for(let u of[0.5,0.25,0.75,0.125,0.875])for(let l of[0.5,0.25,0.75,0.125,0.875])c.push([n+(s-n)*l,i+(r-i)*u]);for(let u of c)if(Yn(u[0],u[1],e)&&!t.some((l)=>Yn(u[0],u[1],l)))return u;return null}function gi(e,t,n,i,s,r){let a=[];for(let l of e){let p=l.nets??0,d=l.path??[];if(p<=0||d.length<2)continue;let g=0;for(let y=1;y{let d=l.sel||l.hov?1:0,g=p.sel||p.hov?1:0;if(g!==d)return g-d;if(p.nets!==l.nets)return p.nets-l.nets;return l.b.id.localeCompare(p.b.id)});let o=[],c=[],u=(l,p,d,g,y)=>[l-d*0.5-y,p-g*0.5-y,l+d*0.5+y,p+g*0.5+y];for(let l of a){let p=l.b.name||"",d=String(l.nets),g=p?`${p} · ${l.nets}`:d,y=(l.sel||l.hov||l.pxLen>=95)&&p?[g,d]:[d],m=null,h=(w,C)=>Math.max(C*0.5+3,Math.min(Math.max(C*0.5+3,n-C*0.5-3),w)),f=(w,C)=>Math.max(C*0.5+3,Math.min(Math.max(C*0.5+3,i-C*0.5-3),w));e:for(let w of y){let C=Math.max(16,w.length*5.9+10),A=15;for(let M of[0.5,0.35,0.65,0.22,0.78]){let P=Jn(l.pts,M);if(!P)continue;let[T,B]=Ve(t,P[0],P[1],n,i),R=h(T,C),O=f(B,15),H=u(R,O,C,15,2);if(!o.some((ae)=>tn(H,ae))){m={id:l.b.id,text:w,cx:R,cy:O,pw:C,ph:15,col:l.col,sel:l.sel};break e}}}if(!m){let w=Jn(l.pts,0.5);if(w){let[C,A]=Ve(t,w[0],w[1],n,i),M=Math.max(16,d.length*6.5+8),P=15,T=h(C,M);for(let B of[-18,18]){let R=f(A+B,15);if(!o.some((O)=>tn(u(T,R,M,15,2),O))){m={id:l.b.id,text:d,cx:T,cy:R,pw:M,ph:15,col:l.col,sel:l.sel};break}}}}if(m)o.push(u(m.cx,m.cy,m.pw,m.ph,2)),c.push(m)}return c}function fi(e,t,n,i,s,r=[]){let a=new Set(s),o=[];for(let l of e){if(!l.r||!l.b||l.b.length!==4)continue;let[p,d]=Ve(t,l.b[0],l.b[1],n,i),[g,y]=Ve(t,l.b[2],l.b[3],n,i),m=Math.abs(g-p),h=Math.abs(y-d);if(m<13||h<9)continue;let f=(p+g)*0.5,w=(d+y)*0.5;if(f<8||f>n-8||w<8||w>i-8)continue;o.push({text:l.r,cx:f,cy:w,bw:l.r.length*5.8+4,bh:11,score:m*h+(a.has(l.r)?1e4:0)})}o.sort((l,p)=>p.score-l.score);let c=[...r],u=[];for(let l of o){let p=[l.cx-l.bw*0.5,l.cy-l.bh*0.5,l.cx+l.bw*0.5,l.cy+l.bh*0.5];if(!c.some((g)=>tn(p,g)))c.push(p),u.push({text:l.text,cx:l.cx,cy:l.cy})}return u}function vi(e){if(!e||typeof e!=="object")return null;let t=e;if(t.panel&&typeof t.panel==="object")return t.panel;if(t.result&&typeof t.result==="object"){let n=t.result.panel;if(n&&typeof n==="object")return n}return null}function $t(e,t){if(!t||t.length===0)return e;let n=new Map;for(let r of e)if(r.layer)n.set(r.layer,r);let i=[],s=new Set;for(let r of t){if(!r.layer)continue;s.add(r.layer);let a=n.get(r.layer);if(a)i.push(a);else i.push({layer:r.layer,index:r.index,title:r.title||`L${r.index} · ${r.layer}`,subtitle:r.subtitle||"",role:r.role,status:"proposed",done:0,approved:0,total:0,items:[]})}for(let r of e)if(r.layer&&!s.has(r.layer))i.push(r);return i}function yi(e,t,n,i,s,r,a,o){return e===t&&n===i&&s===r&&(o===void 0||a>=o)}var wi="#111917",Ls="#16201d",Ss="rgba(212, 224, 219, 0.92)",Ps="rgba(61, 80, 73, 0.72)",Ns="rgba(82, 107, 97, 0.85)";var Ei="#f59e0b",Ms="#eef5f2",xi="#ef4444";function st(e,t){let n=e.trim().replace(/^#/,"");if(n.length===6){let i=parseInt(n.slice(0,2),16),s=parseInt(n.slice(2,4),16),r=parseInt(n.slice(4,6),16);if(!Number.isNaN(i)&&!Number.isNaN(s)&&!Number.isNaN(r))return`rgba(${i}, ${s}, ${r}, ${t})`}return`rgba(20, 184, 166, ${t})`}function Ts(e,t,n){let i=0.14,s=0.45,r=0.85,a=!1;switch(e){case"approved":case"routing":i=0.16,s=0.51,r=0.91;break;case"edited":i=0.2,s=0.56,r=0.95;break;case"routed":case"verified":i=0.08,s=0.26,r=0.59;break;case"rejected":case"failed":i=0.05,s=0.13,r=0.27;break;case"blocked":i=0.18,s=0.48,r=0.88,a=!0;break}if(t)i=Math.min(0.35,i+0.1),s=Math.min(0.71,s+0.12),r=1;else if(n)i=Math.min(0.28,i+0.06),s=Math.min(0.63,s+0.07);return{glow:i,body:s,core:r,bad:a}}function Bs(e,t,n){let i=0.27,s=0.83,r=!1;switch(e){case"approved":case"routing":i=0.36,s=0.91;break;case"edited":i=0.38,s=0.95;break;case"routed":case"verified":i=0.16,s=0.54;break;case"rejected":case"failed":i=0.08,s=0.27;break;case"blocked":i=0.31,s=0.94,r=!0;break}if(t)i=Math.min(0.53,i+0.12),s=1;else if(n)i=Math.min(0.45,i+0.06),s=Math.min(1,s+0.1);return{fill:i,edge:s,bad:r}}function Is(e){let t=e.items??[];if(t.some((n)=>n.state==="blocked"||n.state==="failed"))return{key:"gpui.mgmt.plan.st.blocked",label:"Blocked",tone:"bad"};if(t.some((n)=>n.state==="routing"))return{key:"gpui.mgmt.plan.st.routing",label:"Routing",tone:"accent"};if(t.some((n)=>n.state==="proposed"||n.state==="edited"))return{key:"gpui.mgmt.plan.st.awaiting",label:"Awaiting review",tone:"warn"};if(t.length>0&&t.every((n)=>n.state==="routed"||n.state==="verified"))return{key:"gpui.mgmt.plan.st.routed",label:"Routed",tone:"ok"};if(t.length>0&&t.every((n)=>n.state==="approved"||n.state==="routed"||n.state==="verified"))return{key:"gpui.mgmt.plan.st.approved",label:"Approved",tone:"accent"};return{key:"gpui.mgmt.plan.st.empty",label:"Empty",tone:"faint"}}class ln{root;cb;state=null;cards=new Map;renderedLayerKey="";sharedCam=null;layerCams=new Map;hover=null;selectedVertex=null;drag=null;downPos=null;rafPending=0;constructor(e){this.cb=e,this.root=document.createElement("div"),this.root.className="bp-plan-canvas-grid",this.root.tabIndex=0,this.root.setAttribute("data-testid","mgmt-plan-canvas-grid"),this.root.addEventListener("keydown",(t)=>this.onKeyDown(t))}isDragging(){return this.drag!==null}fitAll(){this.sharedCam=null,this.layerCams.clear(),this.scheduleDraw()}destroy(){if(this.rafPending)cancelAnimationFrame(this.rafPending),this.rafPending=0;for(let e of this.cards.values())e.ro.disconnect();this.cards.clear(),this.root.replaceChildren()}visibleLayers(e){let t=$t(e.layers,e.copperLayers);if(t.length===0)return[];if(e.gridMode==="all")return t;if(e.gridMode==="single"){let s=e.shownLayers.find((a)=>t.some((o)=>o.layer===a))??ct(t)[0]??t[0]?.layer,r=t.find((a)=>a.layer===s);return r?[r]:[]}let n=e.shownLayers.length>0&&e.shownLayers.every((s)=>t.some((r)=>r.layer===s))?e.shownLayers.slice(0,2):ct(t),i=[];for(let s of n){let r=t.find((a)=>a.layer===s);if(r)i.push(r)}return i.length>0?i:t.slice(0,2)}update(e,t){this.state=e;let n=this.visibleLayers(e);this.root.classList.toggle("two-cols",t&&n.length>1);let i=n.map((s)=>s.layer).join("|");if(i!==this.renderedLayerKey){this.renderedLayerKey=i;for(let s of this.cards.values())s.ro.disconnect();this.cards.clear(),this.root.replaceChildren();for(let s of n){let r=this.buildCard(s);this.cards.set(s.layer,r),this.root.appendChild(r.el)}}else for(let s of n){let r=this.cards.get(s.layer);if(r)this.syncCardHeaderAndLegend(r,s)}this.scheduleDraw()}effectiveBbox(e){let t=e.bbox;if(!t||t.length!==4||Math.abs(t[2]-t[0])<0.5||Math.abs(t[3]-t[1])<0.5)return[0,0,100,70];return t}getCam(e,t,n){let i=this.state,s=i?.syncZoom?this.sharedCam:this.layerCams.get(e)??null;if(s&&s.touched)return s;return di(i?this.effectiveBbox(i.board):[0,0,100,70],t,n,14)}setCam(e,t){if(this.state?.syncZoom)this.sharedCam=t;else this.layerCams.set(e,t)}buildCard(e){let t=document.createElement("section");t.className="bp-plan-card",t.setAttribute("data-testid",`mgmt-plan-card-${e.layer}`);let n=document.createElement("div");n.className="bp-plan-card-head";let i=document.createElement("div");i.className="bp-plan-card-head-top";let s=document.createElement("span"),r=e.role==="power"||(e.items?.length??0)>0&&(e.items??[]).every((w)=>w.kind==="plane");s.className="bp-plan-card-bar "+(r?"pwr":"sig");let a=document.createElement("span");a.className="bp-plan-card-title";let o=document.createElement("span");o.className="bp-plan-status-badge";let c=document.createElement("button");c.type="button",c.className="bp-mgmt-btn bp-plan-mini-btn",c.textContent="✓",c.title=b("gpui.mgmt.plan.layer","Approve layer"),c.addEventListener("click",(w)=>{w.stopPropagation(),this.cb.onApproveLayer(e.layer,!0)});let u=document.createElement("button");u.type="button",u.className="bp-mgmt-btn bp-plan-mini-btn",u.textContent="✗",u.title=b("gpui.mgmt.plan.rejectlayer","Reject layer"),u.addEventListener("click",(w)=>{w.stopPropagation(),this.cb.onApproveLayer(e.layer,!1)}),i.append(s,a,o,c,u);let l=document.createElement("div");l.className="bp-plan-card-sub",n.append(i,l);let p=document.createElement("div");p.className="bp-plan-card-canvas-wrap";let d=document.createElement("canvas");d.className="bp-plan-card-canvas",d.setAttribute("data-testid",`mgmt-plan-canvas-${e.layer}`);let g=document.createElement("div");g.className="bp-plan-hover-hud bp-hidden",p.append(d,g);let y=document.createElement("div");y.className="bp-plan-legend bp-hidden",t.append(n,p,y);let m=d.getContext("2d"),h=new ResizeObserver(()=>this.scheduleDraw());h.observe(p),this.attachPointerListeners(d,e.layer);let f={layer:e.layer,el:t,canvas:d,ctx:m,legendEl:y,okBtn:c,noBtn:u,statusEl:o,titleEl:a,subtitleEl:l,hoverHudEl:g,ro:h};return this.syncCardHeaderAndLegend(f,e),f}syncCardHeaderAndLegend(e,t){e.titleEl.textContent=it(t.layer,this.state?.copperLayers,this.state?.layers)||t.title||t.layer;let n=t.subtitle||t.stackup||"";e.subtitleEl.textContent=n,e.subtitleEl.classList.toggle("bp-hidden",!n);let i=t.items??[],s=Is(t);e.statusEl.className=`bp-plan-card-status tone-${s.tone==="warn"?"dim":s.tone}`,e.statusEl.textContent=i.length>0?b(s.key,s.label):"",e.statusEl.classList.toggle("bp-hidden",i.length===0);let r=i.some((o)=>o.state==="proposed"||o.state==="edited");if(e.okBtn)e.okBtn.classList.toggle("bp-hidden",!r);if(e.noBtn)e.noBtn.classList.toggle("bp-hidden",!r);let a=(this.state?.regions??[]).filter((o)=>o.layer===t.layer);if(a.length===0)e.legendEl.classList.add("bp-hidden"),e.legendEl.replaceChildren();else{e.legendEl.classList.remove("bp-hidden");let o=document.createDocumentFragment();for(let c of a){let u=document.createElement("button");u.type="button";let l=this.state?.selectedId===c.id;u.className="bp-plan-legend-chip"+(l?" active":"");let p=document.createElement("span");p.className="bp-plan-legend-sw",p.style.background=Et(c.net||c.id,c.color||"");let d=document.createElement("span");d.textContent=c.net||c.id,u.append(p,d),u.addEventListener("click",()=>{this.cb.onSelect(c.id),this.cb.onFocusItem(c.id)}),o.appendChild(u)}e.legendEl.replaceChildren(o)}}attachPointerListeners(e,t){e.addEventListener("contextmenu",(i)=>i.preventDefault()),e.addEventListener("dblclick",()=>this.fitAll()),e.addEventListener("pointerdown",(i)=>{let s=this.state;if(!s)return;this.root.focus({preventScroll:!0});let r=e.getBoundingClientRect(),a=i.clientX-r.left,o=i.clientY-r.top,c=Math.max(1,r.width),u=Math.max(1,r.height),l=this.getCam(t,c,u),p=Ft(s.bands,s.regions,t,s.selectedId,l,c,u,a,o);if(i.button===2){if(p?.kind==="vertex"){let d=this.getItemPts(p.id,p.isPlane),g=an(d,p.idx,p.isPlane);if(g)this.selectedVertex=null,this.cb.onCommitFields(p.id,{[p.isPlane?"outline":"path"]:g})}return}if(i.button!==0)return;if(e.setPointerCapture(i.pointerId),this.downPos={x:i.clientX,y:i.clientY},p?.kind==="vertex"){let d=this.getItemPts(p.id,p.isPlane),g=d.map((y)=>[y[0],y[1]]);this.selectedVertex={id:p.id,idx:p.idx},this.drag={layer:t,kind:"vertex",id:p.id,isPlane:p.isPlane,idx:p.idx,pts:d.map((y)=>[y[0],y[1]]),origPts:g,moved:!1},this.scheduleDraw()}else if(p?.kind==="midpoint"){let d=this.getItemPts(p.id,p.isPlane),g=d.map((h)=>[h[0],h[1]]),y=ui(d,p.segIdx,p.pos,p.isPlane),m=p.isPlane&&p.segIdx+1>=d.length?y.length-1:Math.min(p.segIdx+1,y.length-1);this.selectedVertex={id:p.id,idx:m},this.patchLocalItem(p.id,p.isPlane,y),this.drag={layer:t,kind:"vertex",id:p.id,isPlane:p.isPlane,idx:m,pts:y,origPts:g,moved:!0},this.scheduleDraw()}else this.selectedVertex=null,this.drag={layer:t,kind:"pan",lastX:a,lastY:o}}),e.addEventListener("pointermove",(i)=>{let s=this.state;if(!s)return;let r=e.getBoundingClientRect(),a=i.clientX-r.left,o=i.clientY-r.top,c=Math.max(1,r.width),u=Math.max(1,r.height);if(this.drag&&this.drag.layer===t){if(this.drag.kind==="pan"){let A=this.getCam(t,c,u);this.setCam(t,pi(A,a-this.drag.lastX,o-this.drag.lastY)),this.drag.lastX=a,this.drag.lastY=o,this.scheduleDraw();return}if(this.downPos&&Math.hypot(i.clientX-this.downPos.x,i.clientY-this.downPos.y)<1.5&&!this.drag.moved)return;let m=this.getCam(t,c,u),[h,f]=Dt(m,a,o,c,u),w=[Math.round(h*1000)/1000,Math.round(f*1000)/1000];this.drag.moved=!0,this.drag.pts[this.drag.idx]=w;let C=this.drag.pts.map((A)=>[A[0],A[1]]);this.patchLocalItem(this.drag.id,this.drag.isPlane,C),this.scheduleDraw();return}let l=this.getCam(t,c,u),p=Ft(s.bands,s.regions,t,s.selectedId,l,c,u,a,o),d=this.hover?.hit?"id"in this.hover.hit?this.hover.hit.id:"":"",g=this.hover?.hit.kind??"",y=p?p.id:"";if(this.hover=p?{layer:t,hit:p}:null,e.style.cursor=p?"pointer":"crosshair",d!==y||(p?.kind??"")!==g)this.syncHoverHud(t),this.scheduleDraw()}),e.addEventListener("pointerleave",()=>{if(this.hover?.layer===t)this.hover=null,this.syncHoverHud(t),this.scheduleDraw()});let n=()=>{let i=this.drag;if(!i||i.layer!==t)return;if(this.drag=null,this.downPos=null,i.kind==="vertex"&&i.moved){let s=i.origPts.map((r)=>[r[0],r[1]]);this.patchLocalItem(i.id,i.isPlane,s)}this.cb.onDragEnd?.(),this.scheduleDraw()};e.addEventListener("pointercancel",n),e.addEventListener("lostpointercapture",n),e.addEventListener("pointerup",(i)=>{let s=this.state,r=this.drag,a=this.downPos;if(this.drag=null,this.downPos=null,e.hasPointerCapture(i.pointerId))e.releasePointerCapture(i.pointerId);if(r&&r.kind==="vertex"&&r.layer===t){if(r.moved)this.cb.onCommitFields(r.id,{[r.isPlane?"outline":"path"]:r.pts});else this.cb.onDragEnd?.(),this.scheduleDraw();return}if(s&&a&&Math.hypot(i.clientX-a.x,i.clientY-a.y)<4.5){let o=e.getBoundingClientRect(),c=i.clientX-o.left,u=i.clientY-o.top,l=Math.max(1,o.width),p=Math.max(1,o.height),d=this.getCam(t,l,p),g=Ft(s.bands,s.regions,t,s.selectedId,d,l,p,c,u);if(g&&(g.kind==="band"||g.kind==="region")){this.cb.onSelect(g.id),this.cb.onFocusItem(g.id);return}if(!g&&s.selectedId){this.cb.onSelect("");return}}this.cb.onDragEnd?.()}),e.addEventListener("wheel",(i)=>{i.preventDefault();let s=e.getBoundingClientRect(),r=i.clientX-s.left,a=i.clientY-s.top,o=Math.max(1,s.width),c=Math.max(1,s.height),u=this.getCam(t,o,c),l=Math.max(0.65,Math.min(1.55,1-i.deltaY*0.002));this.setCam(t,mi(u,l,r,a,o,c)),this.scheduleDraw()},{passive:!1})}patchLocalItem(e,t,n){let i=this.state;if(!i)return;if(t){let s=i.regions.find((r)=>r.id===e);if(s){if(s.outline=n,s.edited=!0,s.state==="proposed")s.state="edited"}}else{let s=i.bands.find((r)=>r.id===e);if(s){if(s.path=n,s.edited=!0,s.state==="proposed")s.state="edited"}}}getItemPts(e,t){let n=this.state;if(!n)return[];if(t)return(n.regions.find((i)=>i.id===e)?.outline??[]).map((i)=>[i[0],i[1]]);return(n.bands.find((i)=>i.id===e)?.path??[]).map((i)=>[i[0],i[1]])}syncHoverHud(e){let t=this.cards.get(e),n=this.state;if(!t||!n)return;if(!this.hover||this.hover.layer!==e){t.hoverHudEl.classList.add("bp-hidden"),t.hoverHudEl.textContent="";return}let i=this.hover.hit.id,s=n.bands.find((o)=>o.id===i),r=n.regions.find((o)=>o.id===i),a="";if(s)a=`${s.name||i} · ${s.nets??0}n · ${(s.width??1.5).toFixed(2)}mm`;else if(r)a=r.reference?`${r.net||i} · ${r.reference}`:r.net||i;if(!a)t.hoverHudEl.classList.add("bp-hidden");else t.hoverHudEl.classList.remove("bp-hidden"),t.hoverHudEl.textContent=a}onKeyDown(e){let t=this.state;if(!t)return;if(e.key==="0"||e.key==="Home"){e.preventDefault(),this.fitAll();return}if(e.key==="Escape"){this.selectedVertex=null,this.cb.onSelect("");return}if(!t.selectedId)return;let n=t.bands.find((a)=>a.id===t.selectedId),i=t.regions.find((a)=>a.id===t.selectedId),s=Boolean(n?.locked??i?.locked),r=e.key.toLowerCase();if(r==="a")e.preventDefault(),this.cb.onQuickApprove([t.selectedId],!0);else if(r==="r")e.preventDefault(),this.cb.onQuickApprove([t.selectedId],!1);else if(r==="l")e.preventDefault(),this.cb.onCommitFields(t.selectedId,{locked:!s});else if(r==="w"&&n&&!s){e.preventDefault();let a=e.shiftKey?-0.25:0.25,o=Math.round(Math.max(0.15,Math.min(25,(n.width??1.5)+a))*100)/100;this.cb.onCommitFields(t.selectedId,{width:o})}else if((e.key==="Delete"||e.key==="Backspace")&&!s&&this.selectedVertex?.id===t.selectedId){e.preventDefault();let a=Boolean(i),o=this.getItemPts(t.selectedId,a),c=an(o,this.selectedVertex.idx,a);if(c)this.selectedVertex=null,this.cb.onCommitFields(t.selectedId,{[a?"outline":"path"]:c})}}scheduleDraw(){if(this.rafPending)return;this.rafPending=requestAnimationFrame(()=>{this.rafPending=0,this.drawAll()})}drawAll(){let e=this.state;if(!e)return;let t=Math.max(0.45,Math.min(1.25,Math.abs(this.effectiveBbox(e.board)[3]-this.effectiveBbox(e.board)[1])/Math.max(1,Math.abs(this.effectiveBbox(e.board)[2]-this.effectiveBbox(e.board)[0]))));for(let n of this.cards.values()){let i=n.canvas.parentElement;if(!i)continue;let s=Math.max(120,Math.round(i.clientWidth)),r=Math.max(165,Math.min(250,Math.round(s*t)));n.canvas.style.height=`${r}px`;let a=Math.max(1,window.devicePixelRatio||1),o=Math.round(s*a),c=Math.round(r*a);if(n.canvas.width!==o||n.canvas.height!==c)n.canvas.width=o,n.canvas.height=c;n.ctx.setTransform(a,0,0,a,0,0),this.drawLayer(n.ctx,n.layer,s,r,e)}}drawLayer(e,t,n,i,s){let r=this.getCam(t,n,i),a=(m,h)=>Ve(r,m,h,n,i);e.fillStyle=wi,e.fillRect(0,0,n,i);let o=(s.board.outline??[]).filter((m)=>m.length>=3);if(e.fillStyle=Ls,o.length>0){e.beginPath();for(let m of o){for(let h=0;hm.layer===t),u=this.hover?.layer===t?this.hover.hit:null;for(let m of c){let h=m.outline??[];if(h.length<3)continue;let f=s.selectedId===m.id,w=u?.id===m.id,C=Bs(m.state||"proposed",f,w),A=Et(m.net||m.id,m.color||"");e.beginPath();for(let P=0;PB)B=H;if(ae>R)R=ae}if(Math.abs(B-P)>=38&&Math.abs(R-T)>=18){let O=bi(h,m.holes??[]);if(O){let[H,ae]=a(O[0],O[1]);e.fillStyle=st(A,f?0.91:0.67),e.font="bold 10px ui-monospace, 'SFMono-Regular', Menlo, monospace",e.textAlign="center",e.textBaseline="middle",e.fillText(M,H,ae)}}}}if(e.strokeStyle=Ss,e.lineWidth=1.25,e.lineCap="round",e.lineJoin="round",o.length>0){e.beginPath();for(let m of o){for(let h=0;hm.layer===t),d=gi(p,r,n,i,s.selectedId,u?.id??""),g=d.map((m)=>[m.cx-m.pw*0.5-1,m.cy-m.ph*0.5-1,m.cx+m.pw*0.5+1,m.cy+m.ph*0.5+1]),y=[];for(let m of p){for(let h of m.from??[])y.push(h);for(let h of m.to??[])y.push(h)}e.fillStyle="rgba(143, 163, 155, 0.72)",e.font="9.5px ui-monospace, 'SFMono-Regular', Menlo, monospace",e.textAlign="center",e.textBaseline="middle";for(let m of fi(l,r,n,i,y,g))e.fillText(m.text,m.cx,m.cy);for(let m of p){let h=m.guides??[];if(h.length===0)continue;let f=s.selectedId===m.id||u?.id===m.id,w=lt(m.name||m.id,m.color||"");e.strokeStyle=st(w,f?0.38:0.17),e.lineWidth=f?1:0.7,e.beginPath();for(let C of h){let[A,M]=a(C[0],C[1]),[P,T]=a(C[2],C[3]);e.moveTo(A,M),e.lineTo(P,T)}e.stroke()}for(let m of p){let h=m.path??[];if(h.length<2)continue;let f=s.selectedId===m.id,w=u?.id===m.id,C=Ts(m.state||"proposed",f,w),A=lt(m.name||m.id,m.color||""),M=on(m.width??1.5,r.scale),P=()=>{e.beginPath();for(let T=0;T{let w=f?h.length:Math.max(0,h.length-1);for(let C=0;Cn.id===e))return;if(this.openPanel!==e)this.togglePanel(e)}getTabs(){return Rt(this.getStateInfo())}isOpen(){return this.openPanel!==""}closePanel(){if(!this.openPanel)return;if(this.openPanel="",this.project)this.cb.hub.rpc("mgmt.panel",{project:this.project,open:""}).catch(()=>{});this.render()}clear(){this.watchGen++,this.bomEditGen++,this.askedProject="",this.digest="",this.project="",this.openPanel="",this.errorMsg="",this.bomEditingId="",this.bomLastUndo=null,this.bomEditStatus="",this.checksStatus="",this.planStatus="",this.planSelectedId="",this.planStackupOpen=!1,this.planShownLayers=[],this.planOptimistic.clear(),this.planOptimisticRev=void 0,this.planHydratedKey="",this.planHydrateAskedKey="",this.planHydrateGen++,this.planHydratedRev=void 0,this.planRenderDeferred=!1,this.planHydratedBoard=null,this.planHydratedDraw=null,this.planNoteOpen=!1,this.planMoveLayerOpen=!1,this.planCanvas?.destroy(),this.planCanvas=null,this.planCommitFields=null,this.fabStatus="",this.render()}async watchProject(e){if(!e||!this.cb.hub.hasFeature("mgmt")){this.clear();return}if(e===this.askedProject&&this.digest){this.render();return}let t=++this.watchGen;if(this.askedProject=e,this.project!==e)this.bomEditGen++,this.digest="",this.project="",this.openPanel="",this.errorMsg="",this.bomSelectedId="",this.bomEditingId="",this.bomEditStatus="",this.bomLastUndo=null,this.checksSelectedId="",this.checksStatus="",this.planStatus="",this.planSelectedId="",this.planStackupOpen=!1,this.planShownLayers=[],this.planOptimistic.clear(),this.planOptimisticRev=void 0,this.planHydratedKey="",this.planHydrateAskedKey="",this.planHydrateGen++,this.planHydratedRev=void 0,this.planRenderDeferred=!1,this.planHydratedBoard=null,this.planHydratedDraw=null,this.planNoteOpen=!1,this.planMoveLayerOpen=!1,this.planCanvas?.destroy(),this.planCanvas=null,this.planCommitFields=null,this.fabStatus="",this.lifeSelectedKey="",this.lifePartSamples=null,this.render();try{let n=await this.cb.hub.rpc("mgmt.watch",{project:e});if(t!==this.watchGen)return;let i=typeof n.digest==="string"?n.digest:"";if(!i){this.render();return}if(this.digest=i,this.project=typeof n.project==="string"&&n.project?n.project:e,n.state&&typeof n.state==="object")this.infos.set(`mgmt.state.${i}`,n.state);if(n.data&&typeof n.data==="object"){for(let[s,r]of Object.entries(n.data))if(r&&typeof r==="object")this.infos.set(`mgmt.${s}.${i}`,r)}this.errorMsg="",this.render()}catch{if(t===this.watchGen)this.render()}}handleInfo(e){let t=!1;for(let[n,i]of Object.entries(e)){if(!n.startsWith("mgmt.")&&!n.startsWith("kicad.checks."))continue;if(i===""||i===null||i===void 0){if(this.infos.delete(n))t=!0;continue}if(typeof i==="string")try{let s=JSON.parse(i);if(s&&typeof s==="object")this.infos.set(n,s),t=!0}catch{}else if(typeof i==="object")this.infos.set(n,i),t=!0}if(t)this.render()}getStateInfo(){if(!this.digest)return null;return this.infos.get(`mgmt.state.${this.digest}`)??null}getPanelData(e){if(!this.digest)return null;return this.infos.get(`mgmt.${e}.${this.digest}`)??null}togglePanel(e){let t=this.openPanel===e?"":e;if(this.openPanel=t,this.errorMsg="",this.render(),this.project)this.cb.hub.rpc("mgmt.panel",{project:this.project,open:t}).catch((n)=>{this.errorMsg=n instanceof Error?n.message:"Could not update panel",this.render()})}render(){if(this.openPanel==="plan"&&this.planCanvas?.isDragging()){this.planRenderDeferred=!0;return}this.planRenderDeferred=!1;let e=this.getStateInfo(),t=Rt(e);if(!this.digest||t.length===0){this.planCanvas?.destroy(),this.planCanvas=null,this.panelEl.classList.remove("bp-plan-expanded"),this.stripEl.classList.add("bp-hidden"),this.panelEl.classList.add("bp-hidden"),this.panelEl.removeAttribute("data-testid"),this.panelEl.replaceChildren(),this.stripEl.replaceChildren(),this.cb.onOpenChange?.(!1);return}this.stripEl.classList.remove("bp-hidden");let n=document.createDocumentFragment(),i=document.createElement("div");i.className="bp-mgmt-tabs";for(let a of t){let o=document.createElement("button");o.type="button";let c=this.openPanel===a.id;o.className="bp-mgmt-tab"+(c?" active":""),o.setAttribute("data-testid",`mgmt-tab-${a.id}`),o.setAttribute("aria-pressed",c?"true":"false");let u=document.createElement("span");u.textContent=pe(a.label),o.appendChild(u);let l=this.getPanelData(a.id),p=Xn(l);if(p){let d=document.createElement("span");d.className=`bp-mgmt-badge bp-tone-${p.tone}`,d.textContent=p.text,o.appendChild(d)}o.addEventListener("click",()=>this.togglePanel(a.id)),i.appendChild(o)}if(n.appendChild(i),this.openPanel){let a=document.createElement("button");a.type="button",a.className="icon bp-mgmt-close",a.textContent="×",a.title=b("gpui.mgmt.close","Close the panel"),a.setAttribute("aria-label",b("gpui.mgmt.close","Close the panel")),a.setAttribute("data-testid","mgmt-close"),a.addEventListener("click",()=>this.closePanel()),n.appendChild(a)}if(this.stripEl.replaceChildren(n),!this.openPanel){this.planCanvas?.destroy(),this.planCanvas=null,this.panelEl.classList.remove("bp-plan-expanded"),this.panelEl.classList.add("bp-hidden"),this.panelEl.removeAttribute("data-testid"),this.panelEl.replaceChildren(),this.cb.onOpenChange?.(!1);return}if(this.openPanel!=="plan")this.planCanvas?.destroy(),this.planCanvas=null,this.panelEl.classList.remove("bp-plan-expanded");else this.panelEl.classList.toggle("bp-plan-expanded",this.planExpanded);this.panelEl.classList.remove("bp-hidden"),this.panelEl.setAttribute("data-testid",`mgmt-panel-${this.openPanel}`),this.cb.onOpenChange?.(!0);let s=this.openPanel==="plan"&&this.planCanvas!==null&&document.activeElement instanceof HTMLElement&&this.panelEl.contains(document.activeElement)&&(document.activeElement===this.planCanvas.root||this.planCanvas.root.contains(document.activeElement)),r=document.createDocumentFragment();if(this.errorMsg){let a=document.createElement("div");a.className="bp-mgmt-note bp-tone-bad",a.textContent=this.errorMsg,r.appendChild(a)}switch(this.openPanel){case"bom":r.appendChild(this.renderBom());break;case"checks":r.appendChild(this.renderChecks());break;case"life":r.appendChild(this.renderLife());break;case"plan":r.appendChild(this.renderPlan());break;case"fab":r.appendChild(this.renderFab());break}if(this.panelEl.replaceChildren(r),s)this.planCanvas?.root.focus({preventScroll:!0})}renderBom(){let e=document.createElement("div");e.className="bp-mgmt-body";let t=this.getPanelData("bom");if(!t)return e.appendChild(this.makeEmpty("Reading the schematic…")),e;let n=Array.isArray(t.lines)?t.lines:[],i=document.createElement("div");i.className="bp-mgmt-head";let s=document.createElement("span");s.className="bp-dim",s.textContent=`${t.parts??0} parts · ${n.length} lines`;let r=document.createElement("span"),a=t.source==="kicad";if(r.className="bp-mgmt-pill"+(a?" accent":""),r.textContent=a?"live":"saved",i.append(s,r),(t.priced??0)>0&&(t.checking??0)===0&&typeof t.cost==="number"){let u=document.createElement("span");u.className="bp-dim",u.textContent=(t.priced??0)<(t.lookups??0)?`≥ ${ot(t.cost)}/board`:`${ot(t.cost)}/board`,i.appendChild(u)}if(t.paused){let u=document.createElement("span");u.className="bp-mgmt-faint",u.textContent="Stock check paused",i.appendChild(u)}if(e.appendChild(i),t.stock_note){let u=document.createElement("div");u.className="bp-mgmt-note bp-mgmt-faint",u.textContent=pe(t.stock_note),e.appendChild(u)}let o=this.bomEditingId?n.find((u)=>u.id===this.bomEditingId)??null:null;if(o)e.appendChild(this.renderBomEditor(o));else{let u=document.createElement("div");u.className="bp-mgmt-filter-row";let l=document.createElement("input");l.type="text",l.className="bp-mgmt-filter",l.placeholder="Filter BOM (ref, value, footprint, MPN, dnp)…",l.value=this.bomFilter,l.setAttribute("data-testid","mgmt-bom-filter"),l.addEventListener("input",()=>{this.bomFilter=l.value,this.renderBomRows(c,n)}),u.appendChild(l),e.appendChild(u)}let c=document.createElement("div");return c.className="bp-mgmt-rows",c.setAttribute("data-testid","mgmt-bom-rows"),this.renderBomRows(c,n),e.appendChild(c),e}renderBomRows(e,t){let n=ei(t,this.bomFilter);if(n.length===0){e.replaceChildren(this.makeEmpty(t.length===0?"No parts found.":"No matching lines."));return}let i=t.some((r)=>Boolean(r.mpn)||Boolean(r.fab)),s=document.createDocumentFragment();for(let r of n){let a=Array.isArray(r.refs)?r.refs:[],o=document.createElement("div");o.className="bp-mgmt-row"+(this.bomSelectedId===r.id?" active":"")+(r.dnp?" faint":""),o.setAttribute("data-testid",`mgmt-bom-row-${r.id}`);let c=document.createElement("div");c.className="bp-mgmt-row-line";let u=document.createElement("span");if(u.className="bp-mgmt-strong bp-mgmt-flex1",u.textContent=jt(a,24),c.appendChild(u),r.dnp){let m=document.createElement("span");m.className="bp-mgmt-pill",m.textContent=b("gpui.mgmt.bom.dnp","DNP"),c.appendChild(m)}else{let m=Qn(r.stock);if(m){let h=document.createElement("span");h.className=`bp-tone-${m.tone}`,h.textContent=m.text,c.appendChild(h)}}let l=document.createElement("button");l.type="button",l.className="bp-mgmt-btn",l.textContent="Edit",l.addEventListener("click",(m)=>{m.stopPropagation(),this.bomEditGen++,this.bomEditingId=r.id,this.bomEditDraft=r.mpn??"",this.bomEditStatus="",this.bomLastUndo=null,this.render()}),c.appendChild(l);let p=document.createElement("div");p.className="bp-mgmt-row-sub";let d=[`${r.qty??a.length}×`,r.value??"",Zn(r.footprint??"")].filter(Boolean).join(" · "),g=document.createElement("span");g.className="bp-dim",g.textContent=d;let y=document.createElement("span");if(y.className="bp-mgmt-flex1",r.mpn)y.textContent=r.mpn;else if(i&&!r.dnp)y.className+=" bp-tone-warn",y.textContent=b("gpui.mgmt.bom.nompn","no MPN");if(p.append(g,y),!r.dnp&&typeof r.stock?.price==="number"){let m=document.createElement("span");m.className="bp-dim",m.textContent=ot(r.stock.price),p.appendChild(m)}if(!r.dnp&&r.stock?.class){let m=document.createElement("span");m.className="bp-mgmt-faint",m.textContent=pe(r.stock.class),p.appendChild(m)}o.append(c,p),o.addEventListener("click",()=>{this.bomSelectedId=r.id,this.renderBomRows(e,t)}),s.appendChild(o)}e.replaceChildren(s)}renderBomEditor(e){let t=document.createElement("div");t.className="bp-mgmt-editor",t.setAttribute("data-testid","mgmt-bom-edit");let n=Array.isArray(e.refs)?e.refs:[],i=document.createElement("div");i.className="bp-mgmt-row-line";let s=document.createElement("span");s.className="bp-mgmt-strong",s.textContent=jt(n,30);let r=document.createElement("button");r.type="button",r.className="icon",r.textContent="×",r.addEventListener("click",()=>{this.bomEditGen++,this.bomEditingId="",this.bomLastUndo=null,this.bomEditStatus="",this.render()}),i.append(s,r);let a=document.createElement("input");a.type="text",a.className="bp-mgmt-filter",a.placeholder="MPN",a.value=this.bomEditDraft,a.addEventListener("input",()=>{this.bomEditDraft=a.value});let o=()=>({watchGen:this.watchGen,editGen:this.bomEditGen,project:this.project,editId:this.bomEditingId}),c=async(d,g=!1)=>{let y=o();this.bomEditStatus="Writing…",this.render();try{let m=await this.cb.hub.rpc("mgmt.bom.edit",d);if(!sn(y,o()))return;this.bomLastUndo=!g&&(m.changed??0)>0?{project:d.project,editId:y.editId,refs:d.refs.slice(),field:d.field,was:typeof m.was==="string"?m.was:d.field==="mpn"?e.mpn??"":e.dnp?"yes":"no"}:null,this.bomEditStatus=g?"Restored":(m.changed??0)===0?"No change":m.via==="kicad"?"Updated in KiCad":"Saved to schematic"}catch(m){if(!sn(y,o()))return;this.bomEditStatus=m instanceof Error?m.message:"Could not save edit"}this.render()},u=document.createElement("div");u.className="bp-mgmt-btn-row";let l=document.createElement("button");l.type="button",l.className="primary bp-mgmt-btn",l.textContent="Save MPN",l.addEventListener("click",()=>{c({project:this.project,refs:n.slice(),field:"mpn",value:this.bomEditDraft.trim()})});let p=document.createElement("button");if(p.type="button",p.className="bp-mgmt-btn",p.textContent=e.dnp?"Clear DNP":"Mark DNP",p.addEventListener("click",()=>{c({project:this.project,refs:n.slice(),field:"dnp",value:e.dnp?"no":"yes"})}),u.append(l,p),this.bomLastUndo&&this.bomLastUndo.project===this.project&&this.bomLastUndo.editId===this.bomEditingId){let d=this.bomLastUndo,g=document.createElement("button");g.type="button",g.className="bp-mgmt-btn",g.textContent="Undo",g.addEventListener("click",()=>{c(li(d),!0)}),u.appendChild(g)}if(t.append(i,a,u),this.bomEditStatus){let d=document.createElement("div");d.className="bp-mgmt-faint",d.textContent=this.bomEditStatus,t.appendChild(d)}return t}renderChecks(){let e=document.createElement("div");e.className="bp-mgmt-body";let t=this.getPanelData("checks");if(!t)return e.appendChild(this.makeEmpty("Reading checks…")),e;let n=Array.isArray(t.groups)?t.groups:[],i=Array.from(new Set(n.map((d)=>d.source).filter(Boolean))),s=(d)=>t.sources?.[d]?.label||d.toUpperCase(),r=(d)=>t.sources?.[d]?.judged===!0,a=document.createElement("div");a.className="bp-mgmt-head bp-mgmt-scroll-x";let o=document.createElement("button");o.type="button",o.className="bp-mgmt-btn"+(this.checksSource===""?" active":""),o.textContent=b("gpui.mgmt.checks.all","All"),o.addEventListener("click",()=>{this.checksSource="",this.render()}),a.appendChild(o);for(let d of i){let g=document.createElement("button");g.type="button",g.className="bp-mgmt-btn"+(this.checksSource===d?" active":""),g.textContent=s(d)+(r(d)?" · judged":""),g.addEventListener("click",()=>{this.checksSource=this.checksSource===d?"":d,this.render()}),a.appendChild(g)}let c=document.createElement("span");c.className="bp-mgmt-flex1";let u=document.createElement("button");if(u.type="button",u.className="bp-mgmt-btn",u.textContent=b("gpui.mgmt.checks.run","Run"),u.addEventListener("click",()=>{let d=this.watchGen,g=this.project;this.checksStatus="Running checks…",this.render(),this.cb.hub.rpc("kicad.checks.run",{project:g}).then(()=>{if(d!==this.watchGen||g!==this.project)return;this.checksStatus="",this.render()}).catch((y)=>{if(d!==this.watchGen||g!==this.project)return;this.checksStatus=y instanceof Error?y.message:"Could not run checks",this.render()})}),a.append(c,u),e.appendChild(a),this.checksStatus){let d=document.createElement("div");d.className="bp-mgmt-note bp-dim",d.textContent=this.checksStatus,e.appendChild(d)}let l=document.createElement("div");l.className="bp-mgmt-rows",l.setAttribute("data-testid","mgmt-checks-rows");let p=ti(n,this.checksSource);if(p.length===0)l.appendChild(this.makeEmpty("No check findings."));else for(let d of p){let g=d.severity==="error"?"bad":d.severity==="warning"?"warn":"faint",y=document.createElement("div");y.className="bp-mgmt-group-head";let m=document.createElement("span");m.className=`bp-mgmt-dot bp-tone-bg-${g}`;let h=document.createElement("span");h.className="bp-mgmt-flex1",h.textContent=`${s(d.source)} · ${d.rule}`;let f=document.createElement("span");f.className=`bp-tone-${g}`,f.textContent=String(d.n),y.append(m,h,f),l.appendChild(y);for(let w of d.rows??[]){let C=document.createElement("div");C.className="bp-mgmt-row"+(this.checksSelectedId===w.id?" active":"");let A=document.createElement("div");if(A.textContent=pe(w.title??""),C.appendChild(A),w.names||this.checksSelectedId===w.id){let M=document.createElement("div");M.className="bp-mgmt-row-sub";let P=document.createElement("span");if(P.className="bp-dim bp-mgmt-flex1",P.textContent=w.names??"",M.appendChild(P),this.checksSelectedId===w.id){let T=document.createElement("button");T.type="button",T.className="bp-mgmt-btn accent",T.textContent=b("gpui.mgmt.checks.fix","Fix with agent"),T.addEventListener("click",(B)=>{B.stopPropagation();let R={watchGen:this.watchGen,project:this.project,threadId:this.cb.getThreadId(),threadGen:this.cb.getThreadGen()};this.cb.hub.rpc("kicad.checks.fix",{project:R.project,id:w.id}).then((O)=>{let H={watchGen:this.watchGen,project:this.project,threadId:this.cb.getThreadId(),threadGen:this.cb.getThreadGen()};if(!rn(R,H))return;if(O.text)this.cb.onSendText(O.text),this.checksStatus="Sent to agent",this.render()}).catch((O)=>{let H={watchGen:this.watchGen,project:this.project,threadId:this.cb.getThreadId(),threadGen:this.cb.getThreadGen()};if(!rn(R,H))return;this.checksStatus=O instanceof Error?O.message:"Could not send finding",this.render()})}),M.appendChild(T)}C.appendChild(M)}C.addEventListener("click",()=>{this.checksSelectedId=w.id,this.cb.hub.rpc("kicad.checks.focus",{project:this.project,id:w.id}).catch(()=>{}),this.render()}),l.appendChild(C)}}return e.appendChild(l),e}renderLife(){let e=document.createElement("div");e.className="bp-mgmt-body";let t=this.getPanelData("life");if(!t)return e.appendChild(this.makeEmpty("Reading lifecycle…")),e;let n=document.createElement("div");n.className="bp-mgmt-head";let i=t.counts??{};for(let c of["active","nrnd","eol"]){let u=i[c]??0,l=nn(c),p=document.createElement("span");p.className=u>0?`bp-tone-${l.tone}`:"bp-mgmt-faint",p.textContent=`${l.label} ${u}`,n.appendChild(p)}if((i.unknown??0)>0){let c=document.createElement("span");c.className="bp-mgmt-faint",c.textContent=`${i.unknown} unknown`,n.appendChild(c)}if(t.since){let c=document.createElement("span");c.className="bp-mgmt-flex1";let u=document.createElement("span");u.className="bp-mgmt-faint",u.textContent=`since ${Ht(t.since)} (${t.samples??0})`,n.append(c,u)}e.appendChild(n);let s=document.createElement("div");s.className="bp-mgmt-rows",s.setAttribute("data-testid","mgmt-life-rows");let r=t.bom?.cost??[],a=t.bom?.instock??[],o=t.bom?.lines??0;if(r.length===0)s.appendChild(this.makeEmpty(o===0?"No line has an MPN or fab part number to follow yet.":"No reading of the fab's stock yet: the BOM panel's lookups start it."));else{let c=r[r.length-1],u=a[a.length-1],l=document.createElement("div");l.className="bp-mgmt-note bp-dim",l.textContent=`Parts/board: ${ot(c[1])} · ${Math.round(u?.[1]??0)}/${o} lines in stock (${Ht(c[0])})`,s.appendChild(l)}for(let c of t.parts??[]){let u=this.lifeSelectedKey===c.key,l=nn(c.lifecycle??"unknown"),p=document.createElement("div");p.className="bp-mgmt-row"+(u?" active":"");let d=document.createElement("div");d.className="bp-mgmt-row-line";let g=document.createElement("span");g.className="bp-mgmt-strong",g.textContent=jt(c.refs??[],14);let y=document.createElement("span");y.className="bp-mgmt-flex1 bp-dim",y.textContent=c.mpn||c.key;let m=document.createElement("span");if(m.className=`bp-tone-${l.tone}`,m.textContent=l.label,d.append(g,y,m),typeof c.stock==="number"){let h=document.createElement("span");h.className="bp-dim",h.textContent=at(c.stock),d.appendChild(h)}if(p.appendChild(d),u){let h=document.createElement("div");if(h.className="bp-mgmt-row-sub bp-mgmt-faint",this.lifePartLoading)h.textContent=b("gpui.mgmt.life.reading","Reading its history…");else if(this.lifePartSamples&&this.lifePartSamples.length>0){let f=this.lifePartSamples[this.lifePartSamples.length-1];h.textContent=`${this.lifePartSamples.length} samples · latest ${f.at?Ht(f.at):""}`+(typeof f.stock==="number"?` · stock ${at(f.stock)}`:"")+(typeof f.price==="number"?` · ${ot(f.price)}`:"")}else h.textContent=b("gpui.mgmt.life.nopart","No reading of this part yet.");p.appendChild(h)}p.addEventListener("click",()=>{if(this.lifeSelectedKey===c.key){this.lifeSelectedKey="",this.lifePartSamples=null,this.render();return}this.lifeSelectedKey=c.key,this.lifePartSamples=null,this.lifePartLoading=!0,this.render(),this.cb.hub.rpc("mgmt.life.part",{project:this.project,key:c.key}).then((h)=>{if(this.lifeSelectedKey!==c.key)return;this.lifePartLoading=!1,this.lifePartSamples=Array.isArray(h.samples)?h.samples:[],this.render()}).catch(()=>{if(this.lifeSelectedKey!==c.key)return;this.lifePartLoading=!1,this.lifePartSamples=[],this.render()})}),s.appendChild(p)}return e.appendChild(s),e}renderPlan(){let e=document.createElement("div");e.className="bp-mgmt-body";let t=this.getPanelData("plan");if(!t)return e.appendChild(this.makeEmpty(b("gpui.mgmt.plan.reading","Reading the routing plan…"))),e;let n=(E,k)=>{let j=this.watchGen,N=this.project;this.planStatus="",this.cb.hub.rpc(E,{pro:N,...k}).catch((K)=>{if(j!==this.watchGen||N!==this.project)return;this.planOptimistic.clear(),this.planStatus=K instanceof Error?K.message:b("gpui.mgmt.plan.refused","KiCad refused"),this.render()})};if(t.revision!==this.planOptimisticRev)this.planOptimisticRev=t.revision,this.planOptimistic.clear();let i=`${this.project}:${t.revision??0}`;if(t.board_trimmed&&this.planHydrateAskedKey!==i&&this.project){this.planHydrateAskedKey=i;let E=this.watchGen,k=++this.planHydrateGen,j=this.project,N=t.revision??0;this.cb.hub.rpc("plan.get",{pro:j,board:!0}).then((K)=>{let te=vi(K);if(!te)return;let D=typeof te.revision==="number"?te.revision:N;if(!yi(E,this.watchGen,k,this.planHydrateGen,j,this.project,D,this.planHydratedRev))return;this.planHydratedRev=D,this.planHydratedKey=`${j}:${D}`,this.planHydratedBoard=te.board??null,this.planHydratedDraw=te.draw??null,this.render()}).catch(()=>{})}let s=t.on===!0,r=document.createElement("div");r.className="bp-plan-header";let a=document.createElement("div");a.className="bp-plan-toggle";let o=document.createElement("span");o.className="bp-mgmt-strong",o.textContent=b("gpui.mgmt.plan.before","Plan before routing"),o.title=s?b("gpui.mgmt.plan.onwords","Before routing a board with 4 or more copper layers or more than 60 nets, the agent proposes corridors and plane regions here. It routes only what you approve."):b("gpui.mgmt.plan.offwords","Agents route as you ask. Turn it on to have them propose a routing plan first and route only what you approve here."),a.appendChild(o);let c=t.awaiting??0,u=t.blocked??0,l=t.done??0,p=t.total??0,d=t.revision??0,g=t.empty?[]:ri(t),y=g.reduce((E,k)=>E+k.count,0);if(!t.empty){let E=si(t),k=document.createElement("span");if(k.className=`bp-plan-status-badge tone-${E.tone}`,k.textContent=b(E.key,E.label),a.appendChild(k),d>0){let N=document.createElement("span");N.className="bp-dim",N.textContent=`v${d}`,a.appendChild(N)}let j=document.createElement("span");if(j.className="bp-plan-header-counts bp-mgmt-flex1 "+(c>0?"bp-tone-warn":u>0?"bp-tone-bad":"bp-dim"),j.textContent=p>0?`${l}/${p} ${b("gpui.mgmt.plan.done","done")}`:c>0?b("web.plan.awaiting","{n} awaiting approval",{n:c}):b("gpui.mgmt.plan.nothing","Nothing awaits your approval"),a.appendChild(j),!t.live){let N=document.createElement("span");N.className="bp-mgmt-pill",N.textContent=b("gpui.mgmt.plan.saved","saved plan"),a.appendChild(N)}}else{let E=document.createElement("span");E.className="bp-mgmt-flex1",a.appendChild(E)}let m=document.createElement("button");m.type="button",m.className="bp-mgmt-btn bp-plan-chip-btn"+(s?" active":""),m.setAttribute("data-testid","mgmt-plan-on"),m.setAttribute("aria-pressed",s?"true":"false"),m.textContent=b("gpui.bots.recall.on","On"),m.addEventListener("click",()=>n("plan.enable",{on:!0}));let h=document.createElement("button");if(h.type="button",h.className="bp-mgmt-btn bp-plan-chip-btn"+(!s?" active":""),h.setAttribute("data-testid","mgmt-plan-off"),h.setAttribute("aria-pressed",!s?"true":"false"),h.textContent=b("gpui.bots.recall.off","Off"),h.addEventListener("click",()=>n("plan.enable",{on:!1})),a.append(m,h),r.appendChild(a),y>0){let E=document.createElement("div");E.className="bp-plan-segbar";for(let k of g){if(k.count<=0)continue;let j=document.createElement("div");j.className=`bp-plan-seg bp-tone-bg-${k.tone}`,j.style.flexGrow=String(k.count),E.appendChild(j)}r.appendChild(E)}e.appendChild(r);for(let E of t.elsewhere??[]){let k=document.createElement("div");k.className="bp-plan-elsewhere";let j=document.createElement("span");j.className="bp-tone-warn bp-mgmt-flex1",j.textContent=b("gpui.mgmt.plan.elsewhere","A routing plan for {board} awaits your approval",{board:E.name||E.rel||""}),k.appendChild(j),e.appendChild(k)}if(t.empty){let E=document.createElement("div");E.className="bp-mgmt-note";let k=document.createElement("div");k.className="bp-dim",k.textContent=b("gpui.mgmt.plan.noboard","No routing plan for this board.");let j=document.createElement("div");return j.className="bp-mgmt-faint",j.textContent=b("gpui.mgmt.plan.emptysub","Layers, corridors, and planes appear here once a plan is proposed."),E.append(k,j),e.appendChild(E),e}let f=t.stackup_summary??"",w=Array.isArray(t.impedances)?t.impedances:[],C=Boolean(f)||w.length>0,A=document.createElement("div");if(A.className="bp-mgmt-head",c>0){let E=document.createElement("button");E.type="button",E.className="primary bp-mgmt-btn",E.setAttribute("data-testid","mgmt-plan-approve-all"),E.textContent=b("gpui.mgmt.plan.all","Approve all"),E.addEventListener("click",()=>n("plan.approve",{layer:"",ids:[],approve:!0})),A.appendChild(E)}if(t.routing){let E=document.createElement("button");E.type="button",E.className="bp-mgmt-btn",E.setAttribute("data-testid","mgmt-plan-stop"),E.textContent=b("gpui.mgmt.plan.stop","Stop routing"),E.addEventListener("click",()=>n("plan.stop",{})),A.appendChild(E)}if(t.live&&l>0){let E=document.createElement("button");E.type="button",E.className="bp-mgmt-btn",E.setAttribute("data-testid","mgmt-plan-verify"),E.textContent=b("gpui.mgmt.plan.verify","Verify"),E.addEventListener("click",()=>n("plan.verify",{})),A.appendChild(E)}let M=document.createElement("span");if(M.className="bp-mgmt-flex1",A.appendChild(M),C){let E=document.createElement("button");E.type="button",E.className="bp-mgmt-btn bp-plan-chip-btn"+(this.planStackupOpen?" active":""),E.setAttribute("data-testid","mgmt-plan-stackup-toggle"),E.setAttribute("aria-expanded",this.planStackupOpen?"true":"false"),E.textContent=`${b("gpui.mgmt.plan.stackup.short","Stackup")} ${this.planStackupOpen?"▾":"▸"}`,E.addEventListener("click",()=>{this.planStackupOpen=!this.planStackupOpen,this.render()}),A.appendChild(E)}let P=document.createElement("button");P.type="button",P.className="bp-mgmt-btn",P.setAttribute("data-testid","mgmt-plan-hide"),P.textContent=this.planHideDone?b("gpui.mgmt.plan.show","Show done"):b("gpui.mgmt.plan.hide","Hide done"),P.addEventListener("click",()=>{this.planHideDone=!this.planHideDone,this.render()}),A.appendChild(P),e.appendChild(A);let T=Array.isArray(t.asks)?t.asks:[];if(T.length>0){let E=T.map((te)=>te.what||"").filter(Boolean).join(", "),k=T[0]?.note||"",j=document.createElement("div");j.className="bp-plan-elsewhere";let N=document.createElement("div");N.className="bp-plan-ask-col";let K=document.createElement("div");if(K.className="bp-tone-warn",K.textContent=E?b("gpui.mgmt.plan.requested","Approval requested: {what}",{what:E}):b("gpui.mgmt.plan.reqplain","Approval requested"),N.appendChild(K),k){let te=document.createElement("div");te.className="bp-dim",te.textContent=k,N.appendChild(te)}j.appendChild(N),e.appendChild(j)}if(this.planStatus){let E=document.createElement("div");E.className="bp-mgmt-note bp-plan-err bp-tone-bad";let k=document.createElement("span");k.className="bp-mgmt-flex1",k.textContent=this.planStatus==="KiCad refused"?b("gpui.mgmt.plan.refused","KiCad refused"):pe(this.planStatus);let j=document.createElement("button");j.type="button",j.className="icon",j.textContent="×",j.title=b("common.close","Close"),j.addEventListener("click",()=>{this.planStatus="",this.render()}),E.append(k,j),e.appendChild(E)}if(t.keys_note){let E=document.createElement("div");E.className="bp-mgmt-note bp-dim";let k="On this KiCad version, approve from this panel: in plan view KiCad's A, R and W keys aren't the plan's yet (A opens Add Footprint). Update KiCad.";E.textContent=t.keys_note===k?b("gpui.mgmt.plan.keysnote",k):pe(t.keys_note),e.appendChild(E)}if(C&&this.planStackupOpen){let E=document.createElement("div");if(E.className="bp-plan-stackup-body",E.setAttribute("data-testid","mgmt-plan-stackup-body"),f){let k=document.createElement("div");k.className="bp-dim",k.textContent=f,E.appendChild(k)}for(let k of w){let j=document.createElement("div");j.className="bp-mgmt-faint",j.textContent=`· ${k}`,E.appendChild(j)}e.appendChild(E)}let B=(E,k,j,N)=>{let K=document.createElement("button");return K.type="button",K.className="bp-mgmt-btn bp-plan-chip-btn"+(k?" active":""),K.setAttribute("data-testid",j),K.setAttribute("aria-pressed",k?"true":"false"),K.textContent=E,K.addEventListener("click",N),K},R=document.createElement("div");if(R.className="bp-plan-viewbar",R.append(B(b("gpui.mgmt.plan.view.canvas","Canvas"),this.planViewMode==="canvas","mgmt-plan-view-canvas",()=>{this.planViewMode="canvas",this.render()}),B(b("gpui.mgmt.plan.view.split","Split"),this.planViewMode==="split","mgmt-plan-view-split",()=>{this.planViewMode="split",this.render()}),B(b("gpui.mgmt.plan.view.list","List"),this.planViewMode==="list","mgmt-plan-view-list",()=>{this.planViewMode="list",this.render()})),this.planViewMode!=="list"){let E=document.createElement("span");E.className="bp-plan-sep";let k=document.createElement("span");k.className="bp-plan-sep";let j=document.createElement("button");j.type="button",j.className="bp-mgmt-btn bp-plan-mini-btn",j.setAttribute("data-testid","mgmt-plan-fit"),j.textContent=b("gpui.mgmt.plan.fit","Fit"),j.addEventListener("click",()=>this.planCanvas?.fitAll()),R.append(E,B(b("gpui.mgmt.plan.grid.pair","Side by side"),this.planGridMode==="pair","mgmt-plan-grid-pair",()=>{this.planGridMode="pair",this.render()}),B(b("gpui.mgmt.plan.grid.all","All layers"),this.planGridMode==="all","mgmt-plan-grid-all",()=>{this.planGridMode="all",this.render()}),B(b("gpui.mgmt.plan.grid.single","Single"),this.planGridMode==="single","mgmt-plan-grid-single",()=>{this.planGridMode="single",this.render()}),k,B(b("gpui.mgmt.plan.sync","Link zoom"),this.planSyncZoom,"mgmt-plan-sync",()=>{this.planSyncZoom=!this.planSyncZoom,this.render()}),j)}let O=document.createElement("span");O.className="bp-mgmt-flex1";let H=document.createElement("button");H.type="button",H.className="bp-mgmt-btn bp-plan-mini-btn",H.setAttribute("data-testid","mgmt-plan-expand"),H.textContent=this.planExpanded?b("gpui.mgmt.plan.compact","Compact"):b("gpui.mgmt.plan.expand","Expand"),H.addEventListener("click",()=>{this.planExpanded=!this.planExpanded,this.render()}),R.append(O,H),e.appendChild(R);let ae=Boolean(this.planHydratedBoard)&&this.planHydratedKey.startsWith(`${this.project}:`)&&(this.planHydratedKey===i||this.planHydratedRev!==void 0&&this.planHydratedRev>=(t.revision??0)),ue=ae&&this.planHydratedBoard?this.planHydratedBoard:t.board??{bbox:[0,0,100,70],outline:[],parts:[]},oe=ae&&this.planHydratedDraw?this.planHydratedDraw:t.draw??{bands:[],regions:[]},we=(oe.bands??[]).map((E)=>{let k=this.planOptimistic.get(E.id);if(!k)return{...E};return{...E,...k,edited:!0,state:E.state==="proposed"?"edited":E.state}}),Le=(oe.regions??[]).map((E)=>{let k=this.planOptimistic.get(E.id);if(!k)return{...E};return{...E,...k,edited:!0,state:E.state==="proposed"?"edited":E.state}}),Ne=[],he=(t.layers??[]).map((E)=>{let k=[];for(let j of E.items??[]){let N=this.planOptimistic.get(j.id);if(!N){k.push(j);continue}let K={...j,width:typeof N.width==="number"?N.width:j.width,locked:typeof N.locked==="boolean"?N.locked:j.locked,edited:!0,state:j.state==="proposed"?"edited":j.state};if(typeof N.layer==="string"&&N.layer!==E.layer)Ne.push({target:N.layer,item:K});else k.push(K)}return{...E,items:k}});for(let E of Ne){let k=he.find((j)=>j.layer===E.target);if(k)k.items=[...k.items??[],E.item]}let be=$t(he,t.copper_layers),I=this.planGridMode==="all"?be.map((E)=>E.layer):this.planGridMode==="single"?[this.planShownLayers.find((E)=>be.some((k)=>k.layer===E))??ct(be)[0]??be[0]?.layer??""].filter(Boolean):this.planShownLayers.length>0&&this.planShownLayers.every((E)=>be.some((k)=>k.layer===E))?this.planShownLayers.slice(0,2):ct(be);if(this.planViewMode!=="list"&&this.planGridMode!=="all"&&be.length>1){let E=document.createElement("div");E.className="bp-plan-layerbar";for(let k of be){let j=I.includes(k.layer),N=(k.items??[]).length,K=it(k.layer,t.copper_layers,be)||k.title||k.layer,te=N>0?`${K} · ${N}`:K,D=B(te,j,`mgmt-plan-layerpill-${k.layer}`,()=>{if(this.planGridMode==="single")this.planShownLayers=[k.layer];else if(this.planGridMode==="pair"){if(!I.includes(k.layer))this.planShownLayers=I.length>=2?[I[0],k.layer]:[...I,k.layer]}else this.planGridMode="single",this.planShownLayers=[k.layer];this.render()});if(N===0&&!j)D.classList.add("empty-layer");E.appendChild(D)}e.appendChild(E)}let le=(E,k)=>{let j=this.planOptimistic.get(E)??{};if(this.planOptimistic.set(E,{...j,...k}),typeof k.layer==="string"){if(this.planGridMode==="single")this.planShownLayers=[k.layer];else if(this.planGridMode==="pair"&&!I.includes(k.layer))this.planShownLayers=I.length>=2?[I[0],k.layer]:[...I,k.layer]}let N=typeof t.revision==="number"?t.revision:void 0;this.render(),n("plan.update",{ops:[{op:"set",id:E,fields:k}],...N!==void 0?{base:N}:{}})};if(this.planCommitFields=le,this.planSelectedId){let E="",k=null;for(let j of he){let N=(j.items??[]).find((K)=>K.id===this.planSelectedId);if(N){E=j.layer,k=N;break}}if(k){let j=it(E,t.copper_layers,be),N=document.createElement("div");N.className="bp-plan-inspector",N.setAttribute("data-testid","mgmt-plan-inspector");let K=document.createElement("div");K.className="bp-plan-ins-row";let te=document.createElement("span");te.className="bp-plan-ins-sw",te.style.background=k.kind==="corridor"?lt(k.name||k.id,k.color||""):Et(k.name||k.id,k.color||"");let D=document.createElement("span");D.className="bp-mgmt-strong",D.textContent=k.name||k.id;let z=document.createElement("span");if(z.className="bp-dim",z.textContent=j,K.append(te,D,z),k.edited||k.state==="edited"){let Y=document.createElement("span");Y.className="bp-plan-ins-pill warn",Y.textContent=b("gpui.mgmt.plan.edited","Edited"),K.appendChild(Y)}if(k.locked){let Y=document.createElement("span");Y.className="bp-plan-ins-pill",Y.textContent=b("gpui.mgmt.plan.locked","Locked"),K.appendChild(Y)}let je=document.createElement("span");je.className="bp-mgmt-flex1",K.appendChild(je);let Se=document.createElement("button");if(Se.type="button",Se.className="bp-mgmt-btn bp-plan-mini-btn",Se.setAttribute("data-testid","mgmt-plan-lock"),Se.textContent=k.locked?b("gpui.mgmt.plan.unlock","Unlock"):b("gpui.mgmt.plan.lock","Lock"),Se.addEventListener("click",()=>le(k.id,{locked:!k.locked})),K.appendChild(Se),k.state==="proposed"||k.state==="edited"){let Y=document.createElement("button");Y.type="button",Y.className="primary bp-mgmt-btn bp-plan-mini-btn",Y.textContent=b("android.hub.machines.approve","Approve"),Y.addEventListener("click",()=>n("plan.approve",{layer:"",ids:[k.id],approve:!0}));let ve=document.createElement("button");ve.type="button",ve.className="bp-mgmt-btn bp-plan-mini-btn",ve.textContent=b("gpui.mgmt.plan.reject","Reject"),ve.addEventListener("click",()=>n("plan.approve",{layer:"",ids:[k.id],approve:!1})),K.append(Y,ve)}let me=document.createElement("button");me.type="button",me.className="bp-mgmt-btn bp-plan-mini-btn",me.setAttribute("data-testid","mgmt-plan-note-toggle"),me.textContent=b("gpui.mgmt.plan.addnote","Add note"),me.addEventListener("click",()=>{this.planNoteOpen=!this.planNoteOpen,this.render()});let Me=document.createElement("button");if(Me.type="button",Me.className="icon",Me.textContent="×",Me.addEventListener("click",()=>{this.planSelectedId="",this.planNoteOpen=!1,this.planMoveLayerOpen=!1,this.render()}),K.append(me,Me),N.appendChild(K),!k.locked){let Y=document.createElement("div");if(Y.className="bp-plan-ins-row",k.kind==="corridor"){let ie=typeof k.width==="number"?k.width:1.5,ke=document.createElement("span");ke.className="bp-dim",ke.textContent=b("gpui.mgmt.plan.width","Width");let He=document.createElement("button");He.type="button",He.className="bp-mgmt-btn bp-plan-mini-btn",He.setAttribute("data-testid","mgmt-plan-w-down"),He.textContent="-",He.addEventListener("click",()=>{let Ue=Math.round(Math.max(0.15,ie-0.25)*100)/100;le(k.id,{width:Ue})});let re=document.createElement("span");re.className="bp-plan-ins-val",re.textContent=`${ie.toFixed(2)}mm`;let ge=document.createElement("button");ge.type="button",ge.className="bp-mgmt-btn bp-plan-mini-btn",ge.setAttribute("data-testid","mgmt-plan-w-up"),ge.textContent="+",ge.addEventListener("click",()=>{let Ue=Math.round(Math.min(25,ie+0.25)*100)/100;le(k.id,{width:Ue})});let _e=document.createElement("span");_e.className="bp-plan-sep",Y.append(ke,He,re,ge,_e)}let ve=(t.copper_layers??[]).length>0?(t.copper_layers??[]).map((ie)=>ie.layer):he.map((ie)=>ie.layer);if(ve.length>0){let ie=document.createElement("span");ie.className="bp-dim",ie.textContent=b("gpui.mgmt.plan.layer.short","Layer"),Y.appendChild(ie),Y.appendChild(B(`${j} ${this.planMoveLayerOpen?"▴":"▾"}`,this.planMoveLayerOpen,"mgmt-plan-move-toggle",()=>{this.planMoveLayerOpen=!this.planMoveLayerOpen,this.render()}))}if(N.appendChild(Y),this.planMoveLayerOpen&&ve.length>0){let ie=document.createElement("div");ie.className="bp-plan-ins-row";for(let ke of ve){let He=it(ke,t.copper_layers,be);ie.appendChild(B(He,ke===E,`mgmt-plan-move-${ke}`,()=>{if(this.planMoveLayerOpen=!1,ke!==E)le(k.id,{layer:ke});else this.render()}))}N.appendChild(ie)}}if(this.planNoteOpen){let Y=document.createElement("form");Y.className="bp-plan-note-form";let ve=document.createElement("input");ve.type="text",ve.className="bp-plan-note-input",ve.setAttribute("data-testid","mgmt-plan-note-input"),ve.placeholder=b("gpui.mgmt.plan.note.placeholder","Steering note for router…");let ie=document.createElement("button");ie.type="submit",ie.className="primary bp-mgmt-btn bp-plan-mini-btn",ie.setAttribute("data-testid","mgmt-plan-note-submit"),ie.textContent=b("gpui.mgmt.plan.addnote","Add note"),Y.append(ve,ie),Y.addEventListener("submit",(ke)=>{ke.preventDefault();let He=ve.value.trim();if(!He)return;ve.value="",this.planNoteOpen=!1;let re=typeof t.revision==="number"?t.revision:void 0;this.render(),n("plan.update",{ops:[{op:"note",target:k.id,text:He}],...re!==void 0?{base:re}:{}})}),N.appendChild(Y)}if(this.planViewMode!=="list"&&!k.locked){let Y=document.createElement("div");Y.className="bp-plan-hint",Y.textContent=b("gpui.mgmt.plan.hint","Drag waypoints to steer · Click + on edge to insert · Right-click vertex to remove"),N.appendChild(Y)}e.appendChild(N)}}let ne=document.createElement("div");ne.className="bp-mgmt-rows"+(this.planViewMode==="split"?" bp-plan-split-list":""),ne.setAttribute("data-testid","mgmt-plan-rows");let X=b("gpui.mgmt.plan.done","done"),ce=hi(this.planViewMode,he,I);if(this.planViewMode==="split"&&ce.length===0){let E=document.createElement("div");E.className="bp-dim",E.style.padding="6px 8px",E.style.fontSize="11px",E.textContent=b("gpui.mgmt.plan.noitems","No corridors or planes on this layer"),ne.appendChild(E)}for(let E of ce){let k=E.items??[],j=it(E.layer,t.copper_layers,be)||E.layer;if(this.planViewMode==="split"){if(ce.length>1){let N=document.createElement("div");N.className="bp-plan-split-divider";let K=E.role==="power"||E.role==="plane",te=document.createElement("span");te.className="bp-plan-card-bar "+(K?"pwr":"sig");let D=document.createElement("span");D.className="bp-mgmt-strong",D.textContent=j;let z=document.createElement("span");z.className="bp-dim",z.textContent=`${E.done??0}/${k.length} ${X}`,N.append(te,D,z),ne.appendChild(N)}}else{let N=document.createElement("div");N.className="bp-mgmt-group-head bp-plan-layer-head";let K=document.createElement("div");K.className="bp-mgmt-row-line";let te=document.createElement("span");te.className="bp-mgmt-strong",te.textContent=j;let D=document.createElement("span");if(D.className="bp-dim bp-mgmt-flex1",D.textContent=`${E.role?`${E.role} · `:""}${E.done??0}/${k.length} ${X}`,K.append(te,D),E.status!=="approved"&&k.length>0){let z=document.createElement("button");z.type="button",z.className="bp-mgmt-btn",z.textContent=b("gpui.mgmt.plan.layer","Approve layer"),z.addEventListener("click",()=>n("plan.approve",{layer:E.layer,ids:[],approve:!0}));let je=document.createElement("button");je.type="button",je.className="bp-mgmt-btn",je.textContent=b("gpui.mgmt.plan.reject","Reject"),je.addEventListener("click",()=>n("plan.approve",{layer:E.layer,ids:[],approve:!1})),K.append(z,je)}if(N.appendChild(K),E.stackup){let z=document.createElement("div");z.className="bp-plan-layer-stackup",z.textContent=E.stackup,N.appendChild(z)}ne.appendChild(N)}for(let N of k){if(this.planHideDone&&ni(N))continue;let K=this.planSelectedId===N.id,te=document.createElement("div");te.className="bp-mgmt-row bp-plan-row"+(K?" active":""),te.setAttribute("data-testid",`mgmt-plan-row-${N.id}`);let D=document.createElement("div");D.className="bp-mgmt-row-line";let z=document.createElement("span");z.className=`bp-plan-swatch bp-plan-st-${N.state||"proposed"}`,z.style.setProperty("--swatch-color",N.color||"#8a8a8a");let je=document.createElement("span");je.className="bp-mgmt-flex1"+(N.state==="blocked"||N.state==="failed"?" bp-tone-bad":N.state==="edited"?" bp-tone-warn":N.state==="rejected"||N.state==="routed"||N.state==="verified"?" bp-dim":""),je.textContent=`${N.name||N.id}${N.locked?" \uD83D\uDD12":""}`;let Se=[];if(N.kind==="plane"){if(N.reference)Se.push(b("gpui.mgmt.plan.reference","over {layer}",{layer:N.reference}))}else{let Y=N.nets??0;Se.push(Y===1?b("web.plan.net.one","1 net"):b("web.plan.nets","{n} nets",{n:Y}))}if(typeof N.width==="number"&&Number.isFinite(N.width))Se.push(`${N.width.toFixed(2)}mm`);if(N.impedance)Se.push(N.impedance);let me=Se.join(" · "),Me=document.createElement("span");if(Me.className="bp-plan-mark "+(N.state==="blocked"||N.state==="failed"?"bp-tone-bad":N.state==="verified"||N.state==="routed"?"bp-tone-ok":N.state==="approved"?"bp-tone-accent":"bp-dim"),Me.textContent=ii(N),D.append(z,je,Me),N.state==="proposed"||N.state==="edited"){let Y=document.createElement("button");Y.type="button",Y.className="bp-mgmt-btn",Y.textContent="✓",Y.title=b("gpui.mgmt.plan.layer","Approve layer"),Y.addEventListener("click",(ie)=>{ie.stopPropagation(),n("plan.approve",{layer:"",ids:[N.id],approve:!0})});let ve=document.createElement("button");ve.type="button",ve.className="bp-mgmt-btn",ve.textContent="✗",ve.title=b("gpui.mgmt.plan.reject","Reject"),ve.addEventListener("click",(ie)=>{ie.stopPropagation(),n("plan.approve",{layer:"",ids:[N.id],approve:!1})}),D.append(Y,ve)}if(te.appendChild(D),me){let Y=document.createElement("div");Y.className="bp-mgmt-row-sub bp-plan-detail bp-dim",Y.textContent=me,te.appendChild(Y)}if(N.state==="routing"&&typeof N.total==="number"&&N.total>0){let Y=document.createElement("div");Y.className="bp-plan-microbar";let ve=document.createElement("div");ve.className="bp-plan-microbar-fill";let ie=Math.max(0,Math.min(100,Math.round((N.routed??0)/N.total*100)));ve.style.width=`${ie}%`,Y.appendChild(ve),te.appendChild(Y)}if(N.problem_text){let Y=document.createElement("div");Y.className="bp-plan-problem",Y.textContent=N.problem_text,te.appendChild(Y)}te.addEventListener("click",()=>{this.planSelectedId=N.id,n("plan.focus",{id:N.id}),this.render()}),ne.appendChild(te)}}if(this.planViewMode!=="list"){if(!this.planCanvas)this.planCanvas=new ln({onSelect:(N)=>{if(this.planSelectedId=N,!N)this.planNoteOpen=!1;this.render()},onFocusItem:(N)=>{n("plan.focus",{id:N})},onDragEnd:()=>{if(this.planRenderDeferred)this.planRenderDeferred=!1,this.render()},onCommitFields:(N,K)=>{(this.planCommitFields??le)(N,K)},onApproveLayer:(N,K)=>{n("plan.approve",{layer:N,ids:[],approve:K})},onQuickApprove:(N,K)=>{n("plan.approve",{layer:"",ids:N,approve:K})}});let E=this.panelEl.parentElement?.classList.contains("bp-has-viewer")===!1,k=this.planExpanded||this.panelEl.clientWidth>=540||E;this.planCanvas.update({gridMode:this.planGridMode,syncZoom:this.planSyncZoom,shownLayers:I,selectedId:this.planSelectedId,board:ue,bands:we,regions:Le,layers:be,copperLayers:t.copper_layers},k);let j=document.createElement("div");j.className="bp-plan-canvas-scroll",j.appendChild(this.planCanvas.root),e.appendChild(j)}if(this.planViewMode!=="canvas")e.appendChild(ne);if((t.draw?.bands?.length??0)>0||(t.draw?.regions?.length??0)>0){let E=document.createElement("div");E.className="bp-plan-footer",E.textContent=b("gpui.mgmt.plan.drawn","The plan's corridors and planes are drawn on the board while this panel is open. Close it to hide them."),e.appendChild(E)}return e}renderFab(){let e=document.createElement("div");e.className="bp-mgmt-body";let t=this.getPanelData("fab");if(!t)return e.appendChild(this.makeEmpty("Reading the fab's profile…")),e;if(t.error){let w=document.createElement("div");return w.className="bp-mgmt-note bp-tone-warn",w.textContent=t.error,e.appendChild(w),e}let n=(w,C={})=>{let A=this.watchGen,M=this.project;this.fabStatus="",this.cb.hub.rpc("fab.profile",{pro:M,action:w,...C}).catch((P)=>{if(A!==this.watchGen||M!==this.project)return;this.fabStatus=P instanceof Error?P.message:"Fab action failed",this.render()})},i=document.createElement("div");i.className="bp-mgmt-head";let s=document.createElement("span");s.className="bp-mgmt-strong",s.textContent=b("gpui.mgmt.fab.thefab","The fab");let r=document.createElement("span");r.className="bp-dim bp-mgmt-flex1",r.textContent=`rev ${t.rev??0}${t.updated?` · ${t.updated}`:""}${t.board?` · ${t.board}`:""} · ${oi(t.tier??"")}`;let a=document.createElement("button");if(a.type="button",a.className="bp-mgmt-btn",a.textContent=b("gpui.mgmt.fab.refresh","Refresh"),a.addEventListener("click",()=>n("refresh")),i.append(s,r,a),e.appendChild(i),this.fabStatus){let w=document.createElement("div");w.className="bp-mgmt-note bp-tone-bad",w.textContent=this.fabStatus,e.appendChild(w)}let o=document.createElement("div");o.className="bp-mgmt-rows",o.setAttribute("data-testid","mgmt-fab-rows");let c=t.review,u=document.createElement("div");u.className="bp-mgmt-row";let l=document.createElement("div");l.className="bp-mgmt-row-line";let p=document.createElement("span"),d=(c?.counts?.error??0)>0;if(p.className="bp-mgmt-flex1 "+(d?"bp-tone-bad":"bp-dim"),p.textContent=c?.running?"Reviewing the design…":c?.at==null?"No design review yet":`${c.counts?.error??0} must-fix · ${c.counts?.warning??0} should-fix · ${c.counts?.info??0} notes${c.scope?` (${c.scope})`:""}`,l.appendChild(p),c?.at!=null){let w=document.createElement("button");w.type="button",w.className="bp-mgmt-btn",w.textContent=b("gpui.mgmt.fab.findings","Findings"),w.addEventListener("click",()=>this.togglePanel("checks")),l.appendChild(w)}if(!c?.running){let w=document.createElement("button");w.type="button",w.className="bp-mgmt-btn",w.textContent=b("gpui.mgmt.fab.reviewbtn","Review"),w.addEventListener("click",()=>n("review")),l.appendChild(w)}if(c?.judge){let w=document.createElement("button");w.type="button",w.className="bp-mgmt-btn",w.textContent=b("gpui.mgmt.fab.judge","Datasheets"),w.addEventListener("click",()=>{if(c.judge)this.cb.onSendText(c.judge)}),l.appendChild(w)}u.appendChild(l),o.appendChild(u);let g=ai(t.drc?.state??""),y=document.createElement("div");y.className="bp-mgmt-row";let m=document.createElement("div");m.className="bp-mgmt-row-line";let h=document.createElement("span");if(h.className="bp-mgmt-flex1 "+(g.button?"bp-tone-warn":"bp-dim"),h.textContent=g.text,m.appendChild(h),g.button){let w=document.createElement("button");w.type="button",w.className="bp-mgmt-btn",w.textContent=g.button,w.addEventListener("click",()=>n("drc")),m.appendChild(w)}y.appendChild(m),o.appendChild(y);for(let w of t.conflicts??[]){let C=document.createElement("div");C.className="bp-mgmt-row bp-tone-bad",C.textContent=w,o.appendChild(C)}for(let w of t.suggestions??[]){let C=document.createElement("div");C.className="bp-mgmt-row";let A=document.createElement("div");A.className="bp-mgmt-row-line";let M=document.createElement("span");M.className="bp-mgmt-flex1 bp-tone-warn",M.textContent=`${w.label||w.key}: board ${w.project??"?"} mm, fab ${w.fab??"?"} mm`;let P=document.createElement("button");P.type="button",P.className="bp-mgmt-btn",P.textContent=b("gpui.mgmt.fab.apply","Apply"),P.addEventListener("click",()=>n("apply",{key:w.key})),A.append(M,P),C.appendChild(A),o.appendChild(C)}if(t.stackup?.chosen){let w=document.createElement("div");w.className="bp-mgmt-row";let C=document.createElement("div");C.className="bp-mgmt-row-line";let A=t.stackup.by==="proposed",M=document.createElement("span");if(M.className="bp-mgmt-flex1 "+(A?"bp-tone-warn":"bp-dim"),M.textContent=`${A?"Proposed: ":""}${t.stackup.chosen}${t.stackup.outer_50_mm?` (50Ω ${t.stackup.outer_50_mm} mm)`:""}`,C.appendChild(M),A){let P=t.stackup.chosen,T=document.createElement("button");T.type="button",T.className="bp-mgmt-btn",T.textContent=b("gpui.mgmt.fab.use","Use"),T.addEventListener("click",()=>n("stackup",{id:P})),C.appendChild(T)}w.appendChild(C),o.appendChild(w)}if(Array.isArray(t.changed)&&t.changed.length>0){let w=document.createElement("div");w.className="bp-mgmt-row";let C=document.createElement("div");C.className="bp-mgmt-row-line";let A=document.createElement("span");A.className="bp-mgmt-flex1 bp-tone-warn",A.textContent=b("gpui.mgmt.fab.changed","Changed since you last looked");let M=document.createElement("button");M.type="button",M.className="bp-mgmt-btn",M.textContent=b("gpui.mgmt.fab.seen","Seen"),M.addEventListener("click",()=>n("seen")),C.append(A,M),w.appendChild(C);for(let P of t.changed.slice(0,12)){let T=document.createElement("div");T.className="bp-mgmt-faint",T.textContent=P,w.appendChild(T)}o.appendChild(w)}let f=Array.isArray(t.limits)?t.limits:[];if(f.length>0){let w=document.createElement("div");w.className="bp-mgmt-group-head";let C=document.createElement("span");C.className="bp-mgmt-flex1",C.textContent=b("gpui.mgmt.fab.limit","Limit");let A=document.createElement("span");A.className="bp-mgmt-col",A.textContent=b("gpui.mgmt.fab.free","Base price");let M=document.createElement("span");M.className="bp-mgmt-col",M.textContent=b("gpui.mgmt.fab.extra","Costs more");let P=document.createElement("span");P.className="bp-mgmt-col bp-mgmt-col-read",P.textContent=b("gpui.mgmt.fab.readcol","Read"),w.append(C,A,M,P),o.appendChild(w);for(let B of f){let R=document.createElement("div");R.className="bp-mgmt-row";let O=document.createElement("div");O.className="bp-mgmt-row-line";let H=document.createElement("span");H.className="bp-mgmt-flex1"+(B.changed?" bp-tone-warn":B.inherited?" bp-dim":""),H.textContent=`${B.changed?"• ":""}${B.label??""}`;let ae=document.createElement("span");ae.className="bp-mgmt-col",ae.textContent=B.free?.text||"—";let ue=document.createElement("span");ue.className="bp-mgmt-col bp-dim",ue.textContent=B.extra?.text||"—";let oe=B.free&&typeof B.free==="object"?B.free:B.extra,we=oe?.fetched??"",Le=Boolean(we)&&oe?.confidence!=="published",Ne=we?Le?`${we}*`:we:"—",he=oe?.source??"",be;if(he.startsWith("https://")&&we){let I=document.createElement("a");I.className="bp-mgmt-col bp-mgmt-col-read bp-mgmt-read-link",I.href=he,I.target="_blank",I.rel="noopener noreferrer",I.textContent=Ne,be=I}else{let I=document.createElement("span");I.className="bp-mgmt-col bp-mgmt-col-read bp-mgmt-faint",I.textContent=Ne,be=I}O.append(H,ae,ue,be),R.appendChild(O),o.appendChild(R)}let T=document.createElement("div");T.className="bp-mgmt-note bp-mgmt-faint",T.textContent=b("gpui.mgmt.fab.derived","* worked out from the fab's page. Dimmed: the rigid board's value. A date opens the source page."),o.appendChild(T)}return e.appendChild(o),e}makeEmpty(e){let t=document.createElement("div");return t.className="bp-mgmt-note bp-mgmt-faint",t.textContent=e,t}}var Rs={trs:(e)=>e,t:(e,t)=>t},js=new Set(["/settle"]);function Ci(e,t){let n=t.trim().toLowerCase();if(!n)return 1;let i=e.toLowerCase();if(i.startsWith(n))return 3;if(i.split(/[^a-z0-9]+/i).some((a)=>a.startsWith(n)))return 2;let r=0;for(let a=0;a0||e.status==="waiting")return{urgency:3,want:"waiting"};if(e.status==="asking")return{urgency:2,want:"question"};if(e.status==="failed"||e.state==="failed")return{urgency:1,want:"failed"};return{urgency:0,want:""}}function Ai(e){let t=e.status||e.state;if(t==="active"||t==="working")return"bp-dot-work";if(t==="finished")return"bp-dot-done";if(t==="waiting"||t==="asking"||t==="blocked"||t==="failed"||(e.waiting??0)>0)return"bp-dot-need";return"bp-dot-idle"}function Li(e,t){let n=t.trim().split(/\s+/)[0]?.toLowerCase()??"";if(!n)return null;let i=e.toLowerCase();if(i.length!==e.length)return null;let s=i.indexOf(n);if(s<0)return null;return[s,s+n.length]}function Si(e,t=Rs){let{t:n,trs:i}=t,s=[],r=new Map;for(let o of e.projects)r.set(o.id,o.title||o.id);let a=e.threads.find((o)=>o.id===e.selectedThreadId)??null;for(let o of e.railItems){if(o.state==="disabled"||o.id==="commands")continue;if(!a&&o.id!=="terminal")continue;s.push({label:i(o.label),place:o.id==="terminal"?"":"viewer",kind:"action",shortcut:o.key?o.key.toUpperCase():void 0,action:{type:"rail",id:o.id}})}if(a)s.push({label:a.pinned?n("menu.unpin","Unpin"):n("menu.pin","Pin"),place:"",kind:"action",action:{type:"thread-act",action:a.pinned?"unpin":"pin"}}),s.push({label:a.settled?n("phone.unsettle","Unsettle"):n("menu.settle","Settle"),place:"",kind:"action",action:{type:"thread-act",action:a.settled?"unsettle":"settle"}}),s.push({label:a.archived?n("palette.unarchive","Unarchive"):n("palette.archive","Archive"),place:"",kind:"action",action:{type:"thread-act",action:a.archived?"unarchive":"archive"}}),s.push({label:n("sheet.rename","Rename thread"),place:"",kind:"action",action:{type:"rename"}}),s.push({label:n("gpui.previous.thread","Previous thread"),place:"",kind:"action",action:{type:"prev-thread"}}),s.push({label:n("gpui.next.thread","Next thread"),place:"",kind:"action",action:{type:"next-thread"}});if(a)for(let o of e.commands){if(!o.word)continue;let c=js.has(o.word.toLowerCase());s.push({label:o.label?`${o.word} — ${o.label}`:o.word,place:o.desc||"command",kind:"command",action:{type:"command",word:o.word,runDirectly:c}})}s.push({label:n("gpui.improvements","Improvements"),place:"",kind:"action",action:{type:"improvements"}}),s.push({label:n("palette.settings","Settings"),place:"",kind:"action",action:{type:"settings"}}),s.push({label:n("gpui.fold.or.unfold.the.sidebar","Fold or unfold the sidebar"),place:"",kind:"action",action:{type:"sidebar"}});for(let o of e.projects)s.push({label:`New thread in ${o.title||o.id}`,place:"",kind:"action",action:{type:"new-thread",projectId:o.id}});for(let o of e.threads){let{urgency:c,want:u}=ki(o);s.push({label:o.title||"Untitled thread",place:o.project?r.get(o.project)??"":"",kind:"thread",urgency:c,want:u,dotClass:Ai(o),action:{type:"thread",id:o.id}})}for(let o of e.bots){if(!o.name||!o.thread)continue;s.push({label:o.name,place:"",kind:"bot",action:{type:"thread",id:o.thread}})}return s}function Pi(e,t,n,i=[],s=10,r=14){let a=t.trim(),o=a.length===0,c=e.slice();if(n?.threads&&n.threads.length>0){let d=new Map;for(let y of i)d.set(y.id,y.title||y.id);let g=new Set;for(let y of c)if(y.action.type==="thread")g.add(y.action.id);for(let y of n.threads){if(!y.id||g.has(y.id))continue;g.add(y.id);let{urgency:m,want:h}=ki(y);c.push({label:y.title||"Untitled thread",place:y.project?d.get(y.project)??"":"",kind:"thread",urgency:m,want:h,dotClass:Ai(y),action:{type:"thread",id:y.id}})}}let u=[];for(let d=0;d0)u.push({score:h,index:d,item:g})}u.sort((d,g)=>{if(o){let h=(g.item.urgency??0)-(d.item.urgency??0);if(h!==0)return h}if(g.score!==d.score)return g.score-d.score;let y=d.item.kind==="thread"?0:1,m=g.item.kind==="thread"?0:1;if(y!==m)return y-m;return d.index-g.index});let l=new Set,p=[];for(let d of u){let g=`${d.item.label}\x00${d.item.place}\x00${d.item.kind}`;if(l.has(g))continue;if(l.add(g),p.push(d.item),p.length>=s)break}if(n?.messages&&n.messages.length>0&&p.length{if(a.target===t)this.close()}),s.addEventListener("input",()=>{this.query=s.value,this.activeIdx=0,this.renderList(),this.scheduleSearch()}),s.addEventListener("keydown",(a)=>{if(a.key==="Escape")a.preventDefault(),a.stopPropagation(),this.close();else if(a.key==="ArrowDown"){if(a.preventDefault(),this.listed.length>0)this.activeIdx=(this.activeIdx+1)%this.listed.length,this.renderList(!0)}else if(a.key==="ArrowUp"){if(a.preventDefault(),this.listed.length>0)this.activeIdx=(this.activeIdx-1+this.listed.length)%this.listed.length,this.renderList(!0)}else if(a.key==="Enter")a.preventDefault(),this.runAt(this.activeIdx)}),this.backdrop=t,this.inputEl=s,this.listEl=r,this.root.appendChild(t),this.renderList(),this.query.trim().length>=2)this.scheduleSearch();s.focus()}close(){if(this.searchTimer!==null)window.clearTimeout(this.searchTimer),this.searchTimer=null;if(this.searchGen++,this.backdrop)this.backdrop.remove(),this.backdrop=null,this.inputEl=null,this.listEl=null;this.prevFocus?.focus(),this.prevFocus=null}scheduleSearch(){if(this.searchTimer!==null)window.clearTimeout(this.searchTimer),this.searchTimer=null;let e=this.query.trim();if(e.length<2){this.searchHits=null,this.searchHitsQuery="";return}if(e===this.searchHitsQuery)return;let t=++this.searchGen;this.searchTimer=window.setTimeout(()=>{this.searchTimer=null,this.cb.onSearch(e).then((n)=>{if(t!==this.searchGen||!this.backdrop)return;if(this.query.trim()!==e)return;this.searchHits=n,this.searchHitsQuery=e,this.renderList()}).catch(()=>{})},180)}runAt(e){let t=this.listed[e];if(!t)return;this.close(),this.cb.onExecute(t.action)}renderList(e=!1){if(!this.listEl)return;let t=this.cb.getState(),n=Si(t,{t:b,trs:pe}),i=this.query.trim()===this.searchHitsQuery?this.searchHits:null;if(this.listed=Pi(n,this.query,i,t.projects),this.activeIdx>=this.listed.length)this.activeIdx=Math.max(0,this.listed.length-1);if(this.listed.length===0){let a=document.createElement("div");a.className="bp-palette-empty",a.textContent=b("gpui.nothing.matches","Nothing matches"),this.listEl.replaceChildren(a);return}let s=document.createDocumentFragment(),r=null;for(let a=0;a0)u.appendChild(document.createTextNode(o.label.slice(0,d)));let y=document.createElement("strong");if(y.className="bp-palette-mark",y.textContent=o.label.slice(d,g),u.appendChild(y),g{if(this.activeIdx!==a)this.activeIdx=a,this.updateActiveClass()}),c.addEventListener("click",()=>this.runAt(a)),a===this.activeIdx)r=c;s.appendChild(c)}if(this.listEl.replaceChildren(s),e&&r)r.scrollIntoView({block:"nearest"})}updateActiveClass(){if(!this.listEl)return;let e=this.listEl.children;for(let t=0;tthis.onPress(e.id));return r}render(){let e=this.items.filter((a)=>a.group!=="tools"),t=this.items.filter((a)=>a.group==="tools"),n=document.createElement("div");n.className="bp-rail-pages";let i;for(let a of e){if(i!==void 0&&a.group!==i){let o=document.createElement("div");o.className="bp-rail-rule",n.appendChild(o)}i=a.group,n.appendChild(this.renderButton(a))}let s=()=>{let a=n.scrollLeft>2,o=n.scrollLeft+n.clientWidth0){let a=document.createElement("div");a.className="bp-rail-tools";for(let o of t)a.appendChild(this.renderButton(o));r.appendChild(a)}this.el.replaceChildren(r)}}var Fs=new Set(["resume","raise","retry","move","signin"]);function Bi(e){if(!e||typeof e!=="object")return null;let t=e,n=(r)=>typeof r==="string"?r:"",i=(Array.isArray(t.actions)?t.actions:[]).filter((r)=>Boolean(r)&&typeof r==="object").map((r)=>({label:n(r.label),act:n(r.act),room:n(r.room),thread:n(r.thread)})),s={line:n(t.line),why:n(t.why),actions:i};return s.line||i.length?s:null}function Gt(e,t){if(e.act==="board")return t&&e.room?{kind:"board",room:e.room}:null;if(e.act==="open")return e.thread?{kind:"thread",id:e.thread}:null;if(Fs.has(e.act)){let n={room:e.room,action:e.act};if(e.thread)n.thread=e.thread;return{kind:"call",method:"swarm.act",params:n}}return null}function Ii(e){let t=e&&typeof e==="object"?e.open:void 0;if(typeof t!=="string")return null;let n=t.indexOf(":"),i=n<0?"":t.slice(n+1);if(!i)return null;if(t.startsWith("account:"))return{kind:"account",id:i};if(t.startsWith("thread:"))return{kind:"thread",id:i};return null}class un{backdrop;titleEl;closeBtn;bodyEl;cb;openState=!1;forceProviders=!1;providersEl=null;constructor(e,t){this.cb=t,this.backdrop=document.createElement("div"),this.backdrop.className="bp-modal-backdrop bp-hidden",this.backdrop.setAttribute("data-testid","settings-modal");let n=document.createElement("div");n.className="bp-modal";let i=document.createElement("div");i.className="bp-modal-head",this.titleEl=document.createElement("h2"),this.titleEl.textContent=`${b("palette.settings","Settings")} · Devices`,this.closeBtn=document.createElement("button"),this.closeBtn.type="button",this.closeBtn.className="icon",this.closeBtn.textContent="×",this.closeBtn.setAttribute("aria-label",b("common.close","Close")),this.closeBtn.addEventListener("click",()=>this.close()),i.append(this.titleEl,this.closeBtn),this.bodyEl=document.createElement("div"),this.bodyEl.className="bp-modal-body",n.append(i,this.bodyEl),this.backdrop.appendChild(n),this.backdrop.addEventListener("click",(s)=>{if(s.target===this.backdrop)this.close()}),e.appendChild(this.backdrop)}isOpen(){return this.openState}async open(){this.openState=!0,this.backdrop.classList.remove("bp-hidden"),await this.refresh()}async openToAccounts(){this.forceProviders=!0,await this.open(),this.providersEl?.scrollIntoView({block:"nearest"})}close(){this.openState=!1,this.forceProviders=!1,this.backdrop.classList.add("bp-hidden")}refreshLocale(){if(this.titleEl.textContent=`${b("palette.settings","Settings")} · Devices`,this.closeBtn.setAttribute("aria-label",b("common.close","Close")),this.openState)this.refresh()}async refresh(){let e=document.createDocumentFragment();this.providersEl=null;let t=this.cb.onGetNoProvider?.()??null;if(t||this.forceProviders){let l=document.createElement("section");l.className="bp-set-section",l.setAttribute("data-testid","settings-providers");let p=document.createElement("div");p.className="bp-set-head",p.textContent=b("web.settings.providers","AI providers");let d=document.createElement("div");d.className="bp-set-row";let g=document.createElement("div");g.className="bp-set-info";let y=document.createElement("div");y.textContent=t?pe(t.head):b("provider.notice.head","No AI provider connected");let m=document.createElement("div");m.className="bp-dim",m.textContent=b("web.settings.providers.browser","Connect a provider in the Backplane desktop or mobile app under Settings → Accounts."),g.append(y,m);let h=document.createElement("div");h.className="bp-set-btns";let f=document.createElement("a");f.className="bp-link-btn primary",f.href=t?.url||"backplane://settings/accounts",f.setAttribute("data-testid","settings-open-accounts"),f.textContent=t?pe(t.button):b("provider.notice.button","Open Settings → Accounts"),h.appendChild(f),d.append(g,h),l.append(p,d),this.providersEl=l,e.appendChild(l)}let n=this.cb.onGetHome?.()??null;if(n){let l=document.createElement("section");l.className="bp-set-section",l.setAttribute("data-testid","settings-home");let p=document.createElement("div");p.className="bp-set-head",p.textContent=b("home.machine","Home machine");let d=document.createElement("div");d.className="bp-set-row";let g=document.createElement("div");g.className="bp-set-info";let y=document.createElement("div"),m=n.kind==="local"?`${n.name||"This machine"} (this machine)`:n.kind==="boat"?`${n.name||"Boat"} (Boat)`:n.name||"Linked machine";y.textContent=m,g.appendChild(y);let h=document.createElement("div");if(h.className="bp-dim",n.moving?.state==="moving")h.textContent=n.moving.step?b("home.moving.step","Moving home to {to}: {step}").replace("{to}",n.moving.to).replace("{step}",n.moving.step):b("home.moving","Moving home to {to}…").replace("{to}",n.moving.to);else if(n.moving?.state==="failed")h.textContent=n.moving.note?b("home.move.failed.note","Home move failed: {note}").replace("{note}",n.moving.note):b("home.move.failed","Home move failed");else if(!n.online)h.textContent=n.queuedCount>0?b("home.away.queued","Home ({name}) is away · {n} queued").replace("{name}",n.name||"home").replace("{n}",String(n.queuedCount)):b("home.away","Home ({name}) is away").replace("{name}",n.name||"home");else h.textContent="Online";if(g.appendChild(h),d.appendChild(g),n.canMoveHere&&this.cb.onMoveHomeHere){let f=document.createElement("button");f.type="button",f.className="primary",f.textContent=b("home.move.here","Make this machine the home"),f.setAttribute("data-testid","home-move-here-btn"),f.addEventListener("click",()=>{f.disabled=!0,this.cb.onMoveHomeHere?.().finally(()=>{this.refresh()})}),d.appendChild(f)}l.append(p,d),e.appendChild(l)}let i=document.createElement("section");i.className="bp-set-section";let s=document.createElement("div");s.className="bp-set-head",s.textContent="This browser";let r=document.createElement("div");r.className="bp-set-row";let a=document.createElement("span");a.className="bp-dim",a.textContent="Sign out and revoke this browser's session cookie.";let o=document.createElement("button");o.type="button",o.className="primary stop",o.textContent=b("agy.signout","Sign out"),o.setAttribute("data-testid","logout-btn"),o.addEventListener("click",()=>{o.disabled=!0,this.cb.onLogout().catch(()=>{a.setAttribute("role","alert"),a.textContent=b("web.logout.failed","Could not confirm sign-out. Try again."),o.disabled=!1})}),r.append(a,o),i.append(s,r),e.appendChild(i);let c=document.createElement("section");c.className="bp-set-section";let u=document.createElement("div");u.className="bp-set-head",u.textContent="Paired devices",c.appendChild(u);try{let l=await this.cb.onLoadDevices();if(l.length===0){let p=document.createElement("div");p.className="bp-dim",p.textContent="No devices listed.",c.appendChild(p)}else for(let p of l){let d=document.createElement("div");d.className="bp-set-row";let g=document.createElement("div");g.className="bp-set-info";let y=document.createElement("div");if(y.textContent=p.title||p.head||"",g.appendChild(y),p.text||p.detail){let m=document.createElement("div");m.className="bp-dim",m.textContent=p.text||p.detail||"",g.appendChild(m)}if(d.appendChild(g),p.buttons?.length){let m=document.createElement("div");m.className="bp-set-btns";for(let h of p.buttons){let f=document.createElement("button");if(f.type="button",h.primary)f.className="primary";if(h.danger)f.className="primary stop";f.textContent=h.label||b("common.remove","Remove"),f.addEventListener("click",()=>{f.disabled=!0,this.cb.onDevicesAct(h.action,h.value).finally(()=>{this.refresh()})}),m.appendChild(f)}d.appendChild(m)}c.appendChild(d)}}catch(l){let p=document.createElement("div");p.className="bp-dim";let d=l instanceof Error&&l.message?l.message:"Not available from a browser";p.textContent=`${d} — manage paired devices in Backplane › Settings › Devices on desktop or a paired phone.`,c.appendChild(p)}e.appendChild(c),this.bodyEl.replaceChildren(e)}}function Ee(e,t,n){let i=document.createElement(e);if(t)i.className=t;if(n)i.textContent=n;return i}function xt(e,t,n=!1){let i=Ee("button",n?"primary":"bp-btn-ghost",e);return i.type="button",i.addEventListener("click",t),i}function hn(e){return Ee("pre","bp-context-code",e)}function $s(e){return Ee("span",`bp-context-badge ${e==="Native"||e==="Enabled"?"active":e==="Untrusted"||e==="Invalid"?"warn":""}`,pe(e))}function Ot(e,t){let n=Ee("div","bp-context-row");return n.append(Ee("strong",void 0,e),$s(t)),n}class bn{fetchContext;dialog=Ee("dialog","bp-context");title=Ee("h2");cwd=Ee("div","bp-context-path");tabs=Ee("div","bp-context-tabs");body=Ee("div","bp-context-body");notice=Ee("p","bp-context-notice");current;thread="";requestId=0;tab=0;busy=!1;constructor(e,t){this.fetchContext=t;let n=Ee("div","bp-context-head"),i=Ee("div");i.append(this.title,this.cwd),this.title.id="bp-context-title",this.dialog.setAttribute("aria-labelledby",this.title.id),this.notice.setAttribute("role","status"),n.append(i,xt(b("common.refresh","Refresh"),()=>{this.load()}),xt(b("common.close","Close"),()=>this.dialog.close())),this.dialog.append(n,this.tabs,this.notice,this.body),this.dialog.addEventListener("close",()=>{this.requestId++}),e.append(this.dialog)}open(e){if(this.thread=e,this.tab=0,this.current=void 0,this.busy=!1,this.title.textContent=b("thread.context.title","Context & Prompt"),this.cwd.textContent="",!this.dialog.open)this.dialog.showModal();this.render(),this.load()}async load(e){if(this.busy)return;let t=++this.requestId;this.busy=!0,this.notice.textContent=b("thread.context.reading","Reading thread context…"),this.render();try{let n=await this.fetchContext(this.thread,e);if(t!==this.requestId)return;this.current=n,this.cwd.textContent=n.cwd,this.notice.textContent=""}catch(n){if(t===this.requestId)this.notice.textContent=String(n)}finally{if(t===this.requestId)this.busy=!1,this.render()}}render(){let e=[b("thread.context.instructions","Instructions"),b("thread.context.system","System Prompt"),b("thread.context.skills","Skills"),b("thread.context.mcp","Project MCPs")];this.tabs.replaceChildren(...e.map((n,i)=>{let s=xt(n,()=>{this.tab=i,this.render(),this.body.scrollTop=0,this.tabs.children[i].focus()});return s.setAttribute("aria-pressed",String(i===this.tab)),s})),this.body.replaceChildren();let t=this.current;if(!t)return;switch(this.tab){case 0:this.instructions(t.instructions);break;case 1:this.prompt(t);break;case 2:this.skills(t.skills);break;case 3:this.mcps(t.mcp);break}}instructions(e){if(!e.length)this.body.append(Ee("p","bp-dim",b("thread.context.none.instructions","No project instructions found.")));for(let t of e){let n=Ee("details","bp-context-card"),i=Ee("summary");if(i.append(Ot(t.path,t.status),Ee("small","bp-dim",b("thread.context.size","{bytes} B · ≈{tokens} tokens",{bytes:t.bytes,tokens:t.estimated_tokens}))),n.append(i,hn(t.preview)),t.note)n.append(Ee("small","bp-dim",t.note));this.body.append(n)}}prompt(e){let t=Ee("div","bp-context-row"),n=xt(b("thread.context.copy","Copy prompt"),()=>{navigator.clipboard.writeText(e.prompt).then(()=>{this.notice.textContent=b("thread.context.copied","Prompt copied.")}).catch((i)=>{this.notice.textContent=String(i)})});t.append(Ee("p","bp-dim",b("thread.context.native.note","Backplane’s launch prompt. Native files are loaded by the provider.")),n),this.body.append(t);for(let[i,s]of[[b("thread.context.base","Backplane"),e.sections.base],[b("thread.context.injected.label","Injected project instructions"),e.sections.instructions],[b("thread.context.index","Available skills index"),e.sections.skills]])if(s)this.body.append(Ee("h3",void 0,i),hn(s))}skills(e){for(let t of["Project","User","Bundled"]){let n=e.filter((i)=>i.scope===t);if(!n.length)continue;this.body.append(Ee("h3",void 0,pe(t)));for(let i of n){let s=Ee("article","bp-context-card");s.append(Ot(i.name,i.status),Ee("p",void 0,i.description),Ee("small","bp-context-path",[i.source,i.provider,i.model].filter(Boolean).join(" · ")),Ee("small","bp-context-path",i.path)),this.body.append(s)}}}mcps(e){if(!e.length)this.body.append(Ee("p","bp-dim",b("thread.context.none.mcp","No project MCP configurations found.")));for(let t of e){let n=Ee("article","bp-context-card");n.append(Ot(t.path,t.state));for(let s of t.servers){let r=s.url||[s.command,...s.args].map((a)=>JSON.stringify(a)).join(" ");if(n.append(Ot(s.name,s.status),hn(r)),s.cwd)n.append(Ee("small","bp-context-path",s.cwd))}if(t.error)n.append(Ee("p","bp-warn",t.error));let i=t.state==="Untrusted"?"trust":t.state==="Enabled"?"disable":t.state==="Disabled"?"enable":"";if(i){let s=i==="trust"?b("thread.context.trust","Trust and enable"):i==="disable"?b("thread.context.disable","Disable"):b("thread.context.enable","Enable"),r=xt(s,()=>{this.load({action:i,path:t.path,sha256:t.sha256})},i==="trust");r.disabled=this.busy;let a=Ee("div","bp-context-actions");a.append(r),n.append(a)}this.body.append(n)}}}var Ri="http://www.w3.org/2000/svg";function ji(){let e=document.createElementNS(Ri,"svg");e.setAttribute("viewBox","0 0 24 24"),e.setAttribute("width","14"),e.setAttribute("height","14"),e.setAttribute("fill","none"),e.setAttribute("stroke","currentColor"),e.setAttribute("stroke-width","1.75"),e.setAttribute("aria-hidden","true"),e.classList.add("bp-folder-icon");let t=document.createElementNS(Ri,"path");return t.setAttribute("d","M3 6h6l2 2h10v11H3z"),e.appendChild(t),e}function Gs(e,t,n,i){let s=e||t||n||"";if(s==="active"||s==="working"||s==="running"||s==="run")return"bp-dot-work";if(s==="finished"||s==="done")return"bp-dot-done";if(s==="waiting"||s==="asking"||s==="blocked"||s==="needs"||s==="failed"||s==="fail"||s==="cut"||s==="interrupted"||s==="limit"||s==="monitoring"||(i??0)>0)return"bp-dot-need";return"bp-dot-idle"}function Hi(e){if(!e)return"";let t=e<10000000000?e*1000:e,n=Math.max(0,Math.floor((Date.now()-t)/1000));if(n<60)return"now";if(n<3600)return`${Math.floor(n/60)}m`;if(n<86400)return`${Math.floor(n/3600)}h`;return`${Math.floor(n/86400)}d`}class gn{el;hostLabel;homeBanner;filterInput;listEl;connEl;filterText="";showSettled=new Set;collapsedProjects=new Set;addShown=!1;sections=null;projects=[];threads=[];bots=[];rooms=[];selectedThreadId="";cb;needErr=new Map;needBusy=new Set;constructor(e,t){this.el=e,this.cb=t;let n=document.createElement("div");n.className="bp-side-host";let i=document.createElement("div");i.className="bp-side-host-left",this.hostLabel=document.createElement("span"),this.hostLabel.textContent="This computer";let s=document.createElement("span");s.className="bp-dim",s.textContent="›",i.append(this.hostLabel,s);let r=document.createElement("button");r.type="button",r.className="icon bp-side-collapse",r.textContent="‹",r.title="Collapse sidebar",r.setAttribute("aria-label","Collapse sidebar"),r.setAttribute("data-testid","sidebar-collapse"),r.addEventListener("click",()=>this.cb.onCollapseSidebar?.()),n.append(i,r);let a=document.createElement("div");a.className="bp-side-head",this.filterInput=document.createElement("input"),this.filterInput.type="search",this.filterInput.className="bp-input bp-side-search";let o=b("sidebar.search.projects","Search projects");this.filterInput.placeholder=o,this.filterInput.setAttribute("aria-label",o),this.filterInput.setAttribute("data-testid","sidebar-filter"),this.filterInput.addEventListener("input",()=>{this.filterText=this.filterInput.value.trim().toLowerCase(),this.render()});let c=document.createElement("button");c.type="button",c.className="icon bp-side-add",c.textContent="+",c.title=b("thread.new","New thread"),c.setAttribute("aria-label",b("thread.new","New thread")),c.setAttribute("data-testid","sidebar-new-thread"),c.addEventListener("click",()=>{let l=this.firstProjectId();if(l)this.cb.onNewThread(l)}),a.append(this.filterInput,c),this.homeBanner=document.createElement("div"),this.homeBanner.className="bp-side-home bp-hidden",this.homeBanner.setAttribute("data-testid","home-away-banner"),this.homeBanner.style.padding="6px 10px",this.homeBanner.style.fontSize="11px",this.homeBanner.style.borderBottom="1px solid var(--line, #2a2a2a)",this.listEl=document.createElement("div"),this.listEl.className="bp-side-list",this.listEl.setAttribute("data-testid","sidebar-list");let u=document.createElement("div");u.className="bp-side-footer",this.connEl=document.createElement("span"),this.connEl.className="bp-conn-status",this.connEl.textContent="Connecting…",this.connEl.setAttribute("data-testid","conn-status"),u.appendChild(this.connEl),this.el.append(n,a,this.homeBanner,this.listEl,u)}setHome(e){if(!e){this.homeBanner.classList.add("bp-hidden"),this.homeBanner.textContent="";return}let t="",n=!1;if(e.moving?.state==="moving")t=e.moving.step?b("home.moving.step","Moving home to {to}: {step}").replace("{to}",e.moving.to).replace("{step}",e.moving.step):b("home.moving","Moving home to {to}…").replace("{to}",e.moving.to);else if(e.moving?.state==="failed")t=e.moving.note?b("home.move.failed.note","Home move failed: {note}").replace("{note}",e.moving.note):b("home.move.failed","Home move failed"),n=!0;else if(!e.online){let i=e.name||"home",s="";if(e.awaySince&&e.awaySince>0){let r=new Date(e.awaySince);s=`${String(r.getHours()).padStart(2,"0")}:${String(r.getMinutes()).padStart(2,"0")}`}if(s&&e.queuedCount>0)t=b("home.away.since.queued","Home ({name}) is away since {time} · {n} queued").replace("{name}",i).replace("{time}",s).replace("{n}",String(e.queuedCount));else if(s)t=b("home.away.since","Home ({name}) is away since {time}").replace("{name}",i).replace("{time}",s);else if(e.queuedCount>0)t=b("home.away.queued","Home ({name}) is away · {n} queued").replace("{name}",i).replace("{n}",String(e.queuedCount));else t=b("home.away","Home ({name}) is away").replace("{name}",i)}if(!t)this.homeBanner.classList.add("bp-hidden"),this.homeBanner.textContent="";else this.homeBanner.textContent=t,this.homeBanner.className=n?"bp-side-home bp-bad":"bp-side-home bp-dim",this.homeBanner.classList.remove("bp-hidden")}setHostName(e){this.hostLabel.textContent=e||"This computer"}setConnStatus(e,t){this.connEl.textContent=e,this.connEl.className=`bp-conn-status ${t}`.trim()}setData(e,t,n,i){this.projects=e,this.threads=t,this.bots=n,this.rooms=i,this.render()}setSections(e,t,n){this.sections=e,this.bots=t,this.rooms=n,this.render()}setSelected(e){this.selectedThreadId=e,this.render()}focusFilter(){this.filterInput.focus()}firstProjectId(){if(this.sections){for(let e of this.sections)if(e.kind==="projects"&&e.rows.length>0){let t=e.rows[0];if(t.id&&!t.off)return t.id}}return this.projects[0]?.id??""}refreshLocale(){let e=b("sidebar.search.projects","Search projects");this.filterInput.placeholder=e,this.filterInput.setAttribute("aria-label",e),this.render()}projectsHead(e){let t=document.createElement("div");if(t.className="bp-side-section-head",!this.cb.onAddProject||this.addShown)return t.textContent=e,t;this.addShown=!0,t.classList.add("bp-side-section-row");let n=document.createElement("span");n.textContent=e;let i=document.createElement("button");i.type="button",i.className="bp-side-sec-plus bp-side-sec-btn",i.textContent="+";let s=b("sidebar.add.project","Add project");return i.title=s,i.setAttribute("aria-label",s),i.setAttribute("data-testid","sidebar-add-project"),i.addEventListener("click",(r)=>{r.stopPropagation(),this.cb.onAddProject?.()}),t.append(n,i),t}renderSectionThreadRow(e,t){let n=document.createElement("div");if(n.className="bp-thread-row"+(e.id===this.selectedThreadId?" active":"")+(e.off?" bp-dim":""),n.setAttribute("data-thread-id",e.id),n.setAttribute("data-testid",`thread-row-${e.id}`),t){let p=document.createElement("span");p.className="bp-tree-branch",p.setAttribute("aria-hidden","true"),n.appendChild(p)}let i=document.createElement("span");i.className=`bp-dot ${Gs(e.status,e.word,e.state)}`;let s=document.createElement("div");if(s.className="bp-thread-title",s.textContent=e.title||"Untitled thread",n.append(i,s),e.word==="needs"){let p=document.createElement("span");if(p.className="bp-badge-need",p.textContent=e.want==="approval"?"!":"•",e.say)p.title=e.say;n.appendChild(p)}else if(e.ago){let p=document.createElement("span");if(p.className="bp-thread-age",p.textContent=e.ago,e.pinned)p.title=b("tools.pinned","Pinned");n.appendChild(p)}let r=e.nav||e.id;if(!e.off&&r&&!r.startsWith("@room:"))n.addEventListener("click",()=>this.cb.onSelectThread(r));let a=e.kind==="swarm"?Bi(e.need):null;if(!a)return n;let o=document.createElement("div");o.className="bp-need-wrap";let c=document.createElement("div");c.className="bp-need"+(t?" nested":"")+(e.off?" bp-dim":""),c.setAttribute("data-testid",`need-${e.id}`);let u=document.createElement("span");u.className="bp-need-line",u.textContent=a.line,u.title=a.line,c.appendChild(u);for(let p of a.actions){if(!Gt(p,Boolean(this.cb.hasRoomView)))continue;let d=document.createElement("button");d.type="button",d.className="bp-need-btn",d.textContent=p.label,d.setAttribute("data-testid",`need-${p.act}-${e.id}`),d.disabled=Boolean(e.off)||this.needBusy.has(e.id)||!this.cb.onNeedAct,d.addEventListener("click",(g)=>{g.stopPropagation();let y=this.cb.onNeedAct;if(!y)return;this.needErr.delete(e.id),this.needBusy.add(e.id),this.render(),y(p).catch((m)=>{this.needErr.set(e.id,m instanceof Error?m.message:String(m))}).finally(()=>{this.needBusy.delete(e.id),this.render()})}),c.appendChild(d)}o.append(n,c);let l=this.needErr.get(e.id);if(l){let p=document.createElement("div");p.className="bp-need-err"+(t?" nested":""),p.textContent=l,o.appendChild(p)}return o}renderHubSections(e,t){let n=this.sections??[],i=new Set;for(let a of n)if(a.kind==="threads")for(let o of a.rows)i.add(o.id);else if(a.kind==="projects")for(let o of a.rows)for(let c of o.threads??[])i.add(c.id);let s=this.selectedThreadId?this.threads.find((a)=>a.id===this.selectedThreadId)??null:null,r=!1;for(let a of n)if(a.kind==="projects"&&a.rows.length>0)r=!0;for(let a of n){if(a.kind==="bub")continue;if(a.kind==="threads"){let o=a.rows.filter((l)=>{if(!t)return!0;return`${l.title} ${l.project??""}`.toLowerCase().includes(t)});if(o.length===0)continue;let c=document.createElement("section");c.className="bp-side-section",c.setAttribute("data-section-id",a.id);let u=document.createElement("div");u.className="bp-side-section-head",u.textContent=a.title.toUpperCase(),c.appendChild(u);for(let l of o)c.appendChild(this.renderSectionThreadRow(l,!1));e.appendChild(c);continue}if(a.kind==="projects"){let o=a.rows.filter((l)=>{if(!t)return!0;if((l.title||l.id).toLowerCase().includes(t))return!0;if((l.threads??[]).some((p)=>p.title.toLowerCase().includes(t)))return!0;if((l.swarms??[]).some((p)=>p.title.toLowerCase().includes(t)))return!0;return!1}),c=Boolean(a.fold&&a.toggle);if(t&&o.length===0)continue;if(!c&&a.id!=="active"&&o.length===0)continue;let u=document.createElement("section");if(u.className="bp-side-section",u.setAttribute("data-section-id",a.id),c){let l=document.createElement("button");l.type="button",l.className="bp-side-section-head bp-side-section-toggle";let p=a.count??o.length,d=a.open?"▾":"▸";if(l.textContent=`${a.title.toUpperCase()} (${p}) ${d}`,a.hint)l.title=a.hint;l.addEventListener("click",()=>{if(a.toggle)this.cb.onToggleSection?.(a.toggle)}),u.appendChild(l)}else u.appendChild(this.projectsHead(a.title.toUpperCase()));if(!c||a.open||Boolean(t)){if(a.id==="active"&&!r&&!t){let l=document.createElement("div");l.className="bp-side-empty",l.textContent="No projects yet.",u.appendChild(l)}for(let l of o){let p=document.createElement("div");if(p.className="bp-proj-group"+(l.off?" bp-dim":""),p.setAttribute("data-project-id",l.id),l.nav||l.key)p.setAttribute("data-project-key",l.nav||l.key||"");let d=document.createElement("div");d.className="bp-proj-head";let g=document.createElement("button");g.type="button",g.className="bp-proj-toggle";let y=ji();if(l.css)y.style.color=l.css;let m=document.createElement("span");if(m.className="bp-proj-name",m.textContent=l.title||l.id,g.append(y,m),l.fold==="project-fold"&&l.nav)g.addEventListener("click",()=>this.cb.onToggleProjectFold?.(l.nav));let h=document.createElement("button");if(h.type="button",h.className="icon bp-proj-add",h.title=b("thread.new","New thread"),h.textContent="+",h.setAttribute("data-testid",`new-thread-${l.id}`),l.off)h.disabled=!0;if(h.addEventListener("click",(f)=>{f.stopPropagation(),this.cb.onNewThread(l.id)}),d.append(g,h),p.appendChild(d),!l.folded||Boolean(t)){let f=Boolean(t)&&(l.title||l.id).toLowerCase().includes(t);for(let w of l.swarms??[]){if(t&&!f&&!w.title.toLowerCase().includes(t))continue;p.appendChild(this.renderSectionThreadRow(w,!0))}for(let w of l.threads??[]){if(t&&!f&&!w.title.toLowerCase().includes(t))continue;p.appendChild(this.renderSectionThreadRow(w,!0))}if(s&&s.project===l.id&&!i.has(s.id)&&(!t||f||s.title.toLowerCase().includes(t)))p.appendChild(this.renderSectionThreadRow({id:s.id,title:s.title,status:s.status,state:s.state,ago:Hi(s.updatedAt),pinned:s.pinned,nav:s.id},!0))}u.appendChild(p)}}e.appendChild(u)}}}render(){this.addShown=!1;let e=document.createDocumentFragment(),t=this.filterText;if(this.sections!==null)this.renderHubSections(e,t);else{let n=new Map;for(let i of this.threads){if(i.archived||i.swarm)continue;if(t){if(!`${i.title} ${i.preview??""}`.toLowerCase().includes(t))continue}let s=n.get(i.project)??[];s.push(i),n.set(i.project,s)}if(e.appendChild(this.projectsHead("ACTIVE")),this.projects.length===0&&this.threads.length===0){let i=document.createElement("div");i.className="bp-side-empty",i.textContent="No projects yet.",e.appendChild(i)}for(let i of this.projects){let s=n.get(i.id)??[];if(t&&s.length===0&&!i.title.toLowerCase().includes(t))continue;let r=document.createElement("section");r.className="bp-proj-group",r.setAttribute("data-project-id",i.id);let a=document.createElement("div");a.className="bp-proj-head";let o=document.createElement("button");o.type="button",o.className="bp-proj-toggle";let c=this.collapsedProjects.has(i.id)&&!t,u=ji();if(i.css)u.style.color=i.css;let l=document.createElement("span");l.className="bp-proj-name",l.textContent=i.title||i.id,o.append(u,l),o.addEventListener("click",()=>{if(this.collapsedProjects.has(i.id))this.collapsedProjects.delete(i.id);else this.collapsedProjects.add(i.id);this.render()});let p=document.createElement("button");if(p.type="button",p.className="icon bp-proj-add",p.title=b("thread.new","New thread"),p.textContent="+",p.setAttribute("data-testid",`new-thread-${i.id}`),p.addEventListener("click",(d)=>{d.stopPropagation(),this.cb.onNewThread(i.id)}),a.append(o,p),r.appendChild(a),!c)for(let d of s)r.appendChild(this.renderSectionThreadRow({id:d.id,title:d.title,status:d.status,state:d.state,ago:Hi(d.updatedAt),pinned:d.pinned,nav:d.id},!0));e.appendChild(r)}}if(!t){let n=document.createElement("section");n.className="bp-proj-group bp-bots-group";let i=document.createElement("div");i.className="bp-side-section-head bp-side-section-row";let s=document.createElement("span");s.textContent=b("tour.title.bots","Bots").toUpperCase();let r=document.createElement("span");r.className="bp-side-sec-plus",r.textContent="+",r.setAttribute("aria-hidden","true"),i.append(s,r),n.appendChild(i);for(let l of this.bots){let p=document.createElement("div");p.className="bp-thread-row"+(l.thread===this.selectedThreadId?" active":"");let d=document.createElement("span");if(d.className="bp-dot bp-dot-idle",l.color)d.style.backgroundColor=l.color;let g=document.createElement("div");g.className="bp-thread-title",g.textContent=`@${l.name}`,p.append(d,g),p.addEventListener("click",()=>this.cb.onSelectBot(l)),n.appendChild(p)}e.appendChild(n);let a=document.createElement("section");a.className="bp-proj-group";let o=document.createElement("div");o.className="bp-side-section-head bp-side-section-row";let c=document.createElement("span");c.textContent=b("bots.rooms","Rooms").toUpperCase();let u=document.createElement("span");u.className="bp-side-sec-plus",u.textContent="+",u.setAttribute("aria-hidden","true"),o.append(c,u),a.appendChild(o);for(let l of this.rooms){let p=document.createElement("div");p.className="bp-thread-row";let d=document.createElement("div");d.className="bp-thread-title",d.textContent=`#${l.name}`,p.appendChild(d),a.appendChild(p)}e.appendChild(a)}this.listEl.replaceChildren(e)}}function Os(e){try{return new URL(e,window.location.origin).searchParams.get("s")||""}catch{return""}}function Ct(e){if(!e)return;for(let t of e.getTracks())try{t.stop()}catch{}}function Vs(e,t){if(t===16000){let r=new Int16Array(e.length);for(let a=0;a0?c/u:0));s[r]=l<0?l*32768:l*32767}return s}class fn{hub;cb;active=!1;starting=!1;sessionGen=0;activeGen=0;abortedGen=0;threadId="";sessionKey="";stream=null;audioCtx=null;processor=null;pendingPcm=[];postChain=Promise.resolve();stopDrain=Promise.resolve();mark=0;constructor(e,t){this.hub=e,this.cb=t}isRecording(){return this.active||this.starting}async toggle(){if(this.active||this.starting)await this.stop();else await this.start()}async start(){if(this.active||this.starting)return;let e=this.cb.getThreadId();if(!e)return;if(!navigator.mediaDevices?.getUserMedia){this.cb.showError("Microphone access is not available in this browser.");return}let t=++this.sessionGen;this.starting=!0,this.threadId=e,this.sessionKey="",this.pendingPcm=[],this.mark=this.cb.getCaret(),this.cb.setRecording(!0);let n;try{n=await navigator.mediaDevices.getUserMedia({audio:!0})}catch{if(t===this.sessionGen)this.starting=!1,this.cb.setRecording(!1),this.cb.showError("Microphone permission denied.");return}if(t!==this.sessionGen||this.cb.getThreadId()!==e){Ct(n);return}if(this.stream=n,await this.stopDrain,t!==this.sessionGen||this.cb.getThreadId()!==e){if(Ct(n),this.stream===n)this.stream=null;return}try{let i=await this.hub.rpc("voice.start",{thread:e,draft:this.cb.getDraft(),caret:this.mark});if(t!==this.sessionGen||this.cb.getThreadId()!==e){if(Ct(n),this.stream===n)this.stream=null;if(!this.active&&!this.starting)this.hub.rpc("voice.stop",{thread:e}).catch(()=>{});return}let s=i.session||(i.path?Os(i.path):"");if(!s)throw Error("Hub did not return a voice session.");this.sessionKey=s,this.activeGen=t,this.starting=!1,this.active=!0,this.startCapture(n,t)}catch(i){if(t===this.sessionGen)this.cleanupAudio(),this.starting=!1,this.active=!1,this.cb.setRecording(!1),this.cb.showError(i instanceof Error?i.message:"Could not start voice dictation.");else if(Ct(n),this.stream===n)this.stream=null}}async stop(){if(!this.active&&!this.starting)return;let e=this.activeGen,t=this.active,n=this.threadId,i=this.sessionKey;this.sessionGen++,this.starting=!1,this.active=!1,this.sessionKey="",this.cb.setRecording(!1),this.cb.setLevel(0),this.cleanupAudio();let r=this.stopDrain.then(async()=>{if(t&&i){let a=new Int16Array(this.pendingPcm);this.pendingPcm=[],this.enqueuePost(i,new Uint8Array(a.buffer),!0,e),await this.postChain}else this.pendingPcm=[];if(t&&n)await this.hub.rpc("voice.stop",{thread:n}).catch(()=>{})});this.stopDrain=r,await r}cancel(){if(!this.active&&!this.starting)return;let e=this.active,t=this.threadId;if(this.abortedGen=Math.max(this.abortedGen,this.sessionGen),this.sessionGen++,this.starting=!1,this.active=!1,this.sessionKey="",this.pendingPcm=[],this.cb.setRecording(!1),this.cb.setLevel(0),this.cleanupAudio(),e&&t&&this.hub.getState()==="connected")this.hub.rpc("voice.stop",{thread:t}).catch(()=>{})}handleFrame(e){let t=String(e.ev??""),n=String(e.thread??"");if(n&&this.cb.getThreadId()&&n!==this.cb.getThreadId())return;if(t==="draft"&&typeof e.text==="string")this.cb.setDraft(e.text),this.mark=e.text.length;else if(t==="edit"){let i=this.cb.getDraft(),s=Number(e.del??0),r=String(e.ins??""),a=Math.max(0,Math.min(i.length,this.mark)),o=Math.max(0,a-s),c=i.slice(0,o)+r+i.slice(a);this.mark=o+r.length,this.cb.setDraft(c)}else if(t==="level")this.cb.setLevel(Math.max(0,Math.min(100,Number(e.v??0))));else if(t==="view"){let i=e.view;if(i&&i.on===!1&&(this.active||this.starting))this.stop()}}startCapture(e,t){let i=new(window.AudioContext||window.webkitAudioContext),s=i.createMediaStreamSource(e),r=i.createScriptProcessor(4096,1,1);r.onaudioprocess=(a)=>{if(!this.active||t!==this.sessionGen||!this.sessionKey)return;let o=Vs(a.inputBuffer.getChannelData(0),i.sampleRate);for(let c=0;c=3200){let c=new Int16Array(this.pendingPcm.splice(0,3200));this.enqueuePost(this.sessionKey,new Uint8Array(c.buffer),!1,t)}},s.connect(r),r.connect(i.destination),this.audioCtx=i,this.processor=r}enqueuePost(e,t,n,i){this.postChain=this.postChain.then(async()=>{if(i<=this.abortedGen)return;try{let s={"Content-Type":"application/octet-stream","X-Voice-Session":e};if(n)s["X-Voice-End"]="1";let r=await fetch("/voice/in",{method:"POST",credentials:"same-origin",headers:s,body:t});if(!r.ok&&!n&&i===this.sessionGen&&this.active)this.failUpload(`Voice upload failed (${r.status}).`)}catch{if(!n&&i===this.sessionGen&&this.active)this.failUpload("Voice upload failed.")}})}failUpload(e){this.abortedGen=Math.max(this.abortedGen,this.sessionGen),this.sessionGen++,this.active=!1,this.starting=!1,this.sessionKey="",this.pendingPcm=[],this.cleanupAudio(),this.cb.setRecording(!1),this.cb.setLevel(0),this.cb.showError(e)}cleanupAudio(){if(this.processor)this.processor.disconnect(),this.processor.onaudioprocess=null,this.processor=null;if(this.audioCtx)this.audioCtx.close().catch(()=>{}),this.audioCtx=null;Ct(this.stream),this.stream=null}}var Di=[3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258],Fi=[0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0],$i=[1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577],Gi=[0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13],Us=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];function kt(e,t){let n=new Int32Array(16),i=0;for(let o=0;o0){if(n[c]++,c>i)i=c}}let s=new Int32Array(16),r=0;for(let o=1;o<=15;o++)s[o]=r,r+=n[o];let a=new Int32Array(r);for(let o=0;o0)a[s[c]++]=o}return{counts:n,symbols:a,maxBits:i}}var Ws=(()=>{let e=new Uint8Array(288);return e.fill(8,0,144),e.fill(9,144,256),e.fill(7,256,280),e.fill(8,280,288),kt(e,288)})(),_s=(()=>{let e=new Uint8Array(32);return e.fill(5),kt(e,32)})();class vn{win=new Uint8Array(32768);winPos=0;feed(e,t=16777216){let n=0,i=0,s=0,r=(p)=>{while(s=e.length)throw Error("truncated deflate frame");i|=e[n++]<>>=p,s-=p,d},a=(p)=>{let d=0,g=0,y=0;for(let m=1;m<=p.maxBits;m++){d|=r(1);let h=p.counts[m];if(d-h{let d=c+p;if(d>t)throw Error("inflated frame exceeds limit");if(d<=o.length)return;let g=o.length;while(g{u(1),o[c++]=p,this.win[this.winPos]=p,this.winPos=this.winPos+1&32767};while(n0){if(n>=e.length&&s<3)break;let p=r(1),d=r(2);if(d===0){if(i=0,s=0,n+4>e.length)throw Error("truncated stored block");let g=e[n]|e[n+1]<<8,y=e[n+2]|e[n+3]<<8;if(n+=4,(g^65535)!==y)throw Error("invalid stored block length");if(n+g>e.length)throw Error("truncated stored payload");u(g);for(let m=0;m=e.length)break}else if(d===1||d===2){let g=Ws,y=_s;if(d===2){let m=r(5)+257,h=r(5)+1,f=r(4)+4,w=new Uint8Array(19);for(let T=0;TA)throw Error("code length overflow");for(let O=0;OA)throw Error("code length overflow");P+=B}else if(T===18){let B=r(7)+11;if(P+B>A)throw Error("code length overflow");P+=B}else throw Error("invalid code length symbol")}g=kt(M,m),y=kt(M.subarray(m),h)}while(!0){let m=a(g);if(m<256)l(m);else if(m===256)break;else{let h=m-257;if(h>=Di.length)throw Error("invalid length symbol");let f=Di[h]+(Fi[h]?r(Fi[h]):0),w=a(y);if(w>=$i.length)throw Error("invalid distance symbol");let C=$i[w]+(Gi[w]?r(Gi[w]):0);u(f);let A=this.winPos-C&32767;for(let M=0;M{this.stateListeners.delete(e)}}onFrame(e){return this.frameListeners.add(e),()=>{this.frameListeners.delete(e)}}onBinary(e){return this.binaryListeners.add(e),()=>{this.binaryListeners.delete(e)}}rpc(e,t={},n=20000){return new Promise((i,s)=>{if(!this.ws||this.ws.readyState!==WebSocket.OPEN){s(Error("Not connected to hub"));return}let r=this.nextId++,a=window.setTimeout(()=>{this.pending.delete(r),s(Error(`RPC timeout: ${e}`))},n);this.pending.set(r,{resolve:i,reject:s,timer:a}),this.ws.send(JSON.stringify({id:r,m:e,p:t}))})}setState(e){this.state=e;for(let t of this.stateListeners)t(e,this.hello)}rejectAllPending(e){for(let[,t]of this.pending)window.clearTimeout(t.timer),t.reject(Error(e));this.pending.clear()}openSocket(){if(this.closed)return;this.inflater=null;let t=`${window.location.protocol==="https:"?"wss:":"ws:"}//${window.location.host}/ws?data=1&enc=json&z=deflate`,n=new WebSocket(t);n.binaryType="arraybuffer",this.ws=n;let i=(s)=>{let r;try{r=JSON.parse(s)}catch{return}if(r.t==="hub.restarting")this.restarting={reason:String(r.reason??""),build:String(r.build??""),text:String(r.text??""),at:Date.now()};if(r.t==="hello")this.restarting=null,this.hello=r,this.features=new Set(this.hello.features??[]),this.inflater=this.hello.z==="deflate"?new vn:null,this.reconnectDelay=500,this.setState("connected");else if(r.t==="reply"&&typeof r.id==="number"){let a=this.pending.get(r.id);if(a)if(this.pending.delete(r.id),window.clearTimeout(a.timer),r.ok)a.resolve(r.result??{});else{let o=r.error,c=typeof o==="string"?o:o&&typeof o==="object"&&("message"in o)?String(o.message):"Request failed",u=typeof r.errorCode==="string"?r.errorCode:void 0,l=typeof r.machine==="string"?r.machine:void 0,p=typeof r.thread==="string"?r.thread:void 0;a.reject(new At(c,{code:u,machine:l,thread:p}))}return}for(let a of this.frameListeners)a(r)};n.addEventListener("message",(s)=>{if(s.data instanceof ArrayBuffer){if(this.inflater){let r;try{r=this.inflater.feed(new Uint8Array(s.data))}catch{n.close();return}if(r.length>0&&r[0]===123)i(this.textDecoder.decode(r));else{let a=r.buffer.slice(r.byteOffset,r.byteOffset+r.byteLength);for(let o of this.binaryListeners)o(a)}return}for(let r of this.binaryListeners)r(s.data);return}if(typeof s.data!=="string")return;i(s.data)}),n.addEventListener("close",(s)=>{if(this.ws===n)this.ws=null;if(this.rejectAllPending("Connection closed"),this.closed)return;if(s.code===4001||s.code===4401||s.code===1008){this.handleRevoked();return}this.probeSessionOrReconnect()}),n.addEventListener("error",()=>{})}async probeSessionOrReconnect(){try{let t=await fetch("/",{method:"GET",credentials:"same-origin",cache:"no-store"});if(t.status===401||t.status===403){this.handleRevoked();return}if(t.ok){if((await t.text()).includes('id="pair-root"')){this.handleRevoked();return}}}catch{}this.setState("reconnecting");let e=this.reconnectDelay;this.reconnectDelay=Math.min(8000,Math.round(this.reconnectDelay*1.6)),this.reconnectTimer=window.setTimeout(()=>{this.reconnectTimer=null,this.openSocket()},e)}handleRevoked(){this.closed=!0,this.setState("revoked"),window.location.replace("/")}}var qs=new TextDecoder;function Oi(e){return e.length>7&&e[0]>=160&&e[0]<=183&&e[1]===1&&e[2]===100&&e[3]===112&&e[4]===108&&e[5]===111&&e[6]===116}function Vi(e){let t=0,n=0;function i(a){if(a<=23)return a;if(a===24){if(t>=e.length)return null;return e[t++]}if(a===25){if(t+2>e.length)return null;let o=e[t]<<8|e[t+1];return t+=2,o}if(a===26){if(t+4>e.length)return null;let o=(e[t]<<24|e[t+1]<<16|e[t+2]<<8|e[t+3])>>>0;return t+=4,o}return null}function s(a){if(n++,a>32||n>400000||t>=e.length)return null;let o=e[t++],c=o>>5,u=i(o&31);if(u===null)return null;switch(c){case 0:return u;case 1:return-1-u;case 2:{if(t+u>e.length)return null;let l=e.subarray(t,t+u);return t+=u,l}case 3:{if(t+u>e.length)return null;let l=qs.decode(e.subarray(t,t+u));return t+=u,l}case 4:{if(u>e.length)return null;let l=Array(u);for(let p=0;p=this.b.length)return this.ok=!1,0;let n=this.b[this.i++],i=7*t;if(i>=28&&(n&240)!==0)return this.ok=!1,0;if(e=(e|(n&127)<>>0,n<128)return e}return this.ok=!1,0}nextI32(){let e=this.nextU32();return e>>>1^-(e&1)}}function Wi(e){let t=0xcbf29ce484222325n,n=0x100000001b3n,i=0xffffffffffffffffn;for(let s=0;stypeof e[m]==="number"?e[m]:h,n=t("l",0),i=t("c",0),s=t("a",255)/255,r=t("m",1),a=t("w",0),o=a/2,c=r===0&&a!==0,u=e.d instanceof Uint8Array?e.d:new Uint8Array(0),l=new Ui(u),p=[],d=[],g=0,y=0;while(l.more()){let m=l.nextU32(),h=p.length,f=1/0,w=1/0,C=-1/0,A=-1/0;if(r===2)g=g+l.nextI32()|0,y=y+l.nextI32()|0,p.push(g,y),f=C=g,w=A=y;else{let P=Math.min(l.nextU32(),1048576);for(let T=0;TC)C=g;if(yA)A=y}}let M=(p.length-h)/2;if(M>0){let P=r===2||M===1?2:r===0?0:1,T=r===0?0:o;d.push({info:m,x0:f-T,y0:w-T,x1:C+T,y1:A+T,at:h,n:M,kind:P})}}return{layer:n,color:i,alpha:s,mode:r,r:o,own:c,pts:new Float32Array(p),pieces:d}}function _i(e,t,n){let i=(a)=>Array.isArray(a)&&a.length>=4?[Number(a[0])||0,Number(a[1])||0,Number(a[2])||0,Number(a[3])||0]:[0,0,0,0],s=Array.isArray(e.cs)?e.cs:[],r=[];for(let a=0;a=0&&o0){n.delete(o.h),n.set(o.h,c);while(n.size>1024){let u=n.keys().next().value;if(u!==void 0)n.delete(u);else break}}}}return{key:typeof e.key==="string"?e.key:"",fam:typeof e.fam==="string"?e.fam:"",base:typeof e.base==="string"?e.base:"",box:i(e.box),edge:i(e.edge),thick:typeof e.thick==="number"?e.thick:1600,note:typeof e.note==="string"?e.note:"",warn:typeof e.warn==="number"?e.warn!==0:!1,chunks:r}}function qi(e,t,n,i=!0){if(n.width<=0||n.height<=0||n.naturalWidth<=0||n.naturalHeight<=0)return null;let s=Math.min(n.width/n.naturalWidth,n.height/n.naturalHeight),r=n.naturalWidth*s,a=n.naturalHeight*s,o=n.left+(n.width-r)/2,c=i?n.top:n.top+(n.height-a)/2,u=(e-o)/r,l=(t-c)/a;if(u<0||u>1||l<0||l>1)return null;return{x:Math.max(0,Math.min(1000,Math.round(u*1000))),y:Math.max(0,Math.min(1000,Math.round(l*1000)))}}var Ki=[["Enter","Enter"],["Tab","Tab"],["Bksp","Backspace"],["Esc","Escape"],["↑","ArrowUp"],["↓","ArrowDown"],["←","ArrowLeft"],["→","ArrowRight"]];function zi(e){let t=e.trim();if(!t)return"";if(/^[a-zA-Z][a-zA-Z0-9+.-]*:/.test(t))return t;return`https://${t}`}class wn{tail=Promise.resolve();enqueue(e){let t=this.tail.then(e,e);return this.tail=t.catch(()=>{}),t}}function Ji(e,t,n){let i=!0,s=!1,r=!1,a="",o=!1,c=!1,u=-1,l=null,p=new wn,d=document.createElement("div");d.className="bp-pane bp-browser-pane",d.setAttribute("data-testid","pane-browser");let g=document.createElement("div");g.className="bp-pane-bar bp-browser-nav";function y(X,ce,E){let k=document.createElement("button");if(k.type="button",k.className="bp-v-btn",k.textContent=X,k.setAttribute("data-testid",ce),E)k.title=E;return k}let m=y("←","browser-back","Back"),h=y("→","browser-forward","Forward"),f=y("↻","browser-reload","Reload"),w=document.createElement("form");w.className="bp-browser-url-form";let C=document.createElement("input");C.type="text",C.className="bp-browser-input",C.placeholder="https://…",C.autocomplete="off",C.spellcheck=!1,C.setAttribute("data-testid","browser-url");let A=y("Go","browser-go","Navigate");A.type="submit",w.append(C,A);let M=y("Take over","browser-takeover");M.classList.add("is-primary"),g.append(m,h,f,w,M);let P=document.createElement("div");P.className="bp-browser-drive-bar",P.hidden=!0;let T=document.createElement("div");T.className="bp-browser-keys-row";let B=document.createElement("input");B.type="text",B.className="bp-browser-input",B.placeholder="Type text or press Enter/Tab/Arrows…",B.autocomplete="off",B.spellcheck=!1,B.setAttribute("data-testid","browser-keys");let R=y("Send","browser-type-send");T.append(B,R);let O=document.createElement("div");O.className="bp-browser-quick-keys";for(let[X,ce]of Ki){let E=y(X,`browser-key-${ce}`);E.addEventListener("click",()=>he("press",{key:ce})),O.append(E)}P.append(T,O);let H=document.createElement("div");H.className="bp-browser-err",H.setAttribute("data-testid","browser-error"),H.hidden=!0;let ae=document.createElement("div");ae.className="bp-browser-stage",ae.setAttribute("data-testid","browser-stage");let ue=document.createElement("img");ue.className="bp-browser-img",ue.alt="Hub browser screen",ue.draggable=!1,ue.hidden=!0,ue.setAttribute("data-testid","browser-frame");let oe=document.createElement("div");oe.className="bp-pane-empty",oe.setAttribute("data-testid","browser-empty"),oe.textContent="Loading browser screen…",ae.append(ue,oe);let we=document.createElement("div");we.className="bp-browser-hint",we.textContent="You have the page: click to tap, scroll to wheel, type in the key box. Hand it back when done.",we.hidden=!0,d.append(g,P,H,ae,we),e.replaceChildren(d);function Le(X){H.textContent=X,H.hidden=!X}function Ne(){P.hidden=!s,we.hidden=!s,M.textContent=s?"Hand back":"Take over",M.setAttribute("data-testid",s?"browser-handback":"browser-takeover"),M.classList.toggle("is-on",s),ue.classList.toggle("is-driving",s)}function he(X,ce={},E){p.enqueue(async()=>{if(!i)return;Le("");try{if(await t.hub.rpc("browser",{thread:n,op:X,...ce}),!i)return;E?.(),le()}catch(k){if(!i)return;Le(k instanceof Error?k.message:String(k))}})}function be(X){he("toolbar",{command:X},()=>{s=!0,Ne()})}m.addEventListener("click",()=>be("back")),h.addEventListener("click",()=>be("forward")),f.addEventListener("click",()=>be("reload")),w.addEventListener("submit",(X)=>{X.preventDefault();let ce=zi(C.value);if(!ce)return;if(C.value=ce,!s)he("takeover",{},()=>{s=!0,Ne()});he("navigate",{url:ce},()=>{s=!0,Ne()})}),M.addEventListener("click",()=>{if(s)he("handback",{},()=>{s=!1,Ne()});else he("takeover",{},()=>{s=!0,Ne(),B.focus()})});function I(){let X=B.value;if(!X)return;B.value="",he("type",{text:X})}R.addEventListener("click",I),B.addEventListener("keydown",(X)=>{if(!s)return;if(X.key==="Enter"){if(X.preventDefault(),B.value)I();he("press",{key:"Enter"});return}if(X.key==="Tab"||X.key==="Escape"||X.key==="ArrowUp"||X.key==="ArrowDown"||X.key==="ArrowLeft"||X.key==="ArrowRight"||X.key==="Backspace"&&B.value==="")X.preventDefault(),he("press",{key:X.key})}),ue.addEventListener("click",(X)=>{if(!s||!r)return;let ce=ue.getBoundingClientRect(),E=qi(X.clientX,X.clientY,{left:ce.left,top:ce.top,width:ce.width,height:ce.height,naturalWidth:ue.naturalWidth,naturalHeight:ue.naturalHeight});if(!E)return;he("click",E)}),ue.addEventListener("wheel",(X)=>{if(!s||!r)return;X.preventDefault();let ce=Math.round(X.deltaX),E=Math.round(X.deltaY);if(ce===0&&E===0)return;he("scroll",{dx:ce,dy:E})},{passive:!1});async function le(){if(!i)return;if(o){c=!0;return}o=!0;try{do{c=!1,l=new AbortController;let X=await fetch(`/bots/${encodeURIComponent(n)}/screen.jpg`,{credentials:"same-origin",cache:"no-store",signal:l.signal});if(!i)return;if(X.ok){let ce=await X.blob();if(!i)return;let E=URL.createObjectURL(ce),k=a;if(a=E,ue.src=E,ue.hidden=!1,oe.hidden=!0,r=!0,k)URL.revokeObjectURL(k)}else if(!r)ue.hidden=!0,oe.hidden=!1,oe.textContent="No browser page yet. An agent opens one when it needs the web."}while(i&&c)}catch{if(!i)return;if(!r)ue.hidden=!0,oe.hidden=!1,oe.textContent="No browser page yet. An agent opens one when it needs the web."}finally{l=null,o=!1}}let ne=t.hub.onFrame((X)=>{if(!i)return;if(X.t==="shot"&&X.bot===n){if(typeof X.n==="number"){if(X.n===u)return;u=X.n}le()}});return le(),{destroy(){if(i=!1,ne(),l?.abort(),a)URL.revokeObjectURL(a),a=""}}}function q(e,t,n){let i=document.createElement(e);if(t)i.className=t;if(n!==void 0)i.textContent=n;return i}function Vt(e){if(!Number.isFinite(e)||e<0)return"";if(e<1024)return`${e} B`;if(e<1048576)return`${Math.round(e/1024)} KB`;return`${(e/1048576).toFixed(1)} MB`}function Xi(e){let t=e.lastIndexOf(".");return t>=0?e.slice(t+1).toLowerCase():""}function zs(e){return["png","jpg","jpeg","gif","webp","svg","bmp","ico"].includes(e)}function Yi(e){return["txt","md","markdown","json","toml","yaml","yml","xml","csv","tsv","rs","ts","tsx","js","mjs","cjs","jsx","css","html","htm","sh","bash","py","c","h","cc","cpp","hpp","go","java","kt","swift","rb","lua","sql","ini","cfg","conf","env","gitignore","lock","log","gbr","gtl","gbl","gts","gbs","gto","gbo","gm1","drl","pos","net","kicad_pro","kicad_prl","kicad_dru","kicad_sym","kicad_mod","kicad_wks"].includes(e)}function Js(e){let t=Xi(e);if(t==="kicad_pcb")return"board";if(t==="kicad_sch")return"schematic";if(t==="step"||t==="stp"||t==="glb")return"mech";return null}function Zi(e,t,n,i){let s=!0,r="",a="",o=q("div","bp-pane bp-files-pane");o.setAttribute("data-testid","pane-files");let c=q("div","bp-pane-bar"),u=q("div","bp-files-crumbs"),l=q("button","bp-v-btn","Refresh");l.type="button",l.addEventListener("click",()=>void h(r)),c.append(u,l);let p=q("div","bp-files-split"),d=q("div","bp-files-list");d.setAttribute("data-testid","files-list");let g=q("div","bp-files-preview");g.setAttribute("data-testid","files-preview"),g.append(q("div","bp-pane-empty","Select a file to preview")),p.append(d,g),o.append(c,p),e.replaceChildren(o);function y(){u.replaceChildren();let f=q("button","bp-crumb-btn","project");if(f.type="button",f.addEventListener("click",()=>void h("")),u.append(f),!r)return;let w=r.split("/").filter(Boolean),C="";for(let A of w){C=C?`${C}/${A}`:A;let M=C;u.append(q("span","bp-vh-sep","/"));let P=q("button","bp-crumb-btn",A);P.type="button",P.addEventListener("click",()=>void h(M)),u.append(P)}}async function m(f,w,C){a=f,g.replaceChildren();let A=q("div","bp-files-prev-head");A.append(q("span","bp-files-prev-name",f));let M=q("div","bp-files-prev-acts"),P=Js(w);if(P){let O=q("button","bp-v-btn is-primary",`Open in ${P}`);O.type="button",O.setAttribute("data-testid","files-open-viewer"),O.addEventListener("click",()=>i(P,f)),M.append(O)}let T=`/files/get?thread=${encodeURIComponent(n)}&path=${encodeURIComponent(f)}`,B=q("a","bp-v-btn","Download");B.href=T,B.download=w,M.append(B),A.append(M),g.append(A);let R=Xi(w);if(zs(R)){let O=q("div","bp-files-img-wrap"),H=document.createElement("img");H.className="bp-files-img",H.alt=w,H.src=T,O.append(H),g.append(O);return}if(C>524288&&!Yi(R)){g.append(q("div","bp-pane-empty",`Binary file (${Vt(C)}). Use Download to save.`));return}if(Yi(R)||C<=65536){let O=q("div","bp-pane-empty","Loading…");g.append(O);try{let H=await fetch(T,{credentials:"same-origin"});if(!s||a!==f)return;if(!H.ok){O.textContent=`Could not load file (${H.status})`;return}if((H.headers.get("content-type")||"").startsWith("image/")){O.remove();let ne=document.createElement("img");ne.className="bp-files-img",ne.alt=w,ne.src=T,g.append(ne);return}let ue=262144,oe=[],we=0,Le=!1;if(H.body){let ne=H.body.getReader();try{while(!0){let{done:X,value:ce}=await ne.read();if(X||!ce)break;if(we+ce.byteLength>ue){let E=ue-we;if(E>0)oe.push(ce.subarray(0,E)),we+=E;Le=!0,await ne.cancel();break}oe.push(ce),we+=ce.byteLength}}finally{ne.releaseLock()}}if(!s||a!==f)return;let Ne=new Uint8Array(we),he=0;for(let ne of oe)Ne.set(ne,he),he+=ne.byteLength;let be=!1;for(let ne=0;neA.dir===M.dir?A.name.localeCompare(M.name):A.dir?-1:1),d.replaceChildren(),f){let A=q("button","bp-file-row is-dir");A.type="button",A.append(q("span","bp-file-icon","↰"),q("span","bp-file-name",".."));let M=f.includes("/")?f.slice(0,f.lastIndexOf("/")):"";A.addEventListener("click",()=>void h(M)),d.append(A)}if(C.length===0){d.append(q("div","bp-pane-empty","Empty folder"));return}for(let A of C){let M=f?`${f}/${A.name}`:A.name,P=q("button","bp-file-row"+(A.dir?" is-dir":"")+(M===a?" is-sel":""));P.type="button",P.setAttribute("data-testid",`file-row-${A.name}`),P.append(q("span","bp-file-icon",A.dir?"▸":"·"),q("span","bp-file-name",A.name),q("span","bp-file-size",A.dir?"":Vt(A.size))),P.addEventListener("click",()=>{if(A.dir)h(M);else d.querySelectorAll(".bp-file-row.is-sel").forEach((T)=>T.classList.remove("is-sel")),P.classList.add("is-sel"),m(M,A.name,A.size)}),d.append(P)}}catch(w){if(!s)return;d.replaceChildren(q("div","bp-pane-empty",w instanceof Error?w.message:String(w)))}}return h(""),{destroy(){s=!1}}}function Qi(e,t,n){let i=!0,s=q("div","bp-pane bp-diff-pane");s.setAttribute("data-testid","pane-diff");let r=q("div","bp-pane-bar"),a=q("span","bp-diff-summary","Loading diff…"),o=q("button","bp-v-btn","Refresh");o.type="button",o.addEventListener("click",()=>void u()),r.append(a,o);let c=q("div","bp-diff-body");c.setAttribute("data-testid","diff-body"),s.append(r,c),e.replaceChildren(s);async function u(){a.textContent="Loading diff…",c.replaceChildren();try{let l=await t.hub.rpc("viewer.diff",{thread:n});if(!i)return;if(l?.nogit){a.textContent="Not a git repository",c.append(q("div","bp-pane-empty","This project is not a git repository."));return}let p=typeof l?.diff==="string"?l.diff:"";if(!p.trim()){a.textContent="Clean working tree",c.append(q("div","bp-pane-empty","No uncommitted changes."));return}let d=p.split(` +`),g=0,y=0,m=0,h=document.createDocumentFragment(),f=q("div","bp-diff-file");for(let w of d){if(w.startsWith("diff --git ")){if(f.childNodes.length>0)h.append(f);f=q("div","bp-diff-file"),g++;let C=w.match(/ b\/(.+)$/);f.append(q("div","bp-diff-file-head",C?C[1]:w));continue}if(w.startsWith("index ")||w.startsWith("--- ")||w.startsWith("+++ "))f.append(q("div","bp-diff-line is-meta",w));else if(w.startsWith("@@"))f.append(q("div","bp-diff-line is-hunk",w));else if(w.startsWith("+"))y++,f.append(q("div","bp-diff-line is-add",w));else if(w.startsWith("-"))m++,f.append(q("div","bp-diff-line is-del",w));else f.append(q("div","bp-diff-line",w))}if(f.childNodes.length>0)h.append(f);a.textContent=`${g||1} file${g===1?"":"s"} · +${y} -${m}`,c.append(h)}catch(l){if(!i)return;a.textContent="Diff unavailable",c.append(q("div","bp-pane-empty",l instanceof Error?l.message:String(l)))}}return u(),{destroy(){i=!1}}}function es(e,t,n){let i=!0,s="checks",r=q("div","bp-pane bp-review-pane");r.setAttribute("data-testid","pane-review");let a=q("div","bp-pane-bar"),o=q("div","bp-review-tabs"),c=q("button","bp-v-btn is-on","Checks"),u=q("button","bp-v-btn","BOM"),l=q("button","bp-v-btn","Comments");c.type=u.type=l.type="button",o.append(c,u,l);let p=q("button","bp-v-btn","Refresh");p.type="button",p.addEventListener("click",()=>void m()),a.append(o,p);let d=q("div","bp-review-body");d.setAttribute("data-testid","review-body"),r.append(a,d),e.replaceChildren(r);function g(h){s=h,c.classList.toggle("is-on",s==="checks"),u.classList.toggle("is-on",s==="bom"),l.classList.toggle("is-on",s==="comments"),m()}c.addEventListener("click",()=>g("checks")),u.addEventListener("click",()=>g("bom")),l.addEventListener("click",()=>g("comments"));function y(h){let f=q("div","bp-review-md"),w=h.split(` +`),C=0;while(C{T.preventDefault();let B=M.value.trim();if(!B)return;P.disabled=!0,t.hub.rpc("review.comment",{thread:n,text:B}).then(()=>{M.value="",P.disabled=!1,m()},()=>{P.disabled=!1})}),d.append(A),C.length===0){d.append(q("div","bp-pane-empty","No review comments yet."));return}for(let T of C){let B=q("div","bp-review-comment"+(T.resolved?" is-resolved":"")),R=[T.by||"review",T.file,T.layer,T.item].filter(Boolean).join(" · ");B.append(q("div","bp-review-comment-meta",R),q("div","bp-review-comment-text",T.text)),d.append(B)}return}let h=await t.hub.rpc("review.page",{thread:n,page:s});if(!i)return;let f=h?.report||{};if(d.replaceChildren(),f.line||f.gate){let w=q("div","bp-review-gate",[f.gate,f.line].filter(Boolean).join(" · "));d.append(w)}if(f.err)d.append(q("div","bp-review-err",f.err));if(Array.isArray(f.tasks)&&f.tasks.length>0){let w=q("div","bp-review-tasks");f.tasks.forEach((C,A)=>{let M=q("label","bp-review-task"),P=document.createElement("input");P.type="checkbox",P.checked=!!(C.done??C.checked);let T=typeof C.index==="number"?C.index:A;P.addEventListener("change",()=>{t.hub.rpc("review.tick",{thread:n,index:T}).then(()=>void m(),()=>{})}),M.append(P,q("span",void 0,C.text||C.label||`Item ${A+1}`)),w.append(M)}),d.append(w)}if(f.md&&f.md.trim())d.append(y(f.md));else if(!f.err&&(!f.tasks||f.tasks.length===0))d.append(q("div","bp-pane-empty",`No ${s==="bom"?"BOM":"design checks"} report available.`))}catch(h){if(!i)return;d.replaceChildren(q("div","bp-pane-empty",h instanceof Error?h.message:String(h)))}}return m(),{destroy(){i=!1}}}function ts(e,t){let n=e>>>16&255,i=e>>>8&255,s=e&255;return t>=0.999?`rgb(${n},${i},${s})`:`rgba(${n},${i},${s},${t.toFixed(3)})`}class En{canvas;ctx;frame=null;masks={off:0,dim:0,lift:255};highlights=new Set;lightTheme=!1;cx=0;cy=0;scale=0.0001;fittedKey="";fitW=0;fitH=0;userMoved=!1;dirty=!1;rafId=0;pointers=new Map;dragStart=null;pinchStart=null;resizeObs;cbs;constructor(e,t={}){this.cbs=t,this.canvas=document.createElement("canvas"),this.canvas.className="bp-viewer-canvas",this.canvas.style.width="100%",this.canvas.style.height="100%",this.canvas.style.display="block",this.canvas.style.touchAction="none",e.appendChild(this.canvas);let n=this.canvas.getContext("2d");if(!n)throw Error("Canvas2D unavailable");this.ctx=n,this.resizeObs=new ResizeObserver(()=>this.scheduleDraw()),this.resizeObs.observe(this.canvas),this.canvas.addEventListener("pointerdown",this.onPointerDown),this.canvas.addEventListener("pointermove",this.onPointerMove),this.canvas.addEventListener("pointerup",this.onPointerUp),this.canvas.addEventListener("pointercancel",this.onPointerUp),this.canvas.addEventListener("wheel",this.onWheel,{passive:!1}),this.canvas.addEventListener("dblclick",this.onDblClick)}setTheme(e){if(this.lightTheme!==e)this.lightTheme=e,this.scheduleDraw()}setFrame(e){if(this.frame=e,e&&e.key!==this.fittedKey)this.fittedKey=e.key,this.fit();else this.scheduleDraw()}setLayers(e){this.masks=e,this.scheduleDraw()}setHighlights(e){this.highlights.clear();for(let[t,n]of e)this.highlights.add(`${t}:${n}`);this.scheduleDraw()}presentMask(){if(!this.frame)return 0;let e=0;for(let t of this.frame.chunks)if(t.layer<32)e=(e|1<>>0;return e>>>0}presentColors(){let e=new Map;if(!this.frame)return e;for(let t of this.frame.chunks)if(!e.has(t.layer))e.set(t.layer,t.color);return e}applyFit(e,t){if(!this.frame||e<10||t<10)return;let n=this.frame.box,i=Math.max(n[2]-n[0],1000),s=Math.max(n[3]-n[1],1000);this.cx=(n[0]+n[2])*0.5,this.cy=(n[1]+n[3])*0.5,this.scale=Math.min(e/i,t/s)*0.92,this.fitW=e,this.fitH=t,this.userMoved=!1}fit(){if(!this.frame)return;this.userMoved=!1,this.fitW=0,this.fitH=0;let e=this.canvas.getBoundingClientRect();if(e.width>=10&&e.height>=10)this.applyFit(e.width,e.height);this.scheduleDraw()}zoomToBoxMm(e){let t=e[0]*1000,n=e[1]*1000,i=e[2]*1000,s=e[3]*1000,r=Math.max(i-t,1000),a=Math.max(s-n,1000),o=this.canvas.getBoundingClientRect(),c=Math.max(o.width,200),u=Math.max(o.height,200);this.cx=(t+i)*0.5,this.cy=(n+s)*0.5,this.scale=Math.min(c/r,u/a)*0.85,this.userMoved=!0,this.scheduleDraw()}scheduleDraw(){if(this.dirty)return;this.dirty=!0,this.rafId=requestAnimationFrame(()=>{this.dirty=!1,this.rafId=0,this.draw()})}draw(){let e=this.canvas.getBoundingClientRect(),t=Math.max(1,Math.round(e.width)),n=Math.max(1,Math.round(e.height)),i=Math.min(window.devicePixelRatio||1,2),s=Math.round(t*i),r=Math.round(n*i);if(this.canvas.width!==s||this.canvas.height!==r)this.canvas.width=s,this.canvas.height=r;let a=this.ctx;a.setTransform(i,0,0,i,0,0),a.fillStyle=this.lightTheme?"#f5f4ef":"#08090b",a.fillRect(0,0,t,n);let o=this.frame;if(!o)return;if(!this.userMoved&&t>=10&&n>=10&&(Math.abs(this.fitW-t)>2||Math.abs(this.fitH-n)>2))this.applyFit(t,n);let c=t*0.5,u=n*0.5,l=this.scale,p=this.cx,d=this.cy,g=p-c/l,y=p+c/l,m=d-u/l,h=d+u/l,{off:f,dim:w,lift:C}=this.masks,A=[],M=[];for(let T=0;T>>B&1)===1)continue;if(B===C)M.push(T);else A.push(T)}let P=A.concat(M);a.lineCap="round",a.lineJoin="round";for(let T=0;T>>R.layer&1)===1,H=R.alpha*(O?0.25:1);if(H<=0.01)continue;this.drawChunk(a,R,H,g,m,y,h,p,d,l,c,u)}if(this.highlights.size>0){a.fillStyle=this.lightTheme?"rgba(245,244,239,0.72)":"rgba(8,9,11,0.72)",a.fillRect(0,0,t,n);let T=this.lightTheme?"rgba(27,29,33,0.77)":"rgba(217,221,228,0.77)";for(let B=0;Br||h.y1a)continue;if(h.n<3)continue;let f=(d[h.at]-o)*u+l,w=(d[h.at+1]-c)*u+p;e.moveTo(f,w);for(let C=1;C0)e.fill()}else if(t.mode===2){let y=Math.max(0.75,t.r*u);e.fillStyle=g,e.beginPath();let m=0;for(let h=0;hr||f.y1a)continue;let w=(d[f.at]-o)*u+l,C=(d[f.at+1]-c)*u+p;e.moveTo(w+y,C),e.arc(w,C,y,0,Math.PI*2),m++}if(m>0)e.fill()}else{e.strokeStyle=g,e.lineWidth=Math.max(1,t.r*2*u),e.beginPath();let y=0;for(let m=0;mr||h.y1a)continue;let f=(d[h.at]-o)*u+l,w=(d[h.at+1]-c)*u+p;if(h.n===1)e.moveTo(f,w),e.lineTo(f+0.01,w);else{e.moveTo(f,w);for(let C=1;C0)e.stroke()}}drawLitPieces(e,t,n,i,s,r,a,o,c,u,l,p,d){let g=t.pts,y=ts(t.color,t.alpha);for(let m=0;ma||h.y1o)continue;let f=(g[h.at]-c)*l+p,w=(g[h.at+1]-u)*l+d;if(h.kind===2){let C=Math.max(1.5,t.r*l);e.fillStyle=y,e.beginPath(),e.arc(f,w,C,0,Math.PI*2),e.fill(),e.strokeStyle=i,e.lineWidth=1.5,e.stroke()}else if(h.kind===0&&h.n>=3){e.fillStyle=y,e.beginPath(),e.moveTo(f,w);for(let C=1;C=0;l--){let p=n.chunks[l];if(p.layer<32&&(u>>>p.layer&1)===1)continue;for(let d=0;dg.x1+a||rg.y1+a)continue;let y=(g.x1-g.x0+1)*(g.y1-g.y0+1);if(y{if(this.canvas.setPointerCapture(e.pointerId),this.pointers.set(e.pointerId,{x:e.clientX,y:e.clientY}),this.pointers.size===1)this.dragStart={x:e.clientX,y:e.clientY,cx:this.cx,cy:this.cy,moved:!1},this.pinchStart=null;else if(this.pointers.size===2){let[t,n]=Array.from(this.pointers.values());this.pinchStart={dist:Math.hypot(n.x-t.x,n.y-t.y)||1,midX:(t.x+n.x)*0.5,midY:(t.y+n.y)*0.5,scale:this.scale,cx:this.cx,cy:this.cy},this.dragStart=null}};onPointerMove=(e)=>{if(!this.pointers.has(e.pointerId))return;if(this.pointers.set(e.pointerId,{x:e.clientX,y:e.clientY}),this.pointers.size===2&&this.pinchStart){let[t,n]=Array.from(this.pointers.values()),i=Math.hypot(n.x-t.x,n.y-t.y)||1,s=(t.x+n.x)*0.5,r=(t.y+n.y)*0.5,a=i/this.pinchStart.dist,o=Math.max(0.0000001,Math.min(2,this.pinchStart.scale*a)),c=this.canvas.getBoundingClientRect(),u=this.pinchStart.midX-c.left-c.width*0.5,l=this.pinchStart.midY-c.top-c.height*0.5,p=s-c.left-c.width*0.5,d=r-c.top-c.height*0.5;this.scale=o,this.cx=this.pinchStart.cx+u/this.pinchStart.scale-p/o,this.cy=this.pinchStart.cy+l/this.pinchStart.scale-d/o,this.userMoved=!0,this.cbs.onUserMove?.(),this.scheduleDraw();return}if(this.dragStart&&this.pointers.size===1){let t=e.clientX-this.dragStart.x,n=e.clientY-this.dragStart.y;if(Math.hypot(t,n)>3)this.dragStart.moved=!0;if(this.dragStart.moved)this.cx=this.dragStart.cx-t/this.scale,this.cy=this.dragStart.cy-n/this.scale,this.userMoved=!0,this.cbs.onUserMove?.(),this.scheduleDraw()}};onPointerUp=(e)=>{let t=this.dragStart&&!this.dragStart.moved&&this.pointers.size===1;if(this.pointers.delete(e.pointerId),this.pointers.size<2)this.pinchStart=null;if(this.pointers.size===0)this.dragStart=null;if(t&&this.cbs.onPick){let n=this.canvas.getBoundingClientRect(),i=this.hitTest(e.clientX-n.left,e.clientY-n.top);this.cbs.onPick(i)}};onWheel=(e)=>{e.preventDefault();let t=this.canvas.getBoundingClientRect(),n=e.clientX-t.left-t.width*0.5,i=e.clientY-t.top-t.height*0.5,s=e.deltaY<0?1.16:0.8620689655172414,r=Math.max(0.0000001,Math.min(2,this.scale*s));this.cx+=n/this.scale-n/r,this.cy+=i/this.scale-i/r,this.scale=r,this.userMoved=!0,this.cbs.onUserMove?.(),this.scheduleDraw()};onDblClick=()=>{this.fit()};destroy(){if(this.rafId)cancelAnimationFrame(this.rafId);this.resizeObs.disconnect(),this.canvas.removeEventListener("pointerdown",this.onPointerDown),this.canvas.removeEventListener("pointermove",this.onPointerMove),this.canvas.removeEventListener("pointerup",this.onPointerUp),this.canvas.removeEventListener("pointercancel",this.onPointerUp),this.canvas.removeEventListener("wheel",this.onWheel),this.canvas.removeEventListener("dblclick",this.onDblClick),this.canvas.remove()}}var ns=[{id:"fit",label:"Fit"},{id:"iso",label:"Iso"},{id:"top",label:"Top"},{id:"bottom",label:"Bottom"},{id:"front",label:"Front"},{id:"right",label:"Right"},{id:"back",label:"Back"},{id:"left",label:"Left"}];function is(e){switch(e){case"top":return{yaw:0,pitch:Math.PI*0.499};case"bottom":return{yaw:0,pitch:-Math.PI*0.499};case"front":return{yaw:0,pitch:0};case"right":return{yaw:Math.PI*0.5,pitch:0};case"back":return{yaw:Math.PI,pitch:0};case"left":return{yaw:-Math.PI*0.5,pitch:0};case"iso":case"fit":default:return{yaw:0.6,pitch:0.7}}}function xn(e,t,n,i){if(!e||!t||!n||!i)return!1;if(!e.startsWith(t))return!1;let s=e.slice(t.length).split(` +`),r=(s[0]||"").split("\t");if(r[0]!=="git"||r[2]!==n)return!1;let a=s[1]||r.slice(4).join("\t");if(!a)return!1;let o=a.replace(/\\/g,"/"),c=i.replace(/\\/g,"/");if(c.startsWith("/")||/^[A-Za-z]:\//.test(c))return o===c;return o===c||o.endsWith(`/${c}`)}class Cn{refs=[];index=-1;lastCommit="";highlightEdits=!1;playing=!1;setRefs(e){if(this.refs=e,this.index>=e.length)this.index=-1,this.highlightEdits=!1}isLive(){return this.index<0||this.index>=this.refs.length}activeRef(){return this.isLive()?null:this.refs[this.index]}step(e){if(this.refs.length===0)return!1;let t=this.index;if(e>0)this.index=Math.min(this.refs.length-1,this.index+1);else this.index=Math.max(-1,this.index-1);if(this.index===-1)this.playing=!1,this.highlightEdits=!1;else this.lastCommit=this.refs[this.index].commit,this.highlightEdits=!0;return this.index!==t}selectCommit(e){if(!e)return this.goLive();let t=this.refs.findIndex((i)=>i.commit===e);if(t<0)return!1;let n=this.index!==t||!this.highlightEdits;return this.index=t,this.lastCommit=e,this.highlightEdits=!0,n}goLive(){let e=this.index!==-1||this.playing||this.highlightEdits;return this.index=-1,this.playing=!1,this.highlightEdits=!1,e}toggleHighlight(){if(this.highlightEdits)return this.goLive(),!1;if(this.refs.length===0)return!1;let e=this.lastCommit?this.refs.findIndex((t)=>t.commit===this.lastCommit):0;return this.index=e>=0?e:0,this.lastCommit=this.refs[this.index].commit,this.highlightEdits=!0,!0}compareRequest(){let e=this.activeRef();if(!e||!this.highlightEdits)return null;return{commit:e.commit,bits:0}}}var Ys=`#version 300 es precision highp float; out vec2 vUv; void main() { @@ -18,7 +18,7 @@ void main() { vUv = vec2(x * 0.5 + 0.5, 1.0 - (y * 0.5 + 0.5)); gl_Position = vec4(x, y, 0.0, 1.0); } -`,Js=`#version 300 es +`,Xs=`#version 300 es precision highp float; in vec2 vUv; uniform vec3 uBgTop; @@ -35,7 +35,7 @@ void main() { vec3 lin = mix(uBgTop, uBgBot, clamp(vUv.y, 0.0, 1.0)); outColor = vec4(linearToSrgb(clamp(lin, 0.0, 1.0)), 1.0); } -`,Ys=`#version 300 es +`,Zs=`#version 300 es precision highp float; layout(location = 0) in vec3 aPos; layout(location = 1) in vec3 aNrm; @@ -53,7 +53,7 @@ void main() { vCol = aCol; gl_Position = uMvp * vec4(aPos, 1.0); } -`,Xs=`#version 300 es +`,Qs=`#version 300 es precision highp float; in vec3 vPos; in vec3 vNrm; @@ -149,8 +149,8 @@ void main() { rgb = rgb / (vec3(1.0) + max(rgb - vec3(0.8), vec3(0.0)) * 0.28); outColor = vec4(linearToSrgb(clamp(rgb, 0.0, 1.0)), alpha * uFade); } -`;function qe(e){let t=e/255;return t<=0.04045?t/12.92:Math.pow((t+0.055)/1.055,2.4)}var Zs=[qe(77),qe(83),qe(94)],Qs=[qe(53),qe(58),qe(67)],er=[qe(245),qe(246),qe(248)],tr=[qe(225),qe(228),qe(233)];function is(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 ss(e,t,n){let i=is(e,e.VERTEX_SHADER,t),s=is(e,e.FRAGMENT_SHADER,n),r=e.createProgram();if(!r)throw Error("createProgram failed");if(e.attachShader(r,i),e.attachShader(r,s),e.linkProgram(r),e.deleteShader(i),e.deleteShader(s),!e.getProgramParameter(r,e.LINK_STATUS)){let a=e.getProgramInfoLog(r)||"program link error";throw e.deleteProgram(r),Error(a)}return r}function nr(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 ir(e,t,n,i){let s=1/Math.tan(e*0.5),r=1/(n-i),a=new Float32Array(16);return a[0]=s/t,a[5]=s,a[10]=(i+n)*r,a[11]=-1,a[14]=2*i*n*r,a}function rs(e){let t=Math.hypot(e[0],e[1],e[2])||1;return[e[0]/t,e[1]/t,e[2]/t]}function as(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 Cn(e,t){return e[0]*t[0]+e[1]*t[1]+e[2]*t[2]}class kn{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=ss(n,zs,Js),this.bgVao=n.createVertexArray(),this.uBgTop=n.getUniformLocation(this.bgProg,"uBgTop"),this.uBgBot=n.getUniformLocation(this.bgProg,"uBgBot"),this.prog=ss(n,Ys,Xs),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=Ui(e.mesh),this.clearParts(),this.cbs.onStatus?.("Building 3D model…");let n=new Uint8Array(e.mesh),i=e.faces instanceof Uint8Array?new Uint8Array(e.faces):void 0,s=[n.buffer];if(i)s.push(i.buffer);this.worker?.postMessage({id:this.nextJobId++,kind:"solid",key:t,n:e.n,mesh:n,faces:i},s);return}if(e.parts&&typeof e.parts==="object"&&!Array.isArray(e.parts)&&!(e.parts instanceof Uint8Array)){if(this.activeKey&&t!==this.activeKey)return;if(this.activeKey=t,this.clearParts(),this.partsTotal=typeof e.parts.of==="number"?e.parts.of:0,this.partsDone=0,this.partsTotal>0)this.cbs.onStatus?.(`Loading parts 0/${this.partsTotal}…`);this.scheduleDraw();return}if(typeof e.part==="string"&&e.mesh instanceof Uint8Array&&e.at instanceof Uint8Array&&typeof e.n==="number"){if(this.activeKey&&t!==this.activeKey)return;let n=new Uint8Array(e.mesh),i=new Uint8Array(e.at),s=e.faces instanceof Uint8Array?new Uint8Array(e.faces):void 0,r=[n.buffer,i.buffer];if(s)r.push(s.buffer);this.worker?.postMessage({id:this.nextJobId++,kind:"part",key:t,partId:e.part,n:e.n,mesh:n,at:i,faces:s,refs:Array.isArray(e.refs)?e.refs:[],done:typeof e.done==="number"?e.done:0},r)}}onWorkerMessage(e){if(e.error){this.cbs.onStatus?.(e.error);return}if(e.key!==this.activeKey||!this.gl)return;if(e.kind==="solid")this.deleteBatch(this.boardBatch),this.boardBatch=this.uploadBatch(e.positions,e.normals,e.colors,0),this.center=[e.center[0],e.center[1],e.center[2]],this.target=[e.center[0],e.center[1],e.center[2]],this.radius=e.radius,this.fit(),this.cbs.onStatus?.(""),this.scheduleDraw();else if(e.kind==="part"){let t=this.uploadBatch(e.positions,e.normals,e.colors,performance.now());if(t)this.partBatches.push(t);if(this.partsDone=e.done||this.partsDone+1,this.partsTotal>0&&this.partsDone>>24===0)r++;else a++;let o=r>0?new Float32Array(r*9):null,c=r>0?new Float32Array(r*9):null,u=r>0?new Float32Array(r*12):null,l=a>0?new Float32Array(a*9):null,p=a>0?new Float32Array(a*9):null,d=a>0?new Float32Array(a*12):null,g=0,y=0;for(let f=0;f>>24&255,A=1-C/255,M=(w>>>16&255)/255,S=(w>>>8&255)/255,T=(w&255)/255,B=f*9;if(C===0&&o&&c&&u){let R=g*9;for(let H=0;H<9;H++)o[R+H]=e[B+H],c[R+H]=t[B+H];let O=g*12;for(let H=0;H<3;H++)u[O+H*4]=M,u[O+H*4+1]=S,u[O+H*4+2]=T,u[O+H*4+3]=1;g++}else if(l&&p&&d){let R=y*9;for(let H=0;H<9;H++)l[R+H]=e[B+H],p[R+H]=t[B+H];let O=y*12;for(let H=0;H<3;H++)d[O+H*4]=M,d[O+H*4+1]=S,d[O+H*4+2]=T,d[O+H*4+3]=A;y++}}let m=o&&c&&u?this.createSubBatch(o,c,u,r*3):null,h=l&&p&&d?this.createSubBatch(l,p,d,a*3):null;if(!m&&!h)return null;return{opaque:m,translucent:h,fadeStartMs:i}}deleteSubBatch(e){let t=this.gl;if(!t||!e)return;t.deleteVertexArray(e.vao),t.deleteBuffer(e.posBuf),t.deleteBuffer(e.nrmBuf),t.deleteBuffer(e.colBuf)}deleteBatch(e){if(!e)return;this.deleteSubBatch(e.opaque),this.deleteSubBatch(e.translucent)}clearParts(){for(let e of this.partBatches)this.deleteBatch(e);this.partBatches=[]}fit(){this.setView("fit")}setView(e){let t=35*Math.PI/180;this.dist=this.radius/Math.sin(t*0.5)*1.15,this.target=[this.center[0],this.center[1],this.center[2]];let{yaw:n,pitch:i}=ns(e);this.yaw=n,this.pitch=i,this.scheduleDraw()}snapPng(){return this.draw(performance.now()),new Promise((e)=>{this.canvas.toBlob((t)=>e(t),"image/png")})}scheduleDraw(){if(this.dirty)return;this.dirty=!0,this.rafId=requestAnimationFrame((e)=>{if(this.dirty=!1,this.rafId=0,this.draw(e))this.scheduleDraw()})}drawSubBatch(e){if(!e||!this.gl)return;this.gl.bindVertexArray(e.vao),this.gl.drawArrays(this.gl.TRIANGLES,0,e.vertCount)}draw(e){let t=this.gl;if(!t||!this.prog)return!1;let n=this.canvas.getBoundingClientRect(),i=Math.max(1,Math.round(n.width)),s=Math.max(1,Math.round(n.height)),r=Math.min(window.devicePixelRatio||1,2),a=Math.round(i*r),o=Math.round(s*r);if(this.canvas.width!==a||this.canvas.height!==o)this.canvas.width=a,this.canvas.height=o;if(t.viewport(0,0,a,o),!this.boardBatch&&this.partBatches.length===0)return!1;if(t.depthMask(!0),t.clear(t.DEPTH_BUFFER_BIT),this.bgProg&&this.bgVao){t.disable(t.DEPTH_TEST),t.disable(t.BLEND),t.depthMask(!1),t.useProgram(this.bgProg);let R=this.lightTheme?er:Zs,O=this.lightTheme?tr:Qs;t.uniform3f(this.uBgTop,R[0],R[1],R[2]),t.uniform3f(this.uBgBot,O[0],O[1],O[2]),t.bindVertexArray(this.bgVao),t.drawArrays(t.TRIANGLE_STRIP,0,4),t.bindVertexArray(null)}let c=Math.cos(this.pitch),u=Math.sin(this.pitch),l=Math.cos(this.yaw),p=Math.sin(this.yaw),d=[this.target[0]+this.dist*c*p,this.target[1]-this.dist*c*l,this.target[2]+this.dist*u],g=rs([this.target[0]-d[0],this.target[1]-d[1],this.target[2]-d[2]]),y=Math.abs(g[2])>0.99?[0,1,0]:[0,0,1],m=rs(as(g,y)),h=as(m,g),f=new Float32Array([m[0],h[0],-g[0],0,m[1],h[1],-g[1],0,m[2],h[2],-g[2],0,-Cn(m,d),-Cn(h,d),Cn(g,d),1]),w=Math.max(0.05,this.dist*0.01),C=Math.max(this.dist*10,this.radius*20),A=ir(35*Math.PI/180,a/o,w,C),M=nr(A,f);t.useProgram(this.prog),t.uniformMatrix4fv(this.uMvp,!1,M),t.uniform3f(this.uEye,d[0],d[1],d[2]),t.uniform3f(this.uRight,m[0],m[1],m[2]),t.uniform3f(this.uUp,h[0],h[1],h[2]),t.uniform3f(this.uFwd,g[0],g[1],g[2]);let S=!1,T=[],B=[];for(let R of this.partBatches){let O=e-R.fadeStartMs,H=R.fadeStartMs===0?1:Math.min(1,Math.max(0,O/300));if(H<1){if(S=!0,H>0)B.push({batch:R,fade:H})}else T.push(R)}if(t.enable(t.DEPTH_TEST),t.depthMask(!0),t.disable(t.BLEND),t.uniform1f(this.uFade,1),this.boardBatch)this.drawSubBatch(this.boardBatch.opaque);for(let R of T)this.drawSubBatch(R.opaque);if(t.depthMask(!1),t.enable(t.BLEND),t.uniform1f(this.uFade,1),this.boardBatch)this.drawSubBatch(this.boardBatch.translucent);for(let R of T)this.drawSubBatch(R.translucent);for(let{batch:R,fade:O}of B)t.uniform1f(this.uFade,O),this.drawSubBatch(R.opaque),this.drawSubBatch(R.translucent);return t.depthMask(!0),t.bindVertexArray(null),S}onPointerDown=(e)=>{if(this.canvas.setPointerCapture(e.pointerId),this.pointers.set(e.pointerId,{x:e.clientX,y:e.clientY,button:e.button,shift:e.shiftKey}),this.pointers.size===2){let[t,n]=Array.from(this.pointers.values());this.pinchDist=Math.hypot(n.x-t.x,n.y-t.y)||1}};onPointerMove=(e)=>{let t=this.pointers.get(e.pointerId);if(!t)return;let n=e.clientX-t.x,i=e.clientY-t.y;if(t.x=e.clientX,t.y=e.clientY,this.pointers.size===2){let[s,r]=Array.from(this.pointers.values()),a=Math.hypot(r.x-s.x,r.y-s.y)||1;if(this.pinchDist>0)this.dist=Math.max(this.radius*0.05,Math.min(this.radius*20,this.dist*(this.pinchDist/a)));this.pinchDist=a,this.cbs.onUserMove?.(),this.scheduleDraw();return}if(t.button===2||t.button===1||t.shift){let s=this.dist*0.0014,r=Math.cos(this.yaw),a=Math.sin(this.yaw);this.target[0]-=n*r*s,this.target[1]-=n*a*s,this.target[2]+=i*s}else this.yaw+=n*0.008,this.pitch=Math.max(-Math.PI*0.49,Math.min(Math.PI*0.49,this.pitch+i*0.008));this.cbs.onUserMove?.(),this.scheduleDraw()};onPointerUp=(e)=>{if(this.pointers.delete(e.pointerId),this.pointers.size<2)this.pinchDist=0};onWheel=(e)=>{e.preventDefault();let t=e.deltaY<0?0.8620689655172414:1.16;this.dist=Math.max(this.radius*0.05,Math.min(this.radius*20,this.dist*t)),this.cbs.onUserMove?.(),this.scheduleDraw()};onDblClick=()=>{this.fit()};onContextMenu=(e)=>{e.preventDefault()};destroy(){if(this.rafId)cancelAnimationFrame(this.rafId);if(this.resizeObs.disconnect(),this.canvas.removeEventListener("pointerdown",this.onPointerDown),this.canvas.removeEventListener("pointermove",this.onPointerMove),this.canvas.removeEventListener("pointerup",this.onPointerUp),this.canvas.removeEventListener("pointercancel",this.onPointerUp),this.canvas.removeEventListener("wheel",this.onWheel),this.canvas.removeEventListener("dblclick",this.onDblClick),this.canvas.removeEventListener("contextmenu",this.onContextMenu),this.deleteBatch(this.boardBatch),this.clearParts(),this.gl){if(this.bgVao)this.gl.deleteVertexArray(this.bgVao);if(this.bgProg)this.gl.deleteProgram(this.bgProg);if(this.prog)this.gl.deleteProgram(this.prog)}this.worker?.terminate(),this.canvas.remove()}}var os=64,sr=16777216;function rr(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 At(e){if(!e)return"";let t=e.replace(/\\/g,"/").replace(/\/+$/,""),n=t.lastIndexOf("/");return n>=0?t.slice(n+1):t}function ls(e){switch(e){case"board":return b("viewer.board","Board");case"schematic":return b("viewer.schematic","Schematic");case"3d":return b("viewer.solid","3D");case"gerbers":return b("gpui.gerbers","Gerbers");case"mech":return b("viewer.mech","Mech");case"files":return b("viewer.files","Files");case"diff":return b("viewer.diff","Diff");case"review":return b("viewer.review","Review");case"browser":return b("bots.tab.browser","Browser");case"terminal":return b("viewer.terminal","Terminal");default:return e?e.charAt(0).toUpperCase()+e.slice(1):""}}function An(e){return e==="board"||e==="schematic"||e==="gerbers"}function ar(e){return e==="files"||e==="diff"||e==="review"||e==="browser"||e==="terminal"}function Ln(e,t){let n=document.createElement("div");n.className="bp-vh";let i=document.createElement("div");i.className="bp-vh-title";let s=document.createElement("span");s.className="bp-vh-page";let r=document.createElement("span");r.className="bp-vh-sep",r.textContent="·",r.hidden=!0;let a=document.createElement("span");a.className="bp-vh-file",a.hidden=!0,i.append(s,r,a);let o=document.createElement("div");o.className="bp-vh-actions",n.append(i,o);let c=document.createElement("div");c.className="bp-solid-bar",c.setAttribute("data-testid","solid-presets-bar"),c.hidden=!0;let u=document.createElement("div");u.className="bp-v-banner",u.hidden=!0;let l=document.createElement("div");l.className="bp-v-stage-wrap";let p=document.createElement("div");p.className="bp-v-stage";let d=document.createElement("div");d.className="bp-v-overlay",d.hidden=!0;let g=document.createElement("div");g.className="bp-v-layers",g.hidden=!0;let y=document.createElement("div");y.className="bp-v-info",y.hidden=!0,l.append(p,d,g,y);let m=document.createElement("div");m.className="bp-history-bar",m.setAttribute("data-testid","viewer-history-bar"),m.hidden=!0,e.replaceChildren(n,c,u,l,m);let h="",f="",w=0,C=!1,A=new Set,M=[],S=0,T=new Map,B=new Map,R={},O=[],H="",ae="",ue=!1,oe=!1,we=0,Le=!1,Ne=0,he="",be=0,I=null,le=null,ne=null,X=null,ce=null,E=new xn,k=0,j=!1,P="",K="",ee="",D="";document.addEventListener("click",(F)=>{if(!j)return;if(F.target instanceof Node&&m.contains(F.target))return;j=!1,me()}),document.addEventListener("keydown",(F)=>{if(j&&F.key==="Escape")j=!1,me()});function z(){if(k)window.clearInterval(k),k=0;E.playing=!1}function je(){let F=f==="3d"||f==="mech";if(c.hidden=!F,!F)return;if(c.childElementCount>0)return;for(let W of ts){let V=document.createElement("button");V.type="button",V.className="bp-v-btn",V.textContent=W.label,V.setAttribute("data-testid",`solid-view-${W.id}`),V.addEventListener("click",()=>{ne?.setView(W.id)}),c.append(V)}let U=document.createElement("button");U.type="button",U.className="bp-v-btn",U.textContent="Snap view",U.setAttribute("data-testid","solid-snap"),U.addEventListener("click",()=>{if(!ne)return;ne.snapPng().then((W)=>{if(!W)return;let V=URL.createObjectURL(W),G=document.createElement("a");G.href=V;let Z=(He()||f||"view").replace(/[^a-zA-Z0-9._-]/g,"_");G.download=`${Z}-snap.png`,G.click(),setTimeout(()=>URL.revokeObjectURL(V),1000)})}),c.append(U)}async function Se(){if(!h||f!=="board"&&f!=="schematic")return;me();let F=E.compareRequest();if(!F){P="",K="",ee="",D="",await $e(!1);return}let U=`${f}|${F.commit}|${F.bits}|${ae}`;if(U===D&&A.size>0){ke(E.highlightEdits?`Comparing against ${E.activeRef()?.label||F.commit.slice(0,7)} (edits highlighted)`:`Comparing against ${E.activeRef()?.label||F.commit.slice(0,7)}`,!1);return}let W=++w;A.clear(),T.clear(),Ye(),C=!0,P="",K=F.commit,ee="",D=U;try{let V=ae||(f==="schematic"?R.sch:R.pcb)||"";if(!V){let Ce=await t.hub.rpc("viewer.files",{thread:h});if(W!==w)return;R=Ce||{},re(),V=(f==="schematic"?R.sch:R.pcb)||""}if(!V)throw Error(`Unable to resolve ${f} file path for compare`);let G=await t.hub.rpc("viewer.compare",{thread:h,kind:f,commit:F.commit,bits:F.bits,...ae?{path:ae}:{}});if(W!==w)return;let Z=typeof G?.root==="string"?G.root:"",Q=f==="schematic"?"1":"0";P=Z?`${Q}|${Z}|diff -`:`${Q}|`,K=F.commit,ee=V.startsWith("/")||/^[A-Za-z]:[\\/]/.test(V)||!Z?V:`${Z.replace(/\/+$/,"")}/${V.replace(/^\/+/,"")}`,C=!1;let xe=M;Ye();for(let Ce of xe)if(Ce.kind==="bin")Ge(Ce.buf);else We(Ce.key,Ce.none,Ce.retryable);ke(E.highlightEdits?`Comparing against ${E.activeRef()?.label||F.commit.slice(0,7)} (edits highlighted)`:`Viewing snapshot: ${E.activeRef()?.label||F.commit.slice(0,7)}`,!1)}catch(V){if(W!==w)return;C=!1,P="",K="",ee="",D="",Ye(),ke(V instanceof Error?V.message:String(V),!0)}}function me(){let F=f==="board"||f==="schematic";if(m.hidden=!F,!F)return;let U=document.createElement("div");U.className="bp-history-group";let W=document.createElement("button");W.type="button",W.className="bp-v-btn",W.textContent="<",W.title="Older snapshot",W.disabled=E.refs.length===0||E.index>=E.refs.length-1,W.setAttribute("data-testid","history-prev"),W.addEventListener("click",()=>{if(z(),E.step(1))Se()});let V=document.createElement("button");V.type="button",V.className="bp-v-btn"+(E.playing?" is-on":""),V.textContent=E.playing?"⏸":"▶",V.title=E.playing?"Pause history":"Play history",V.disabled=E.refs.length===0,V.setAttribute("data-testid","history-play"),V.addEventListener("click",()=>{if(E.playing){z(),me();return}if(E.refs.length===0)return;if(E.playing=!0,E.isLive())E.index=E.refs.length-1,Se();else me();k=window.setInterval(()=>{if(!E.playing||f!=="board"&&f!=="schematic"){z(),me();return}if(E.step(-1))Se();else z(),me()},1400)});let G=document.createElement("button");G.type="button",G.className="bp-v-btn",G.textContent=">",G.title="Newer snapshot",G.disabled=E.isLive(),G.setAttribute("data-testid","history-next"),G.addEventListener("click",()=>{if(z(),E.step(-1))Se()});let Z=document.createElement("button");Z.type="button",Z.className="bp-v-btn"+(E.isLive()?" is-on":""),Z.textContent="Live",Z.setAttribute("data-testid","history-live"),Z.addEventListener("click",()=>{if(z(),E.goLive())ke("",!1),Se()});let Q=document.createElement("span");Q.className="bp-history-label",Q.setAttribute("data-testid","history-label");let xe=E.activeRef();Q.textContent=xe?xe.label||xe.commit.slice(0,7):E.refs.length>0?`Live (${E.refs.length} saved)`:"Live",U.append(W,V,G,Z,Q);let Ce=document.createElement("div");Ce.className="bp-history-group";let Pe=document.createElement("button");Pe.type="button",Pe.className="bp-v-btn"+(E.highlightEdits?" is-on":""),Pe.textContent="Highlight edits",Pe.disabled=E.refs.length===0,Pe.setAttribute("data-testid","history-highlight"),Pe.addEventListener("click",()=>{z(),E.toggleHighlight(),Se()});let Re=document.createElement("div");Re.className="bp-history-menu-wrap";let ye=document.createElement("button");if(ye.type="button",ye.className="bp-v-btn"+(j||!E.isLive()?" is-on":""),ye.disabled=E.refs.length===0,ye.setAttribute("data-testid","history-compare"),ye.setAttribute("aria-haspopup","menu"),ye.setAttribute("aria-expanded",String(j)),ye.textContent=xe?`Compare: ${xe.label||xe.commit.slice(0,7)} ▾`:"Compare ▾",ye.addEventListener("click",(Te)=>{Te.stopPropagation(),j=!j,me()}),Re.append(ye),j&&E.refs.length>0){let Te=document.createElement("div");Te.className="bp-history-menu",Te.setAttribute("role","menu"),Te.setAttribute("data-testid","history-compare-menu");let Ke=(Ie,mt,Nt)=>{let ze=document.createElement("button");ze.type="button",ze.className="bp-history-menu-item"+(Nt?" is-active":""),ze.setAttribute("role","menuitem"),ze.setAttribute("data-commit",mt),ze.textContent=Ie,ze.addEventListener("click",()=>{if(j=!1,z(),E.selectCommit(mt)){if(E.isLive())ke("",!1);Se()}else me()}),Te.append(ze)};Ke("Live (working tree)","",E.isLive());for(let Ie of E.refs)Ke(Ie.label||Ie.commit.slice(0,7),Ie.commit,xe?.commit===Ie.commit);Re.append(Te)}Ce.append(Pe,Re),m.replaceChildren(U,Ce)}async function Me(F){if(!F)return;try{let U=await t.hub.rpc("viewer.refs",{thread:F});if(F!==h)return;E.setRefs(Array.isArray(U?.refs)?U.refs:[]),me()}catch{if(F!==h)return;E.setRefs([]),me()}}function Y(){return document.documentElement.classList.contains("light")}let fe=new MutationObserver(()=>{let F=Y();le?.setTheme(F),ne?.setTheme(F),ce?.setTheme(F)});fe.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]});function ie(F,U="",W=!1){if(F==="none"){d.hidden=!0,d.replaceChildren();return}d.hidden=!1,d.className=`bp-v-overlay is-${F}`;let V=document.createElement("div");V.className="bp-v-state-card";let G=document.createElement("div");if(G.className="bp-v-state-msg",G.textContent=U,V.append(G),W){let Z=document.createElement("button");Z.type="button",Z.className="bp-v-btn is-primary",Z.textContent=b("tools.retry","Retry"),Z.addEventListener("click",()=>void $e(!0)),V.append(Z)}d.replaceChildren(V)}function ke(F,U){u.textContent=F,u.hidden=!F,u.classList.toggle("is-warn",U)}function He(){if(ae)return At(ae);if(f==="board"||f==="3d")return At(R.pcb);if(f==="schematic")return At(R.sch);if(f==="mech")return At(H);return""}function re(){s.textContent=ls(f);let F=He();if(r.hidden=!F,a.hidden=!F,a.textContent=F,o.replaceChildren(),f==="mech"&&O.length>1){let W=document.createElement("select");W.className="bp-v-select",W.setAttribute("aria-label",b("viewer.mech","Mech"));for(let V of O){let G=document.createElement("option");G.value=V,G.textContent=At(V),G.selected=V===H,W.append(G)}W.addEventListener("change",()=>{H=W.value,re(),$e(!1)}),o.append(W)}if(An(f)){let W=document.createElement("button");W.type="button",W.className="bp-v-btn"+(Le?" is-on":""),W.textContent=I?.layerHead||"Layers",W.setAttribute("data-testid","viewer-layers-btn"),W.addEventListener("click",()=>{if(Le=!Le,g.hidden=!Le,W.classList.toggle("is-on",Le),Le)_e("","")}),o.append(W)}if(f==="board"||f==="schematic"||f==="3d"||f==="mech"||f==="gerbers"){let W=document.createElement("button");W.type="button",W.className="bp-v-btn",W.textContent="Fit",W.setAttribute("data-testid","viewer-fit-btn"),W.addEventListener("click",()=>{le?.fit(),ne?.fit()}),o.append(W)}if((f==="board"||f==="schematic")&&t.hub.hasFeature("follow")){let W=document.createElement("button");W.type="button",W.className="bp-v-btn"+(ue&&!oe?" is-on":""),W.textContent=ue?oe?b("gpui.follow.paused","Follow (paused)"):"Follow agent":"Follow agent",W.setAttribute("data-testid","viewer-follow-btn"),W.addEventListener("click",()=>void tt()),o.append(W)}let U=document.createElement("button");U.type="button",U.className="bp-v-btn bp-v-close",U.textContent="✕",U.title=b("common.close","Close"),U.setAttribute("aria-label",b("common.close","Close")),U.setAttribute("data-testid","viewer-close-btn"),U.addEventListener("click",()=>t.closeViewer()),o.append(U)}function ge(){if(!I){g.replaceChildren();return}let F=document.createDocumentFragment(),U=document.createElement("div");U.className="bp-v-layers-head";let W=document.createElement("span");if(W.textContent=I.layerHead||"Layers",U.append(W),I.layerReset){let Q=document.createElement("button");Q.type="button",Q.className="bp-v-btn",Q.textContent="Reset",Q.addEventListener("click",()=>void _e("reset","")),U.append(Q)}if(F.append(U),I.layerModes){let Q=document.createElement("div");Q.className="bp-v-layers-modes",["All","Dim","Only"].forEach((xe,Ce)=>{let Pe=document.createElement("button");Pe.type="button",Pe.className="bp-v-btn"+(I?.layerMode===Ce?" is-on":""),Pe.textContent=xe,Pe.addEventListener("click",()=>void _e("mode",String(Ce))),Q.append(Pe)}),F.append(Q)}let V=le?.presentColors()??new Map,G=(I.layerList||[]).concat(I.layerMarks||[]),Z=document.createElement("div");Z.className="bp-v-layers-list";for(let Q of G){let xe=V.get(Q.layer);if(xe===void 0)continue;let Ce=document.createElement("div");Ce.className="bp-v-layer-row"+(Q.active?" is-focus":"");let Pe=document.createElement("input");Pe.type="checkbox",Pe.checked=Q.on!==!1,Pe.addEventListener("change",()=>void _e("toggle",String(Q.layer)));let Re=document.createElement("span");Re.className="bp-v-layer-swatch";let ye=xe>>>16&255,Te=xe>>>8&255,Ke=xe&255;Re.style.background=Q.on!==!1?`rgb(${ye},${Te},${Ke})`:`rgba(${ye},${Te},${Ke},0.2)`;let Ie=document.createElement("button");Ie.type="button",Ie.className="bp-v-layer-name",Ie.textContent=Q.name,Ie.addEventListener("click",()=>void _e("pick",String(Q.layer))),Ce.append(Pe,Re,Ie),Z.append(Ce)}F.append(Z),g.replaceChildren(F)}async function _e(F,U){if(!An(f))return;let W=w;try{let V=await t.hub.rpc("viewer.layers",{kind:f,present:be,off:Ne,focus:he,...F?{action:F,value:U}:{}});if(W!==w||!V)return;Ne=Number(V.own)||0,he=typeof V.focus==="string"?V.focus:"",I=V;let G={off:Number(V.off)||0,dim:Number(V.dim)||0,lift:typeof V.lift==="number"?V.lift:255};if(le?.setLayers(G),re(),Le)ge()}catch{}}async function Ue(){if(!ue||oe||!h||!t.hub.hasFeature("follow"))return;oe=!0,re();try{await t.hub.rpc("viewer.follow",{thread:h,action:"pause"})}catch{}}async function tt(){if(!h||!t.hub.hasFeature("follow"))return;let F=!ue?"on":oe?"resume":"off";try{let U=await t.hub.rpc("viewer.follow",{thread:h,action:F});if(ue=!!U.on,oe=!!U.paused,re(),U.on&&!U.paused&&U.focus&&Array.isArray(U.focus.box)&&U.focus.box.length===4&&(U.seq||0)>we)we=U.seq||we,le?.zoomToBoxMm([U.focus.box[0],U.focus.box[1],U.focus.box[2],U.focus.box[3]])}catch{}}function de(){y.hidden=!0,y.replaceChildren(),le?.setHighlights([])}function dt(F){let U=F.split(";").filter(Boolean),W=U.shift()||F,V=[],G="",Z="";for(let Re of U){if(Re.startsWith("g="))continue;let ye=Re.indexOf("=");if(ye>0){let Te=Re.slice(0,ye),Ke=Re.slice(ye+1);if((Te==="ref"||Te==="symbol")&&!G)G=Ke;if(Te==="net"&&!Z)Z=Ke;V.push([Te,Ke])}else V.push([Re,""])}let Q=document.createElement("div");Q.className="bp-v-info-head";let xe=document.createElement("span");xe.className="bp-v-info-title",xe.textContent=W;let Ce=document.createElement("button");Ce.type="button",Ce.className="bp-v-info-x",Ce.textContent="×",Ce.setAttribute("aria-label","Clear selection"),Ce.addEventListener("click",de),Q.append(xe,Ce);let Pe=document.createElement("div");Pe.className="bp-v-info-rows";for(let[Re,ye]of V){let Te=document.createElement("span");Te.className="bp-v-info-chip",Te.textContent=ye?`${Re}: ${ye}`:Re,Pe.append(Te)}return y.replaceChildren(Q,...V.length>0?[Pe]:[]),y.hidden=!1,{ref:G||void 0,net:Z||void 0}}async function Je(F){if(!F){de();return}let U=Array.from(A)[0]||"";if(!U)return;let W=w;try{let V=await t.hub.rpc("viewer.info",{key:U,at:F.at,idx:F.idx});if(W!==w)return;let G=typeof V.info==="string"?V.info:"";if(!G){de();return}let{ref:Z,net:Q}=dt(G),xe=[];if(Z)xe.push(["ref",Z]);if(Q)xe.push(["net",Q]);let Ce=[[F.at,F.idx]];for(let[Pe,Re]of xe){let ye=await t.hub.rpc("viewer.probe",{key:U,name:Pe,value:Re});if(W!==w)return;if(Array.isArray(ye.matches))for(let Te of ye.matches)Ce.push(Te)}le?.setHighlights(Ce)}catch{de()}}function pt(){X?.destroy(),X=null,ce?.destroy(),ce=null,le?.destroy(),le=null,ne?.destroy(),ne=null,p.replaceChildren(),Le=!1,g.hidden=!0,y.hidden=!0,y.replaceChildren(),ke("",!1),ie("none")}function Ye(){M=[],S=0}async function $e(F){if(!h||!f)return;let U=++w;if(A.clear(),C=!1,Ye(),pt(),re(),je(),me(),(f==="board"||f==="schematic")&&h)Me(h);if(ar(f)){if(t.hub.rpc("viewer.watch",{thread:h,kind:""}).catch(()=>{}),f==="files")X=Xi(p,t,h,(G,Z)=>{if(f=G,ae=Z,G==="mech")H=Z;$e(!1)});else if(f==="diff")X=Zi(p,t,h);else if(f==="review")X=Qi(p,t,h);else if(f==="browser")X=zi(p,t,h);else if(f==="terminal")ie("loading","Loading terminal…"),import("/assets/terminal.js").then((Z)=>{if(U!==w)return;if(ie("none"),Z?.mountTerminalPane)ce=Z.mountTerminalPane(p,t,h,Y());else ie("error","Terminal chunk missing",!0)},(Z)=>{if(U!==w)return;ie("error",Z instanceof Error?Z.message:String(Z),!0)});return}if(ie("loading","Loading…"),!R.root)try{let G=await t.hub.rpc("viewer.files",{thread:h});if(U!==w)return;R=G||{},re()}catch{}if(f==="gerbers"&&R.hasGerbers===!1){ie("empty","No Gerbers in this project",!1);return}let W=Y();if(f==="3d"||f==="mech")ne=new kn(p,{onStatus:(G,Z)=>{if(Z)ie("none"),ke(G,!1);else if(G)ie("loading",G);else ie("none"),ke("",!1)},onUserMove:()=>void Ue()}),ne.setTheme(W);else if(f==="board"||f==="schematic"||f==="gerbers")le=new wn(p,{onPick:(G)=>void Je(G),onUserMove:()=>void Ue()}),le.setTheme(W);else{ie("empty",`${ls(f)} is not available in this viewer`,!1);return}let V={thread:h};if(F)V.force=!0;if(f==="mech"){if(O.length===0)try{let G=await t.hub.rpc("mech.list",{thread:h});if(U!==w)return;if(O=Array.isArray(G.parts)?G.parts:[],!H)H=G.primary||O[0]||"";re()}catch(G){if(U!==w)return;ie("error",G instanceof Error?G.message:String(G),!0);return}if(!H){ie("empty",b("gpui.rail.no.mech","No mechanical parts in this project"),!1);return}V.kind="3d",V.path=H}else{if(V.kind=f,ae&&(f==="board"||f==="schematic"))V.path=ae;if(f==="3d"&&!F&&ne){let G=ne.keptToken();if(G)V.kept=G}if((f==="board"||f==="schematic"||f==="gerbers")&&!F&&t.hub.hasFeature("keptChunks"))V.keptChunks=Array.from(B.keys())}C=!0,P="",K="",ee="",D="";try{let G=await t.hub.rpc("viewer.watch",V);if(U!==w)return;A=new Set(Array.isArray(G.keys)?G.keys:[]),C=!1;let Z=M;Ye();for(let Q of Z)if(Q.kind==="bin")Ge(Q.buf);else We(Q.key,Q.none,Q.retryable)}catch(G){if(U!==w)return;C=!1,A.clear(),Ye();let Z=G instanceof Error?G.message:String(G),Q=/no gerbers|not in this project|another machine/i.test(Z);ie(Q?"empty":"error",Z,!Q)}}function We(F,U,W){if(C){if(M.length{if(F.t==="plot"&&typeof F.none==="string"&&typeof F.key==="string")We(F.key,F.none,F.retryable===!0)}),Oe=Tt(()=>{if(f)re()}),Pt=(F)=>{if(F.key==="Escape"&&f&&!y.hidden)de()};return window.addEventListener("keydown",Pt),{open(F,U){if(U!==h){if(h=U,R={},O=[],H="",T.clear(),ue=!1,oe=!1,we=0,Ne=0,he="",be=0,I=null,t.hub.hasFeature("follow"))t.hub.rpc("viewer.follow",{thread:U}).then((W)=>{if(U!==h)return;if(ue=!!W.on,oe=!!W.paused,we=Number(W.seq)||0,f)re()}).catch(()=>{})}if(F!==f)z(),E.goLive(),Ne=0,he="",be=0,I=null;f=F,ae="",$e(!1)},reconcileHas(F){if(f&&!rr(f,F))t.closeViewer()},close(){if(w++,C=!1,z(),j=!1,P="",K="",ee="",D="",E.goLive(),c.hidden=!0,m.hidden=!0,Ye(),h)t.hub.rpc("viewer.watch",{thread:h,kind:""}).catch(()=>{});f="",A.clear(),pt()}}}var cs="http://www.w3.org/2000/svg";function Lt(e){let t=document.createElementNS(cs,"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(cs,"path");i.setAttribute("d",n),t.appendChild(i)}return t}function or(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 ds(e,t){if(!e)return!0;if(t==="board"||t==="3d")return e.board!==!1;if(t==="schematic")return e.schematic!==!1;if(t==="mech")return e.mech!==!1;if(t==="gerbers")return e.gerbers!==!1;return!0}function ps(e){if(!e)return;let t=e==="light";document.documentElement.classList.toggle("light",t);try{localStorage.setItem("bp.theme",t?"light":"dark")}catch{}}function lr(){return`web-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`}function ms(){let e=document.getElementById("root");if(!e)return;try{if(localStorage.getItem("bp.theme")==="light")document.documentElement.classList.add("light")}catch{}let t=document.createElement("header");t.className="bp-topbar",t.setAttribute("data-testid","topbar");let n=document.createElement("button");n.type="button",n.className="icon bp-side-toggle",n.textContent="☰",n.title="Toggle sidebar",n.setAttribute("aria-label","Toggle sidebar");let i=document.createElement("div");i.className="bp-brand";let s=document.createElement("img");s.src="/assets/favicon.svg",s.alt="Backplane",s.className="bp-logo";let r=document.createElement("span");r.className="bp-brand-name bp-hide-phone",r.textContent="Backplane";let a=document.createElement("span");a.className="bp-crumb-sep bp-hide-phone",a.textContent="/";let o=document.createElement("span");o.className="bp-crumb-proj bp-hide-phone";let c=document.createElement("span");c.className="bp-crumb-sep bp-hide-phone",c.textContent="/";let u=document.createElement("span");u.className="bp-crumb-thread",u.setAttribute("data-testid","thread-title");let l=document.createElement("span");l.className="bp-plan-top-badge bp-hidden",l.setAttribute("data-testid","plan-top-badge"),i.append(s,r,a,o,c,u,l);let p=document.createElement("div");p.className="bp-top-state bp-hide-phone bp-hidden";let d=document.createElement("span");d.className="bp-top-state-lbl",d.textContent="STATE";let g=document.createElement("span");g.className="bp-dot bp-dot-idle";let y=document.createElement("span");y.className="bp-top-state-word",p.append(d,g,y);let m=document.createElement("div");m.className="bp-top-acts bp-hide-phone bp-hidden";let h=document.createElement("button");h.type="button",h.className="bp-btn-ghost bp-top-act";let f=document.createElement("span");f.textContent=b("menu.pin","Pin"),h.append(Lt(["M12 17v5","M9 3h6l1 7 3 3H5l3-3 1-7z"]),f);let w=document.createElement("button");w.type="button",w.className="bp-btn-ghost bp-top-act";let C=document.createElement("span");C.textContent=b("menu.settle","Settle"),w.append(Lt(["M12 22a10 10 0 1 0 0-20 10 10 0 0 0 0 20z","M9 12l2 2 4-4"]),C);let A=document.createElement("div");A.className="bp-menu-wrap";let M=document.createElement("button");M.type="button",M.className="bp-btn-ghost bp-top-act",M.textContent="▾",M.title="Thread menu",M.setAttribute("aria-label","Thread menu"),M.setAttribute("data-testid","thread-menu-btn");let S=document.createElement("div");S.className="bp-popover bp-hidden",S.setAttribute("data-testid","thread-menu"),A.append(M,S),m.append(h,w,A);let T=document.createElement("div");T.className="bp-top-right";let B=document.createElement("button");B.type="button",B.className="bp-btn-ghost bp-top-act bp-hide-tablet",B.setAttribute("data-testid","improvements-btn");let R=document.createElement("span");R.textContent=b("gpui.improvements","Improvements"),B.append(Lt(["M12 2l2.4 7.4H22l-6.2 4.5 2.4 7.4L12 16.8l-6.2 4.5 2.4-7.4L2 9.4h7.6z"]),R);let O=document.createElement("button");O.type="button",O.className="bp-cmd-box bp-hide-tablet",O.textContent="> Jump or run a command";let H=document.createElement("button");H.type="button",H.className="icon bp-top-icon",H.title="Search",H.setAttribute("aria-label","Search"),H.appendChild(Lt(["M11 19a8 8 0 1 0 0-16 8 8 0 0 0 0 16z","M21 21l-4.3-4.3"]));let ae=document.createElement("button");ae.type="button",ae.className="icon bp-top-icon",ae.title=b("palette.settings","Settings"),ae.setAttribute("aria-label",b("palette.settings","Settings")),ae.setAttribute("data-testid","settings-btn"),ae.appendChild(Lt(["M12 15a3 3 0 1 0 0-6 3 3 0 0 0 0 6z","M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 1 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 1 1-4 0v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 1 1-2.83-2.83l.06-.06a1.65 1.65 0 0 0 .33-1.82 1.65 1.65 0 0 0-1.51-1H3a2 2 0 1 1 0-4h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 1 1 2.83-2.83l.06.06a1.65 1.65 0 0 0 1.82.33H9a1.65 1.65 0 0 0 1-1.51V3a2 2 0 1 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 1 1 2.83 2.83l-.06.06a1.65 1.65 0 0 0-.33 1.82V9c.26.6.85 1 1.51 1H21a2 2 0 1 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z"])),T.append(B,O,H,ae),t.append(n,i,p,m,T);let ue=document.createElement("div");ue.className="bp-body";let oe=document.createElement("aside");oe.className="bp-sidebar",oe.setAttribute("data-testid","sidebar");let we=document.createElement("main");we.className="bp-center";let Le=document.createElement("div");Le.className="bp-right-area bp-hidden",Le.setAttribute("data-testid","right-area");let Ne=document.createElement("div");Ne.className="bp-right-top";let he=document.createElement("section");he.className="bp-viewer-pane bp-hidden",he.setAttribute("data-testid","viewer-pane"),Ne.appendChild(he),Le.appendChild(Ne);let be=document.createElement("nav");be.className="bp-rail",be.setAttribute("aria-label","Viewer rail"),be.setAttribute("data-testid","viewer-rail"),ue.append(oe,we,Le,be),e.append(t,ue);let I=new vn,le=null,ne=new Set,X=0,ce=null,E=[],k=[],j=[],P=[],K=[],ee=[],D="",z=0,je=0,Se=null,me=null,Me="",Y=null,fe=20,ie={},ke=new Map;function He(v,x){ke.delete(v),ke.set(v,x);while(ke.size>fe){let L=ke.keys().next().value;if(L!==void 0)ke.delete(L);else break}}let re=new bn(oe,{onSelectThread:(v)=>{if(v===D&&Se!==null){oe.classList.remove("bp-sidebar-open");return}Ie(v)},onNewThread:(v)=>{Vt(v)},onSelectBot:(v)=>{Ie(v.thread)},onThreadAct:(v,x)=>{Ze(v,x)},onToggleSection:(v)=>{if(ne.has(v))ne.delete(v);else ne.add(v);ye()},onToggleProjectFold:(v)=>{I.rpc("sidebar.act",{action:"project-fold",value:v}).then(()=>ye()).catch(()=>{})},onCollapseSidebar:()=>{oe.classList.remove("bp-sidebar-open"),oe.classList.add("bp-sidebar-collapsed")},onNeedAct:async(v)=>{let x=$t(v,!1);if(!x)return;if(x.kind==="thread"){Ie(x.id);return}if(x.kind!=="call")return;let L=Bi(await I.rpc(x.method,x.params));if(L?.kind==="thread")Ie(L.id);ye()},hasRoomView:!1,onAddProject:()=>We.open({mode:"folder"})}),ge=new Xt(we,{onLoadOlder:()=>{ze()},onGoToEntry:(v)=>{Nt(v)},onOpenAccounts:()=>{F()},onAnswerAsk:(v,x)=>{I.rpc("ask.answer",{ask:v,answer:x}).catch((L)=>{de.showError(L instanceof Error?L.message:"Could not send answer")})},onToggleReview:(v)=>{if(!D)return;let x=z;I.rpc("thread.review",{thread:D,on:v}).then((L)=>{if(x===z)ge.setReview(L.review??null)}).catch(()=>{})},onUnansweredAction:(v,x)=>{if(!D)return;if(v==="again"||v==="thread-again")I.rpc("thread.again",{thread:D,value:x}).catch(()=>{});else I.rpc("thread.act",{thread:D,action:v,value:x}).catch(()=>{})},onReplyEntry:(v)=>{if(!I.hasFeature("reply")){let x=(v.text||"").split(` +`;function qe(e){let t=e/255;return t<=0.04045?t/12.92:Math.pow((t+0.055)/1.055,2.4)}var er=[qe(77),qe(83),qe(94)],tr=[qe(53),qe(58),qe(67)],nr=[qe(245),qe(246),qe(248)],ir=[qe(225),qe(228),qe(233)];function ss(e,t,n){let i=e.createShader(t);if(!i)throw Error("createShader failed");if(e.shaderSource(i,n),e.compileShader(i),!e.getShaderParameter(i,e.COMPILE_STATUS)){let s=e.getShaderInfoLog(i)||"shader compile error";throw e.deleteShader(i),Error(s)}return i}function rs(e,t,n){let i=ss(e,e.VERTEX_SHADER,t),s=ss(e,e.FRAGMENT_SHADER,n),r=e.createProgram();if(!r)throw Error("createProgram failed");if(e.attachShader(r,i),e.attachShader(r,s),e.linkProgram(r),e.deleteShader(i),e.deleteShader(s),!e.getProgramParameter(r,e.LINK_STATUS)){let a=e.getProgramInfoLog(r)||"program link error";throw e.deleteProgram(r),Error(a)}return r}function sr(e,t){let n=new Float32Array(16);for(let i=0;i<4;i++)for(let s=0;s<4;s++)n[i*4+s]=e[0+s]*t[i*4+0]+e[4+s]*t[i*4+1]+e[8+s]*t[i*4+2]+e[12+s]*t[i*4+3];return n}function rr(e,t,n,i){let s=1/Math.tan(e*0.5),r=1/(n-i),a=new Float32Array(16);return a[0]=s/t,a[5]=s,a[10]=(i+n)*r,a[11]=-1,a[14]=2*i*n*r,a}function as(e){let t=Math.hypot(e[0],e[1],e[2])||1;return[e[0]/t,e[1]/t,e[2]/t]}function os(e,t){return[e[1]*t[2]-e[2]*t[1],e[2]*t[0]-e[0]*t[2],e[0]*t[1]-e[1]*t[0]]}function kn(e,t){return e[0]*t[0]+e[1]*t[1]+e[2]*t[2]}class An{canvas;gl=null;bgProg=null;bgVao=null;uBgTop=null;uBgBot=null;prog=null;uMvp=null;uEye=null;uRight=null;uUp=null;uFwd=null;uFade=null;worker=null;boardBatch=null;partBatches=[];activeKey="";lastMeshId="";nextJobId=1;partsTotal=0;partsDone=0;center=[0,0,0];target=[0,0,0];radius=50;dist=120;yaw=0.6;pitch=0.7;lightTheme=!1;dirty=!1;rafId=0;pointers=new Map;pinchDist=0;resizeObs;cbs;constructor(e,t={}){this.cbs=t,this.canvas=document.createElement("canvas"),this.canvas.className="bp-viewer-canvas",this.canvas.style.width="100%",this.canvas.style.height="100%",this.canvas.style.display="block",this.canvas.style.touchAction="none",e.appendChild(this.canvas);let n=this.canvas.getContext("webgl2",{antialias:!0,alpha:!1,preserveDrawingBuffer:!0});if(n)this.gl=n,this.bgProg=rs(n,Ys,Xs),this.bgVao=n.createVertexArray(),this.uBgTop=n.getUniformLocation(this.bgProg,"uBgTop"),this.uBgBot=n.getUniformLocation(this.bgProg,"uBgBot"),this.prog=rs(n,Zs,Qs),this.uMvp=n.getUniformLocation(this.prog,"uMvp"),this.uEye=n.getUniformLocation(this.prog,"uEye"),this.uRight=n.getUniformLocation(this.prog,"uRight"),this.uUp=n.getUniformLocation(this.prog,"uUp"),this.uFwd=n.getUniformLocation(this.prog,"uFwd"),this.uFade=n.getUniformLocation(this.prog,"uFade"),n.enable(n.DEPTH_TEST),n.blendFunc(n.SRC_ALPHA,n.ONE_MINUS_SRC_ALPHA);else this.cbs.onStatus?.("WebGL2 is unavailable in this browser");try{this.worker=new Worker("/assets/mesh-worker.js",{type:"module"}),this.worker.onmessage=(i)=>this.onWorkerMessage(i.data)}catch{this.cbs.onStatus?.("3D worker unavailable")}this.resizeObs=new ResizeObserver(()=>this.scheduleDraw()),this.resizeObs.observe(this.canvas),this.canvas.addEventListener("pointerdown",this.onPointerDown),this.canvas.addEventListener("pointermove",this.onPointerMove),this.canvas.addEventListener("pointerup",this.onPointerUp),this.canvas.addEventListener("pointercancel",this.onPointerUp),this.canvas.addEventListener("wheel",this.onWheel,{passive:!1}),this.canvas.addEventListener("dblclick",this.onDblClick),this.canvas.addEventListener("contextmenu",this.onContextMenu)}keptToken(){return this.activeKey&&this.lastMeshId?`${this.activeKey} ${this.lastMeshId}`:""}setTheme(e){if(this.lightTheme!==e)this.lightTheme=e,this.scheduleDraw()}handleFrame(e){let t=typeof e.key==="string"?e.key:"";if(!t)return;if(e.mesh instanceof Uint8Array&&typeof e.n==="number"&&!e.part){this.activeKey=t,this.lastMeshId=Wi(e.mesh),this.clearParts(),this.cbs.onStatus?.("Building 3D model…");let n=new Uint8Array(e.mesh),i=e.faces instanceof Uint8Array?new Uint8Array(e.faces):void 0,s=[n.buffer];if(i)s.push(i.buffer);this.worker?.postMessage({id:this.nextJobId++,kind:"solid",key:t,n:e.n,mesh:n,faces:i},s);return}if(e.parts&&typeof e.parts==="object"&&!Array.isArray(e.parts)&&!(e.parts instanceof Uint8Array)){if(this.activeKey&&t!==this.activeKey)return;if(this.activeKey=t,this.clearParts(),this.partsTotal=typeof e.parts.of==="number"?e.parts.of:0,this.partsDone=0,this.partsTotal>0)this.cbs.onStatus?.(`Loading parts 0/${this.partsTotal}…`);this.scheduleDraw();return}if(typeof e.part==="string"&&e.mesh instanceof Uint8Array&&e.at instanceof Uint8Array&&typeof e.n==="number"){if(this.activeKey&&t!==this.activeKey)return;let n=new Uint8Array(e.mesh),i=new Uint8Array(e.at),s=e.faces instanceof Uint8Array?new Uint8Array(e.faces):void 0,r=[n.buffer,i.buffer];if(s)r.push(s.buffer);this.worker?.postMessage({id:this.nextJobId++,kind:"part",key:t,partId:e.part,n:e.n,mesh:n,at:i,faces:s,refs:Array.isArray(e.refs)?e.refs:[],done:typeof e.done==="number"?e.done:0},r)}}onWorkerMessage(e){if(e.error){this.cbs.onStatus?.(e.error);return}if(e.key!==this.activeKey||!this.gl)return;if(e.kind==="solid")this.deleteBatch(this.boardBatch),this.boardBatch=this.uploadBatch(e.positions,e.normals,e.colors,0),this.center=[e.center[0],e.center[1],e.center[2]],this.target=[e.center[0],e.center[1],e.center[2]],this.radius=e.radius,this.fit(),this.cbs.onStatus?.(""),this.scheduleDraw();else if(e.kind==="part"){let t=this.uploadBatch(e.positions,e.normals,e.colors,performance.now());if(t)this.partBatches.push(t);if(this.partsDone=e.done||this.partsDone+1,this.partsTotal>0&&this.partsDone>>24===0)r++;else a++;let o=r>0?new Float32Array(r*9):null,c=r>0?new Float32Array(r*9):null,u=r>0?new Float32Array(r*12):null,l=a>0?new Float32Array(a*9):null,p=a>0?new Float32Array(a*9):null,d=a>0?new Float32Array(a*12):null,g=0,y=0;for(let f=0;f>>24&255,A=1-C/255,M=(w>>>16&255)/255,P=(w>>>8&255)/255,T=(w&255)/255,B=f*9;if(C===0&&o&&c&&u){let R=g*9;for(let H=0;H<9;H++)o[R+H]=e[B+H],c[R+H]=t[B+H];let O=g*12;for(let H=0;H<3;H++)u[O+H*4]=M,u[O+H*4+1]=P,u[O+H*4+2]=T,u[O+H*4+3]=1;g++}else if(l&&p&&d){let R=y*9;for(let H=0;H<9;H++)l[R+H]=e[B+H],p[R+H]=t[B+H];let O=y*12;for(let H=0;H<3;H++)d[O+H*4]=M,d[O+H*4+1]=P,d[O+H*4+2]=T,d[O+H*4+3]=A;y++}}let m=o&&c&&u?this.createSubBatch(o,c,u,r*3):null,h=l&&p&&d?this.createSubBatch(l,p,d,a*3):null;if(!m&&!h)return null;return{opaque:m,translucent:h,fadeStartMs:i}}deleteSubBatch(e){let t=this.gl;if(!t||!e)return;t.deleteVertexArray(e.vao),t.deleteBuffer(e.posBuf),t.deleteBuffer(e.nrmBuf),t.deleteBuffer(e.colBuf)}deleteBatch(e){if(!e)return;this.deleteSubBatch(e.opaque),this.deleteSubBatch(e.translucent)}clearParts(){for(let e of this.partBatches)this.deleteBatch(e);this.partBatches=[]}fit(){this.setView("fit")}setView(e){let t=35*Math.PI/180;this.dist=this.radius/Math.sin(t*0.5)*1.15,this.target=[this.center[0],this.center[1],this.center[2]];let{yaw:n,pitch:i}=is(e);this.yaw=n,this.pitch=i,this.scheduleDraw()}snapPng(){return this.draw(performance.now()),new Promise((e)=>{this.canvas.toBlob((t)=>e(t),"image/png")})}scheduleDraw(){if(this.dirty)return;this.dirty=!0,this.rafId=requestAnimationFrame((e)=>{if(this.dirty=!1,this.rafId=0,this.draw(e))this.scheduleDraw()})}drawSubBatch(e){if(!e||!this.gl)return;this.gl.bindVertexArray(e.vao),this.gl.drawArrays(this.gl.TRIANGLES,0,e.vertCount)}draw(e){let t=this.gl;if(!t||!this.prog)return!1;let n=this.canvas.getBoundingClientRect(),i=Math.max(1,Math.round(n.width)),s=Math.max(1,Math.round(n.height)),r=Math.min(window.devicePixelRatio||1,2),a=Math.round(i*r),o=Math.round(s*r);if(this.canvas.width!==a||this.canvas.height!==o)this.canvas.width=a,this.canvas.height=o;if(t.viewport(0,0,a,o),!this.boardBatch&&this.partBatches.length===0)return!1;if(t.depthMask(!0),t.clear(t.DEPTH_BUFFER_BIT),this.bgProg&&this.bgVao){t.disable(t.DEPTH_TEST),t.disable(t.BLEND),t.depthMask(!1),t.useProgram(this.bgProg);let R=this.lightTheme?nr:er,O=this.lightTheme?ir:tr;t.uniform3f(this.uBgTop,R[0],R[1],R[2]),t.uniform3f(this.uBgBot,O[0],O[1],O[2]),t.bindVertexArray(this.bgVao),t.drawArrays(t.TRIANGLE_STRIP,0,4),t.bindVertexArray(null)}let c=Math.cos(this.pitch),u=Math.sin(this.pitch),l=Math.cos(this.yaw),p=Math.sin(this.yaw),d=[this.target[0]+this.dist*c*p,this.target[1]-this.dist*c*l,this.target[2]+this.dist*u],g=as([this.target[0]-d[0],this.target[1]-d[1],this.target[2]-d[2]]),y=Math.abs(g[2])>0.99?[0,1,0]:[0,0,1],m=as(os(g,y)),h=os(m,g),f=new Float32Array([m[0],h[0],-g[0],0,m[1],h[1],-g[1],0,m[2],h[2],-g[2],0,-kn(m,d),-kn(h,d),kn(g,d),1]),w=Math.max(0.05,this.dist*0.01),C=Math.max(this.dist*10,this.radius*20),A=rr(35*Math.PI/180,a/o,w,C),M=sr(A,f);t.useProgram(this.prog),t.uniformMatrix4fv(this.uMvp,!1,M),t.uniform3f(this.uEye,d[0],d[1],d[2]),t.uniform3f(this.uRight,m[0],m[1],m[2]),t.uniform3f(this.uUp,h[0],h[1],h[2]),t.uniform3f(this.uFwd,g[0],g[1],g[2]);let P=!1,T=[],B=[];for(let R of this.partBatches){let O=e-R.fadeStartMs,H=R.fadeStartMs===0?1:Math.min(1,Math.max(0,O/300));if(H<1){if(P=!0,H>0)B.push({batch:R,fade:H})}else T.push(R)}if(t.enable(t.DEPTH_TEST),t.depthMask(!0),t.disable(t.BLEND),t.uniform1f(this.uFade,1),this.boardBatch)this.drawSubBatch(this.boardBatch.opaque);for(let R of T)this.drawSubBatch(R.opaque);if(t.depthMask(!1),t.enable(t.BLEND),t.uniform1f(this.uFade,1),this.boardBatch)this.drawSubBatch(this.boardBatch.translucent);for(let R of T)this.drawSubBatch(R.translucent);for(let{batch:R,fade:O}of B)t.uniform1f(this.uFade,O),this.drawSubBatch(R.opaque),this.drawSubBatch(R.translucent);return t.depthMask(!0),t.bindVertexArray(null),P}onPointerDown=(e)=>{if(this.canvas.setPointerCapture(e.pointerId),this.pointers.set(e.pointerId,{x:e.clientX,y:e.clientY,button:e.button,shift:e.shiftKey}),this.pointers.size===2){let[t,n]=Array.from(this.pointers.values());this.pinchDist=Math.hypot(n.x-t.x,n.y-t.y)||1}};onPointerMove=(e)=>{let t=this.pointers.get(e.pointerId);if(!t)return;let n=e.clientX-t.x,i=e.clientY-t.y;if(t.x=e.clientX,t.y=e.clientY,this.pointers.size===2){let[s,r]=Array.from(this.pointers.values()),a=Math.hypot(r.x-s.x,r.y-s.y)||1;if(this.pinchDist>0)this.dist=Math.max(this.radius*0.05,Math.min(this.radius*20,this.dist*(this.pinchDist/a)));this.pinchDist=a,this.cbs.onUserMove?.(),this.scheduleDraw();return}if(t.button===2||t.button===1||t.shift){let s=this.dist*0.0014,r=Math.cos(this.yaw),a=Math.sin(this.yaw);this.target[0]-=n*r*s,this.target[1]-=n*a*s,this.target[2]+=i*s}else this.yaw+=n*0.008,this.pitch=Math.max(-Math.PI*0.49,Math.min(Math.PI*0.49,this.pitch+i*0.008));this.cbs.onUserMove?.(),this.scheduleDraw()};onPointerUp=(e)=>{if(this.pointers.delete(e.pointerId),this.pointers.size<2)this.pinchDist=0};onWheel=(e)=>{e.preventDefault();let t=e.deltaY<0?0.8620689655172414:1.16;this.dist=Math.max(this.radius*0.05,Math.min(this.radius*20,this.dist*t)),this.cbs.onUserMove?.(),this.scheduleDraw()};onDblClick=()=>{this.fit()};onContextMenu=(e)=>{e.preventDefault()};destroy(){if(this.rafId)cancelAnimationFrame(this.rafId);if(this.resizeObs.disconnect(),this.canvas.removeEventListener("pointerdown",this.onPointerDown),this.canvas.removeEventListener("pointermove",this.onPointerMove),this.canvas.removeEventListener("pointerup",this.onPointerUp),this.canvas.removeEventListener("pointercancel",this.onPointerUp),this.canvas.removeEventListener("wheel",this.onWheel),this.canvas.removeEventListener("dblclick",this.onDblClick),this.canvas.removeEventListener("contextmenu",this.onContextMenu),this.deleteBatch(this.boardBatch),this.clearParts(),this.gl){if(this.bgVao)this.gl.deleteVertexArray(this.bgVao);if(this.bgProg)this.gl.deleteProgram(this.bgProg);if(this.prog)this.gl.deleteProgram(this.prog)}this.worker?.terminate(),this.canvas.remove()}}var ls=64,ar=16777216;function or(e,t){switch(e){case"board":case"3d":return t.board!==!1;case"schematic":return t.schematic!==!1;case"mech":return t.mech!==!1;case"gerbers":return t.gerbers!==!1;default:return!0}}function Lt(e){if(!e)return"";let t=e.replace(/\\/g,"/").replace(/\/+$/,""),n=t.lastIndexOf("/");return n>=0?t.slice(n+1):t}function cs(e){switch(e){case"board":return b("viewer.board","Board");case"schematic":return b("viewer.schematic","Schematic");case"3d":return b("viewer.solid","3D");case"gerbers":return b("gpui.gerbers","Gerbers");case"mech":return b("viewer.mech","Mech");case"files":return b("viewer.files","Files");case"diff":return b("viewer.diff","Diff");case"review":return b("viewer.review","Review");case"browser":return b("bots.tab.browser","Browser");case"terminal":return b("viewer.terminal","Terminal");default:return e?e.charAt(0).toUpperCase()+e.slice(1):""}}function Ln(e){return e==="board"||e==="schematic"||e==="gerbers"}function lr(e){return e==="files"||e==="diff"||e==="review"||e==="browser"||e==="terminal"}function Sn(e,t){let n=document.createElement("div");n.className="bp-vh";let i=document.createElement("div");i.className="bp-vh-title";let s=document.createElement("span");s.className="bp-vh-page";let r=document.createElement("span");r.className="bp-vh-sep",r.textContent="·",r.hidden=!0;let a=document.createElement("span");a.className="bp-vh-file",a.hidden=!0,i.append(s,r,a);let o=document.createElement("div");o.className="bp-vh-actions",n.append(i,o);let c=document.createElement("div");c.className="bp-solid-bar",c.setAttribute("data-testid","solid-presets-bar"),c.hidden=!0;let u=document.createElement("div");u.className="bp-v-banner",u.hidden=!0;let l=document.createElement("div");l.className="bp-v-stage-wrap";let p=document.createElement("div");p.className="bp-v-stage";let d=document.createElement("div");d.className="bp-v-overlay",d.hidden=!0;let g=document.createElement("div");g.className="bp-v-layers",g.hidden=!0;let y=document.createElement("div");y.className="bp-v-info",y.hidden=!0,l.append(p,d,g,y);let m=document.createElement("div");m.className="bp-history-bar",m.setAttribute("data-testid","viewer-history-bar"),m.hidden=!0,e.replaceChildren(n,c,u,l,m);let h="",f="",w=0,C=!1,A=new Set,M=[],P=0,T=new Map,B=new Map,R={},O=[],H="",ae="",ue=!1,oe=!1,we=0,Le=!1,Ne=0,he="",be=0,I=null,le=null,ne=null,X=null,ce=null,E=new Cn,k=0,j=!1,N="",K="",te="",D="";document.addEventListener("click",(F)=>{if(!j)return;if(F.target instanceof Node&&m.contains(F.target))return;j=!1,me()}),document.addEventListener("keydown",(F)=>{if(j&&F.key==="Escape")j=!1,me()});function z(){if(k)window.clearInterval(k),k=0;E.playing=!1}function je(){let F=f==="3d"||f==="mech";if(c.hidden=!F,!F)return;if(c.childElementCount>0)return;for(let _ of ns){let V=document.createElement("button");V.type="button",V.className="bp-v-btn",V.textContent=_.label,V.setAttribute("data-testid",`solid-view-${_.id}`),V.addEventListener("click",()=>{ne?.setView(_.id)}),c.append(V)}let U=document.createElement("button");U.type="button",U.className="bp-v-btn",U.textContent="Snap view",U.setAttribute("data-testid","solid-snap"),U.addEventListener("click",()=>{if(!ne)return;ne.snapPng().then((_)=>{if(!_)return;let V=URL.createObjectURL(_),G=document.createElement("a");G.href=V;let Z=(He()||f||"view").replace(/[^a-zA-Z0-9._-]/g,"_");G.download=`${Z}-snap.png`,G.click(),setTimeout(()=>URL.revokeObjectURL(V),1000)})}),c.append(U)}async function Se(){if(!h||f!=="board"&&f!=="schematic")return;me();let F=E.compareRequest();if(!F){N="",K="",te="",D="",await $e(!1);return}let U=`${f}|${F.commit}|${F.bits}|${ae}`;if(U===D&&A.size>0){ke(E.highlightEdits?`Comparing against ${E.activeRef()?.label||F.commit.slice(0,7)} (edits highlighted)`:`Comparing against ${E.activeRef()?.label||F.commit.slice(0,7)}`,!1);return}let _=++w;A.clear(),T.clear(),Ye(),C=!0,N="",K=F.commit,te="",D=U;try{let V=ae||(f==="schematic"?R.sch:R.pcb)||"";if(!V){let Ce=await t.hub.rpc("viewer.files",{thread:h});if(_!==w)return;R=Ce||{},re(),V=(f==="schematic"?R.sch:R.pcb)||""}if(!V)throw Error(`Unable to resolve ${f} file path for compare`);let G=await t.hub.rpc("viewer.compare",{thread:h,kind:f,commit:F.commit,bits:F.bits,...ae?{path:ae}:{}});if(_!==w)return;let Z=typeof G?.root==="string"?G.root:"",ee=f==="schematic"?"1":"0";N=Z?`${ee}|${Z}|diff +`:`${ee}|`,K=F.commit,te=V.startsWith("/")||/^[A-Za-z]:[\\/]/.test(V)||!Z?V:`${Z.replace(/\/+$/,"")}/${V.replace(/^\/+/,"")}`,C=!1;let xe=M;Ye();for(let Ce of xe)if(Ce.kind==="bin")Ge(Ce.buf);else We(Ce.key,Ce.none,Ce.retryable);ke(E.highlightEdits?`Comparing against ${E.activeRef()?.label||F.commit.slice(0,7)} (edits highlighted)`:`Viewing snapshot: ${E.activeRef()?.label||F.commit.slice(0,7)}`,!1)}catch(V){if(_!==w)return;C=!1,N="",K="",te="",D="",Ye(),ke(V instanceof Error?V.message:String(V),!0)}}function me(){let F=f==="board"||f==="schematic";if(m.hidden=!F,!F)return;let U=document.createElement("div");U.className="bp-history-group";let _=document.createElement("button");_.type="button",_.className="bp-v-btn",_.textContent="<",_.title="Older snapshot",_.disabled=E.refs.length===0||E.index>=E.refs.length-1,_.setAttribute("data-testid","history-prev"),_.addEventListener("click",()=>{if(z(),E.step(1))Se()});let V=document.createElement("button");V.type="button",V.className="bp-v-btn"+(E.playing?" is-on":""),V.textContent=E.playing?"⏸":"▶",V.title=E.playing?"Pause history":"Play history",V.disabled=E.refs.length===0,V.setAttribute("data-testid","history-play"),V.addEventListener("click",()=>{if(E.playing){z(),me();return}if(E.refs.length===0)return;if(E.playing=!0,E.isLive())E.index=E.refs.length-1,Se();else me();k=window.setInterval(()=>{if(!E.playing||f!=="board"&&f!=="schematic"){z(),me();return}if(E.step(-1))Se();else z(),me()},1400)});let G=document.createElement("button");G.type="button",G.className="bp-v-btn",G.textContent=">",G.title="Newer snapshot",G.disabled=E.isLive(),G.setAttribute("data-testid","history-next"),G.addEventListener("click",()=>{if(z(),E.step(-1))Se()});let Z=document.createElement("button");Z.type="button",Z.className="bp-v-btn"+(E.isLive()?" is-on":""),Z.textContent="Live",Z.setAttribute("data-testid","history-live"),Z.addEventListener("click",()=>{if(z(),E.goLive())ke("",!1),Se()});let ee=document.createElement("span");ee.className="bp-history-label",ee.setAttribute("data-testid","history-label");let xe=E.activeRef();ee.textContent=xe?xe.label||xe.commit.slice(0,7):E.refs.length>0?`Live (${E.refs.length} saved)`:"Live",U.append(_,V,G,Z,ee);let Ce=document.createElement("div");Ce.className="bp-history-group";let Pe=document.createElement("button");Pe.type="button",Pe.className="bp-v-btn"+(E.highlightEdits?" is-on":""),Pe.textContent="Highlight edits",Pe.disabled=E.refs.length===0,Pe.setAttribute("data-testid","history-highlight"),Pe.addEventListener("click",()=>{z(),E.toggleHighlight(),Se()});let Re=document.createElement("div");Re.className="bp-history-menu-wrap";let ye=document.createElement("button");if(ye.type="button",ye.className="bp-v-btn"+(j||!E.isLive()?" is-on":""),ye.disabled=E.refs.length===0,ye.setAttribute("data-testid","history-compare"),ye.setAttribute("aria-haspopup","menu"),ye.setAttribute("aria-expanded",String(j)),ye.textContent=xe?`Compare: ${xe.label||xe.commit.slice(0,7)} ▾`:"Compare ▾",ye.addEventListener("click",(Te)=>{Te.stopPropagation(),j=!j,me()}),Re.append(ye),j&&E.refs.length>0){let Te=document.createElement("div");Te.className="bp-history-menu",Te.setAttribute("role","menu"),Te.setAttribute("data-testid","history-compare-menu");let Ke=(Ie,mt,Mt)=>{let ze=document.createElement("button");ze.type="button",ze.className="bp-history-menu-item"+(Mt?" is-active":""),ze.setAttribute("role","menuitem"),ze.setAttribute("data-commit",mt),ze.textContent=Ie,ze.addEventListener("click",()=>{if(j=!1,z(),E.selectCommit(mt)){if(E.isLive())ke("",!1);Se()}else me()}),Te.append(ze)};Ke("Live (working tree)","",E.isLive());for(let Ie of E.refs)Ke(Ie.label||Ie.commit.slice(0,7),Ie.commit,xe?.commit===Ie.commit);Re.append(Te)}Ce.append(Pe,Re),m.replaceChildren(U,Ce)}async function Me(F){if(!F)return;try{let U=await t.hub.rpc("viewer.refs",{thread:F});if(F!==h)return;E.setRefs(Array.isArray(U?.refs)?U.refs:[]),me()}catch{if(F!==h)return;E.setRefs([]),me()}}function Y(){return document.documentElement.classList.contains("light")}let ve=new MutationObserver(()=>{let F=Y();le?.setTheme(F),ne?.setTheme(F),ce?.setTheme(F)});ve.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]});function ie(F,U="",_=!1){if(F==="none"){d.hidden=!0,d.replaceChildren();return}d.hidden=!1,d.className=`bp-v-overlay is-${F}`;let V=document.createElement("div");V.className="bp-v-state-card";let G=document.createElement("div");if(G.className="bp-v-state-msg",G.textContent=U,V.append(G),_){let Z=document.createElement("button");Z.type="button",Z.className="bp-v-btn is-primary",Z.textContent=b("tools.retry","Retry"),Z.addEventListener("click",()=>void $e(!0)),V.append(Z)}d.replaceChildren(V)}function ke(F,U){u.textContent=F,u.hidden=!F,u.classList.toggle("is-warn",U)}function He(){if(ae)return Lt(ae);if(f==="board"||f==="3d")return Lt(R.pcb);if(f==="schematic")return Lt(R.sch);if(f==="mech")return Lt(H);return""}function re(){s.textContent=cs(f);let F=He();if(r.hidden=!F,a.hidden=!F,a.textContent=F,o.replaceChildren(),f==="mech"&&O.length>1){let _=document.createElement("select");_.className="bp-v-select",_.setAttribute("aria-label",b("viewer.mech","Mech"));for(let V of O){let G=document.createElement("option");G.value=V,G.textContent=Lt(V),G.selected=V===H,_.append(G)}_.addEventListener("change",()=>{H=_.value,re(),$e(!1)}),o.append(_)}if(Ln(f)){let _=document.createElement("button");_.type="button",_.className="bp-v-btn"+(Le?" is-on":""),_.textContent=I?.layerHead||"Layers",_.setAttribute("data-testid","viewer-layers-btn"),_.addEventListener("click",()=>{if(Le=!Le,g.hidden=!Le,_.classList.toggle("is-on",Le),Le)_e("","")}),o.append(_)}if(f==="board"||f==="schematic"||f==="3d"||f==="mech"||f==="gerbers"){let _=document.createElement("button");_.type="button",_.className="bp-v-btn",_.textContent="Fit",_.setAttribute("data-testid","viewer-fit-btn"),_.addEventListener("click",()=>{le?.fit(),ne?.fit()}),o.append(_)}if((f==="board"||f==="schematic")&&t.hub.hasFeature("follow")){let _=document.createElement("button");_.type="button",_.className="bp-v-btn"+(ue&&!oe?" is-on":""),_.textContent=ue?oe?b("gpui.follow.paused","Follow (paused)"):"Follow agent":"Follow agent",_.setAttribute("data-testid","viewer-follow-btn"),_.addEventListener("click",()=>void tt()),o.append(_)}let U=document.createElement("button");U.type="button",U.className="bp-v-btn bp-v-close",U.textContent="✕",U.title=b("common.close","Close"),U.setAttribute("aria-label",b("common.close","Close")),U.setAttribute("data-testid","viewer-close-btn"),U.addEventListener("click",()=>t.closeViewer()),o.append(U)}function ge(){if(!I){g.replaceChildren();return}let F=document.createDocumentFragment(),U=document.createElement("div");U.className="bp-v-layers-head";let _=document.createElement("span");if(_.textContent=I.layerHead||"Layers",U.append(_),I.layerReset){let ee=document.createElement("button");ee.type="button",ee.className="bp-v-btn",ee.textContent="Reset",ee.addEventListener("click",()=>void _e("reset","")),U.append(ee)}if(F.append(U),I.layerModes){let ee=document.createElement("div");ee.className="bp-v-layers-modes",["All","Dim","Only"].forEach((xe,Ce)=>{let Pe=document.createElement("button");Pe.type="button",Pe.className="bp-v-btn"+(I?.layerMode===Ce?" is-on":""),Pe.textContent=xe,Pe.addEventListener("click",()=>void _e("mode",String(Ce))),ee.append(Pe)}),F.append(ee)}let V=le?.presentColors()??new Map,G=(I.layerList||[]).concat(I.layerMarks||[]),Z=document.createElement("div");Z.className="bp-v-layers-list";for(let ee of G){let xe=V.get(ee.layer);if(xe===void 0)continue;let Ce=document.createElement("div");Ce.className="bp-v-layer-row"+(ee.active?" is-focus":"");let Pe=document.createElement("input");Pe.type="checkbox",Pe.checked=ee.on!==!1,Pe.addEventListener("change",()=>void _e("toggle",String(ee.layer)));let Re=document.createElement("span");Re.className="bp-v-layer-swatch";let ye=xe>>>16&255,Te=xe>>>8&255,Ke=xe&255;Re.style.background=ee.on!==!1?`rgb(${ye},${Te},${Ke})`:`rgba(${ye},${Te},${Ke},0.2)`;let Ie=document.createElement("button");Ie.type="button",Ie.className="bp-v-layer-name",Ie.textContent=ee.name,Ie.addEventListener("click",()=>void _e("pick",String(ee.layer))),Ce.append(Pe,Re,Ie),Z.append(Ce)}F.append(Z),g.replaceChildren(F)}async function _e(F,U){if(!Ln(f))return;let _=w;try{let V=await t.hub.rpc("viewer.layers",{kind:f,present:be,off:Ne,focus:he,...F?{action:F,value:U}:{}});if(_!==w||!V)return;Ne=Number(V.own)||0,he=typeof V.focus==="string"?V.focus:"",I=V;let G={off:Number(V.off)||0,dim:Number(V.dim)||0,lift:typeof V.lift==="number"?V.lift:255};if(le?.setLayers(G),re(),Le)ge()}catch{}}async function Ue(){if(!ue||oe||!h||!t.hub.hasFeature("follow"))return;oe=!0,re();try{await t.hub.rpc("viewer.follow",{thread:h,action:"pause"})}catch{}}async function tt(){if(!h||!t.hub.hasFeature("follow"))return;let F=!ue?"on":oe?"resume":"off";try{let U=await t.hub.rpc("viewer.follow",{thread:h,action:F});if(ue=!!U.on,oe=!!U.paused,re(),U.on&&!U.paused&&U.focus&&Array.isArray(U.focus.box)&&U.focus.box.length===4&&(U.seq||0)>we)we=U.seq||we,le?.zoomToBoxMm([U.focus.box[0],U.focus.box[1],U.focus.box[2],U.focus.box[3]])}catch{}}function de(){y.hidden=!0,y.replaceChildren(),le?.setHighlights([])}function dt(F){let U=F.split(";").filter(Boolean),_=U.shift()||F,V=[],G="",Z="";for(let Re of U){if(Re.startsWith("g="))continue;let ye=Re.indexOf("=");if(ye>0){let Te=Re.slice(0,ye),Ke=Re.slice(ye+1);if((Te==="ref"||Te==="symbol")&&!G)G=Ke;if(Te==="net"&&!Z)Z=Ke;V.push([Te,Ke])}else V.push([Re,""])}let ee=document.createElement("div");ee.className="bp-v-info-head";let xe=document.createElement("span");xe.className="bp-v-info-title",xe.textContent=_;let Ce=document.createElement("button");Ce.type="button",Ce.className="bp-v-info-x",Ce.textContent="×",Ce.setAttribute("aria-label","Clear selection"),Ce.addEventListener("click",de),ee.append(xe,Ce);let Pe=document.createElement("div");Pe.className="bp-v-info-rows";for(let[Re,ye]of V){let Te=document.createElement("span");Te.className="bp-v-info-chip",Te.textContent=ye?`${Re}: ${ye}`:Re,Pe.append(Te)}return y.replaceChildren(ee,...V.length>0?[Pe]:[]),y.hidden=!1,{ref:G||void 0,net:Z||void 0}}async function Je(F){if(!F){de();return}let U=Array.from(A)[0]||"";if(!U)return;let _=w;try{let V=await t.hub.rpc("viewer.info",{key:U,at:F.at,idx:F.idx});if(_!==w)return;let G=typeof V.info==="string"?V.info:"";if(!G){de();return}let{ref:Z,net:ee}=dt(G),xe=[];if(Z)xe.push(["ref",Z]);if(ee)xe.push(["net",ee]);let Ce=[[F.at,F.idx]];for(let[Pe,Re]of xe){let ye=await t.hub.rpc("viewer.probe",{key:U,name:Pe,value:Re});if(_!==w)return;if(Array.isArray(ye.matches))for(let Te of ye.matches)Ce.push(Te)}le?.setHighlights(Ce)}catch{de()}}function pt(){X?.destroy(),X=null,ce?.destroy(),ce=null,le?.destroy(),le=null,ne?.destroy(),ne=null,p.replaceChildren(),Le=!1,g.hidden=!0,y.hidden=!0,y.replaceChildren(),ke("",!1),ie("none")}function Ye(){M=[],P=0}async function $e(F){if(!h||!f)return;let U=++w;if(A.clear(),C=!1,Ye(),pt(),re(),je(),me(),(f==="board"||f==="schematic")&&h)Me(h);if(lr(f)){if(t.hub.rpc("viewer.watch",{thread:h,kind:""}).catch(()=>{}),f==="files")X=Zi(p,t,h,(G,Z)=>{if(f=G,ae=Z,G==="mech")H=Z;$e(!1)});else if(f==="diff")X=Qi(p,t,h);else if(f==="review")X=es(p,t,h);else if(f==="browser")X=Ji(p,t,h);else if(f==="terminal")ie("loading","Loading terminal…"),import("/assets/terminal.js").then((Z)=>{if(U!==w)return;if(ie("none"),Z?.mountTerminalPane)ce=Z.mountTerminalPane(p,t,h,Y());else ie("error","Terminal chunk missing",!0)},(Z)=>{if(U!==w)return;ie("error",Z instanceof Error?Z.message:String(Z),!0)});return}if(ie("loading","Loading…"),!R.root)try{let G=await t.hub.rpc("viewer.files",{thread:h});if(U!==w)return;R=G||{},re()}catch{}if(f==="gerbers"&&R.hasGerbers===!1){ie("empty","No Gerbers in this project",!1);return}let _=Y();if(f==="3d"||f==="mech")ne=new An(p,{onStatus:(G,Z)=>{if(Z)ie("none"),ke(G,!1);else if(G)ie("loading",G);else ie("none"),ke("",!1)},onUserMove:()=>void Ue()}),ne.setTheme(_);else if(f==="board"||f==="schematic"||f==="gerbers")le=new En(p,{onPick:(G)=>void Je(G),onUserMove:()=>void Ue()}),le.setTheme(_);else{ie("empty",`${cs(f)} is not available in this viewer`,!1);return}let V={thread:h};if(F)V.force=!0;if(f==="mech"){if(O.length===0)try{let G=await t.hub.rpc("mech.list",{thread:h});if(U!==w)return;if(O=Array.isArray(G.parts)?G.parts:[],!H)H=G.primary||O[0]||"";re()}catch(G){if(U!==w)return;ie("error",G instanceof Error?G.message:String(G),!0);return}if(!H){ie("empty",b("gpui.rail.no.mech","No mechanical parts in this project"),!1);return}V.kind="3d",V.path=H}else{if(V.kind=f,ae&&(f==="board"||f==="schematic"))V.path=ae;if(f==="3d"&&!F&&ne){let G=ne.keptToken();if(G)V.kept=G}if((f==="board"||f==="schematic"||f==="gerbers")&&!F&&t.hub.hasFeature("keptChunks"))V.keptChunks=Array.from(B.keys())}C=!0,N="",K="",te="",D="";try{let G=await t.hub.rpc("viewer.watch",V);if(U!==w)return;A=new Set(Array.isArray(G.keys)?G.keys:[]),C=!1;let Z=M;Ye();for(let ee of Z)if(ee.kind==="bin")Ge(ee.buf);else We(ee.key,ee.none,ee.retryable)}catch(G){if(U!==w)return;C=!1,A.clear(),Ye();let Z=G instanceof Error?G.message:String(G),ee=/no gerbers|not in this project|another machine/i.test(Z);ie(ee?"empty":"error",Z,!ee)}}function We(F,U,_){if(C){if(M.length{if(F.t==="plot"&&typeof F.none==="string"&&typeof F.key==="string")We(F.key,F.none,F.retryable===!0)}),Oe=Bt(()=>{if(f)re()}),Nt=(F)=>{if(F.key==="Escape"&&f&&!y.hidden)de()};return window.addEventListener("keydown",Nt),{open(F,U){if(U!==h){if(h=U,R={},O=[],H="",T.clear(),ue=!1,oe=!1,we=0,Ne=0,he="",be=0,I=null,t.hub.hasFeature("follow"))t.hub.rpc("viewer.follow",{thread:U}).then((_)=>{if(U!==h)return;if(ue=!!_.on,oe=!!_.paused,we=Number(_.seq)||0,f)re()}).catch(()=>{})}if(F!==f)z(),E.goLive(),Ne=0,he="",be=0,I=null;f=F,ae="",$e(!1)},reconcileHas(F){if(f&&!or(f,F))t.closeViewer()},close(){if(w++,C=!1,z(),j=!1,N="",K="",te="",D="",E.goLive(),c.hidden=!0,m.hidden=!0,Ye(),h)t.hub.rpc("viewer.watch",{thread:h,kind:""}).catch(()=>{});f="",A.clear(),pt()}}}var ds="http://www.w3.org/2000/svg";function St(e){let t=document.createElementNS(ds,"svg");t.setAttribute("viewBox","0 0 24 24"),t.setAttribute("width","13"),t.setAttribute("height","13"),t.setAttribute("fill","none"),t.setAttribute("stroke","currentColor"),t.setAttribute("stroke-width","1.8"),t.setAttribute("aria-hidden","true");for(let n of e){let i=document.createElementNS(ds,"path");i.setAttribute("d",n),t.appendChild(i)}return t}function cr(e){if(!e)return"bp-dot-idle";let t=e.status||e.state;if(t==="active"||t==="working")return"bp-dot-work";if(t==="finished")return"bp-dot-done";if(t==="waiting"||t==="asking"||t==="blocked"||t==="failed"||(e.waiting??0)>0)return"bp-dot-need";return"bp-dot-idle"}function ps(e,t){if(!e)return!0;if(t==="board"||t==="3d")return e.board!==!1;if(t==="schematic")return e.schematic!==!1;if(t==="mech")return e.mech!==!1;if(t==="gerbers")return e.gerbers!==!1;return!0}function ms(e){if(!e)return;let t=e==="light";document.documentElement.classList.toggle("light",t);try{localStorage.setItem("bp.theme",t?"light":"dark")}catch{}}function dr(){return`web-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`}function us(){let e=document.getElementById("root");if(!e)return;try{if(localStorage.getItem("bp.theme")==="light")document.documentElement.classList.add("light")}catch{}let t=document.createElement("header");t.className="bp-topbar",t.setAttribute("data-testid","topbar");let n=document.createElement("button");n.type="button",n.className="icon bp-side-toggle",n.textContent="☰",n.title="Toggle sidebar",n.setAttribute("aria-label","Toggle sidebar");let i=document.createElement("div");i.className="bp-brand";let s=document.createElement("img");s.src="/assets/favicon.svg",s.alt="Backplane",s.className="bp-logo";let r=document.createElement("span");r.className="bp-brand-name bp-hide-phone",r.textContent="Backplane";let a=document.createElement("span");a.className="bp-crumb-sep bp-hide-phone",a.textContent="/";let o=document.createElement("span");o.className="bp-crumb-proj bp-hide-phone";let c=document.createElement("span");c.className="bp-crumb-sep bp-hide-phone",c.textContent="/";let u=document.createElement("span");u.className="bp-crumb-thread",u.setAttribute("data-testid","thread-title");let l=document.createElement("span");l.className="bp-plan-top-badge bp-hidden",l.setAttribute("data-testid","plan-top-badge"),i.append(s,r,a,o,c,u,l);let p=document.createElement("div");p.className="bp-top-state bp-hide-phone bp-hidden";let d=document.createElement("span");d.className="bp-top-state-lbl",d.textContent="STATE";let g=document.createElement("span");g.className="bp-dot bp-dot-idle";let y=document.createElement("span");y.className="bp-top-state-word",p.append(d,g,y);let m=document.createElement("div");m.className="bp-top-acts bp-hide-phone bp-hidden";let h=document.createElement("button");h.type="button",h.className="bp-btn-ghost bp-top-act";let f=document.createElement("span");f.textContent=b("menu.pin","Pin"),h.append(St(["M12 17v5","M9 3h6l1 7 3 3H5l3-3 1-7z"]),f);let w=document.createElement("button");w.type="button",w.className="bp-btn-ghost bp-top-act";let C=document.createElement("span");C.textContent=b("menu.settle","Settle"),w.append(St(["M12 22a10 10 0 1 0 0-20 10 10 0 0 0 0 20z","M9 12l2 2 4-4"]),C);let A=document.createElement("div");A.className="bp-menu-wrap";let M=document.createElement("button");M.type="button",M.className="bp-btn-ghost bp-top-act",M.textContent="▾",M.title="Thread menu",M.setAttribute("aria-label","Thread menu"),M.setAttribute("data-testid","thread-menu-btn");let P=document.createElement("div");P.className="bp-popover bp-hidden",P.setAttribute("data-testid","thread-menu"),A.append(M,P),m.append(h,w,A);let T=document.createElement("div");T.className="bp-top-right";let B=document.createElement("button");B.type="button",B.className="bp-btn-ghost bp-top-act bp-hide-tablet",B.setAttribute("data-testid","improvements-btn");let R=document.createElement("span");R.textContent=b("gpui.improvements","Improvements"),B.append(St(["M12 2l2.4 7.4H22l-6.2 4.5 2.4 7.4L12 16.8l-6.2 4.5 2.4-7.4L2 9.4h7.6z"]),R);let O=document.createElement("button");O.type="button",O.className="bp-cmd-box bp-hide-tablet",O.textContent="> Jump or run a command";let H=document.createElement("button");H.type="button",H.className="icon bp-top-icon",H.title="Search",H.setAttribute("aria-label","Search"),H.appendChild(St(["M11 19a8 8 0 1 0 0-16 8 8 0 0 0 0 16z","M21 21l-4.3-4.3"]));let ae=document.createElement("button");ae.type="button",ae.className="icon bp-top-icon",ae.title=b("palette.settings","Settings"),ae.setAttribute("aria-label",b("palette.settings","Settings")),ae.setAttribute("data-testid","settings-btn"),ae.appendChild(St(["M12 15a3 3 0 1 0 0-6 3 3 0 0 0 0 6z","M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 1 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 1 1-4 0v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 1 1-2.83-2.83l.06-.06a1.65 1.65 0 0 0 .33-1.82 1.65 1.65 0 0 0-1.51-1H3a2 2 0 1 1 0-4h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 1 1 2.83-2.83l.06.06a1.65 1.65 0 0 0 1.82.33H9a1.65 1.65 0 0 0 1-1.51V3a2 2 0 1 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 1 1 2.83 2.83l-.06.06a1.65 1.65 0 0 0-.33 1.82V9c.26.6.85 1 1.51 1H21a2 2 0 1 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z"])),T.append(B,O,H,ae),t.append(n,i,p,m,T);let ue=document.createElement("div");ue.className="bp-body";let oe=document.createElement("aside");oe.className="bp-sidebar",oe.setAttribute("data-testid","sidebar");let we=document.createElement("main");we.className="bp-center";let Le=document.createElement("div");Le.className="bp-right-area bp-hidden",Le.setAttribute("data-testid","right-area");let Ne=document.createElement("div");Ne.className="bp-right-top";let he=document.createElement("section");he.className="bp-viewer-pane bp-hidden",he.setAttribute("data-testid","viewer-pane"),Ne.appendChild(he),Le.appendChild(Ne);let be=document.createElement("nav");be.className="bp-rail",be.setAttribute("aria-label","Viewer rail"),be.setAttribute("data-testid","viewer-rail"),ue.append(oe,we,Le,be),e.append(t,ue);let I=new yn,le=null,ne=new Set,X=0,ce=null,E=[],k=[],j=[],N=[],K=[],te=[],D="",z=0,je=0,Se=null,me=null,Me="",Y=null,ve=20,ie={},ke=new Map;function He(v,x){ke.delete(v),ke.set(v,x);while(ke.size>ve){let L=ke.keys().next().value;if(L!==void 0)ke.delete(L);else break}}let re=new gn(oe,{onSelectThread:(v)=>{if(v===D&&Se!==null){oe.classList.remove("bp-sidebar-open");return}Ie(v)},onNewThread:(v)=>{Ut(v)},onSelectBot:(v)=>{Ie(v.thread)},onThreadAct:(v,x)=>{Ze(v,x)},onToggleSection:(v)=>{if(ne.has(v))ne.delete(v);else ne.add(v);ye()},onToggleProjectFold:(v)=>{I.rpc("sidebar.act",{action:"project-fold",value:v}).then(()=>ye()).catch(()=>{})},onCollapseSidebar:()=>{oe.classList.remove("bp-sidebar-open"),oe.classList.add("bp-sidebar-collapsed")},onNeedAct:async(v)=>{let x=Gt(v,!1);if(!x)return;if(x.kind==="thread"){Ie(x.id);return}if(x.kind!=="call")return;let L=Ii(await I.rpc(x.method,x.params));if(L?.kind==="thread")Ie(L.id);ye()},hasRoomView:!1,onAddProject:()=>We.open({mode:"folder"})}),ge=new Zt(we,{onLoadOlder:()=>{ze()},onGoToEntry:(v)=>{Mt(v)},onOpenAccounts:()=>{F()},onAnswerAsk:(v,x)=>{I.rpc("ask.answer",{ask:v,answer:x}).catch((L)=>{de.showError(L instanceof Error?L.message:"Could not send answer")})},onToggleReview:(v)=>{if(!D)return;let x=z;I.rpc("thread.review",{thread:D,on:v}).then((L)=>{if(x===z)ge.setReview(L.review??null)}).catch(()=>{})},onUnansweredAction:(v,x)=>{if(!D)return;if(v==="again"||v==="thread-again")I.rpc("thread.again",{thread:D,value:x}).catch(()=>{});else I.rpc("thread.act",{thread:D,action:v,value:x}).catch(()=>{})},onReplyEntry:(v)=>{if(!I.hasFeature("reply")){let x=(v.text||"").split(` `)[0]?.slice(0,100)??"";if(x)de.prependDraft(`> ${x} -`);return}if(!v.text||!v.text.trim()||v.live||v.id.startsWith("local-"))return;ut({id:v.id,text:v.text,role:v.kind==="user"?"user":"assistant"})},onLoadImage:async(v,x)=>{try{let L={entry:v,path:x};if(I.hasFeature("blobs"))L.metaOnly=!0;let N=await I.rpc("message.image",L);if(N.blob&&N.blob.startsWith("/blob/"))return{url:N.blob};if(N.mime&&N.data)return{mime:N.mime,data:N.data}}catch{}return null}});function _e(v){if(!v)return null;if(v.planMode)return v.planMode;if(v.provider==="claude")return{phase:"off",interaction:"default",once:!1};return null}function Ue(v,x){if(!D)return;let L=z,N=D;I.rpc(v,x).then((q)=>{if(L!==z||D!==N)return;if(q.thread){let te=k.findIndex((ve)=>ve.id===q.thread.id);if(te>=0)k[te]=q.thread;else k.unshift(q.thread);re.setData(E,k,j,P),ge.updateThreadMeta(q.thread),G(),de.setState(!0,q.thread.state==="working")}}).catch((q)=>{if(L===z&&D===N)de.showError(q instanceof Error?q.message:"Could not change Plan mode")})}let tt,de=new Qt(we,{onSend:(v,x)=>{Pn(v,x)},onRunCommand:(v)=>{Nn(v)},onInterrupt:()=>{if(D)I.rpc("turn.interrupt",{thread:D}).catch(()=>{})},onQueryMentions:async(v,x)=>{try{return(await I.rpc("mentions.list",{q:v,kind:x,limit:10})).items??[]}catch{return[]}},onToggleVoice:()=>{tt.toggle()},onCyclePlanMode:()=>{let v=k.find((L)=>L.id===D)??null,x=_e(v);if(!x||!D)return;if(x.interaction!=="plan")Ue("thread.planonce",{thread:D,on:!0});else if(x.once)Ue("thread.pick",{thread:D,action:"interaction",value:"plan"});else Ue("thread.pick",{thread:D,action:"interaction",value:"default"})},onSetPlanMode:(v)=>{if(!D)return;if(v==="once")Ue("thread.planonce",{thread:D,on:!0});else if(v==="always")Ue("thread.pick",{thread:D,action:"interaction",value:"plan"});else Ue("thread.pick",{thread:D,action:"interaction",value:"default"})}});tt=new gn(I,{getThreadId:()=>D,getDraft:()=>de.getDraft(),getCaret:()=>de.getCaret(),setDraft:(v)=>de.setDraft(v),setRecording:(v)=>de.setVoiceRecording(v),setLevel:(v)=>de.setVoiceLevel(v),showError:(v)=>de.showError(v)});function dt(){let v=Me!=="",x=Je.isOpen();Le.classList.toggle("bp-hidden",!v&&!x),Le.classList.toggle("bp-has-viewer",v),Le.classList.toggle("bp-has-mgmt",x)}let Je=new ln(Ne,Le,{hub:I,getThreadId:()=>D,getThreadGen:()=>z,onSendText:(v)=>{Pn(v)},onOpenChange:()=>dt()});function pt(v){let x=window.prompt("Rename thread",v.title||"");if(!x||!x.trim())return;I.rpc("thread.act",{thread:v.id,action:"rename",title:x.trim()}).then((L)=>{if(L.thread)k=k.map((N)=>N.id===L.thread.id?L.thread:N),G(),ye()}).catch((L)=>{de.showError(L instanceof Error?L.message:"Could not rename thread")})}function Ye(v){switch(v.type){case"thread":Ie(v.id);break;case"rail":if(!D&&v.id!=="terminal")break;if(Me===v.id)Z();else Q(v.id);break;case"thread-act":if(D)Ze(D,v.action);break;case"new-thread":Vt(v.projectId);break;case"rename":{let x=k.find((L)=>L.id===D);if(x)pt(x);break}case"prev-thread":case"next-thread":{let x=k.filter((te)=>!te.archived&&!te.swarm);if(x.length<2)break;let L=x.findIndex((te)=>te.id===D),N=v.type==="next-thread"?1:-1,q=x[(L<0?0:L+N+x.length)%x.length];if(q)Ie(q.id);break}case"command":if(v.runDirectly)Nn(v.word);else de.setDraft(`${v.word} `),de.focus();break;case"improvements":V();break;case"settings":Oe.open();break;case"sidebar":oe.classList.toggle("bp-sidebar-open"),oe.classList.toggle("bp-sidebar-collapsed");break}}let $e=new cn(e,{getState:()=>({selectedThreadId:D,threads:k,projects:E,bots:j,railItems:K,commands:ee}),onSearch:async(v)=>{if(!I.hasFeature("search"))return{threads:[],projects:[],messages:[]};return I.rpc("search",{q:v,limit:20})},onExecute:Ye}),We=new zt(e,{hub:I,onProjectAdded:(v)=>{if(ye(),v.id)Vt(v.id)},onCloneDone:(v)=>{if(ye(),v.thread)Ie(v.thread)}}),Ge=new pn(be,(v)=>{if(v==="commands"){$e.open();return}if(!D)return;if(Me===v)Z();else Q(v)}),nt=null,St=null,Oe=new mn(e,{onLoadDevices:async()=>(await I.rpc("devices.page",{})).rows??[],onDevicesAct:async(v,x)=>{await I.rpc("devices.page.act",{action:v,value:x})},onGetHome:()=>nt,onMoveHomeHere:async()=>{await I.rpc("home.move",{to:"back"})},onGetNoProvider:()=>St,onLogout:()=>Wn(()=>{I.disconnect(),window.location.replace("/")})});function Pt(v){if(St=v,ge.setNoProvider(v),Oe.isOpen())Oe.refresh()}function F(){Oe.openToAccounts()}function U(v,x){let L=v instanceof Error?v.message:x;de.showError(L,Pi(L)?{label:b("provider.notice.button","Open Settings → Accounts"),onClick:F}:void 0)}h.addEventListener("click",()=>{let v=k.find((x)=>x.id===D);if(v)Ze(v.id,v.pinned?"unpin":"pin")}),w.addEventListener("click",()=>{let v=k.find((x)=>x.id===D);if(v)Ze(v.id,v.settled?"unsettle":"settle")});let W=new hn(e,(v,x)=>x?I.rpc("thread.context.mcp",{thread:v,...x}):I.rpc("thread.context",{thread:v}));M.addEventListener("click",(v)=>{v.stopPropagation();let x=k.find((q)=>q.id===D);if(!x)return;if(!S.classList.contains("bp-hidden")){S.classList.add("bp-hidden");return}let L=[{label:"Rename…",run:()=>pt(x)},{label:x.pinned?b("menu.unpin","Unpin"):b("menu.pin","Pin"),run:()=>{Ze(x.id,x.pinned?"unpin":"pin")}},{label:x.settled?b("phone.unsettle","Unsettle"):b("menu.settle","Settle"),run:()=>{Ze(x.id,x.settled?"unsettle":"settle")}},{label:x.archived?"Unarchive":"Archive",run:()=>{Ze(x.id,x.archived?"unarchive":"archive")}},{label:"Delete",danger:!0,run:()=>{if(window.confirm("Delete this thread?"))Ze(x.id,"delete")}}];if(I.hasFeature("threadContext"))L.unshift({label:b("thread.context.title","Context & Prompt"),run:()=>W.open(x.id)});let N=document.createDocumentFragment();for(let q of L){let te=document.createElement("button");te.type="button",te.className="bp-popover-item"+(q.danger?" danger":""),te.textContent=q.label,te.addEventListener("click",()=>{S.classList.add("bp-hidden"),q.run()}),N.appendChild(te)}S.replaceChildren(N),S.classList.remove("bp-hidden")}),document.addEventListener("click",()=>S.classList.add("bp-hidden"));async function V(){let v=document.createElement("div");v.className="bp-modal-backdrop",v.setAttribute("data-testid","improvements-modal");let x=document.createElement("div");x.className="bp-modal";let L=document.createElement("div");L.className="bp-modal-head";let N=document.createElement("h2");N.textContent=b("gpui.improvements","Improvements");let q=document.createElement("button");q.type="button",q.className="icon",q.textContent="×",q.addEventListener("click",()=>v.remove()),L.append(N,q);let te=document.createElement("div");te.className="bp-modal-body",te.textContent="Loading…",x.append(L,te),v.appendChild(x),v.addEventListener("click",(ve)=>{if(ve.target===v)v.remove()}),e.appendChild(v);try{let ve=await I.rpc("improvements.projects",{}),De=ve.projects??[];if(De.length===0){te.textContent="No projects available for Improvements.";return}let Qe=document.createDocumentFragment();for(let Ae of De){let se=document.createElement("div");se.className="bp-set-row";let Xe=document.createElement("div");Xe.className="bp-set-info",Xe.textContent=Ae.title||Ae.name||Ae.id;let et=document.createElement("button");et.type="button",et.className=Ae.id===ve.project?"primary":"",et.textContent=Ae.id===ve.project?"Active":"Select",et.addEventListener("click",()=>{I.rpc("improvements.project",{project:Ae.id}).then(()=>v.remove()).catch(()=>{})}),se.append(Xe,et),Qe.appendChild(se)}te.replaceChildren(Qe)}catch(ve){te.textContent=ve instanceof Error?ve.message:"Could not load Improvements."}}B.addEventListener("click",()=>{V()}),O.addEventListener("click",()=>$e.open()),H.addEventListener("click",()=>$e.open()),ae.addEventListener("click",()=>{Oe.open()}),n.addEventListener("click",()=>{oe.classList.toggle("bp-sidebar-open"),oe.classList.toggle("bp-sidebar-collapsed")});function G(){let v=k.find((N)=>N.id===D)??null,x=v?E.find((N)=>N.id===v.project):void 0;o.textContent=x?.title??"",a.classList.toggle("bp-hidden",!x),c.classList.toggle("bp-hidden",!v),u.textContent=v?v.title||"Untitled thread":"";let L=_e(v);if(de.setPlanMode(L),!L||L.phase==="off")l.classList.add("bp-hidden"),l.classList.remove("is-exec"),l.textContent="";else l.classList.remove("bp-hidden"),l.classList.toggle("is-exec",L.phase==="executing"),l.title=b("gpui.planmode.tip","Plan before acting (1 turn, always, or off)"),l.textContent=L.phase==="armed"&&L.once?b("gpui.planmode.top.once","Plan (1 turn)"):L.phase==="armed"?b("gpui.mgmt.plan.tab","Plan"):L.phase==="planning"?b("gpui.planmode.top.planning","Planning"):L.phase==="pending"?b("gpui.planmode.top.pending","Review plan"):b("gpui.planmode.top.executing","Building plan");if(p.classList.toggle("bp-hidden",!v),m.classList.toggle("bp-hidden",!v),v){g.className=`bp-dot ${or(v)}`,y.textContent=v.status||v.state||"idle",f.textContent=v.pinned?b("menu.unpin","Unpin"):b("menu.pin","Pin"),C.textContent=v.settled?b("phone.unsettle","Unsettle"):b("menu.settle","Settle");let N=v;de.setModelChip(v.chip||v.model||"default",v.provider,N.ctxPct??N.contextPct),de.setMemory(v.memory)}else de.setModelChip("default"),de.setMemory(null)}function Z(v=!0){if(je++,Me="",Ge.setActive(""),he.classList.add("bp-hidden"),Y?.close(),dt(),v&&D&&I.getState()==="connected")I.rpc("viewer.watch",{thread:D,kind:""}).catch(()=>{})}function Q(v){if(je++,Me=v,Ge.setActive(v),he.classList.remove("bp-hidden"),dt(),!Y&&typeof Ln==="function")Y=Ln(he,{hub:I,getThreadId:()=>D,closeViewer:()=>Z(!0)});if(Y)Y.open(v,D);else{let x=document.createElement("div");x.className="bp-viewer-placeholder";let L=document.createElement("div");L.className="bp-viewer-bar";let N=document.createElement("span");N.textContent=v.toUpperCase();let q=document.createElement("button");q.type="button",q.className="icon",q.textContent="×",q.addEventListener("click",()=>Z(!0)),L.append(N,q);let te=document.createElement("div");te.className="bp-dim bp-viewer-msg",te.textContent=`Viewer pane (${v}).`,x.append(L,te),he.replaceChildren(x)}}async function xe(v,x){if(!v||!I.hasFeature("rail")){if(x===z)K=[],Ge.setItems([]);return}let L=++je;try{let N=await I.rpc("viewer.rail",{thread:v,page:Me});if(x!==z||L!==je)return;let q=Array.isArray(N.rail)?N.rail:Array.isArray(N.items)?N.items:[];if(K=q,Ge.setItems(q),N.has){if(Y?.reconcileHas?.(N.has),Me&&!ds(N.has,Me))Z(!0)}}catch{if(x===z&&L===je)K=[],Ge.setItems([])}}function Ce(v){for(let x of v)if(x.kind==="threads"){for(let L of x.rows)if(!L.off&&(L.nav||L.id)&&!(L.nav||"").startsWith("@room:"))return L.nav||L.id}else if(x.kind==="projects"){for(let L of x.rows)for(let N of L.threads??[])if(!N.off&&(N.nav||N.id)&&!(N.nav||"").startsWith("@room:"))return N.nav||N.id}return""}function Pe(v,x){for(let L of v)if(L.kind==="threads"){if(L.rows.some((N)=>(N.nav||N.id)===x))return!0}else if(L.kind==="projects"){for(let N of L.rows)if((N.threads??[]).some((q)=>(q.nav||q.id)===x))return!0}return!1}function Re(v){let x=[];for(let L of v){if(L.kind!=="projects")continue;for(let N of L.rows)x.push({id:N.id,title:N.title,css:N.css,color:N.color})}if(x.length>0)E=x}async function ye(){if(!I.hasFeature("sections"))return!1;let v=++X;try{let x=await I.rpc("sidebar.sections",{open:Array.from(ne)});if(v!==X)return!0;let L=Array.isArray(x.sections)?x.sections:[];return le=L,Re(L),re.setData(E,k,j,P),re.setSections(L,j,P),G(),!0}catch{return!1}}function Te(){if(!I.hasFeature("sections"))return;if(ce!==null)window.clearTimeout(ce);ce=window.setTimeout(()=>{ce=null,ye()},150)}async function Ke(){if(Se=null,I.hasFeature("bots"))try{let x=await I.rpc("bots.list",{});j=x.bots??[],P=x.rooms??[]}catch{}if(I.hasFeature("shell")){let x=await I.rpc("shell.sync",{have:ie,settled:25}),L=new Set(x.removed??[]),N=new Set((x.projects??[]).map((q)=>q.id));if(L.size>0||N.size>0)E=[...E.filter((q)=>!L.has(q.id)&&!N.has(q.id)),...x.projects??[]],k=[...k.filter((q)=>!L.has(q.project)&&!N.has(q.project)),...x.threads??[]];else if(Array.isArray(x.threads)&&x.threads.length>0){let q=new Map(k.map((te)=>[te.id,te]));for(let te of x.threads)q.set(te.id,te);k=Array.from(q.values())}if(x.sections!==void 0){let q=Array.isArray(x.sections)?x.sections:Array.isArray(x.sections?.sections)?x.sections.sections:null;if(q)le=q,Re(q)}if(x.h)ie=x.h;re.setData(E,k,j,P),re.setSections(le,j,P)}else if(I.hasFeature("sections")){let[x,L]=await Promise.all([I.rpc("sidebar.sections",{open:Array.from(ne)}).catch(()=>null),I.rpc("threads.list",{limit:200,archived:!1}).catch(()=>({threads:[]}))]);if(k=L.threads??[],x&&Array.isArray(x.sections)){let N=x.sections;if(!N.some((te)=>te.kind==="projects"&&te.rows.length>0)){let te=N.find((ve)=>ve.kind==="projects"&&ve.fold&&ve.toggle&&(ve.count??0)>0);if(te?.toggle&&!ne.has(te.toggle)){ne.add(te.toggle);let ve=await I.rpc("sidebar.sections",{open:Array.from(ne)}).catch(()=>null);if(ve&&Array.isArray(ve.sections))N=ve.sections}}le=N,Re(N),re.setData(E,k,j,P),re.setSections(N,j,P)}else le=null,E=(await I.rpc("projects.list",{limit:100})).projects??[],re.setSections(null,j,P),re.setData(E,k,j,P);await I.rpc("subscribe",{topic:"lists"}).catch(()=>{})}else{le=null;let[x,L]=await Promise.all([I.rpc("projects.list",{limit:100}),I.rpc("threads.list",{limit:200,archived:!1})]);E=x.projects??[],k=L.threads??[],re.setSections(null,j,P),re.setData(E,k,j,P),await I.rpc("subscribe",{topic:"lists"}).catch(()=>{})}let v=D;if(!v){let x="";try{x=localStorage.getItem("bp.lastThread")||""}catch{}if(x&&(le&&Pe(le,x)||k.some((L)=>L.id===x)))v=x;else if(le)v=Ce(le);if(!v)v=(k.find((N)=>!N.archived&&!N.swarm&&!N.settled)??k.find((N)=>!N.archived&&!N.swarm))?.id??""}if(v&&(le&&Pe(le,v)||k.some((x)=>x.id===v)))await Ie(v);else D="",K=[],Ge.setItems([]),de.setState(!1,!1),G()}async function Ie(v){if(D&&D!==v){tt.cancel();let Ae=ge.getEntries();if(Ae.length>0){let se=ke.get(D);He(D,{entries:Ae,ids:se?.ids??Ae.map((Xe)=>Xe.id),olderCursor:me,review:se?.review??null,unanswered:se?.unanswered??null,rail:se?.rail??K,hashes:se?.hashes??{}})}}let x=++z;je++,ut(null);let L=Se;if(Se=null,L!==null)I.rpc("unsubscribe",{sub:L}).catch(()=>{});D=v;let N=ke.get(v);me=N?.olderCursor??null;try{localStorage.setItem("bp.lastThread",v)}catch{}re.setSelected(v),oe.classList.remove("bp-sidebar-open"),G();let q=k.find((Ae)=>Ae.id===v)??null;if(N)ge.setThread(q,N.entries,Boolean(N.olderCursor),N.review,N.unanswered),K=N.rail,Ge.setItems(N.rail);else ge.setLoading(q),K=[],Ge.setItems([]);if(de.setState(!0,q?.state==="working"),I.hasFeature("open")){let Ae={};if(N){for(let[Be,bt]of Object.entries(N.hashes))Ae[Be]=bt;for(let Be of N.entries)if(Be.h)Ae[Be.id]=Be.h}let se;try{se=await I.rpc("thread.open",{thread:v,limit:40,have:Ae})}catch(Be){if(x===z){let bt=Be instanceof Error&&Be.message?Be.message:"Could not load messages.";ge.setError(q,bt,()=>{Ie(v)})}return}if(x!==z){if(se.sub!==void 0&&se.sub!==null)I.rpc("unsubscribe",{sub:se.sub}).catch(()=>{});return}if(Se=se.sub??null,se.thread){q=se.thread;let Be=k.findIndex((bt)=>bt.id===se.thread.id);if(Be>=0)k[Be]=se.thread;else k.unshift(se.thread);G(),de.setState(!0,q.state==="working")}if("next"in se)me=se.next??null;let Xe=new Map;if(N)for(let Be of N.entries)Xe.set(Be.id,Be);for(let Be of se.entries??[])Xe.set(Be.id,Be);let et=se.ids??N?.ids??(se.entries??[]).map((Be)=>Be.id),Tn=et.map((Be)=>Xe.get(Be)).filter((Be)=>Boolean(Be)),ht=N?.rail??[];if(se.rail!==void 0){if(Array.isArray(se.rail))ht=se.rail;else if(ht=Array.isArray(se.rail?.rail)?se.rail.rail:Array.isArray(se.rail?.items)?se.rail.items:[],se.rail?.has){if(Y?.reconcileHas?.(se.rail.has),Me&&!ds(se.rail.has,Me))Z(!0)}}K=ht,Ge.setItems(ht);let Ut=N?.review??null;if(I.hasFeature("reviewmode"))try{let Be=await I.rpc("thread.review",{thread:v});if(x!==z)return;Ut=Be.review??null}catch{}if(x!==z)return;let Bn="unanswered"in se?se.unanswered??null:N?.unanswered??null,us=se.h??N?.hashes??{};if(He(v,{entries:Tn,ids:et,olderCursor:me,review:Ut,unanswered:Bn,rail:ht,hashes:us}),ge.setThread(q,Tn,Boolean(me),Ut,Bn),mt(v,x),Me)Q(Me);return}let te;try{te=await I.rpc("thread.entries",{thread:v,limit:40})}catch(Ae){if(x===z){let se=Ae instanceof Error&&Ae.message?Ae.message:"Could not load messages.";ge.setError(q,se,()=>{Ie(v)})}return}if(x!==z)return;if(te.thread){let Ae=k.findIndex((se)=>se.id===te.thread.id);if(Ae>=0)k[Ae]=te.thread;else k.unshift(te.thread);G()}me=te.next??null;let ve=null;if(I.hasFeature("reviewmode"))try{let Ae=await I.rpc("thread.review",{thread:v});if(x!==z)return;ve=Ae.review??null}catch{}if(x!==z)return;let De=te.entries??[],Qe=te.unanswered??null;He(v,{entries:De,ids:De.map((Ae)=>Ae.id),olderCursor:me,review:ve,unanswered:Qe,rail:N?.rail??[],hashes:N?.hashes??{}}),ge.setThread(q,De,Boolean(me),ve,Qe);try{let se=(await I.rpc("subscribe",{topic:"thread",thread:v})).sub??null;if(se!==null){if(x!==z){I.rpc("unsubscribe",{sub:se}).catch(()=>{});return}Se=se}}catch{}if(x!==z)return;if(xe(v,x),mt(v,x),Me)Q(Me)}async function mt(v,x){if(!v||!I.hasFeature("mgmt")){if(x===z)Je.clear();return}let L=k.find((q)=>q.id===v),N=L?.project?E.find((q)=>q.id===L.project)?.root??"":"";if(!N&&I.hasFeature("viewers"))try{let q=await I.rpc("viewer.files",{thread:v});if(x!==z)return;N=q.pcb||q.sch||q.root||""}catch{}if(x!==z)return;if(N)await Je.watchProject(N);else Je.clear()}async function Nt(v){let x=z;for(let L=0;L<25&&x===z;L++){if(ge.goTo(v))return;if(!me)return;let N=me;if(await ze(),me===N)return}}async function ze(){if(!D||!me){ge.clearLoadingOlder();return}let v=z,x=D,L=me;try{let N=await I.rpc("thread.entries",{thread:x,limit:40,before:L});if(v!==z||D!==x)return;me=N.next??null,ge.prependEntries(N.entries??[],Boolean(me))}catch{if(v===z)ge.clearLoadingOlder()}}async function Vt(v){try{let x=await I.rpc("thread.create",{project:v});if(x.thread)k=[x.thread,...k.filter((L)=>L.id!==x.thread.id)],re.setData(E,k,j,P),ye(),await Ie(x.thread.id),de.focus()}catch(x){U(x,"Could not create thread")}}let rt=null;function Sn(v){return(v.split(` -`).map((x)=>x.trim()).find((x)=>x.length>0)??"").slice(0,200)}function ut(v){rt=v,de.setReply(v?{who:v.role==="user"?b("secret.you","You"):b("model.col.agent","Agent"),line:Sn(v.text)}:null,()=>{if(rt)Nt(rt.id)},()=>ut(null))}async function Pn(v,x=[]){if(!D)return;let L=z,N=D,q=lr(),te=`local-${q}`,ve=rt&&v.trim()&&I.hasFeature("reply")?rt:null;if(ve)ut(null);ge.upsertEntry({id:te,kind:"user",text:v,at:Date.now(),clientId:q,...ve?{replyTo:{id:ve.id,quote:Sn(ve.text)}}:{},attachments:x.map((De)=>({name:De.name,mime:De.mime,previewUrl:`data:${De.mime};base64,${De.data}`}))});try{let De={thread:N,text:v,clientId:q};if(x.length>0)De.attachments=x;if(ve)De.replyTo={id:ve.id,text:ve.text};let Qe=await I.rpc("message.send",De);if(L!==z||D!==N)return;if(Qe.entry)ge.upsertEntry(Qe.entry)}catch(De){if(L===z&&D===N){if(ge.removeEntry(te),de.setDraft(v),ve&&!rt)ut(ve);U(De,"Failed to send message")}}}async function Nn(v){if(!D)return;let x=z,L=D;try{let N=await I.rpc("composer.run",{thread:L,text:v});if(x!==z||D!==L)return;if(N.error)de.setDraft(v),U(Error(N.error),N.error);else if(N.kind==="edit"&&typeof N.text==="string")de.setDraft(N.text);else if(N.kind==="project")We.open({mode:"folder"});else if(N.kind==="clone")We.open({mode:"clone",repo:N.repo??"",text:N.text??""})}catch(N){if(x===z&&D===L)de.setDraft(v),U(N,"Command refused")}}async function Ze(v,x){try{let L=await I.rpc("thread.act",{thread:v,action:x});if(L.thread){if(k=k.map((N)=>N.id===L.thread.id?L.thread:N),re.setData(E,k,j,P),L.thread.id===D)ge.updateThreadMeta(L.thread),G()}ye()}catch(L){de.showError(L instanceof Error?L.message:`Action "${x}" not allowed`)}}function Mn(v,x){if(!v||!v.text||x-v.at>=300000)return"";let L=v.build.split("-").pop()??"";if(v.reason==="build"&&L)return b("hub.restarting.build",v.text,{build:L});if(v.reason==="stop")return b("hub.stopped",v.text);return b("hub.restarting",v.text)}function Mt(v){if(v==="connected")re.setConnStatus(b("gpui.acct.connected","Connected"),"bp-ok");else if(v==="reconnecting"&&Mn(I.restarting,Date.now()))re.setConnStatus(Mn(I.restarting,Date.now()),"");else if(v==="reconnecting")re.setConnStatus("Reconnecting…","bp-warn");else if(v==="revoked")re.setConnStatus(b("gpui.acct.sign.in.expired","Sign-in expired"),"bp-bad");else re.setConnStatus("Connecting…","")}Tt(()=>{Mt(I.getState()),R.textContent=b("gpui.improvements","Improvements"),ae.title=b("palette.settings","Settings"),ae.setAttribute("aria-label",b("palette.settings","Settings")),G(),re.refreshLocale(),ge.refreshLocale(),de.refreshLocale(),Ge.render(),Oe.refreshLocale(),We.refreshLocale()}),I.onState((v,x)=>{if(v==="connected"&&x){if(x.locale)Fn(x.locale);if(x.theme)ps(x.theme);if(x.name)re.setHostName(x.name);if(nt=x.home??null,re.setHome(nt),Pt(dn(x.noProvider)),Oe.isOpen())Oe.refresh();Mt(v);let L=typeof x.hubBack==="string"?String(x.hubBack):"";if(L)try{let N=JSON.parse(L);if(N.reason==="crash")re.setConnStatus(b("hub.back.crash",N.text??""),"bp-warn"),window.setTimeout(()=>Mt(I.getState()),6000)}catch{}if(de.setFeatures(I.hasFeature("images"),I.hasFeature("voice")),Array.isArray(x.commands))ee=x.commands,de.setCommands(ee);else ee=[];Ke(),We.reconcile()}else tt.cancel(),Mt(v)}),I.onFrame((v)=>{if(v.t==="voice"){tt.handleFrame(v);return}if(v.t==="info"&&v.info&&typeof v.info==="object"){let L=v.info;if(Object.prototype.hasOwnProperty.call(L,"provider.notice"))Pt(dn(L["provider.notice"]));Je.handleInfo(L);return}if(v.t!=="d")return;let x=v;if(x.k==="clone"||x.k==="clone.repos"||x.k==="clone.signin"){We.handleFrame(x);return}switch(x.k){case"project":{let L=x.project;if(!L)break;let N=E.findIndex((q)=>q.id===L.id);if(N>=0)E[N]=L;else E.unshift(L);re.setData(E,k,j,P),G(),Te();break}case"thread":{let L=x.thread;if(!L)break;let N=k.findIndex((q)=>q.id===L.id);if(N>=0)k[N]=L;else k.unshift(L);if(re.setData(E,k,j,P),L.id===D)ge.updateThreadMeta(L),G(),de.setState(!0,L.state==="working");Te();break}case"thread.removed":{let L=String(x.id??"");k=k.filter((N)=>N.id!==L),re.setData(E,k,j,P),Te();break}case"entry":{if(x.thread===D&&x.entry)ge.upsertEntry(x.entry);break}case"text":{if(x.thread===D)ge.appendLiveText(String(x.entry??""),String(x.append??""),Number(x.at??Date.now()));break}case"turn":{if(x.thread===D){let L=String(x.state??"idle");de.setState(!0,L==="working"),xe(D,z)}Te();break}case"btw":{if(x.thread===D)ge.showBtw(String(x.q??""),String(x.a??""));break}case"unanswered":{if(x.thread===D)ge.setUnanswered(x.unanswered??null);break}case"theme":{if(typeof x.theme==="string")ps(x.theme);break}case"home":{if(nt=x.home??null,re.setHome(nt),Oe.isOpen())Oe.refresh();break}default:break}}),window.addEventListener("keydown",(v)=>{let x=v.key.toLowerCase();if((v.ctrlKey||v.metaKey)&&(x==="k"||v.shiftKey&&x==="p"))if(v.preventDefault(),$e.isOpen())$e.close();else $e.open();else if(v.key==="Escape"){if($e.isOpen())$e.close();else if(We.isOpen())We.escape();else if(Oe.isOpen())Oe.close();else if(ge.closePlanRevise());else if(Je.isOpen())Je.closePanel()}}),I.connect()}if(document.readyState==="loading")document.addEventListener("DOMContentLoaded",ms);else ms(); +`);return}if(!v.text||!v.text.trim()||v.live||v.id.startsWith("local-"))return;ut({id:v.id,text:v.text,role:v.kind==="user"?"user":"assistant"})},onLoadImage:async(v,x)=>{try{let L={entry:v,path:x};if(I.hasFeature("blobs"))L.metaOnly=!0;let S=await I.rpc("message.image",L);if(S.blob&&S.blob.startsWith("/blob/"))return{url:S.blob};if(S.mime&&S.data)return{mime:S.mime,data:S.data}}catch{}return null}});function _e(v){if(!v)return null;if(v.planMode)return v.planMode;if(v.provider==="claude")return{phase:"off",interaction:"default",once:!1};return null}function Ue(v,x){if(!D)return;let L=z,S=D;I.rpc(v,x).then((W)=>{if(L!==z||D!==S)return;if(W.thread){let Q=k.findIndex((fe)=>fe.id===W.thread.id);if(Q>=0)k[Q]=W.thread;else k.unshift(W.thread);re.setData(E,k,j,N),ge.updateThreadMeta(W.thread),G(),de.setState(!0,W.thread.state==="working")}}).catch((W)=>{if(L===z&&D===S)de.showError(W instanceof Error?W.message:"Could not change Plan mode")})}let tt,de=new en(we,{onSend:(v,x)=>{Nn(v,x)},onRunCommand:(v)=>{Mn(v)},onInterrupt:()=>{if(D)I.rpc("turn.interrupt",{thread:D}).catch(()=>{})},onQueryMentions:async(v,x)=>{try{return(await I.rpc("mentions.list",{q:v,kind:x,limit:10})).items??[]}catch{return[]}},onToggleVoice:()=>{tt.toggle()},onCyclePlanMode:()=>{let v=k.find((L)=>L.id===D)??null,x=_e(v);if(!x||!D)return;if(x.interaction!=="plan")Ue("thread.planonce",{thread:D,on:!0});else if(x.once)Ue("thread.pick",{thread:D,action:"interaction",value:"plan"});else Ue("thread.pick",{thread:D,action:"interaction",value:"default"})},onSetPlanMode:(v)=>{if(!D)return;if(v==="once")Ue("thread.planonce",{thread:D,on:!0});else if(v==="always")Ue("thread.pick",{thread:D,action:"interaction",value:"plan"});else Ue("thread.pick",{thread:D,action:"interaction",value:"default"})}});tt=new fn(I,{getThreadId:()=>D,getDraft:()=>de.getDraft(),getCaret:()=>de.getCaret(),setDraft:(v)=>de.setDraft(v),setRecording:(v)=>de.setVoiceRecording(v),setLevel:(v)=>de.setVoiceLevel(v),showError:(v)=>de.showError(v)});function dt(){let v=Me!=="",x=Je.isOpen();Le.classList.toggle("bp-hidden",!v&&!x),Le.classList.toggle("bp-has-viewer",v),Le.classList.toggle("bp-has-mgmt",x)}let Je=new cn(Ne,Le,{hub:I,getThreadId:()=>D,getThreadGen:()=>z,onSendText:(v)=>{Nn(v)},onOpenChange:()=>dt()});function pt(v){let x=window.prompt("Rename thread",v.title||"");if(!x||!x.trim())return;I.rpc("thread.act",{thread:v.id,action:"rename",title:x.trim()}).then((L)=>{if(L.thread)k=k.map((S)=>S.id===L.thread.id?L.thread:S),G(),ye()}).catch((L)=>{de.showError(L instanceof Error?L.message:"Could not rename thread")})}function Ye(v){switch(v.type){case"thread":Ie(v.id);break;case"rail":if(!D&&v.id!=="terminal")break;if(Me===v.id)Z();else ee(v.id);break;case"thread-act":if(D)Ze(D,v.action);break;case"new-thread":Ut(v.projectId);break;case"rename":{let x=k.find((L)=>L.id===D);if(x)pt(x);break}case"prev-thread":case"next-thread":{let x=k.filter((Q)=>!Q.archived&&!Q.swarm);if(x.length<2)break;let L=x.findIndex((Q)=>Q.id===D),S=v.type==="next-thread"?1:-1,W=x[(L<0?0:L+S+x.length)%x.length];if(W)Ie(W.id);break}case"command":if(v.runDirectly)Mn(v.word);else de.setDraft(`${v.word} `),de.focus();break;case"improvements":V();break;case"settings":Oe.open();break;case"sidebar":oe.classList.toggle("bp-sidebar-open"),oe.classList.toggle("bp-sidebar-collapsed");break}}let $e=new dn(e,{getState:()=>({selectedThreadId:D,threads:k,projects:E,bots:j,railItems:K,commands:te}),onSearch:async(v)=>{if(!I.hasFeature("search"))return{threads:[],projects:[],messages:[]};return I.rpc("search",{q:v,limit:20})},onExecute:Ye}),We=new Jt(e,{hub:I,onProjectAdded:(v)=>{if(ye(),v.id)Ut(v.id)},onCloneDone:(v)=>{if(ye(),v.thread)Ie(v.thread)}}),Ge=new mn(be,(v)=>{if(v==="commands"){$e.open();return}if(!D)return;if(Me===v)Z();else ee(v)}),nt=null,Pt=null,Oe=new un(e,{onLoadDevices:async()=>(await I.rpc("devices.page",{})).rows??[],onDevicesAct:async(v,x)=>{await I.rpc("devices.page.act",{action:v,value:x})},onGetHome:()=>nt,onMoveHomeHere:async()=>{await I.rpc("home.move",{to:"back"})},onGetNoProvider:()=>Pt,onLogout:()=>_n(()=>{I.disconnect(),window.location.replace("/")})});function Nt(v){if(Pt=v,ge.setNoProvider(v),Oe.isOpen())Oe.refresh()}function F(){Oe.openToAccounts()}function U(v,x){let L=v instanceof Error?v.message:x,S=v instanceof At?v:null,W=S?.code,Q=S?.machine,fe=W==="no_provider_remote"&&Q?b("provider.notice.senderr.remote","No AI provider connected on {machine}. Open Settings → Accounts on {machine} to connect Claude, Codex, Antigravity, or another provider.").replaceAll("{machine}",Q):L;de.showError(fe,Ni(L,W)?{label:b("provider.notice.button","Open Settings → Accounts"),onClick:F}:void 0)}h.addEventListener("click",()=>{let v=k.find((x)=>x.id===D);if(v)Ze(v.id,v.pinned?"unpin":"pin")}),w.addEventListener("click",()=>{let v=k.find((x)=>x.id===D);if(v)Ze(v.id,v.settled?"unsettle":"settle")});let _=new bn(e,(v,x)=>x?I.rpc("thread.context.mcp",{thread:v,...x}):I.rpc("thread.context",{thread:v}));M.addEventListener("click",(v)=>{v.stopPropagation();let x=k.find((W)=>W.id===D);if(!x)return;if(!P.classList.contains("bp-hidden")){P.classList.add("bp-hidden");return}let L=[{label:"Rename…",run:()=>pt(x)},{label:x.pinned?b("menu.unpin","Unpin"):b("menu.pin","Pin"),run:()=>{Ze(x.id,x.pinned?"unpin":"pin")}},{label:x.settled?b("phone.unsettle","Unsettle"):b("menu.settle","Settle"),run:()=>{Ze(x.id,x.settled?"unsettle":"settle")}},{label:x.archived?"Unarchive":"Archive",run:()=>{Ze(x.id,x.archived?"unarchive":"archive")}},{label:"Delete",danger:!0,run:()=>{if(window.confirm("Delete this thread?"))Ze(x.id,"delete")}}];if(I.hasFeature("threadContext"))L.unshift({label:b("thread.context.title","Context & Prompt"),run:()=>_.open(x.id)});let S=document.createDocumentFragment();for(let W of L){let Q=document.createElement("button");Q.type="button",Q.className="bp-popover-item"+(W.danger?" danger":""),Q.textContent=W.label,Q.addEventListener("click",()=>{P.classList.add("bp-hidden"),W.run()}),S.appendChild(Q)}P.replaceChildren(S),P.classList.remove("bp-hidden")}),document.addEventListener("click",()=>P.classList.add("bp-hidden"));async function V(){let v=document.createElement("div");v.className="bp-modal-backdrop",v.setAttribute("data-testid","improvements-modal");let x=document.createElement("div");x.className="bp-modal";let L=document.createElement("div");L.className="bp-modal-head";let S=document.createElement("h2");S.textContent=b("gpui.improvements","Improvements");let W=document.createElement("button");W.type="button",W.className="icon",W.textContent="×",W.addEventListener("click",()=>v.remove()),L.append(S,W);let Q=document.createElement("div");Q.className="bp-modal-body",Q.textContent="Loading…",x.append(L,Q),v.appendChild(x),v.addEventListener("click",(fe)=>{if(fe.target===v)v.remove()}),e.appendChild(v);try{let fe=await I.rpc("improvements.projects",{}),De=fe.projects??[];if(De.length===0){Q.textContent="No projects available for Improvements.";return}let Qe=document.createDocumentFragment();for(let Ae of De){let se=document.createElement("div");se.className="bp-set-row";let Xe=document.createElement("div");Xe.className="bp-set-info",Xe.textContent=Ae.title||Ae.name||Ae.id;let et=document.createElement("button");et.type="button",et.className=Ae.id===fe.project?"primary":"",et.textContent=Ae.id===fe.project?"Active":"Select",et.addEventListener("click",()=>{I.rpc("improvements.project",{project:Ae.id}).then(()=>v.remove()).catch(()=>{})}),se.append(Xe,et),Qe.appendChild(se)}Q.replaceChildren(Qe)}catch(fe){Q.textContent=fe instanceof Error?fe.message:"Could not load Improvements."}}B.addEventListener("click",()=>{V()}),O.addEventListener("click",()=>$e.open()),H.addEventListener("click",()=>$e.open()),ae.addEventListener("click",()=>{Oe.open()}),n.addEventListener("click",()=>{oe.classList.toggle("bp-sidebar-open"),oe.classList.toggle("bp-sidebar-collapsed")});function G(){let v=k.find((S)=>S.id===D)??null,x=v?E.find((S)=>S.id===v.project):void 0;o.textContent=x?.title??"",a.classList.toggle("bp-hidden",!x),c.classList.toggle("bp-hidden",!v),u.textContent=v?v.title||"Untitled thread":"";let L=_e(v);if(de.setPlanMode(L),!L||L.phase==="off")l.classList.add("bp-hidden"),l.classList.remove("is-exec"),l.textContent="";else l.classList.remove("bp-hidden"),l.classList.toggle("is-exec",L.phase==="executing"),l.title=b("gpui.planmode.tip","Plan before acting (1 turn, always, or off)"),l.textContent=L.phase==="armed"&&L.once?b("gpui.planmode.top.once","Plan (1 turn)"):L.phase==="armed"?b("gpui.mgmt.plan.tab","Plan"):L.phase==="planning"?b("gpui.planmode.top.planning","Planning"):L.phase==="pending"?b("gpui.planmode.top.pending","Review plan"):b("gpui.planmode.top.executing","Building plan");if(p.classList.toggle("bp-hidden",!v),m.classList.toggle("bp-hidden",!v),v){g.className=`bp-dot ${cr(v)}`,y.textContent=v.status||v.state||"idle",f.textContent=v.pinned?b("menu.unpin","Unpin"):b("menu.pin","Pin"),C.textContent=v.settled?b("phone.unsettle","Unsettle"):b("menu.settle","Settle");let S=v;de.setModelChip(v.chip||v.model||"default",v.provider,S.ctxPct??S.contextPct),de.setMemory(v.memory)}else de.setModelChip("default"),de.setMemory(null)}function Z(v=!0){if(je++,Me="",Ge.setActive(""),he.classList.add("bp-hidden"),Y?.close(),dt(),v&&D&&I.getState()==="connected")I.rpc("viewer.watch",{thread:D,kind:""}).catch(()=>{})}function ee(v){if(je++,Me=v,Ge.setActive(v),he.classList.remove("bp-hidden"),dt(),!Y&&typeof Sn==="function")Y=Sn(he,{hub:I,getThreadId:()=>D,closeViewer:()=>Z(!0)});if(Y)Y.open(v,D);else{let x=document.createElement("div");x.className="bp-viewer-placeholder";let L=document.createElement("div");L.className="bp-viewer-bar";let S=document.createElement("span");S.textContent=v.toUpperCase();let W=document.createElement("button");W.type="button",W.className="icon",W.textContent="×",W.addEventListener("click",()=>Z(!0)),L.append(S,W);let Q=document.createElement("div");Q.className="bp-dim bp-viewer-msg",Q.textContent=`Viewer pane (${v}).`,x.append(L,Q),he.replaceChildren(x)}}async function xe(v,x){if(!v||!I.hasFeature("rail")){if(x===z)K=[],Ge.setItems([]);return}let L=++je;try{let S=await I.rpc("viewer.rail",{thread:v,page:Me});if(x!==z||L!==je)return;let W=Array.isArray(S.rail)?S.rail:Array.isArray(S.items)?S.items:[];if(K=W,Ge.setItems(W),S.has){if(Y?.reconcileHas?.(S.has),Me&&!ps(S.has,Me))Z(!0)}}catch{if(x===z&&L===je)K=[],Ge.setItems([])}}function Ce(v){for(let x of v)if(x.kind==="threads"){for(let L of x.rows)if(!L.off&&(L.nav||L.id)&&!(L.nav||"").startsWith("@room:"))return L.nav||L.id}else if(x.kind==="projects"){for(let L of x.rows)for(let S of L.threads??[])if(!S.off&&(S.nav||S.id)&&!(S.nav||"").startsWith("@room:"))return S.nav||S.id}return""}function Pe(v,x){for(let L of v)if(L.kind==="threads"){if(L.rows.some((S)=>(S.nav||S.id)===x))return!0}else if(L.kind==="projects"){for(let S of L.rows)if((S.threads??[]).some((W)=>(W.nav||W.id)===x))return!0}return!1}function Re(v){let x=[];for(let L of v){if(L.kind!=="projects")continue;for(let S of L.rows)x.push({id:S.id,title:S.title,css:S.css,color:S.color})}if(x.length>0)E=x}async function ye(){if(!I.hasFeature("sections"))return!1;let v=++X;try{let x=await I.rpc("sidebar.sections",{open:Array.from(ne)});if(v!==X)return!0;let L=Array.isArray(x.sections)?x.sections:[];return le=L,Re(L),re.setData(E,k,j,N),re.setSections(L,j,N),G(),!0}catch{return!1}}function Te(){if(!I.hasFeature("sections"))return;if(ce!==null)window.clearTimeout(ce);ce=window.setTimeout(()=>{ce=null,ye()},150)}async function Ke(){if(Se=null,I.hasFeature("bots"))try{let x=await I.rpc("bots.list",{});j=x.bots??[],N=x.rooms??[]}catch{}if(I.hasFeature("shell")){let x=await I.rpc("shell.sync",{have:ie,settled:25}),L=new Set(x.removed??[]),S=new Set((x.projects??[]).map((W)=>W.id));if(L.size>0||S.size>0)E=[...E.filter((W)=>!L.has(W.id)&&!S.has(W.id)),...x.projects??[]],k=[...k.filter((W)=>!L.has(W.project)&&!S.has(W.project)),...x.threads??[]];else if(Array.isArray(x.threads)&&x.threads.length>0){let W=new Map(k.map((Q)=>[Q.id,Q]));for(let Q of x.threads)W.set(Q.id,Q);k=Array.from(W.values())}if(x.sections!==void 0){let W=Array.isArray(x.sections)?x.sections:Array.isArray(x.sections?.sections)?x.sections.sections:null;if(W)le=W,Re(W)}if(x.h)ie=x.h;re.setData(E,k,j,N),re.setSections(le,j,N)}else if(I.hasFeature("sections")){let[x,L]=await Promise.all([I.rpc("sidebar.sections",{open:Array.from(ne)}).catch(()=>null),I.rpc("threads.list",{limit:200,archived:!1}).catch(()=>({threads:[]}))]);if(k=L.threads??[],x&&Array.isArray(x.sections)){let S=x.sections;if(!S.some((Q)=>Q.kind==="projects"&&Q.rows.length>0)){let Q=S.find((fe)=>fe.kind==="projects"&&fe.fold&&fe.toggle&&(fe.count??0)>0);if(Q?.toggle&&!ne.has(Q.toggle)){ne.add(Q.toggle);let fe=await I.rpc("sidebar.sections",{open:Array.from(ne)}).catch(()=>null);if(fe&&Array.isArray(fe.sections))S=fe.sections}}le=S,Re(S),re.setData(E,k,j,N),re.setSections(S,j,N)}else le=null,E=(await I.rpc("projects.list",{limit:100})).projects??[],re.setSections(null,j,N),re.setData(E,k,j,N);await I.rpc("subscribe",{topic:"lists"}).catch(()=>{})}else{le=null;let[x,L]=await Promise.all([I.rpc("projects.list",{limit:100}),I.rpc("threads.list",{limit:200,archived:!1})]);E=x.projects??[],k=L.threads??[],re.setSections(null,j,N),re.setData(E,k,j,N),await I.rpc("subscribe",{topic:"lists"}).catch(()=>{})}let v=D;if(!v){let x="";try{x=localStorage.getItem("bp.lastThread")||""}catch{}if(x&&(le&&Pe(le,x)||k.some((L)=>L.id===x)))v=x;else if(le)v=Ce(le);if(!v)v=(k.find((S)=>!S.archived&&!S.swarm&&!S.settled)??k.find((S)=>!S.archived&&!S.swarm))?.id??""}if(v&&(le&&Pe(le,v)||k.some((x)=>x.id===v)))await Ie(v);else D="",K=[],Ge.setItems([]),de.setState(!1,!1),G()}async function Ie(v){if(D&&D!==v){tt.cancel();let Ae=ge.getEntries();if(Ae.length>0){let se=ke.get(D);He(D,{entries:Ae,ids:se?.ids??Ae.map((Xe)=>Xe.id),olderCursor:me,review:se?.review??null,unanswered:se?.unanswered??null,rail:se?.rail??K,hashes:se?.hashes??{}})}}let x=++z;je++,ut(null);let L=Se;if(Se=null,L!==null)I.rpc("unsubscribe",{sub:L}).catch(()=>{});D=v;let S=ke.get(v);me=S?.olderCursor??null;try{localStorage.setItem("bp.lastThread",v)}catch{}re.setSelected(v),oe.classList.remove("bp-sidebar-open"),G();let W=k.find((Ae)=>Ae.id===v)??null;if(S)ge.setThread(W,S.entries,Boolean(S.olderCursor),S.review,S.unanswered),K=S.rail,Ge.setItems(S.rail);else ge.setLoading(W),K=[],Ge.setItems([]);if(de.setState(!0,W?.state==="working"),I.hasFeature("open")){let Ae={};if(S){for(let[Be,bt]of Object.entries(S.hashes))Ae[Be]=bt;for(let Be of S.entries)if(Be.h)Ae[Be.id]=Be.h}let se;try{se=await I.rpc("thread.open",{thread:v,limit:40,have:Ae})}catch(Be){if(x===z){let bt=Be instanceof Error&&Be.message?Be.message:"Could not load messages.";ge.setError(W,bt,()=>{Ie(v)})}return}if(x!==z){if(se.sub!==void 0&&se.sub!==null)I.rpc("unsubscribe",{sub:se.sub}).catch(()=>{});return}if(Se=se.sub??null,se.thread){W=se.thread;let Be=k.findIndex((bt)=>bt.id===se.thread.id);if(Be>=0)k[Be]=se.thread;else k.unshift(se.thread);G(),de.setState(!0,W.state==="working")}if("next"in se)me=se.next??null;let Xe=new Map;if(S)for(let Be of S.entries)Xe.set(Be.id,Be);for(let Be of se.entries??[])Xe.set(Be.id,Be);let et=se.ids??S?.ids??(se.entries??[]).map((Be)=>Be.id),Bn=et.map((Be)=>Xe.get(Be)).filter((Be)=>Boolean(Be)),ht=S?.rail??[];if(se.rail!==void 0){if(Array.isArray(se.rail))ht=se.rail;else if(ht=Array.isArray(se.rail?.rail)?se.rail.rail:Array.isArray(se.rail?.items)?se.rail.items:[],se.rail?.has){if(Y?.reconcileHas?.(se.rail.has),Me&&!ps(se.rail.has,Me))Z(!0)}}K=ht,Ge.setItems(ht);let Wt=S?.review??null;if(I.hasFeature("reviewmode"))try{let Be=await I.rpc("thread.review",{thread:v});if(x!==z)return;Wt=Be.review??null}catch{}if(x!==z)return;let In="unanswered"in se?se.unanswered??null:S?.unanswered??null,hs=se.h??S?.hashes??{};if(He(v,{entries:Bn,ids:et,olderCursor:me,review:Wt,unanswered:In,rail:ht,hashes:hs}),ge.setThread(W,Bn,Boolean(me),Wt,In),mt(v,x),Me)ee(Me);return}let Q;try{Q=await I.rpc("thread.entries",{thread:v,limit:40})}catch(Ae){if(x===z){let se=Ae instanceof Error&&Ae.message?Ae.message:"Could not load messages.";ge.setError(W,se,()=>{Ie(v)})}return}if(x!==z)return;if(Q.thread){let Ae=k.findIndex((se)=>se.id===Q.thread.id);if(Ae>=0)k[Ae]=Q.thread;else k.unshift(Q.thread);G()}me=Q.next??null;let fe=null;if(I.hasFeature("reviewmode"))try{let Ae=await I.rpc("thread.review",{thread:v});if(x!==z)return;fe=Ae.review??null}catch{}if(x!==z)return;let De=Q.entries??[],Qe=Q.unanswered??null;He(v,{entries:De,ids:De.map((Ae)=>Ae.id),olderCursor:me,review:fe,unanswered:Qe,rail:S?.rail??[],hashes:S?.hashes??{}}),ge.setThread(W,De,Boolean(me),fe,Qe);try{let se=(await I.rpc("subscribe",{topic:"thread",thread:v})).sub??null;if(se!==null){if(x!==z){I.rpc("unsubscribe",{sub:se}).catch(()=>{});return}Se=se}}catch{}if(x!==z)return;if(xe(v,x),mt(v,x),Me)ee(Me)}async function mt(v,x){if(!v||!I.hasFeature("mgmt")){if(x===z)Je.clear();return}let L=k.find((W)=>W.id===v),S=L?.project?E.find((W)=>W.id===L.project)?.root??"":"";if(!S&&I.hasFeature("viewers"))try{let W=await I.rpc("viewer.files",{thread:v});if(x!==z)return;S=W.pcb||W.sch||W.root||""}catch{}if(x!==z)return;if(S)await Je.watchProject(S);else Je.clear()}async function Mt(v){let x=z;for(let L=0;L<25&&x===z;L++){if(ge.goTo(v))return;if(!me)return;let S=me;if(await ze(),me===S)return}}async function ze(){if(!D||!me){ge.clearLoadingOlder();return}let v=z,x=D,L=me;try{let S=await I.rpc("thread.entries",{thread:x,limit:40,before:L});if(v!==z||D!==x)return;me=S.next??null,ge.prependEntries(S.entries??[],Boolean(me))}catch{if(v===z)ge.clearLoadingOlder()}}async function Ut(v){try{let x=await I.rpc("thread.create",{project:v});if(x.thread)k=[x.thread,...k.filter((L)=>L.id!==x.thread.id)],re.setData(E,k,j,N),ye(),await Ie(x.thread.id),de.focus()}catch(x){U(x,"Could not create thread")}}let rt=null;function Pn(v){return(v.split(` +`).map((x)=>x.trim()).find((x)=>x.length>0)??"").slice(0,200)}function ut(v){rt=v,de.setReply(v?{who:v.role==="user"?b("secret.you","You"):b("model.col.agent","Agent"),line:Pn(v.text)}:null,()=>{if(rt)Mt(rt.id)},()=>ut(null))}async function Nn(v,x=[]){if(!D)return;let L=z,S=D,W=dr(),Q=`local-${W}`,fe=rt&&v.trim()&&I.hasFeature("reply")?rt:null;if(fe)ut(null);ge.upsertEntry({id:Q,kind:"user",text:v,at:Date.now(),clientId:W,...fe?{replyTo:{id:fe.id,quote:Pn(fe.text)}}:{},attachments:x.map((De)=>({name:De.name,mime:De.mime,previewUrl:`data:${De.mime};base64,${De.data}`}))});try{let De={thread:S,text:v,clientId:W};if(x.length>0)De.attachments=x;if(fe)De.replyTo={id:fe.id,text:fe.text};let Qe=await I.rpc("message.send",De);if(L!==z||D!==S)return;if(Qe.entry)ge.upsertEntry(Qe.entry)}catch(De){if(L===z&&D===S){if(ge.removeEntry(Q),de.setDraft(v),fe&&!rt)ut(fe);U(De,"Failed to send message")}}}async function Mn(v){if(!D)return;let x=z,L=D;try{let S=await I.rpc("composer.run",{thread:L,text:v});if(x!==z||D!==L)return;if(S.error)de.setDraft(v),U(new At(S.error,{code:S.errorCode,machine:S.machine}),S.error);else if(S.kind==="btw"&&typeof S.a==="string")ge.showBtw(S.q??"",S.a);else if(S.kind==="edit"&&typeof S.text==="string")de.setDraft(S.text);else if(S.kind==="project")We.open({mode:"folder"});else if(S.kind==="clone")We.open({mode:"clone",repo:S.repo??"",text:S.text??""})}catch(S){if(x===z&&D===L)de.setDraft(v),U(S,"Command refused")}}async function Ze(v,x){try{let L=await I.rpc("thread.act",{thread:v,action:x});if(L.thread){if(k=k.map((S)=>S.id===L.thread.id?L.thread:S),re.setData(E,k,j,N),L.thread.id===D)ge.updateThreadMeta(L.thread),G()}ye()}catch(L){de.showError(L instanceof Error?L.message:`Action "${x}" not allowed`)}}function Tn(v,x){if(!v||!v.text||x-v.at>=300000)return"";let L=v.build.split("-").pop()??"";if(v.reason==="build"&&L)return b("hub.restarting.build",v.text,{build:L});if(v.reason==="stop")return b("hub.stopped",v.text);return b("hub.restarting",v.text)}function Tt(v){if(v==="connected")re.setConnStatus(b("gpui.acct.connected","Connected"),"bp-ok");else if(v==="reconnecting"&&Tn(I.restarting,Date.now()))re.setConnStatus(Tn(I.restarting,Date.now()),"");else if(v==="reconnecting")re.setConnStatus("Reconnecting…","bp-warn");else if(v==="revoked")re.setConnStatus(b("gpui.acct.sign.in.expired","Sign-in expired"),"bp-bad");else re.setConnStatus("Connecting…","")}Bt(()=>{Tt(I.getState()),R.textContent=b("gpui.improvements","Improvements"),ae.title=b("palette.settings","Settings"),ae.setAttribute("aria-label",b("palette.settings","Settings")),G(),re.refreshLocale(),ge.refreshLocale(),de.refreshLocale(),Ge.render(),Oe.refreshLocale(),We.refreshLocale()}),I.onState((v,x)=>{if(v==="connected"&&x){if(x.locale)$n(x.locale);if(x.theme)ms(x.theme);if(x.name)re.setHostName(x.name);if(nt=x.home??null,re.setHome(nt),Nt(pn(x.noProvider)),Oe.isOpen())Oe.refresh();Tt(v);let L=typeof x.hubBack==="string"?String(x.hubBack):"";if(L)try{let S=JSON.parse(L);if(S.reason==="crash")re.setConnStatus(b("hub.back.crash",S.text??""),"bp-warn"),window.setTimeout(()=>Tt(I.getState()),6000)}catch{}if(de.setFeatures(I.hasFeature("images"),I.hasFeature("voice")),Array.isArray(x.commands))te=x.commands,de.setCommands(te);else te=[];Ke(),We.reconcile()}else tt.cancel(),Tt(v)}),I.onFrame((v)=>{if(v.t==="voice"){tt.handleFrame(v);return}if(v.t==="info"&&v.info&&typeof v.info==="object"){let L=v.info;if(Object.prototype.hasOwnProperty.call(L,"provider.notice"))Nt(pn(L["provider.notice"]));Je.handleInfo(L);return}if(v.t!=="d")return;let x=v;if(x.k==="clone"||x.k==="clone.repos"||x.k==="clone.signin"){We.handleFrame(x);return}switch(x.k){case"project":{let L=x.project;if(!L)break;let S=E.findIndex((W)=>W.id===L.id);if(S>=0)E[S]=L;else E.unshift(L);re.setData(E,k,j,N),G(),Te();break}case"thread":{let L=x.thread;if(!L)break;let S=k.findIndex((W)=>W.id===L.id);if(S>=0)k[S]=L;else k.unshift(L);if(re.setData(E,k,j,N),L.id===D)ge.updateThreadMeta(L),G(),de.setState(!0,L.state==="working");Te();break}case"thread.removed":{let L=String(x.id??"");k=k.filter((S)=>S.id!==L),re.setData(E,k,j,N),Te();break}case"entry":{if(x.thread===D&&x.entry)ge.upsertEntry(x.entry);break}case"text":{if(x.thread===D)ge.appendLiveText(String(x.entry??""),String(x.append??""),Number(x.at??Date.now()));break}case"turn":{if(x.thread===D){let L=String(x.state??"idle");de.setState(!0,L==="working"),xe(D,z)}Te();break}case"btw":{if(x.thread===D)ge.showBtw(String(x.q??""),String(x.a??""));break}case"unanswered":{if(x.thread===D)ge.setUnanswered(x.unanswered??null);break}case"theme":{if(typeof x.theme==="string")ms(x.theme);break}case"home":{if(nt=x.home??null,re.setHome(nt),Oe.isOpen())Oe.refresh();break}default:break}}),window.addEventListener("keydown",(v)=>{let x=v.key.toLowerCase();if((v.ctrlKey||v.metaKey)&&(x==="k"||v.shiftKey&&x==="p"))if(v.preventDefault(),$e.isOpen())$e.close();else $e.open();else if(v.key==="Escape"){if($e.isOpen())$e.close();else if(We.isOpen())We.escape();else if(Oe.isOpen())Oe.close();else if(ge.closePlanRevise());else if(Je.isOpen())Je.closePanel()}}),I.connect()}if(document.readyState==="loading")document.addEventListener("DOMContentLoaded",us);else us(); diff --git a/web/dist/assets/pair.js b/web/dist/assets/pair.js index d831957033..c2a7d581e5 100644 --- a/web/dist/assets/pair.js +++ b/web/dist/assets/pair.js @@ -1 +1 @@ -var U={en:{"agy.signout":"Sign out","android.hub.machines.approve":"Approve","android.load.earlier":"load earlier","approval.dismiss":"Dismiss","approval.implement":"Implement","ask.plan":"Proposed plan","bots.rooms":"Rooms","bots.tab.browser":"Browser","common.cancel":"Cancel","common.close":"Close","common.copy":"Copy","common.delete":"Delete","common.refresh":"Refresh","common.remove":"Remove","common.save":"Save","composer.placeholder":"Ask anything: @bot, >thread, %project, #room, $skill, /btw","composer.send":"Send","composer.stop":"Stop","gpui.acct.connected":"Connected","gpui.acct.not.connected":"Not connected","gpui.acct.sign.in.expired":"Sign-in expired","gpui.ask.plan.ready":"Ready for review","gpui.ask.plan.revise":"Revise","gpui.ask.plan.reviseph":"What should change in the plan?","gpui.ask.plan.sendrev":"Send revision","gpui.b.in.reply.to":"↩ In reply to: {quote}","gpui.b.replying.to":"↩ Replying to: {line}","gpui.bots.recall.off":"Off","gpui.bots.recall.on":"On","gpui.c.term.collapse":"Collapse","gpui.c.term.expand":"Expand","gpui.commands":"Commands","gpui.e.open.folder":"Open folder","gpui.filter.projects.and.threads":"Filter projects and threads","gpui.fold.or.unfold.the.sidebar":"Fold or unfold the sidebar","gpui.follow.paused":"Following paused","gpui.follow.wait":"Following: waiting for the agent's next edit","gpui.gerbers":"Gerbers","gpui.improvements":"Improvements","gpui.jump.to.a.thread.run":"Jump to a thread, run a command or find what was said","gpui.mgmt.bom.dnp":"DNP","gpui.mgmt.bom.nompn":"no MPN","gpui.mgmt.checks.all":"All","gpui.mgmt.checks.fix":"Fix with agent","gpui.mgmt.checks.run":"Run","gpui.mgmt.close":"Close the panel","gpui.mgmt.fab.apply":"Apply","gpui.mgmt.fab.changed":"Changed since you last looked","gpui.mgmt.fab.derived":"* worked out from the fab's page (a mil in mm, a ring from a diameter). Dimmed: the rigid board's value, where this board's page says nothing else. A date opens the page it was read from.","gpui.mgmt.fab.extra":"Costs more","gpui.mgmt.fab.findings":"Findings","gpui.mgmt.fab.free":"Base price","gpui.mgmt.fab.judge":"Datasheets","gpui.mgmt.fab.limit":"Limit","gpui.mgmt.fab.readcol":"Read","gpui.mgmt.fab.refresh":"Refresh","gpui.mgmt.fab.reviewbtn":"Review","gpui.mgmt.fab.seen":"Seen","gpui.mgmt.fab.thefab":"The fab","gpui.mgmt.fab.use":"Use","gpui.mgmt.life.nopart":"No reading of this part yet.","gpui.mgmt.life.reading":"Reading its history…","gpui.mgmt.plan.addnote":"Add note","gpui.mgmt.plan.all":"Approve all","gpui.mgmt.plan.before":"Plan before routing","gpui.mgmt.plan.compact":"Compact","gpui.mgmt.plan.done":"done","gpui.mgmt.plan.drawn":"The plan's corridors and planes are drawn on the board while this panel is open. Close it to hide them.","gpui.mgmt.plan.edited":"Edited","gpui.mgmt.plan.elsewhere":"A routing plan for {board} awaits your approval","gpui.mgmt.plan.emptysub":"Layers, corridors, and planes appear here once a plan is proposed.","gpui.mgmt.plan.expand":"Expand","gpui.mgmt.plan.fit":"Fit","gpui.mgmt.plan.grid.all":"All layers","gpui.mgmt.plan.grid.pair":"Side by side","gpui.mgmt.plan.grid.single":"Single","gpui.mgmt.plan.hide":"Hide done","gpui.mgmt.plan.hint":"Drag waypoints to steer · Click + on edge to insert · Right-click vertex to remove","gpui.mgmt.plan.keysnote":"On this KiCad version, approve from this panel: in plan view KiCad's A, R and W keys aren't the plan's yet (A opens Add Footprint). Update KiCad.","gpui.mgmt.plan.layer":"Approve layer","gpui.mgmt.plan.layer.short":"Layer","gpui.mgmt.plan.lock":"Lock","gpui.mgmt.plan.locked":"Locked","gpui.mgmt.plan.noboard":"No routing plan for this board.","gpui.mgmt.plan.noitems":"No corridors or planes on this layer","gpui.mgmt.plan.note.placeholder":"Steering note for router…","gpui.mgmt.plan.nothing":"Nothing awaits your approval","gpui.mgmt.plan.offwords":"Agents route as you ask. Turn it on to have them propose a routing plan first and route only what you approve here.","gpui.mgmt.plan.onwords":"Before routing a board with 4 or more copper layers or more than 60 nets, the agent proposes corridors and plane regions here. It routes only what you approve.","gpui.mgmt.plan.reading":"Reading the routing plan…","gpui.mgmt.plan.reference":"over {layer}","gpui.mgmt.plan.refused":"KiCad refused","gpui.mgmt.plan.reject":"Reject","gpui.mgmt.plan.rejectlayer":"Reject layer","gpui.mgmt.plan.reqplain":"Approval requested","gpui.mgmt.plan.requested":"Approval requested: {what}","gpui.mgmt.plan.saved":"saved plan","gpui.mgmt.plan.show":"Show done","gpui.mgmt.plan.st.approved":"Approved","gpui.mgmt.plan.st.awaiting":"Awaiting review","gpui.mgmt.plan.st.blocked":"Blocked","gpui.mgmt.plan.st.empty":"Empty","gpui.mgmt.plan.st.partial":"Partial","gpui.mgmt.plan.st.rejected":"Rejected","gpui.mgmt.plan.st.routed":"Routed","gpui.mgmt.plan.st.routing":"Routing","gpui.mgmt.plan.st.verified":"Verified","gpui.mgmt.plan.stackup.short":"Stackup","gpui.mgmt.plan.stop":"Stop routing","gpui.mgmt.plan.sync":"Link zoom","gpui.mgmt.plan.tab":"Plan","gpui.mgmt.plan.unlock":"Unlock","gpui.mgmt.plan.verify":"Verify","gpui.mgmt.plan.view.canvas":"Canvas","gpui.mgmt.plan.view.list":"List","gpui.mgmt.plan.view.split":"Split","gpui.mgmt.plan.width":"Width","gpui.next.thread":"Next thread","gpui.nothing.matches":"Nothing matches","gpui.planmode.bar.always":"Plan mode — explores and proposes a plan before editing","gpui.planmode.bar.executing":"Building the approved plan","gpui.planmode.bar.once":"Plan mode (1 turn) — explores and proposes a plan before editing","gpui.planmode.bar.pending":"Proposed plan awaits review below","gpui.planmode.bar.planning":"Planning — drafting a plan before edits","gpui.planmode.chip.building":"Building","gpui.planmode.chip.once":"Plan · 1t","gpui.planmode.scope.always":"Always","gpui.planmode.scope.once":"1 turn","gpui.planmode.tip":"Plan before acting (1 turn, always, or off)","gpui.planmode.top.executing":"Building plan","gpui.planmode.top.once":"Plan (1 turn)","gpui.planmode.top.pending":"Review plan","gpui.planmode.top.planning":"Planning","gpui.previous.thread":"Previous thread","gpui.rail.no.board":"No board in this project","gpui.rail.no.mech":"No mechanical parts in this project","gpui.rail.no.schematic":"No schematic in this project","gpui.rail.split.needs.both":"Split needs a board and a schematic","home.away":"Home ({name}) is away","home.away.queued":"Home ({name}) is away · {n} queued","home.away.since":"Home ({name}) is away since {time}","home.away.since.queued":"Home ({name}) is away since {time} · {n} queued","home.machine":"Home machine","home.move.failed":"Home move failed","home.move.failed.note":"Home move failed: {note}","home.move.here":"Make this machine the home","home.moving":"Moving home to {to}…","home.moving.step":"Moving home to {to}: {step}","hub.back.crash":"Backplane is back after it stopped unexpectedly","hub.restarting":"Restarting Backplane…","hub.restarting.build":"Restarting Backplane… (new build {build})","hub.stopped":"Backplane stopped","ios.hub.address.field":"Hub address","menu.pin":"Pin","menu.settle":"Settle","menu.unpin":"Unpin","model.col.agent":"Agent","notify.settled":"Settled","palette.archive":"Archive thread","palette.command.placeholder":"Type a command or a thread","palette.diff":"Diff: what this thread changed","palette.newthread":"New thread","palette.settings":"Settings","palette.terminal":"Terminal","palette.unarchive":"Unarchive thread","phone.unsettle":"Unsettle","provider.notice.button":"Open Settings → Accounts","provider.notice.head":"No AI provider connected","provider.notice.senderr":"No AI provider connected yet. Open Settings → Accounts to connect Claude, Codex, Antigravity, or another provider.","provider.notice.text.none":"Connect Claude, Codex, Antigravity, or another provider to start chatting.","provider.notice.text.signedout":"Sign in to Claude, Codex, or another provider in Settings → Accounts to start chatting.","reply.action":"Reply","reply.cancel":"Cancel reply","reply.to":"In reply to:","secret.you":"You","settings.lang":"Language","sheet.rename":"Rename thread","sidebar.add.project":"Add project","sidebar.search.projects":"Search projects","thread.context.base":"Backplane","thread.context.copied":"Prompt copied.","thread.context.copy":"Copy prompt","thread.context.disable":"Disable","thread.context.enable":"Enable","thread.context.index":"Available skills index","thread.context.injected.label":"Injected project instructions","thread.context.instructions":"Instructions","thread.context.mcp":"Project MCPs","thread.context.native.note":"Backplane’s launch prompt. Native files are loaded by the provider.","thread.context.none.instructions":"No project instructions found.","thread.context.none.mcp":"No project MCP configurations found.","thread.context.reading":"Reading thread context…","thread.context.size":"{bytes} B · ≈{tokens} tokens","thread.context.skills":"Skills","thread.context.system":"System Prompt","thread.context.title":"Context & Prompt","thread.context.trust":"Trust and enable","thread.new":"New thread","tools.pinned":"Pinned","tools.retry":"Retry","tour.title.bots":"Bots","viewer.board":"Board","viewer.diff":"Diff","viewer.files":"Files","viewer.mech":"Mech","viewer.review":"Review","viewer.schematic":"Schematic","viewer.solid":"3D","web.chat.answer.btn":"Answer","web.chat.answer.placeholder":"Type answer…","web.chat.answered":"Answered: {answer}","web.chat.choose":"Choose a project thread on the left to begin.","web.chat.empty":"No messages yet. Type below to start a turn.","web.chat.finished":"Finished {time}","web.chat.finished.dur":"Finished {time} · {dur}","web.chat.loading":"Loading messages…","web.chat.review.mode":"Review mode","web.chat.streaming":"Streaming…","web.clone.add.dir":"Add {dir}","web.clone.back":"Back","web.clone.change.folder":"Change folder","web.clone.cloned":"Cloned {repo} into {dest}","web.clone.cloning":"Cloning {repo} into {dest}","web.clone.copied":"Copied","web.clone.first":"First message: {text}","web.clone.folder.name":"Folder name","web.clone.go":"Clone","web.clone.loading":"Loading…","web.clone.no.folders":"No folders here","web.clone.open.project":"Open the project","web.clone.open.thread":"Open the thread","web.clone.private":"private","web.clone.repo.placeholder":"https or ssh URL, or owner/repo","web.clone.retry":"Try again","web.clone.same":"Already cloned there: it is added as it is.","web.clone.signin":"Sign in to GitHub","web.clone.signin.done":"Signed in to GitHub","web.clone.signin.enter":"Enter this code on GitHub:","web.clone.signin.wait":"Starting GitHub sign-in…","web.clone.start.thread":"Start a thread","web.clone.stopped":"Stopped cloning {repo}","web.clone.tab":"Clone from git","web.clone.up":"Up","web.clone.use.dir":"Use {dir}","web.composer.attach":"Attach image","web.composer.maximages":"At most {max} images per message.","web.composer.unsupported":"Unsupported image type: {type}","web.composer.voice":"Voice dictation","web.logout.failed":"Could not confirm sign-out. Try again.","web.pair.approve.in":"Approve on desktop or paired phone · expires in {time}","web.pair.approved":"Approved. Opening Backplane…","web.pair.cancelled":"Cancelled.","web.pair.code":"Comparison code","web.pair.denied":"Pairing request was denied.","web.pair.expired":"Pairing code expired. Request a new code to try again.","web.pair.failed":"Pairing request failed ({status})","web.pair.name":"Browser name","web.pair.nocode":"Hub did not return a comparison code.","web.pair.ratelimited":"Too many pairing attempts. Wait a moment and try again.","web.pair.request":"Request pairing","web.pair.requesting":"Requesting pairing code…","web.pair.subtitle":"Pair this browser with your hub. Approve the 6-digit code in Backplane › Settings › Devices.","web.pair.unreachable":"Could not reach the hub. Check your tailnet connection.","web.plan.awaiting":"{n} awaiting approval","web.plan.net.one":"1 net","web.plan.nets":"{n} nets","web.settings.providers":"AI providers","web.settings.providers.browser":"Connect a provider in the Backplane desktop or mobile app under Settings → Accounts."},es:{"agy.signout":"Cerrar sesión","android.hub.machines.approve":"Aprobar","android.load.earlier":"cargar anteriores","approval.dismiss":"Descartar","approval.implement":"Implementar","ask.plan":"Plan propuesto","bots.rooms":"Salas","bots.tab.browser":"Navegador","common.cancel":"Cancelar","common.close":"Cerrar","common.copy":"Copiar","common.delete":"Eliminar","common.refresh":"Actualizar","common.remove":"Quitar","common.save":"Guardar","composer.placeholder":"Pregunta lo que sea: @bot, >hilo, %proyecto, #sala, $skill, /btw","composer.send":"Enviar","composer.stop":"Detener","gpui.acct.connected":"Conectado","gpui.acct.not.connected":"No conectado","gpui.acct.sign.in.expired":"Sesión caducada","gpui.ask.plan.ready":"Listo para revisar","gpui.ask.plan.revise":"Revisar","gpui.ask.plan.reviseph":"¿Qué debería cambiar en el plan?","gpui.ask.plan.sendrev":"Enviar revisión","gpui.b.in.reply.to":"↩ En respuesta a: {quote}","gpui.b.replying.to":"↩ Respondiendo a: {line}","gpui.bots.recall.off":"Desactivado","gpui.bots.recall.on":"Activado","gpui.c.term.collapse":"Contraer","gpui.c.term.expand":"Expandir","gpui.commands":"Comandos","gpui.e.open.folder":"Abrir carpeta","gpui.filter.projects.and.threads":"Filtrar proyectos e hilos","gpui.fold.or.unfold.the.sidebar":"Plegar o desplegar la barra lateral","gpui.follow.paused":"Seguimiento en pausa","gpui.follow.wait":"Siguiendo: esperando la próxima edición del agente","gpui.gerbers":"Gerbers","gpui.improvements":"Mejoras","gpui.jump.to.a.thread.run":"Saltar a un hilo, ejecutar un comando o buscar lo dicho","gpui.mgmt.bom.dnp":"DNP","gpui.mgmt.bom.nompn":"sin MPN","gpui.mgmt.checks.all":"Todas","gpui.mgmt.checks.fix":"Corregir con agente","gpui.mgmt.checks.run":"Ejecutar","gpui.mgmt.close":"Cerrar el panel","gpui.mgmt.fab.apply":"Aplicar","gpui.mgmt.fab.changed":"Cambió desde la última vez que miraste","gpui.mgmt.fab.derived":"* calculado desde la página del fabricante (un mil en mm, un anillo desde un diámetro). Atenuado: el valor de la placa rígida, cuando la página de esta placa no dice otra cosa. Una fecha abre la página de la que se leyó.","gpui.mgmt.fab.extra":"Cuesta más","gpui.mgmt.fab.findings":"Hallazgos","gpui.mgmt.fab.free":"Precio base","gpui.mgmt.fab.judge":"Hojas de datos","gpui.mgmt.fab.limit":"Límite","gpui.mgmt.fab.readcol":"Leído","gpui.mgmt.fab.refresh":"Actualizar","gpui.mgmt.fab.reviewbtn":"Revisar","gpui.mgmt.fab.seen":"Visto","gpui.mgmt.fab.thefab":"El fabricante","gpui.mgmt.fab.use":"Usar","gpui.mgmt.life.nopart":"Sin lectura de esta pieza aún.","gpui.mgmt.life.reading":"Leyendo su historial…","gpui.mgmt.plan.addnote":"Añadir nota","gpui.mgmt.plan.all":"Aprobar todo","gpui.mgmt.plan.before":"Planificar antes de rutear","gpui.mgmt.plan.compact":"Compacto","gpui.mgmt.plan.done":"hecho","gpui.mgmt.plan.drawn":"Los corredores y planos del plan se dibujan en la placa mientras este panel está abierto. Ciérralo para ocultarlos.","gpui.mgmt.plan.edited":"Editado","gpui.mgmt.plan.elsewhere":"Un plan de ruteo para {board} espera tu aprobación","gpui.mgmt.plan.emptysub":"Las capas, corredores y planos aparecerán aquí cuando se proponga un plan.","gpui.mgmt.plan.expand":"Expandir","gpui.mgmt.plan.fit":"Ajustar","gpui.mgmt.plan.grid.all":"Todas las capas","gpui.mgmt.plan.grid.pair":"Lado a lado","gpui.mgmt.plan.grid.single":"Única","gpui.mgmt.plan.hide":"Ocultar hechos","gpui.mgmt.plan.hint":"Arrastra vértices para guiar · Clic en + del borde para insertar · Clic derecho en vértice para quitar","gpui.mgmt.plan.keysnote":"En esta versión de KiCad, aprueba desde este panel: en la vista de plan las teclas A, R y W de KiCad aún no son del plan (A abre Añadir Huella). Actualiza KiCad.","gpui.mgmt.plan.layer":"Aprobar capa","gpui.mgmt.plan.layer.short":"Capa","gpui.mgmt.plan.lock":"Bloquear","gpui.mgmt.plan.locked":"Bloqueado","gpui.mgmt.plan.noboard":"No hay plan de ruteo para esta placa.","gpui.mgmt.plan.noitems":"Sin corredores ni planos en esta capa","gpui.mgmt.plan.note.placeholder":"Nota de guiado para el router…","gpui.mgmt.plan.nothing":"Nada espera tu aprobación","gpui.mgmt.plan.offwords":"Los agentes rutean como les pidas. Actívalo para que primero propongan un plan de ruteo y ruteen solo lo que apruebes aquí.","gpui.mgmt.plan.onwords":"Antes de rutear una placa con 4 o más capas de cobre o más de 60 redes, el agente propone aquí corredores y regiones de plano. Solo rutea lo que apruebes.","gpui.mgmt.plan.reading":"Leyendo el plan de ruteo…","gpui.mgmt.plan.reference":"sobre {layer}","gpui.mgmt.plan.refused":"KiCad lo rechazó","gpui.mgmt.plan.reject":"Rechazar","gpui.mgmt.plan.rejectlayer":"Rechazar capa","gpui.mgmt.plan.reqplain":"Aprobación solicitada","gpui.mgmt.plan.requested":"Aprobación solicitada: {what}","gpui.mgmt.plan.saved":"plan guardado","gpui.mgmt.plan.show":"Mostrar hechos","gpui.mgmt.plan.st.approved":"Aprobado","gpui.mgmt.plan.st.awaiting":"Esperando revisión","gpui.mgmt.plan.st.blocked":"Bloqueado","gpui.mgmt.plan.st.empty":"Vacío","gpui.mgmt.plan.st.partial":"Parcial","gpui.mgmt.plan.st.rejected":"Rechazado","gpui.mgmt.plan.st.routed":"Ruteado","gpui.mgmt.plan.st.routing":"Ruteando","gpui.mgmt.plan.st.verified":"Verificado","gpui.mgmt.plan.stackup.short":"Apilamiento","gpui.mgmt.plan.stop":"Detener ruteo","gpui.mgmt.plan.sync":"Vincular zoom","gpui.mgmt.plan.tab":"Plan","gpui.mgmt.plan.unlock":"Desbloquear","gpui.mgmt.plan.verify":"Verificar","gpui.mgmt.plan.view.canvas":"Lienzo","gpui.mgmt.plan.view.list":"Lista","gpui.mgmt.plan.view.split":"Dividido","gpui.mgmt.plan.width":"Ancho","gpui.next.thread":"Hilo siguiente","gpui.nothing.matches":"Nada coincide","gpui.planmode.bar.always":"Modo plan — explora y propone un plan antes de editar","gpui.planmode.bar.executing":"Ejecutando el plan aprobado","gpui.planmode.bar.once":"Modo plan (1 turno) — explora y propone un plan antes de editar","gpui.planmode.bar.pending":"El plan propuesto espera revisión abajo","gpui.planmode.bar.planning":"Planificando — redactando un plan antes de editar","gpui.planmode.chip.building":"Ejecutando","gpui.planmode.chip.once":"Plan · 1t","gpui.planmode.scope.always":"Siempre","gpui.planmode.scope.once":"1 turno","gpui.planmode.tip":"Planificar antes de actuar (1 turno, siempre u off)","gpui.planmode.top.executing":"Ejecutando plan","gpui.planmode.top.once":"Plan (1 turno)","gpui.planmode.top.pending":"Revisar plan","gpui.planmode.top.planning":"Planificando","gpui.previous.thread":"Hilo anterior","gpui.rail.no.board":"Este proyecto no tiene placa","gpui.rail.no.mech":"Este proyecto no tiene piezas mecánicas","gpui.rail.no.schematic":"Este proyecto no tiene esquema","gpui.rail.split.needs.both":"La vista dividida requiere una placa y un esquema","home.away":"El inicio ({name}) no está disponible","home.away.queued":"El inicio ({name}) no está disponible · {n} en cola","home.away.since":"El inicio ({name}) no está disponible desde las {time}","home.away.since.queued":"El inicio ({name}) no está disponible desde las {time} · {n} en cola","home.machine":"Máquina de inicio","home.move.failed":"No se pudo mover el inicio","home.move.failed.note":"No se pudo mover el inicio: {note}","home.move.here":"Hacer de esta máquina el inicio","home.moving":"Moviendo el inicio a {to}…","home.moving.step":"Moviendo el inicio a {to}: {step}","hub.back.crash":"Backplane volvió tras detenerse de forma inesperada","hub.restarting":"Reiniciando Backplane…","hub.restarting.build":"Reiniciando Backplane… (nueva compilación {build})","hub.stopped":"Backplane se detuvo","ios.hub.address.field":"Dirección del hub","menu.pin":"Fijar","menu.settle":"Cerrar","menu.unpin":"Desfijar","model.col.agent":"Agente","notify.settled":"Cerrado","palette.archive":"Archivar hilo","palette.command.placeholder":"Escribe un comando o un hilo","palette.diff":"Diff: qué cambió este hilo","palette.newthread":"Nuevo hilo","palette.settings":"Ajustes","palette.terminal":"Terminal","palette.unarchive":"Desarchivar hilo","phone.unsettle":"Reabrir","provider.notice.button":"Abrir Configuración → Cuentas","provider.notice.head":"No hay ningún proveedor de IA conectado","provider.notice.senderr":"Aún no hay ningún proveedor de IA conectado. Abre Configuración → Cuentas para conectar Claude, Codex, Antigravity u otro proveedor.","provider.notice.text.none":"Conecta Claude, Codex, Antigravity u otro proveedor para empezar a chatear.","provider.notice.text.signedout":"Inicia sesión en Claude, Codex u otro proveedor en Configuración → Cuentas para empezar a chatear.","reply.action":"Responder","reply.cancel":"Cancelar respuesta","reply.to":"En respuesta a:","secret.you":"Tú","settings.lang":"Idioma","sheet.rename":"Renombrar hilo","sidebar.add.project":"Añadir proyecto","sidebar.search.projects":"Buscar proyectos","thread.context.base":"Backplane","thread.context.copied":"Se copiaron las instrucciones.","thread.context.copy":"Copiar instrucciones","thread.context.disable":"Desactivar","thread.context.enable":"Activar","thread.context.index":"Índice de habilidades disponibles","thread.context.injected.label":"Instrucciones del proyecto añadidas","thread.context.instructions":"Instrucciones","thread.context.mcp":"MCP del proyecto","thread.context.native.note":"Instrucciones de inicio de Backplane. El proveedor carga los archivos nativos.","thread.context.none.instructions":"No se encontraron instrucciones del proyecto.","thread.context.none.mcp":"No se encontraron configuraciones MCP del proyecto.","thread.context.reading":"Leyendo el contexto del hilo…","thread.context.size":"{bytes} B · ≈{tokens} tokens","thread.context.skills":"Habilidades","thread.context.system":"Instrucciones del sistema","thread.context.title":"Contexto e instrucciones","thread.context.trust":"Confiar y activar","thread.new":"Nuevo hilo","tools.pinned":"Fijado","tools.retry":"Reintentar","tour.title.bots":"Bots","viewer.board":"Placa","viewer.diff":"Diff","viewer.files":"Archivos","viewer.mech":"Mech","viewer.review":"Revisión","viewer.schematic":"Esquemático","viewer.solid":"3D","web.chat.answer.btn":"Responder","web.chat.answer.placeholder":"Escribe una respuesta…","web.chat.answered":"Respondido: {answer}","web.chat.choose":"Elige un hilo de proyecto a la izquierda para empezar.","web.chat.empty":"Aún no hay mensajes. Escribe abajo para iniciar un turno.","web.chat.finished":"Terminado {time}","web.chat.finished.dur":"Terminado {time} · {dur}","web.chat.loading":"Cargando mensajes…","web.chat.review.mode":"Modo de revisión","web.chat.streaming":"Transmitiendo…","web.clone.add.dir":"Añadir {dir}","web.clone.back":"Atrás","web.clone.change.folder":"Cambiar carpeta","web.clone.cloned":"{repo} clonado en {dest}","web.clone.cloning":"Clonando {repo} en {dest}","web.clone.copied":"Copiado","web.clone.first":"Primer mensaje: {text}","web.clone.folder.name":"Nombre de la carpeta","web.clone.go":"Clonar","web.clone.loading":"Cargando…","web.clone.no.folders":"No hay carpetas aquí","web.clone.open.project":"Abrir el proyecto","web.clone.open.thread":"Abrir el hilo","web.clone.private":"privado","web.clone.repo.placeholder":"URL https o ssh, o propietario/repositorio","web.clone.retry":"Reintentar","web.clone.same":"Ya está clonado ahí: se añade tal cual.","web.clone.signin":"Iniciar sesión en GitHub","web.clone.signin.done":"Sesión iniciada en GitHub","web.clone.signin.enter":"Introduce este código en GitHub:","web.clone.signin.wait":"Iniciando sesión en GitHub…","web.clone.start.thread":"Empezar un hilo","web.clone.stopped":"Se detuvo la clonación de {repo}","web.clone.tab":"Clonar desde git","web.clone.up":"Subir","web.clone.use.dir":"Usar {dir}","web.composer.attach":"Adjuntar imagen","web.composer.maximages":"Como máximo {max} imágenes por mensaje.","web.composer.unsupported":"Tipo de imagen no compatible: {type}","web.composer.voice":"Dictado por voz","web.logout.failed":"No se pudo confirmar el cierre de sesión. Inténtalo de nuevo.","web.pair.approve.in":"Aprueba en el escritorio o en un teléfono vinculado · caduca en {time}","web.pair.approved":"Aprobado. Abriendo Backplane…","web.pair.cancelled":"Cancelado.","web.pair.code":"Código de comparación","web.pair.denied":"Se rechazó la solicitud de vinculación.","web.pair.expired":"El código de vinculación caducó. Solicita uno nuevo para intentarlo otra vez.","web.pair.failed":"Falló la solicitud de vinculación ({status})","web.pair.name":"Nombre del navegador","web.pair.nocode":"El hub no devolvió un código de comparación.","web.pair.ratelimited":"Demasiados intentos de vinculación. Espera un momento e inténtalo de nuevo.","web.pair.request":"Solicitar vinculación","web.pair.requesting":"Solicitando código de vinculación…","web.pair.subtitle":"Vincula este navegador con tu hub. Aprueba el código de 6 dígitos en Backplane › Ajustes › Dispositivos.","web.pair.unreachable":"No se pudo conectar con el hub. Comprueba tu conexión de tailnet.","web.plan.awaiting":"{n} esperando aprobación","web.plan.net.one":"1 red","web.plan.nets":"{n} redes","web.settings.providers":"Proveedores de IA","web.settings.providers.browser":"Conecta un proveedor en la aplicación de escritorio o móvil de Backplane en Configuración → Cuentas."},ja:{"agy.signout":"サインアウト","android.hub.machines.approve":"承認","android.load.earlier":"以前のメッセージを読み込む","approval.dismiss":"閉じる","approval.implement":"実装","ask.plan":"提案されたプラン","bots.rooms":"ルーム","bots.tab.browser":"ブラウザ","common.cancel":"キャンセル","common.close":"閉じる","common.copy":"コピー","common.delete":"削除","common.refresh":"更新","common.remove":"削除","common.save":"保存","composer.placeholder":"何でも質問:@bot、>thread、%project、#room、$skill、/btw","composer.send":"送信","composer.stop":"停止","gpui.acct.connected":"接続済み","gpui.acct.not.connected":"未接続","gpui.acct.sign.in.expired":"サインインの期限切れ","gpui.ask.plan.ready":"確認待ち","gpui.ask.plan.revise":"修正","gpui.ask.plan.reviseph":"計画のどこを変更しますか?","gpui.ask.plan.sendrev":"修正を送る","gpui.b.in.reply.to":"↩ 返信先:{quote}","gpui.b.replying.to":"↩ 返信中:{line}","gpui.bots.recall.off":"オフ","gpui.bots.recall.on":"オン","gpui.c.term.collapse":"折りたたむ","gpui.c.term.expand":"展開","gpui.commands":"コマンド","gpui.e.open.folder":"フォルダを開く","gpui.filter.projects.and.threads":"プロジェクトとスレッドを絞り込む","gpui.fold.or.unfold.the.sidebar":"サイドバーを折りたたむ/開く","gpui.follow.paused":"追従を一時停止中","gpui.follow.wait":"追従中: エージェントの次の編集を待っています","gpui.gerbers":"ガーバー","gpui.improvements":"改善","gpui.jump.to.a.thread.run":"スレッドへ移動、コマンドを実行、または発言を検索","gpui.mgmt.bom.dnp":"実装しない","gpui.mgmt.bom.nompn":"MPNなし","gpui.mgmt.checks.all":"すべて","gpui.mgmt.checks.fix":"エージェントに直してもらう","gpui.mgmt.checks.run":"実行","gpui.mgmt.close":"パネルを閉じる","gpui.mgmt.fab.apply":"適用","gpui.mgmt.fab.changed":"前回見てから変わったところ","gpui.mgmt.fab.derived":"* 製造元のページから計算した値です(milをmmに、径からランドを)。薄い色の項目はリジッド基板の値です(この基板のページに記載がないもの)。日付を押すと読んだページが開きます。","gpui.mgmt.fab.extra":"追加料金","gpui.mgmt.fab.findings":"指摘","gpui.mgmt.fab.free":"基本料金","gpui.mgmt.fab.judge":"データシート","gpui.mgmt.fab.limit":"項目","gpui.mgmt.fab.readcol":"読んだ日","gpui.mgmt.fab.refresh":"再読み込み","gpui.mgmt.fab.reviewbtn":"レビュー","gpui.mgmt.fab.seen":"確認済み","gpui.mgmt.fab.thefab":"製造元","gpui.mgmt.fab.use":"使う","gpui.mgmt.life.nopart":"この部品の記録はまだありません。","gpui.mgmt.life.reading":"履歴を読んでいます…","gpui.mgmt.plan.addnote":"メモを追加","gpui.mgmt.plan.all":"すべて承認","gpui.mgmt.plan.before":"配線前に計画する","gpui.mgmt.plan.compact":"標準","gpui.mgmt.plan.done":"完了","gpui.mgmt.plan.drawn":"計画の配線経路とプレーンは、このパネルを開いている間だけ基板上に表示されます。閉じると消えます。","gpui.mgmt.plan.edited":"編集済み","gpui.mgmt.plan.elsewhere":"{board}の配線計画が承認を待っています","gpui.mgmt.plan.emptysub":"計画が提案されると、レイヤー・コリドー・ベタ領域がここに表示されます。","gpui.mgmt.plan.expand":"拡大","gpui.mgmt.plan.fit":"全体表示","gpui.mgmt.plan.grid.all":"全レイヤー","gpui.mgmt.plan.grid.pair":"並べて表示","gpui.mgmt.plan.grid.single":"単一","gpui.mgmt.plan.hide":"完了を隠す","gpui.mgmt.plan.hint":"頂点をドラッグして誘導 · 辺の + をクリックで追加 · 頂点を右クリックで削除","gpui.mgmt.plan.keysnote":"このバージョンのKiCadでは、このパネルから承認してください。プランビューでのKiCadのA・R・Wキーはまだ計画のものではありません(Aはフットプリントの追加を開きます)。KiCadを更新してください。","gpui.mgmt.plan.layer":"層を承認","gpui.mgmt.plan.layer.short":"レイヤー","gpui.mgmt.plan.lock":"ロック","gpui.mgmt.plan.locked":"ロック中","gpui.mgmt.plan.noboard":"この基板の配線計画はありません。","gpui.mgmt.plan.noitems":"このレイヤーにコリドーまたはプレーンがありません","gpui.mgmt.plan.note.placeholder":"ルーターへの指示メモ…","gpui.mgmt.plan.nothing":"承認待ちはありません","gpui.mgmt.plan.offwords":"エージェントは指示どおりに配線します。オンにすると、まず配線計画を提案し、ここで承認したものだけを配線します。","gpui.mgmt.plan.onwords":"銅箔層が4層以上、またはネットが60本を超える基板では、配線の前にエージェントがここで配線経路とプレーン領域を提案します。承認したものだけを配線します。","gpui.mgmt.plan.reading":"配線計画を読んでいます…","gpui.mgmt.plan.reference":"基準 {layer}","gpui.mgmt.plan.refused":"KiCad が拒否しました","gpui.mgmt.plan.reject":"却下","gpui.mgmt.plan.rejectlayer":"レイヤーを却下","gpui.mgmt.plan.reqplain":"承認が求められています","gpui.mgmt.plan.requested":"承認が求められています: {what}","gpui.mgmt.plan.saved":"保存された計画","gpui.mgmt.plan.show":"完了を表示","gpui.mgmt.plan.st.approved":"承認済み","gpui.mgmt.plan.st.awaiting":"承認待ち","gpui.mgmt.plan.st.blocked":"ブロック","gpui.mgmt.plan.st.empty":"空","gpui.mgmt.plan.st.partial":"一部完了","gpui.mgmt.plan.st.rejected":"却下","gpui.mgmt.plan.st.routed":"配線済み","gpui.mgmt.plan.st.routing":"配線中","gpui.mgmt.plan.st.verified":"検証済み","gpui.mgmt.plan.stackup.short":"スタックアップ","gpui.mgmt.plan.stop":"配線を止める","gpui.mgmt.plan.sync":"ズーム連動","gpui.mgmt.plan.tab":"計画","gpui.mgmt.plan.unlock":"ロック解除","gpui.mgmt.plan.verify":"検証","gpui.mgmt.plan.view.canvas":"キャンバス","gpui.mgmt.plan.view.list":"リスト","gpui.mgmt.plan.view.split":"分割","gpui.mgmt.plan.width":"幅","gpui.next.thread":"次のスレッド","gpui.nothing.matches":"一致するものはありません","gpui.planmode.bar.always":"計画モード — 編集前に調査して計画を提案します","gpui.planmode.bar.executing":"承認された計画を実行しています","gpui.planmode.bar.once":"計画モード (1回) — 編集前に調査して計画を提案します","gpui.planmode.bar.pending":"提案された計画が下のレビューを待っています","gpui.planmode.bar.planning":"計画中 — 編集前の計画を作成しています","gpui.planmode.chip.building":"実行中","gpui.planmode.chip.once":"計画 · 1回","gpui.planmode.scope.always":"常時","gpui.planmode.scope.once":"1回","gpui.planmode.tip":"実行前に計画を作成 (1回・常時・オフ)","gpui.planmode.top.executing":"計画を実行中","gpui.planmode.top.once":"計画 (1回)","gpui.planmode.top.pending":"計画を確認","gpui.planmode.top.planning":"計画中","gpui.previous.thread":"前のスレッド","gpui.rail.no.board":"このプロジェクトには基板がありません","gpui.rail.no.mech":"このプロジェクトには機械部品がありません","gpui.rail.no.schematic":"このプロジェクトには回路図がありません","gpui.rail.split.needs.both":"分割表示には基板と回路図が必要です","home.away":"ホーム({name})はオフラインです","home.away.queued":"ホーム({name})はオフラインです · {n} 件待機中","home.away.since":"ホーム({name})は {time} からオフラインです","home.away.since.queued":"ホーム({name})は {time} からオフラインです · {n} 件待機中","home.machine":"ホームマシン","home.move.failed":"ホームの移動に失敗しました","home.move.failed.note":"ホームの移動に失敗しました: {note}","home.move.here":"このマシンをホームにする","home.moving":"ホームを {to} へ移動中…","home.moving.step":"ホームを {to} へ移動中: {step}","hub.back.crash":"予期せず停止したBackplaneが戻りました","hub.restarting":"Backplaneを再起動しています…","hub.restarting.build":"Backplaneを再起動しています…(新しいビルド {build})","hub.stopped":"Backplaneは停止しました","ios.hub.address.field":"ハブのアドレス","menu.pin":"ピン留め","menu.settle":"完了","menu.unpin":"ピン留めを解除","model.col.agent":"エージェント","notify.settled":"完了","palette.archive":"スレッドをアーカイブ","palette.command.placeholder":"コマンドまたはスレッドを入力","palette.diff":"差分:このスレッドの変更","palette.newthread":"新しいスレッド","palette.settings":"設定","palette.terminal":"ターミナル","palette.unarchive":"スレッドのアーカイブを解除","phone.unsettle":"未完了に戻す","provider.notice.button":"設定 → アカウントを開く","provider.notice.head":"AI プロバイダーが接続されていません","provider.notice.senderr":"AI プロバイダーがまだ接続されていません。設定 → アカウントを開いて、Claude、Codex、Antigravity などのプロバイダーを接続してください。","provider.notice.text.none":"チャットを始めるには、Claude、Codex、Antigravity などのプロバイダーを接続してください。","provider.notice.text.signedout":"チャットを始めるには、設定 → アカウントで Claude、Codex などのプロバイダーにサインインしてください。","reply.action":"返信","reply.cancel":"返信をやめる","reply.to":"返信先:","secret.you":"あなた","settings.lang":"言語","sheet.rename":"スレッド名を変更","sidebar.add.project":"プロジェクトを追加","sidebar.search.projects":"プロジェクトを検索","thread.context.base":"Backplane","thread.context.copied":"プロンプトをコピーしました。","thread.context.copy":"プロンプトをコピー","thread.context.disable":"無効にする","thread.context.enable":"有効にする","thread.context.index":"利用可能なスキルの一覧","thread.context.injected.label":"追加されたプロジェクトの指示","thread.context.instructions":"指示","thread.context.mcp":"プロジェクトの MCP","thread.context.native.note":"Backplane が起動時に渡すプロンプトです。ネイティブファイルはプロバイダーが読み込みます。","thread.context.none.instructions":"プロジェクトの指示が見つかりません。","thread.context.none.mcp":"プロジェクトの MCP 設定が見つかりません。","thread.context.reading":"スレッドのコンテキストを読み込み中…","thread.context.size":"{bytes} B・約{tokens}トークン","thread.context.skills":"スキル","thread.context.system":"システムプロンプト","thread.context.title":"コンテキストとプロンプト","thread.context.trust":"承認して有効にする","thread.new":"新しいスレッド","tools.pinned":"固定中","tools.retry":"再試行","tour.title.bots":"ボット","viewer.board":"基板","viewer.diff":"差分","viewer.files":"ファイル","viewer.mech":"Mech","viewer.review":"レビュー","viewer.schematic":"回路図","viewer.solid":"3D","web.chat.answer.btn":"回答","web.chat.answer.placeholder":"回答を入力…","web.chat.answered":"回答済み: {answer}","web.chat.choose":"左側からプロジェクトのスレッドを選んで開始してください。","web.chat.empty":"まだメッセージはありません。下に入力して開始してください。","web.chat.finished":"完了 {time}","web.chat.finished.dur":"完了 {time} · {dur}","web.chat.loading":"メッセージを読み込んでいます…","web.chat.review.mode":"レビューモード","web.chat.streaming":"受信中…","web.clone.add.dir":"{dir} を追加","web.clone.back":"戻る","web.clone.change.folder":"フォルダを変更","web.clone.cloned":"{repo} を {dest} にクローンしました","web.clone.cloning":"{repo} を {dest} にクローン中","web.clone.copied":"コピーしました","web.clone.first":"最初のメッセージ: {text}","web.clone.folder.name":"フォルダ名","web.clone.go":"クローン","web.clone.loading":"読み込み中…","web.clone.no.folders":"フォルダがありません","web.clone.open.project":"プロジェクトを開く","web.clone.open.thread":"スレッドを開く","web.clone.private":"非公開","web.clone.repo.placeholder":"https / ssh の URL、または owner/repo","web.clone.retry":"もう一度","web.clone.same":"すでにそこにクローンされています: そのまま追加します。","web.clone.signin":"GitHub にサインイン","web.clone.signin.done":"GitHub にサインインしました","web.clone.signin.enter":"このコードを GitHub に入力してください:","web.clone.signin.wait":"GitHub のサインインを開始しています…","web.clone.start.thread":"スレッドを開始","web.clone.stopped":"{repo} のクローンを中止しました","web.clone.tab":"git からクローン","web.clone.up":"上へ","web.clone.use.dir":"{dir} を使う","web.composer.attach":"画像を添付","web.composer.maximages":"1 件のメッセージに添付できる画像は最大 {max} 枚です。","web.composer.unsupported":"未対応の画像形式です: {type}","web.composer.voice":"音声入力","web.logout.failed":"サインアウトを確認できませんでした。もう一度お試しください。","web.pair.approve.in":"デスクトップまたはペアリング済みの端末で承認してください · 有効期限 {time}","web.pair.approved":"承認されました。Backplane を開いています…","web.pair.cancelled":"キャンセルしました。","web.pair.code":"確認コード","web.pair.denied":"ペアリングのリクエストが拒否されました。","web.pair.expired":"ペアリングコードの有効期限が切れました。新しいコードをリクエストしてください。","web.pair.failed":"ペアリングのリクエストに失敗しました ({status})","web.pair.name":"ブラウザー名","web.pair.nocode":"ハブから確認コードが返されませんでした。","web.pair.ratelimited":"ペアリングの試行回数が多すぎます。しばらく待ってからやり直してください。","web.pair.request":"ペアリングをリクエスト","web.pair.requesting":"ペアリングコードをリクエストしています…","web.pair.subtitle":"このブラウザーをハブとペアリングします。Backplane › 設定 › デバイス で 6 桁のコードを承認してください。","web.pair.unreachable":"ハブに接続できませんでした。tailnet の接続を確認してください。","web.plan.awaiting":"{n} 件が承認待ち","web.plan.net.one":"1 ネット","web.plan.nets":"{n} ネット","web.settings.providers":"AI プロバイダー","web.settings.providers.browser":"Backplane のデスクトップまたはモバイルアプリの設定 → アカウントからプロバイダーを接続してください。"}};function Q(a,t){if(!t)return a;return a.replace(/\{([a-zA-Z0-9_.-]+)\}/g,(s,r)=>Object.prototype.hasOwnProperty.call(t,r)?String(t[r]):s)}var F=te(),W=new Set,V=new Map;for(let[a,t]of Object.entries(U.en||{}))if(typeof t==="string"&&!V.has(t))V.set(t,a);function te(){let a=typeof navigator<"u"&&navigator.language?navigator.language.toLowerCase():"en";if(a.startsWith("ja"))return"ja";if(a.startsWith("es"))return"es";return"en"}function Y(){if(typeof document<"u"&&document.documentElement)document.documentElement.lang=F}Y();function me(a){return W.add(a),()=>{W.delete(a)}}function ue(a){if(!a)return!1;let t=a.toLowerCase(),s=t.startsWith("ja")?"ja":t.startsWith("es")?"es":t.startsWith("en")?"en":"";if(!s)return!1;let r=s!==F;if(F=s,Y(),r)for(let d of W)d(F);return r}function c(a,t,s){let d=(U[F]||U.en||{})[a]??U.en?.[a]??t??a;return Q(d,s)}function ge(a){if(!a)return"";let t=V.get(a);if(!t)return a;return c(t,a)}var ae=[[1,26,7,1,[]],[2,44,10,1,[6,18]],[3,70,15,1,[6,22]],[4,100,20,1,[6,26]],[5,134,26,1,[6,30]],[6,172,18,2,[6,34]]],O=new Uint8Array(512),_=new Uint8Array(256);{let a=1;for(let t=0;t<255;t++)if(O[t]=a,_[a]=t,a<<=1,a&256)a^=285;for(let t=255;t<512;t++)O[t]=O[t-255]}function J(a,t){return a===0||t===0?0:O[_[a]+_[t]]}function ne(a){let t=new Uint8Array([1]);for(let s=0;s{let m=e-i*n;return Math.ceil((12+t.length*8)/8)<=m});if(!s)return null;let[r,d,u,f,S]=s,w=d-u*f,g=[],E=(e,i)=>{for(let n=i-1;n>=0;n--)g.push(e>>>n&1)};E(4,4),E(t.length,8);for(let e of t)E(e,8);for(let e=0;e<4&&g.length{if(e<0||i<0||e>=p||i>=p)return;H[e*p+i]=n?1:0,A[e*p+i]=1},N=(e,i)=>{for(let n=-1;n<=7;n++)for(let m=-1;m<=7;m++){let k=e+n,l=i+m,o=n>=0&&n<=6&&m>=0&&m<=6&&(n===0||n===6||m===0||m===6||n>=2&&n<=4&&m>=2&&m<=4);b(k,l,o)}};N(0,0),N(0,p-7),N(p-7,0);for(let e=8;e=1;e-=2){if(e===6)e=5;let i=(e+1&2)===0;for(let n=0;n>>3]>>>7-(j&7)&1,j++;let o=(m+l&1)===0?h^1:h;H[m*p+l]=o}}}let R=30660;for(let e=0;e<=5;e++)b(8,e,(R>>>14-e&1)===1);b(8,7,(R>>>8&1)===1),b(8,8,(R>>>7&1)===1),b(7,8,(R>>>6&1)===1);for(let e=0;e<=5;e++)b(5-e,8,(R>>>5-e&1)===1);for(let e=0;e<8;e++)b(8,p-1-e,(R>>>e&1)===1);for(let e=0;e<7;e++)b(p-7+e,8,(R>>>14-e&1)===1);return{size:p,modules:H}}function X(a){let t=oe(a);if(!t)return null;let s=2,r=t.size+s*2,d=document.createElementNS("http://www.w3.org/2000/svg","svg");d.setAttribute("viewBox",`0 0 ${r} ${r}`),d.setAttribute("role","img"),d.setAttribute("aria-label",`QR code for ${a}`),d.setAttribute("shape-rendering","crispEdges"),d.classList.add("bp-qr-svg");let u=document.createElementNS("http://www.w3.org/2000/svg","rect");u.setAttribute("width",String(r)),u.setAttribute("height",String(r)),u.setAttribute("fill","#ffffff"),d.appendChild(u);let f="";for(let w=0;w{let h=l.trim();if(!h)return;let o=h.startsWith("https://")?h:`https://${h}`;if(!o.startsWith("https://")||o.length<=8)return;let x=document.createElement("div");x.className="bp-pair-addr-meta";let v=document.createElement("div");v.className="bp-pair-code-label",v.textContent=c("ios.hub.address.field","Hub address");let y=document.createElement("code");y.className="bp-pair-addr-url",y.textContent=o,y.setAttribute("data-testid","pair-address");let P=document.createElement("button");P.type="button",P.className="bp-pair-copy";let I=c("common.copy","Copy");P.textContent=I,P.addEventListener("click",()=>{navigator.clipboard?.writeText(o).then(()=>{P.textContent=c("web.clone.copied","Copied"),window.setTimeout(()=>{P.textContent=I},1200)}).catch(()=>{})}),x.append(v,y,P);let z=document.createDocumentFragment();z.appendChild(x);let K=X(o);if(K){let G=document.createElement("div");G.className="bp-pair-qr",G.setAttribute("data-testid","pair-qr"),G.appendChild(K),z.appendChild(G)}p.replaceChildren(z),p.classList.remove("bp-hidden")};fetch("/auth/web/info",{credentials:"same-origin"}).then(async(l)=>{if(!l.ok)return;let h=await l.json();if(typeof h.address==="string")H(h.address)}).catch(()=>{}),t.append(s,u,f,E,C,p),a.appendChild(t);let A=null,b=null,N=null,j=0,D=0,R=150,e=1000;function i(){if(j++,N)N.abort(),N=null;if(A!==null)window.clearTimeout(A),A=null;if(b!==null)window.clearInterval(b),b=null}function n(l="",h=!1){i(),f.classList.remove("bp-hidden"),E.classList.add("bp-hidden"),g.disabled=!1,C.textContent=l,C.className=h?"bp-pair-status bp-bad":"bp-pair-status"}function m(){let l=D-Date.now();if(l<=0){n(c("web.pair.expired","Pairing code expired. Request a new code to try again."),!0);return}B.textContent=c("web.pair.approve.in","Approve on desktop or paired phone · expires in {time}",{time:pe(l)})}async function k(l){if(l!==j)return;if(D>0&&Date.now()>=D){n(c("web.pair.expired","Pairing code expired. Request a new code to try again."),!0);return}let h=new AbortController;N=h;try{let o=await fetch("/auth/web/poll",{method:"POST",credentials:"same-origin",headers:{"Content-Type":"application/json"},body:"{}",signal:h.signal});if(l!==j)return;if(e=1000,o.status===202){A=window.setTimeout(()=>{k(l)},150);return}if(o.status===200||o.status===204){let v={};if(o.status===200)try{v=await o.json()}catch{}if(l!==j)return;let y=(v.state||v.status||"").toLowerCase();if(o.status===204||v.approved===!0||y==="approved"||y==="ok"){i(),C.textContent=c("web.pair.approved","Approved. Opening Backplane…"),C.className="bp-pair-status bp-ok",window.location.replace("/");return}if(y==="denied"||y==="rejected"){n(c("web.pair.denied","Pairing request was denied."),!0);return}if(y==="expired"){n(c("web.pair.expired","Pairing code expired. Request a new code to try again."),!0);return}A=window.setTimeout(()=>{k(l)},150);return}if(o.status===429){let v=Number(o.headers.get("Retry-After")||"5"),y=Math.max(2000,(Number.isFinite(v)?v:5)*1000);A=window.setTimeout(()=>{k(l)},y);return}if(o.status===401||o.status===403||o.status===404||o.status===410){let v="";try{let y=await o.json();v=(y.state||y.status||y.error||"").toLowerCase()}catch{}if(l!==j)return;if(v==="denied"||v==="rejected"||o.status===403)n(c("web.pair.denied","Pairing request was denied."),!0);else n(c("web.pair.expired","Pairing code expired. Request a new code to try again."),!0);return}let x=e;e=Math.min(1e4,Math.round(e*1.8)),A=window.setTimeout(()=>{k(l)},x)}catch{if(l!==j)return;let o=e;e=Math.min(1e4,Math.round(e*1.8)),A=window.setTimeout(()=>{k(l)},o)}finally{if(N===h)N=null}}L.addEventListener("click",()=>{n(c("web.pair.cancelled","Cancelled."))}),f.addEventListener("submit",async(l)=>{l.preventDefault();let h=w.value.trim()||Z();g.disabled=!0,C.textContent=c("web.pair.requesting","Requesting pairing code…"),C.className="bp-pair-status";try{let o=await fetch("/auth/web/request",{method:"POST",credentials:"same-origin",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:h})});if(!o.ok){let I=c("web.pair.failed","Pairing request failed ({status})",{status:o.status});try{let z=await o.json();if(z.error)I=z.error}catch{}if(o.status===429)I=c("web.pair.ratelimited","Too many pairing attempts. Wait a moment and try again.");n(I,!0);return}let x=await o.json(),v=x.code||x.checkCode||"";if(!v){n(c("web.pair.nocode","Hub did not return a comparison code."),!0);return}let y=Date.now();D=x.expiresAt?x.expiresAt<10000000000?x.expiresAt*1000:x.expiresAt:y+(x.expiresIn?x.expiresIn*1000:120000),i();let P=j;e=1000,R=x.pollMs&&x.pollMs>=100?x.pollMs:150,M.textContent=re(v),f.classList.add("bp-hidden"),E.classList.remove("bp-hidden"),C.textContent="",m(),b=window.setInterval(m,1000),A=window.setTimeout(()=>{k(P)},R)}catch{n(c("web.pair.unreachable","Could not reach the hub. Check your tailnet connection."),!0)}})}if(document.readyState==="loading")document.addEventListener("DOMContentLoaded",ee);else ee(); +var U={en:{"agy.signout":"Sign out","android.hub.machines.approve":"Approve","android.load.earlier":"load earlier","approval.dismiss":"Dismiss","approval.implement":"Implement","ask.plan":"Proposed plan","bots.rooms":"Rooms","bots.tab.browser":"Browser","common.cancel":"Cancel","common.close":"Close","common.copy":"Copy","common.delete":"Delete","common.refresh":"Refresh","common.remove":"Remove","common.save":"Save","composer.placeholder":"Ask anything: @bot, >thread, %project, #room, $skill, /btw","composer.send":"Send","composer.stop":"Stop","gpui.acct.connected":"Connected","gpui.acct.not.connected":"Not connected","gpui.acct.sign.in.expired":"Sign-in expired","gpui.ask.plan.ready":"Ready for review","gpui.ask.plan.revise":"Revise","gpui.ask.plan.reviseph":"What should change in the plan?","gpui.ask.plan.sendrev":"Send revision","gpui.b.in.reply.to":"↩ In reply to: {quote}","gpui.b.replying.to":"↩ Replying to: {line}","gpui.bots.recall.off":"Off","gpui.bots.recall.on":"On","gpui.c.term.collapse":"Collapse","gpui.c.term.expand":"Expand","gpui.commands":"Commands","gpui.e.open.folder":"Open folder","gpui.filter.projects.and.threads":"Filter projects and threads","gpui.fold.or.unfold.the.sidebar":"Fold or unfold the sidebar","gpui.follow.paused":"Following paused","gpui.follow.wait":"Following: waiting for the agent's next edit","gpui.gerbers":"Gerbers","gpui.improvements":"Improvements","gpui.jump.to.a.thread.run":"Jump to a thread, run a command or find what was said","gpui.mgmt.bom.dnp":"DNP","gpui.mgmt.bom.nompn":"no MPN","gpui.mgmt.checks.all":"All","gpui.mgmt.checks.fix":"Fix with agent","gpui.mgmt.checks.run":"Run","gpui.mgmt.close":"Close the panel","gpui.mgmt.fab.apply":"Apply","gpui.mgmt.fab.changed":"Changed since you last looked","gpui.mgmt.fab.derived":"* worked out from the fab's page (a mil in mm, a ring from a diameter). Dimmed: the rigid board's value, where this board's page says nothing else. A date opens the page it was read from.","gpui.mgmt.fab.extra":"Costs more","gpui.mgmt.fab.findings":"Findings","gpui.mgmt.fab.free":"Base price","gpui.mgmt.fab.judge":"Datasheets","gpui.mgmt.fab.limit":"Limit","gpui.mgmt.fab.readcol":"Read","gpui.mgmt.fab.refresh":"Refresh","gpui.mgmt.fab.reviewbtn":"Review","gpui.mgmt.fab.seen":"Seen","gpui.mgmt.fab.thefab":"The fab","gpui.mgmt.fab.use":"Use","gpui.mgmt.life.nopart":"No reading of this part yet.","gpui.mgmt.life.reading":"Reading its history…","gpui.mgmt.plan.addnote":"Add note","gpui.mgmt.plan.all":"Approve all","gpui.mgmt.plan.before":"Plan before routing","gpui.mgmt.plan.compact":"Compact","gpui.mgmt.plan.done":"done","gpui.mgmt.plan.drawn":"The plan's corridors and planes are drawn on the board while this panel is open. Close it to hide them.","gpui.mgmt.plan.edited":"Edited","gpui.mgmt.plan.elsewhere":"A routing plan for {board} awaits your approval","gpui.mgmt.plan.emptysub":"Layers, corridors, and planes appear here once a plan is proposed.","gpui.mgmt.plan.expand":"Expand","gpui.mgmt.plan.fit":"Fit","gpui.mgmt.plan.grid.all":"All layers","gpui.mgmt.plan.grid.pair":"Side by side","gpui.mgmt.plan.grid.single":"Single","gpui.mgmt.plan.hide":"Hide done","gpui.mgmt.plan.hint":"Drag waypoints to steer · Click + on edge to insert · Right-click vertex to remove","gpui.mgmt.plan.keysnote":"On this KiCad version, approve from this panel: in plan view KiCad's A, R and W keys aren't the plan's yet (A opens Add Footprint). Update KiCad.","gpui.mgmt.plan.layer":"Approve layer","gpui.mgmt.plan.layer.short":"Layer","gpui.mgmt.plan.lock":"Lock","gpui.mgmt.plan.locked":"Locked","gpui.mgmt.plan.noboard":"No routing plan for this board.","gpui.mgmt.plan.noitems":"No corridors or planes on this layer","gpui.mgmt.plan.note.placeholder":"Steering note for router…","gpui.mgmt.plan.nothing":"Nothing awaits your approval","gpui.mgmt.plan.offwords":"Agents route as you ask. Turn it on to have them propose a routing plan first and route only what you approve here.","gpui.mgmt.plan.onwords":"Before routing a board with 4 or more copper layers or more than 60 nets, the agent proposes corridors and plane regions here. It routes only what you approve.","gpui.mgmt.plan.reading":"Reading the routing plan…","gpui.mgmt.plan.reference":"over {layer}","gpui.mgmt.plan.refused":"KiCad refused","gpui.mgmt.plan.reject":"Reject","gpui.mgmt.plan.rejectlayer":"Reject layer","gpui.mgmt.plan.reqplain":"Approval requested","gpui.mgmt.plan.requested":"Approval requested: {what}","gpui.mgmt.plan.saved":"saved plan","gpui.mgmt.plan.show":"Show done","gpui.mgmt.plan.st.approved":"Approved","gpui.mgmt.plan.st.awaiting":"Awaiting review","gpui.mgmt.plan.st.blocked":"Blocked","gpui.mgmt.plan.st.empty":"Empty","gpui.mgmt.plan.st.partial":"Partial","gpui.mgmt.plan.st.rejected":"Rejected","gpui.mgmt.plan.st.routed":"Routed","gpui.mgmt.plan.st.routing":"Routing","gpui.mgmt.plan.st.verified":"Verified","gpui.mgmt.plan.stackup.short":"Stackup","gpui.mgmt.plan.stop":"Stop routing","gpui.mgmt.plan.sync":"Link zoom","gpui.mgmt.plan.tab":"Plan","gpui.mgmt.plan.unlock":"Unlock","gpui.mgmt.plan.verify":"Verify","gpui.mgmt.plan.view.canvas":"Canvas","gpui.mgmt.plan.view.list":"List","gpui.mgmt.plan.view.split":"Split","gpui.mgmt.plan.width":"Width","gpui.next.thread":"Next thread","gpui.nothing.matches":"Nothing matches","gpui.planmode.bar.always":"Plan mode — explores and proposes a plan before editing","gpui.planmode.bar.executing":"Building the approved plan","gpui.planmode.bar.once":"Plan mode (1 turn) — explores and proposes a plan before editing","gpui.planmode.bar.pending":"Proposed plan awaits review below","gpui.planmode.bar.planning":"Planning — drafting a plan before edits","gpui.planmode.chip.building":"Building","gpui.planmode.chip.once":"Plan · 1t","gpui.planmode.scope.always":"Always","gpui.planmode.scope.once":"1 turn","gpui.planmode.tip":"Plan before acting (1 turn, always, or off)","gpui.planmode.top.executing":"Building plan","gpui.planmode.top.once":"Plan (1 turn)","gpui.planmode.top.pending":"Review plan","gpui.planmode.top.planning":"Planning","gpui.previous.thread":"Previous thread","gpui.rail.no.board":"No board in this project","gpui.rail.no.mech":"No mechanical parts in this project","gpui.rail.no.schematic":"No schematic in this project","gpui.rail.split.needs.both":"Split needs a board and a schematic","home.away":"Home ({name}) is away","home.away.queued":"Home ({name}) is away · {n} queued","home.away.since":"Home ({name}) is away since {time}","home.away.since.queued":"Home ({name}) is away since {time} · {n} queued","home.machine":"Home machine","home.move.failed":"Home move failed","home.move.failed.note":"Home move failed: {note}","home.move.here":"Make this machine the home","home.moving":"Moving home to {to}…","home.moving.step":"Moving home to {to}: {step}","hub.back.crash":"Backplane is back after it stopped unexpectedly","hub.restarting":"Restarting Backplane…","hub.restarting.build":"Restarting Backplane… (new build {build})","hub.stopped":"Backplane stopped","ios.hub.address.field":"Hub address","menu.pin":"Pin","menu.settle":"Settle","menu.unpin":"Unpin","model.col.agent":"Agent","notify.settled":"Settled","palette.archive":"Archive thread","palette.command.placeholder":"Type a command or a thread","palette.diff":"Diff: what this thread changed","palette.newthread":"New thread","palette.settings":"Settings","palette.terminal":"Terminal","palette.unarchive":"Unarchive thread","phone.unsettle":"Unsettle","provider.notice.button":"Open Settings → Accounts","provider.notice.head":"No AI provider connected","provider.notice.senderr":"No AI provider connected yet. Open Settings → Accounts to connect Claude, Codex, Antigravity, or another provider.","provider.notice.senderr.remote":"No AI provider connected on {machine}. Open Settings → Accounts on {machine} to connect Claude, Codex, Antigravity, or another provider.","provider.notice.text.none":"Connect Claude, Codex, Antigravity, or another provider to start chatting.","provider.notice.text.signedout":"Sign in to Claude, Codex, or another provider in Settings → Accounts to start chatting.","reply.action":"Reply","reply.cancel":"Cancel reply","reply.to":"In reply to:","secret.you":"You","settings.lang":"Language","sheet.rename":"Rename thread","sidebar.add.project":"Add project","sidebar.search.projects":"Search projects","thread.context.base":"Backplane","thread.context.copied":"Prompt copied.","thread.context.copy":"Copy prompt","thread.context.disable":"Disable","thread.context.enable":"Enable","thread.context.index":"Available skills index","thread.context.injected.label":"Injected project instructions","thread.context.instructions":"Instructions","thread.context.mcp":"Project MCPs","thread.context.native.note":"Backplane’s launch prompt. Native files are loaded by the provider.","thread.context.none.instructions":"No project instructions found.","thread.context.none.mcp":"No project MCP configurations found.","thread.context.reading":"Reading thread context…","thread.context.size":"{bytes} B · ≈{tokens} tokens","thread.context.skills":"Skills","thread.context.system":"System Prompt","thread.context.title":"Context & Prompt","thread.context.trust":"Trust and enable","thread.new":"New thread","tools.pinned":"Pinned","tools.retry":"Retry","tour.title.bots":"Bots","viewer.board":"Board","viewer.diff":"Diff","viewer.files":"Files","viewer.mech":"Mech","viewer.review":"Review","viewer.schematic":"Schematic","viewer.solid":"3D","web.chat.answer.btn":"Answer","web.chat.answer.placeholder":"Type answer…","web.chat.answered":"Answered: {answer}","web.chat.choose":"Choose a project thread on the left to begin.","web.chat.empty":"No messages yet. Type below to start a turn.","web.chat.finished":"Finished {time}","web.chat.finished.dur":"Finished {time} · {dur}","web.chat.loading":"Loading messages…","web.chat.review.mode":"Review mode","web.chat.streaming":"Streaming…","web.clone.add.dir":"Add {dir}","web.clone.back":"Back","web.clone.change.folder":"Change folder","web.clone.cloned":"Cloned {repo} into {dest}","web.clone.cloning":"Cloning {repo} into {dest}","web.clone.copied":"Copied","web.clone.first":"First message: {text}","web.clone.folder.name":"Folder name","web.clone.go":"Clone","web.clone.loading":"Loading…","web.clone.no.folders":"No folders here","web.clone.open.project":"Open the project","web.clone.open.thread":"Open the thread","web.clone.private":"private","web.clone.repo.placeholder":"https or ssh URL, or owner/repo","web.clone.retry":"Try again","web.clone.same":"Already cloned there: it is added as it is.","web.clone.signin":"Sign in to GitHub","web.clone.signin.done":"Signed in to GitHub","web.clone.signin.enter":"Enter this code on GitHub:","web.clone.signin.wait":"Starting GitHub sign-in…","web.clone.start.thread":"Start a thread","web.clone.stopped":"Stopped cloning {repo}","web.clone.tab":"Clone from git","web.clone.up":"Up","web.clone.use.dir":"Use {dir}","web.composer.attach":"Attach image","web.composer.maximages":"At most {max} images per message.","web.composer.unsupported":"Unsupported image type: {type}","web.composer.voice":"Voice dictation","web.logout.failed":"Could not confirm sign-out. Try again.","web.pair.approve.in":"Approve on desktop or paired phone · expires in {time}","web.pair.approved":"Approved. Opening Backplane…","web.pair.cancelled":"Cancelled.","web.pair.code":"Comparison code","web.pair.denied":"Pairing request was denied.","web.pair.expired":"Pairing code expired. Request a new code to try again.","web.pair.failed":"Pairing request failed ({status})","web.pair.name":"Browser name","web.pair.nocode":"Hub did not return a comparison code.","web.pair.ratelimited":"Too many pairing attempts. Wait a moment and try again.","web.pair.request":"Request pairing","web.pair.requesting":"Requesting pairing code…","web.pair.subtitle":"Pair this browser with your hub. Approve the 6-digit code in Backplane › Settings › Devices.","web.pair.unreachable":"Could not reach the hub. Check your tailnet connection.","web.plan.awaiting":"{n} awaiting approval","web.plan.net.one":"1 net","web.plan.nets":"{n} nets","web.settings.providers":"AI providers","web.settings.providers.browser":"Connect a provider in the Backplane desktop or mobile app under Settings → Accounts."},es:{"agy.signout":"Cerrar sesión","android.hub.machines.approve":"Aprobar","android.load.earlier":"cargar anteriores","approval.dismiss":"Descartar","approval.implement":"Implementar","ask.plan":"Plan propuesto","bots.rooms":"Salas","bots.tab.browser":"Navegador","common.cancel":"Cancelar","common.close":"Cerrar","common.copy":"Copiar","common.delete":"Eliminar","common.refresh":"Actualizar","common.remove":"Quitar","common.save":"Guardar","composer.placeholder":"Pregunta lo que sea: @bot, >hilo, %proyecto, #sala, $skill, /btw","composer.send":"Enviar","composer.stop":"Detener","gpui.acct.connected":"Conectado","gpui.acct.not.connected":"No conectado","gpui.acct.sign.in.expired":"Sesión caducada","gpui.ask.plan.ready":"Listo para revisar","gpui.ask.plan.revise":"Revisar","gpui.ask.plan.reviseph":"¿Qué debería cambiar en el plan?","gpui.ask.plan.sendrev":"Enviar revisión","gpui.b.in.reply.to":"↩ En respuesta a: {quote}","gpui.b.replying.to":"↩ Respondiendo a: {line}","gpui.bots.recall.off":"Desactivado","gpui.bots.recall.on":"Activado","gpui.c.term.collapse":"Contraer","gpui.c.term.expand":"Expandir","gpui.commands":"Comandos","gpui.e.open.folder":"Abrir carpeta","gpui.filter.projects.and.threads":"Filtrar proyectos e hilos","gpui.fold.or.unfold.the.sidebar":"Plegar o desplegar la barra lateral","gpui.follow.paused":"Seguimiento en pausa","gpui.follow.wait":"Siguiendo: esperando la próxima edición del agente","gpui.gerbers":"Gerbers","gpui.improvements":"Mejoras","gpui.jump.to.a.thread.run":"Saltar a un hilo, ejecutar un comando o buscar lo dicho","gpui.mgmt.bom.dnp":"DNP","gpui.mgmt.bom.nompn":"sin MPN","gpui.mgmt.checks.all":"Todas","gpui.mgmt.checks.fix":"Corregir con agente","gpui.mgmt.checks.run":"Ejecutar","gpui.mgmt.close":"Cerrar el panel","gpui.mgmt.fab.apply":"Aplicar","gpui.mgmt.fab.changed":"Cambió desde la última vez que miraste","gpui.mgmt.fab.derived":"* calculado desde la página del fabricante (un mil en mm, un anillo desde un diámetro). Atenuado: el valor de la placa rígida, cuando la página de esta placa no dice otra cosa. Una fecha abre la página de la que se leyó.","gpui.mgmt.fab.extra":"Cuesta más","gpui.mgmt.fab.findings":"Hallazgos","gpui.mgmt.fab.free":"Precio base","gpui.mgmt.fab.judge":"Hojas de datos","gpui.mgmt.fab.limit":"Límite","gpui.mgmt.fab.readcol":"Leído","gpui.mgmt.fab.refresh":"Actualizar","gpui.mgmt.fab.reviewbtn":"Revisar","gpui.mgmt.fab.seen":"Visto","gpui.mgmt.fab.thefab":"El fabricante","gpui.mgmt.fab.use":"Usar","gpui.mgmt.life.nopart":"Sin lectura de esta pieza aún.","gpui.mgmt.life.reading":"Leyendo su historial…","gpui.mgmt.plan.addnote":"Añadir nota","gpui.mgmt.plan.all":"Aprobar todo","gpui.mgmt.plan.before":"Planificar antes de rutear","gpui.mgmt.plan.compact":"Compacto","gpui.mgmt.plan.done":"hecho","gpui.mgmt.plan.drawn":"Los corredores y planos del plan se dibujan en la placa mientras este panel está abierto. Ciérralo para ocultarlos.","gpui.mgmt.plan.edited":"Editado","gpui.mgmt.plan.elsewhere":"Un plan de ruteo para {board} espera tu aprobación","gpui.mgmt.plan.emptysub":"Las capas, corredores y planos aparecerán aquí cuando se proponga un plan.","gpui.mgmt.plan.expand":"Expandir","gpui.mgmt.plan.fit":"Ajustar","gpui.mgmt.plan.grid.all":"Todas las capas","gpui.mgmt.plan.grid.pair":"Lado a lado","gpui.mgmt.plan.grid.single":"Única","gpui.mgmt.plan.hide":"Ocultar hechos","gpui.mgmt.plan.hint":"Arrastra vértices para guiar · Clic en + del borde para insertar · Clic derecho en vértice para quitar","gpui.mgmt.plan.keysnote":"En esta versión de KiCad, aprueba desde este panel: en la vista de plan las teclas A, R y W de KiCad aún no son del plan (A abre Añadir Huella). Actualiza KiCad.","gpui.mgmt.plan.layer":"Aprobar capa","gpui.mgmt.plan.layer.short":"Capa","gpui.mgmt.plan.lock":"Bloquear","gpui.mgmt.plan.locked":"Bloqueado","gpui.mgmt.plan.noboard":"No hay plan de ruteo para esta placa.","gpui.mgmt.plan.noitems":"Sin corredores ni planos en esta capa","gpui.mgmt.plan.note.placeholder":"Nota de guiado para el router…","gpui.mgmt.plan.nothing":"Nada espera tu aprobación","gpui.mgmt.plan.offwords":"Los agentes rutean como les pidas. Actívalo para que primero propongan un plan de ruteo y ruteen solo lo que apruebes aquí.","gpui.mgmt.plan.onwords":"Antes de rutear una placa con 4 o más capas de cobre o más de 60 redes, el agente propone aquí corredores y regiones de plano. Solo rutea lo que apruebes.","gpui.mgmt.plan.reading":"Leyendo el plan de ruteo…","gpui.mgmt.plan.reference":"sobre {layer}","gpui.mgmt.plan.refused":"KiCad lo rechazó","gpui.mgmt.plan.reject":"Rechazar","gpui.mgmt.plan.rejectlayer":"Rechazar capa","gpui.mgmt.plan.reqplain":"Aprobación solicitada","gpui.mgmt.plan.requested":"Aprobación solicitada: {what}","gpui.mgmt.plan.saved":"plan guardado","gpui.mgmt.plan.show":"Mostrar hechos","gpui.mgmt.plan.st.approved":"Aprobado","gpui.mgmt.plan.st.awaiting":"Esperando revisión","gpui.mgmt.plan.st.blocked":"Bloqueado","gpui.mgmt.plan.st.empty":"Vacío","gpui.mgmt.plan.st.partial":"Parcial","gpui.mgmt.plan.st.rejected":"Rechazado","gpui.mgmt.plan.st.routed":"Ruteado","gpui.mgmt.plan.st.routing":"Ruteando","gpui.mgmt.plan.st.verified":"Verificado","gpui.mgmt.plan.stackup.short":"Apilamiento","gpui.mgmt.plan.stop":"Detener ruteo","gpui.mgmt.plan.sync":"Vincular zoom","gpui.mgmt.plan.tab":"Plan","gpui.mgmt.plan.unlock":"Desbloquear","gpui.mgmt.plan.verify":"Verificar","gpui.mgmt.plan.view.canvas":"Lienzo","gpui.mgmt.plan.view.list":"Lista","gpui.mgmt.plan.view.split":"Dividido","gpui.mgmt.plan.width":"Ancho","gpui.next.thread":"Hilo siguiente","gpui.nothing.matches":"Nada coincide","gpui.planmode.bar.always":"Modo plan — explora y propone un plan antes de editar","gpui.planmode.bar.executing":"Ejecutando el plan aprobado","gpui.planmode.bar.once":"Modo plan (1 turno) — explora y propone un plan antes de editar","gpui.planmode.bar.pending":"El plan propuesto espera revisión abajo","gpui.planmode.bar.planning":"Planificando — redactando un plan antes de editar","gpui.planmode.chip.building":"Ejecutando","gpui.planmode.chip.once":"Plan · 1t","gpui.planmode.scope.always":"Siempre","gpui.planmode.scope.once":"1 turno","gpui.planmode.tip":"Planificar antes de actuar (1 turno, siempre u off)","gpui.planmode.top.executing":"Ejecutando plan","gpui.planmode.top.once":"Plan (1 turno)","gpui.planmode.top.pending":"Revisar plan","gpui.planmode.top.planning":"Planificando","gpui.previous.thread":"Hilo anterior","gpui.rail.no.board":"Este proyecto no tiene placa","gpui.rail.no.mech":"Este proyecto no tiene piezas mecánicas","gpui.rail.no.schematic":"Este proyecto no tiene esquema","gpui.rail.split.needs.both":"La vista dividida requiere una placa y un esquema","home.away":"El inicio ({name}) no está disponible","home.away.queued":"El inicio ({name}) no está disponible · {n} en cola","home.away.since":"El inicio ({name}) no está disponible desde las {time}","home.away.since.queued":"El inicio ({name}) no está disponible desde las {time} · {n} en cola","home.machine":"Máquina de inicio","home.move.failed":"No se pudo mover el inicio","home.move.failed.note":"No se pudo mover el inicio: {note}","home.move.here":"Hacer de esta máquina el inicio","home.moving":"Moviendo el inicio a {to}…","home.moving.step":"Moviendo el inicio a {to}: {step}","hub.back.crash":"Backplane volvió tras detenerse de forma inesperada","hub.restarting":"Reiniciando Backplane…","hub.restarting.build":"Reiniciando Backplane… (nueva compilación {build})","hub.stopped":"Backplane se detuvo","ios.hub.address.field":"Dirección del hub","menu.pin":"Fijar","menu.settle":"Cerrar","menu.unpin":"Desfijar","model.col.agent":"Agente","notify.settled":"Cerrado","palette.archive":"Archivar hilo","palette.command.placeholder":"Escribe un comando o un hilo","palette.diff":"Diff: qué cambió este hilo","palette.newthread":"Nuevo hilo","palette.settings":"Ajustes","palette.terminal":"Terminal","palette.unarchive":"Desarchivar hilo","phone.unsettle":"Reabrir","provider.notice.button":"Abrir Configuración → Cuentas","provider.notice.head":"No hay ningún proveedor de IA conectado","provider.notice.senderr":"Aún no hay ningún proveedor de IA conectado. Abre Configuración → Cuentas para conectar Claude, Codex, Antigravity u otro proveedor.","provider.notice.senderr.remote":"No hay ningún proveedor de IA conectado en {machine}. Abre Configuración → Cuentas en {machine} para conectar Claude, Codex, Antigravity u otro proveedor.","provider.notice.text.none":"Conecta Claude, Codex, Antigravity u otro proveedor para empezar a chatear.","provider.notice.text.signedout":"Inicia sesión en Claude, Codex u otro proveedor en Configuración → Cuentas para empezar a chatear.","reply.action":"Responder","reply.cancel":"Cancelar respuesta","reply.to":"En respuesta a:","secret.you":"Tú","settings.lang":"Idioma","sheet.rename":"Renombrar hilo","sidebar.add.project":"Añadir proyecto","sidebar.search.projects":"Buscar proyectos","thread.context.base":"Backplane","thread.context.copied":"Se copiaron las instrucciones.","thread.context.copy":"Copiar instrucciones","thread.context.disable":"Desactivar","thread.context.enable":"Activar","thread.context.index":"Índice de habilidades disponibles","thread.context.injected.label":"Instrucciones del proyecto añadidas","thread.context.instructions":"Instrucciones","thread.context.mcp":"MCP del proyecto","thread.context.native.note":"Instrucciones de inicio de Backplane. El proveedor carga los archivos nativos.","thread.context.none.instructions":"No se encontraron instrucciones del proyecto.","thread.context.none.mcp":"No se encontraron configuraciones MCP del proyecto.","thread.context.reading":"Leyendo el contexto del hilo…","thread.context.size":"{bytes} B · ≈{tokens} tokens","thread.context.skills":"Habilidades","thread.context.system":"Instrucciones del sistema","thread.context.title":"Contexto e instrucciones","thread.context.trust":"Confiar y activar","thread.new":"Nuevo hilo","tools.pinned":"Fijado","tools.retry":"Reintentar","tour.title.bots":"Bots","viewer.board":"Placa","viewer.diff":"Diff","viewer.files":"Archivos","viewer.mech":"Mech","viewer.review":"Revisión","viewer.schematic":"Esquemático","viewer.solid":"3D","web.chat.answer.btn":"Responder","web.chat.answer.placeholder":"Escribe una respuesta…","web.chat.answered":"Respondido: {answer}","web.chat.choose":"Elige un hilo de proyecto a la izquierda para empezar.","web.chat.empty":"Aún no hay mensajes. Escribe abajo para iniciar un turno.","web.chat.finished":"Terminado {time}","web.chat.finished.dur":"Terminado {time} · {dur}","web.chat.loading":"Cargando mensajes…","web.chat.review.mode":"Modo de revisión","web.chat.streaming":"Transmitiendo…","web.clone.add.dir":"Añadir {dir}","web.clone.back":"Atrás","web.clone.change.folder":"Cambiar carpeta","web.clone.cloned":"{repo} clonado en {dest}","web.clone.cloning":"Clonando {repo} en {dest}","web.clone.copied":"Copiado","web.clone.first":"Primer mensaje: {text}","web.clone.folder.name":"Nombre de la carpeta","web.clone.go":"Clonar","web.clone.loading":"Cargando…","web.clone.no.folders":"No hay carpetas aquí","web.clone.open.project":"Abrir el proyecto","web.clone.open.thread":"Abrir el hilo","web.clone.private":"privado","web.clone.repo.placeholder":"URL https o ssh, o propietario/repositorio","web.clone.retry":"Reintentar","web.clone.same":"Ya está clonado ahí: se añade tal cual.","web.clone.signin":"Iniciar sesión en GitHub","web.clone.signin.done":"Sesión iniciada en GitHub","web.clone.signin.enter":"Introduce este código en GitHub:","web.clone.signin.wait":"Iniciando sesión en GitHub…","web.clone.start.thread":"Empezar un hilo","web.clone.stopped":"Se detuvo la clonación de {repo}","web.clone.tab":"Clonar desde git","web.clone.up":"Subir","web.clone.use.dir":"Usar {dir}","web.composer.attach":"Adjuntar imagen","web.composer.maximages":"Como máximo {max} imágenes por mensaje.","web.composer.unsupported":"Tipo de imagen no compatible: {type}","web.composer.voice":"Dictado por voz","web.logout.failed":"No se pudo confirmar el cierre de sesión. Inténtalo de nuevo.","web.pair.approve.in":"Aprueba en el escritorio o en un teléfono vinculado · caduca en {time}","web.pair.approved":"Aprobado. Abriendo Backplane…","web.pair.cancelled":"Cancelado.","web.pair.code":"Código de comparación","web.pair.denied":"Se rechazó la solicitud de vinculación.","web.pair.expired":"El código de vinculación caducó. Solicita uno nuevo para intentarlo otra vez.","web.pair.failed":"Falló la solicitud de vinculación ({status})","web.pair.name":"Nombre del navegador","web.pair.nocode":"El hub no devolvió un código de comparación.","web.pair.ratelimited":"Demasiados intentos de vinculación. Espera un momento e inténtalo de nuevo.","web.pair.request":"Solicitar vinculación","web.pair.requesting":"Solicitando código de vinculación…","web.pair.subtitle":"Vincula este navegador con tu hub. Aprueba el código de 6 dígitos en Backplane › Ajustes › Dispositivos.","web.pair.unreachable":"No se pudo conectar con el hub. Comprueba tu conexión de tailnet.","web.plan.awaiting":"{n} esperando aprobación","web.plan.net.one":"1 red","web.plan.nets":"{n} redes","web.settings.providers":"Proveedores de IA","web.settings.providers.browser":"Conecta un proveedor en la aplicación de escritorio o móvil de Backplane en Configuración → Cuentas."},ja:{"agy.signout":"サインアウト","android.hub.machines.approve":"承認","android.load.earlier":"以前のメッセージを読み込む","approval.dismiss":"閉じる","approval.implement":"実装","ask.plan":"提案されたプラン","bots.rooms":"ルーム","bots.tab.browser":"ブラウザ","common.cancel":"キャンセル","common.close":"閉じる","common.copy":"コピー","common.delete":"削除","common.refresh":"更新","common.remove":"削除","common.save":"保存","composer.placeholder":"何でも質問:@bot、>thread、%project、#room、$skill、/btw","composer.send":"送信","composer.stop":"停止","gpui.acct.connected":"接続済み","gpui.acct.not.connected":"未接続","gpui.acct.sign.in.expired":"サインインの期限切れ","gpui.ask.plan.ready":"確認待ち","gpui.ask.plan.revise":"修正","gpui.ask.plan.reviseph":"計画のどこを変更しますか?","gpui.ask.plan.sendrev":"修正を送る","gpui.b.in.reply.to":"↩ 返信先:{quote}","gpui.b.replying.to":"↩ 返信中:{line}","gpui.bots.recall.off":"オフ","gpui.bots.recall.on":"オン","gpui.c.term.collapse":"折りたたむ","gpui.c.term.expand":"展開","gpui.commands":"コマンド","gpui.e.open.folder":"フォルダを開く","gpui.filter.projects.and.threads":"プロジェクトとスレッドを絞り込む","gpui.fold.or.unfold.the.sidebar":"サイドバーを折りたたむ/開く","gpui.follow.paused":"追従を一時停止中","gpui.follow.wait":"追従中: エージェントの次の編集を待っています","gpui.gerbers":"ガーバー","gpui.improvements":"改善","gpui.jump.to.a.thread.run":"スレッドへ移動、コマンドを実行、または発言を検索","gpui.mgmt.bom.dnp":"実装しない","gpui.mgmt.bom.nompn":"MPNなし","gpui.mgmt.checks.all":"すべて","gpui.mgmt.checks.fix":"エージェントに直してもらう","gpui.mgmt.checks.run":"実行","gpui.mgmt.close":"パネルを閉じる","gpui.mgmt.fab.apply":"適用","gpui.mgmt.fab.changed":"前回見てから変わったところ","gpui.mgmt.fab.derived":"* 製造元のページから計算した値です(milをmmに、径からランドを)。薄い色の項目はリジッド基板の値です(この基板のページに記載がないもの)。日付を押すと読んだページが開きます。","gpui.mgmt.fab.extra":"追加料金","gpui.mgmt.fab.findings":"指摘","gpui.mgmt.fab.free":"基本料金","gpui.mgmt.fab.judge":"データシート","gpui.mgmt.fab.limit":"項目","gpui.mgmt.fab.readcol":"読んだ日","gpui.mgmt.fab.refresh":"再読み込み","gpui.mgmt.fab.reviewbtn":"レビュー","gpui.mgmt.fab.seen":"確認済み","gpui.mgmt.fab.thefab":"製造元","gpui.mgmt.fab.use":"使う","gpui.mgmt.life.nopart":"この部品の記録はまだありません。","gpui.mgmt.life.reading":"履歴を読んでいます…","gpui.mgmt.plan.addnote":"メモを追加","gpui.mgmt.plan.all":"すべて承認","gpui.mgmt.plan.before":"配線前に計画する","gpui.mgmt.plan.compact":"標準","gpui.mgmt.plan.done":"完了","gpui.mgmt.plan.drawn":"計画の配線経路とプレーンは、このパネルを開いている間だけ基板上に表示されます。閉じると消えます。","gpui.mgmt.plan.edited":"編集済み","gpui.mgmt.plan.elsewhere":"{board}の配線計画が承認を待っています","gpui.mgmt.plan.emptysub":"計画が提案されると、レイヤー・コリドー・ベタ領域がここに表示されます。","gpui.mgmt.plan.expand":"拡大","gpui.mgmt.plan.fit":"全体表示","gpui.mgmt.plan.grid.all":"全レイヤー","gpui.mgmt.plan.grid.pair":"並べて表示","gpui.mgmt.plan.grid.single":"単一","gpui.mgmt.plan.hide":"完了を隠す","gpui.mgmt.plan.hint":"頂点をドラッグして誘導 · 辺の + をクリックで追加 · 頂点を右クリックで削除","gpui.mgmt.plan.keysnote":"このバージョンのKiCadでは、このパネルから承認してください。プランビューでのKiCadのA・R・Wキーはまだ計画のものではありません(Aはフットプリントの追加を開きます)。KiCadを更新してください。","gpui.mgmt.plan.layer":"層を承認","gpui.mgmt.plan.layer.short":"レイヤー","gpui.mgmt.plan.lock":"ロック","gpui.mgmt.plan.locked":"ロック中","gpui.mgmt.plan.noboard":"この基板の配線計画はありません。","gpui.mgmt.plan.noitems":"このレイヤーにコリドーまたはプレーンがありません","gpui.mgmt.plan.note.placeholder":"ルーターへの指示メモ…","gpui.mgmt.plan.nothing":"承認待ちはありません","gpui.mgmt.plan.offwords":"エージェントは指示どおりに配線します。オンにすると、まず配線計画を提案し、ここで承認したものだけを配線します。","gpui.mgmt.plan.onwords":"銅箔層が4層以上、またはネットが60本を超える基板では、配線の前にエージェントがここで配線経路とプレーン領域を提案します。承認したものだけを配線します。","gpui.mgmt.plan.reading":"配線計画を読んでいます…","gpui.mgmt.plan.reference":"基準 {layer}","gpui.mgmt.plan.refused":"KiCad が拒否しました","gpui.mgmt.plan.reject":"却下","gpui.mgmt.plan.rejectlayer":"レイヤーを却下","gpui.mgmt.plan.reqplain":"承認が求められています","gpui.mgmt.plan.requested":"承認が求められています: {what}","gpui.mgmt.plan.saved":"保存された計画","gpui.mgmt.plan.show":"完了を表示","gpui.mgmt.plan.st.approved":"承認済み","gpui.mgmt.plan.st.awaiting":"承認待ち","gpui.mgmt.plan.st.blocked":"ブロック","gpui.mgmt.plan.st.empty":"空","gpui.mgmt.plan.st.partial":"一部完了","gpui.mgmt.plan.st.rejected":"却下","gpui.mgmt.plan.st.routed":"配線済み","gpui.mgmt.plan.st.routing":"配線中","gpui.mgmt.plan.st.verified":"検証済み","gpui.mgmt.plan.stackup.short":"スタックアップ","gpui.mgmt.plan.stop":"配線を止める","gpui.mgmt.plan.sync":"ズーム連動","gpui.mgmt.plan.tab":"計画","gpui.mgmt.plan.unlock":"ロック解除","gpui.mgmt.plan.verify":"検証","gpui.mgmt.plan.view.canvas":"キャンバス","gpui.mgmt.plan.view.list":"リスト","gpui.mgmt.plan.view.split":"分割","gpui.mgmt.plan.width":"幅","gpui.next.thread":"次のスレッド","gpui.nothing.matches":"一致するものはありません","gpui.planmode.bar.always":"計画モード — 編集前に調査して計画を提案します","gpui.planmode.bar.executing":"承認された計画を実行しています","gpui.planmode.bar.once":"計画モード (1回) — 編集前に調査して計画を提案します","gpui.planmode.bar.pending":"提案された計画が下のレビューを待っています","gpui.planmode.bar.planning":"計画中 — 編集前の計画を作成しています","gpui.planmode.chip.building":"実行中","gpui.planmode.chip.once":"計画 · 1回","gpui.planmode.scope.always":"常時","gpui.planmode.scope.once":"1回","gpui.planmode.tip":"実行前に計画を作成 (1回・常時・オフ)","gpui.planmode.top.executing":"計画を実行中","gpui.planmode.top.once":"計画 (1回)","gpui.planmode.top.pending":"計画を確認","gpui.planmode.top.planning":"計画中","gpui.previous.thread":"前のスレッド","gpui.rail.no.board":"このプロジェクトには基板がありません","gpui.rail.no.mech":"このプロジェクトには機械部品がありません","gpui.rail.no.schematic":"このプロジェクトには回路図がありません","gpui.rail.split.needs.both":"分割表示には基板と回路図が必要です","home.away":"ホーム({name})はオフラインです","home.away.queued":"ホーム({name})はオフラインです · {n} 件待機中","home.away.since":"ホーム({name})は {time} からオフラインです","home.away.since.queued":"ホーム({name})は {time} からオフラインです · {n} 件待機中","home.machine":"ホームマシン","home.move.failed":"ホームの移動に失敗しました","home.move.failed.note":"ホームの移動に失敗しました: {note}","home.move.here":"このマシンをホームにする","home.moving":"ホームを {to} へ移動中…","home.moving.step":"ホームを {to} へ移動中: {step}","hub.back.crash":"予期せず停止したBackplaneが戻りました","hub.restarting":"Backplaneを再起動しています…","hub.restarting.build":"Backplaneを再起動しています…(新しいビルド {build})","hub.stopped":"Backplaneは停止しました","ios.hub.address.field":"ハブのアドレス","menu.pin":"ピン留め","menu.settle":"完了","menu.unpin":"ピン留めを解除","model.col.agent":"エージェント","notify.settled":"完了","palette.archive":"スレッドをアーカイブ","palette.command.placeholder":"コマンドまたはスレッドを入力","palette.diff":"差分:このスレッドの変更","palette.newthread":"新しいスレッド","palette.settings":"設定","palette.terminal":"ターミナル","palette.unarchive":"スレッドのアーカイブを解除","phone.unsettle":"未完了に戻す","provider.notice.button":"設定 → アカウントを開く","provider.notice.head":"AI プロバイダーが接続されていません","provider.notice.senderr":"AI プロバイダーがまだ接続されていません。設定 → アカウントを開いて、Claude、Codex、Antigravity などのプロバイダーを接続してください。","provider.notice.senderr.remote":"{machine} に AI プロバイダーが接続されていません。{machine} で設定 → アカウントを開いて、Claude、Codex、Antigravity などのプロバイダーを接続してください。","provider.notice.text.none":"チャットを始めるには、Claude、Codex、Antigravity などのプロバイダーを接続してください。","provider.notice.text.signedout":"チャットを始めるには、設定 → アカウントで Claude、Codex などのプロバイダーにサインインしてください。","reply.action":"返信","reply.cancel":"返信をやめる","reply.to":"返信先:","secret.you":"あなた","settings.lang":"言語","sheet.rename":"スレッド名を変更","sidebar.add.project":"プロジェクトを追加","sidebar.search.projects":"プロジェクトを検索","thread.context.base":"Backplane","thread.context.copied":"プロンプトをコピーしました。","thread.context.copy":"プロンプトをコピー","thread.context.disable":"無効にする","thread.context.enable":"有効にする","thread.context.index":"利用可能なスキルの一覧","thread.context.injected.label":"追加されたプロジェクトの指示","thread.context.instructions":"指示","thread.context.mcp":"プロジェクトの MCP","thread.context.native.note":"Backplane が起動時に渡すプロンプトです。ネイティブファイルはプロバイダーが読み込みます。","thread.context.none.instructions":"プロジェクトの指示が見つかりません。","thread.context.none.mcp":"プロジェクトの MCP 設定が見つかりません。","thread.context.reading":"スレッドのコンテキストを読み込み中…","thread.context.size":"{bytes} B・約{tokens}トークン","thread.context.skills":"スキル","thread.context.system":"システムプロンプト","thread.context.title":"コンテキストとプロンプト","thread.context.trust":"承認して有効にする","thread.new":"新しいスレッド","tools.pinned":"固定中","tools.retry":"再試行","tour.title.bots":"ボット","viewer.board":"基板","viewer.diff":"差分","viewer.files":"ファイル","viewer.mech":"Mech","viewer.review":"レビュー","viewer.schematic":"回路図","viewer.solid":"3D","web.chat.answer.btn":"回答","web.chat.answer.placeholder":"回答を入力…","web.chat.answered":"回答済み: {answer}","web.chat.choose":"左側からプロジェクトのスレッドを選んで開始してください。","web.chat.empty":"まだメッセージはありません。下に入力して開始してください。","web.chat.finished":"完了 {time}","web.chat.finished.dur":"完了 {time} · {dur}","web.chat.loading":"メッセージを読み込んでいます…","web.chat.review.mode":"レビューモード","web.chat.streaming":"受信中…","web.clone.add.dir":"{dir} を追加","web.clone.back":"戻る","web.clone.change.folder":"フォルダを変更","web.clone.cloned":"{repo} を {dest} にクローンしました","web.clone.cloning":"{repo} を {dest} にクローン中","web.clone.copied":"コピーしました","web.clone.first":"最初のメッセージ: {text}","web.clone.folder.name":"フォルダ名","web.clone.go":"クローン","web.clone.loading":"読み込み中…","web.clone.no.folders":"フォルダがありません","web.clone.open.project":"プロジェクトを開く","web.clone.open.thread":"スレッドを開く","web.clone.private":"非公開","web.clone.repo.placeholder":"https / ssh の URL、または owner/repo","web.clone.retry":"もう一度","web.clone.same":"すでにそこにクローンされています: そのまま追加します。","web.clone.signin":"GitHub にサインイン","web.clone.signin.done":"GitHub にサインインしました","web.clone.signin.enter":"このコードを GitHub に入力してください:","web.clone.signin.wait":"GitHub のサインインを開始しています…","web.clone.start.thread":"スレッドを開始","web.clone.stopped":"{repo} のクローンを中止しました","web.clone.tab":"git からクローン","web.clone.up":"上へ","web.clone.use.dir":"{dir} を使う","web.composer.attach":"画像を添付","web.composer.maximages":"1 件のメッセージに添付できる画像は最大 {max} 枚です。","web.composer.unsupported":"未対応の画像形式です: {type}","web.composer.voice":"音声入力","web.logout.failed":"サインアウトを確認できませんでした。もう一度お試しください。","web.pair.approve.in":"デスクトップまたはペアリング済みの端末で承認してください · 有効期限 {time}","web.pair.approved":"承認されました。Backplane を開いています…","web.pair.cancelled":"キャンセルしました。","web.pair.code":"確認コード","web.pair.denied":"ペアリングのリクエストが拒否されました。","web.pair.expired":"ペアリングコードの有効期限が切れました。新しいコードをリクエストしてください。","web.pair.failed":"ペアリングのリクエストに失敗しました ({status})","web.pair.name":"ブラウザー名","web.pair.nocode":"ハブから確認コードが返されませんでした。","web.pair.ratelimited":"ペアリングの試行回数が多すぎます。しばらく待ってからやり直してください。","web.pair.request":"ペアリングをリクエスト","web.pair.requesting":"ペアリングコードをリクエストしています…","web.pair.subtitle":"このブラウザーをハブとペアリングします。Backplane › 設定 › デバイス で 6 桁のコードを承認してください。","web.pair.unreachable":"ハブに接続できませんでした。tailnet の接続を確認してください。","web.plan.awaiting":"{n} 件が承認待ち","web.plan.net.one":"1 ネット","web.plan.nets":"{n} ネット","web.settings.providers":"AI プロバイダー","web.settings.providers.browser":"Backplane のデスクトップまたはモバイルアプリの設定 → アカウントからプロバイダーを接続してください。"}};function Q(a,t){if(!t)return a;return a.replace(/\{([a-zA-Z0-9_.-]+)\}/g,(s,r)=>Object.prototype.hasOwnProperty.call(t,r)?String(t[r]):s)}var O=te(),W=new Set,V=new Map;for(let[a,t]of Object.entries(U.en||{}))if(typeof t==="string"&&!V.has(t))V.set(t,a);function te(){let a=typeof navigator<"u"&&navigator.language?navigator.language.toLowerCase():"en";if(a.startsWith("ja"))return"ja";if(a.startsWith("es"))return"es";return"en"}function Y(){if(typeof document<"u"&&document.documentElement)document.documentElement.lang=O}Y();function me(a){return W.add(a),()=>{W.delete(a)}}function ue(a){if(!a)return!1;let t=a.toLowerCase(),s=t.startsWith("ja")?"ja":t.startsWith("es")?"es":t.startsWith("en")?"en":"";if(!s)return!1;let r=s!==O;if(O=s,Y(),r)for(let d of W)d(O);return r}function c(a,t,s){let d=(U[O]||U.en||{})[a]??U.en?.[a]??t??a;return Q(d,s)}function ge(a){if(!a)return"";let t=V.get(a);if(!t)return a;return c(t,a)}var ae=[[1,26,7,1,[]],[2,44,10,1,[6,18]],[3,70,15,1,[6,22]],[4,100,20,1,[6,26]],[5,134,26,1,[6,30]],[6,172,18,2,[6,34]]],F=new Uint8Array(512),_=new Uint8Array(256);{let a=1;for(let t=0;t<255;t++)if(F[t]=a,_[a]=t,a<<=1,a&256)a^=285;for(let t=255;t<512;t++)F[t]=F[t-255]}function J(a,t){return a===0||t===0?0:F[_[a]+_[t]]}function ne(a){let t=new Uint8Array([1]);for(let s=0;s{let m=e-i*n;return Math.ceil((12+t.length*8)/8)<=m});if(!s)return null;let[r,d,u,f,j]=s,w=d-u*f,g=[],E=(e,i)=>{for(let n=i-1;n>=0;n--)g.push(e>>>n&1)};E(4,4),E(t.length,8);for(let e of t)E(e,8);for(let e=0;e<4&&g.length{if(e<0||i<0||e>=p||i>=p)return;H[e*p+i]=n?1:0,A[e*p+i]=1},N=(e,i)=>{for(let n=-1;n<=7;n++)for(let m=-1;m<=7;m++){let k=e+n,l=i+m,o=n>=0&&n<=6&&m>=0&&m<=6&&(n===0||n===6||m===0||m===6||n>=2&&n<=4&&m>=2&&m<=4);b(k,l,o)}};N(0,0),N(0,p-7),N(p-7,0);for(let e=8;e=1;e-=2){if(e===6)e=5;let i=(e+1&2)===0;for(let n=0;n>>3]>>>7-(S&7)&1,S++;let o=(m+l&1)===0?h^1:h;H[m*p+l]=o}}}let R=30660;for(let e=0;e<=5;e++)b(8,e,(R>>>14-e&1)===1);b(8,7,(R>>>8&1)===1),b(8,8,(R>>>7&1)===1),b(7,8,(R>>>6&1)===1);for(let e=0;e<=5;e++)b(5-e,8,(R>>>5-e&1)===1);for(let e=0;e<8;e++)b(8,p-1-e,(R>>>e&1)===1);for(let e=0;e<7;e++)b(p-7+e,8,(R>>>14-e&1)===1);return{size:p,modules:H}}function X(a){let t=oe(a);if(!t)return null;let s=2,r=t.size+s*2,d=document.createElementNS("http://www.w3.org/2000/svg","svg");d.setAttribute("viewBox",`0 0 ${r} ${r}`),d.setAttribute("role","img"),d.setAttribute("aria-label",`QR code for ${a}`),d.setAttribute("shape-rendering","crispEdges"),d.classList.add("bp-qr-svg");let u=document.createElementNS("http://www.w3.org/2000/svg","rect");u.setAttribute("width",String(r)),u.setAttribute("height",String(r)),u.setAttribute("fill","#ffffff"),d.appendChild(u);let f="";for(let w=0;w{let h=l.trim();if(!h)return;let o=h.startsWith("https://")?h:`https://${h}`;if(!o.startsWith("https://")||o.length<=8)return;let x=document.createElement("div");x.className="bp-pair-addr-meta";let v=document.createElement("div");v.className="bp-pair-code-label",v.textContent=c("ios.hub.address.field","Hub address");let y=document.createElement("code");y.className="bp-pair-addr-url",y.textContent=o,y.setAttribute("data-testid","pair-address");let P=document.createElement("button");P.type="button",P.className="bp-pair-copy";let D=c("common.copy","Copy");P.textContent=D,P.addEventListener("click",()=>{navigator.clipboard?.writeText(o).then(()=>{P.textContent=c("web.clone.copied","Copied"),window.setTimeout(()=>{P.textContent=D},1200)}).catch(()=>{})}),x.append(v,y,P);let z=document.createDocumentFragment();z.appendChild(x);let K=X(o);if(K){let G=document.createElement("div");G.className="bp-pair-qr",G.setAttribute("data-testid","pair-qr"),G.appendChild(K),z.appendChild(G)}p.replaceChildren(z),p.classList.remove("bp-hidden")};fetch("/auth/web/info",{credentials:"same-origin"}).then(async(l)=>{if(!l.ok)return;let h=await l.json();if(typeof h.address==="string")H(h.address)}).catch(()=>{}),t.append(s,u,f,E,C,p),a.appendChild(t);let A=null,b=null,N=null,S=0,I=0,R=150,e=1000;function i(){if(S++,N)N.abort(),N=null;if(A!==null)window.clearTimeout(A),A=null;if(b!==null)window.clearInterval(b),b=null}function n(l="",h=!1){i(),f.classList.remove("bp-hidden"),E.classList.add("bp-hidden"),g.disabled=!1,C.textContent=l,C.className=h?"bp-pair-status bp-bad":"bp-pair-status"}function m(){let l=I-Date.now();if(l<=0){n(c("web.pair.expired","Pairing code expired. Request a new code to try again."),!0);return}B.textContent=c("web.pair.approve.in","Approve on desktop or paired phone · expires in {time}",{time:pe(l)})}async function k(l){if(l!==S)return;if(I>0&&Date.now()>=I){n(c("web.pair.expired","Pairing code expired. Request a new code to try again."),!0);return}let h=new AbortController;N=h;try{let o=await fetch("/auth/web/poll",{method:"POST",credentials:"same-origin",headers:{"Content-Type":"application/json"},body:"{}",signal:h.signal});if(l!==S)return;if(e=1000,o.status===202){A=window.setTimeout(()=>{k(l)},150);return}if(o.status===200||o.status===204){let v={};if(o.status===200)try{v=await o.json()}catch{}if(l!==S)return;let y=(v.state||v.status||"").toLowerCase();if(o.status===204||v.approved===!0||y==="approved"||y==="ok"){i(),C.textContent=c("web.pair.approved","Approved. Opening Backplane…"),C.className="bp-pair-status bp-ok",window.location.replace("/");return}if(y==="denied"||y==="rejected"){n(c("web.pair.denied","Pairing request was denied."),!0);return}if(y==="expired"){n(c("web.pair.expired","Pairing code expired. Request a new code to try again."),!0);return}A=window.setTimeout(()=>{k(l)},150);return}if(o.status===429){let v=Number(o.headers.get("Retry-After")||"5"),y=Math.max(2000,(Number.isFinite(v)?v:5)*1000);A=window.setTimeout(()=>{k(l)},y);return}if(o.status===401||o.status===403||o.status===404||o.status===410){let v="";try{let y=await o.json();v=(y.state||y.status||y.error||"").toLowerCase()}catch{}if(l!==S)return;if(v==="denied"||v==="rejected"||o.status===403)n(c("web.pair.denied","Pairing request was denied."),!0);else n(c("web.pair.expired","Pairing code expired. Request a new code to try again."),!0);return}let x=e;e=Math.min(1e4,Math.round(e*1.8)),A=window.setTimeout(()=>{k(l)},x)}catch{if(l!==S)return;let o=e;e=Math.min(1e4,Math.round(e*1.8)),A=window.setTimeout(()=>{k(l)},o)}finally{if(N===h)N=null}}L.addEventListener("click",()=>{n(c("web.pair.cancelled","Cancelled."))}),f.addEventListener("submit",async(l)=>{l.preventDefault();let h=w.value.trim()||Z();g.disabled=!0,C.textContent=c("web.pair.requesting","Requesting pairing code…"),C.className="bp-pair-status";try{let o=await fetch("/auth/web/request",{method:"POST",credentials:"same-origin",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:h})});if(!o.ok){let D=c("web.pair.failed","Pairing request failed ({status})",{status:o.status});try{let z=await o.json();if(z.error)D=z.error}catch{}if(o.status===429)D=c("web.pair.ratelimited","Too many pairing attempts. Wait a moment and try again.");n(D,!0);return}let x=await o.json(),v=x.code||x.checkCode||"";if(!v){n(c("web.pair.nocode","Hub did not return a comparison code."),!0);return}let y=Date.now();I=x.expiresAt?x.expiresAt<10000000000?x.expiresAt*1000:x.expiresAt:y+(x.expiresIn?x.expiresIn*1000:120000),i();let P=S;e=1000,R=x.pollMs&&x.pollMs>=100?x.pollMs:150,M.textContent=re(v),f.classList.add("bp-hidden"),E.classList.remove("bp-hidden"),C.textContent="",m(),b=window.setInterval(m,1000),A=window.setTimeout(()=>{k(P)},R)}catch{n(c("web.pair.unreachable","Could not reach the hub. Check your tailnet connection."),!0)}})}if(document.readyState==="loading")document.addEventListener("DOMContentLoaded",ee);else ee(); diff --git a/web/dist/manifest.json b/web/dist/manifest.json index b0d0c6598a..0d370b320d 100644 --- a/web/dist/manifest.json +++ b/web/dist/manifest.json @@ -1,6 +1,6 @@ { "version": 1, - "totalAssetGzipBytes": 204447, + "totalAssetGzipBytes": 204945, "styleTokensSha256": "a4fed1b1c7bc676acc328907343eb5dcf87e426383d05617c632e48c0c3f2b80", "i18nKeys": [ "agy.signout", @@ -172,6 +172,7 @@ "provider.notice.button", "provider.notice.head", "provider.notice.senderr", + "provider.notice.senderr.remote", "provider.notice.text.none", "provider.notice.text.signedout", "reply.action", @@ -273,10 +274,10 @@ "web.settings.providers", "web.settings.providers.browser" ], - "i18nSubsetSha256": "c5451f43bfc32b547a5384f4d92d2a92e87fcc59aca5173e30ba302c9768b39f", + "i18nSubsetSha256": "1e3903ee550528a5ebc0c6b57a5b20c6f882fb39bdb7d47c0859cc9fad28658c", "inputs": { "web/src/addproject.ts": "06a7ff3e13cd78d993ebca7f638d5d623da06c0099186ad534bae8f184dbe44f", - "web/src/app.ts": "4f9001b183913757804743d4016c9966566e6859ecd73da01c6480995083b32d", + "web/src/app.ts": "9cd9a49cc844b2fd48e5026c02abb59e6b358fd04405812cf0ecc62c031cf497", "web/src/chat.ts": "27730f5adfcbb51eecf2f3a7cbd75562c964105dbb6a131697898977432c7892", "web/src/clone-model.ts": "d265df49436e14f415bbeb2a271ffa3552f9163be62bdc0158cecc10c3cdae45", "web/src/composer.ts": "f351b271d59ae560ae57360a8a301fc7df7d4d3adbe2c8933577fd7201399dc0", @@ -293,10 +294,10 @@ "web/src/palette-model.ts": "ae359cc71e98e84774428355a5048fd9ba0e1da2d45fa18290b4313c50c50ee4", "web/src/palette.ts": "bcd5c4585f57cc80a9cf29bf1b9da6ebbd33a3ab68f8f2a918c37c58060c8e48", "web/src/plan-canvas.ts": "49a0af6ef960301d4ea75f2fcd48628e01d983431d96329f37e6a3704bafd498", - "web/src/provider-notice.ts": "93be1b0fc2658ec18f7f74e1db30db4e0626e391fa88b10950b1cc314039f677", + "web/src/provider-notice.ts": "96efd0b9ce7981efadfdbba3e2eac7b7fa00cf18f3126f980b9d087022084e29", "web/src/qr.ts": "04b634557884b8f512a7b03ad9638c1c15a299ffaea0103d1bdeec6338d9b9d3", "web/src/rail.ts": "5fb391094992578cb6f54d35d53559951a584c43fcfc2ee6f4f2cc3897acfe46", - "web/src/settings.ts": "62c4555c27efcedfda8024e1b7b9e3c63b1c1d4cef5fb6d8be0614ee997ec609", + "web/src/settings.ts": "4ec089580e4d2f04fb28462cb49cc164893c114af154d849c21ad5448a520433", "web/src/shell.css": "a029915be277456b83f1cb11f2cae2db131294fb469bd535e9c14764fbc73762", "web/src/sidebar.ts": "0c326c895375f8a2718ec424b07ca59006d7bc0938f05fe8e3e231ffb6af375f", "web/src/swarm-need.ts": "503bbf5ffe0389f068847571c792321b0ad5c8d26a18c73b8e41c0a8989e227f", @@ -314,21 +315,21 @@ "web/src/viewers/viewer-pane.ts": "0021e2ac702c7b4960f685d822b6f3cf4728589b4cca54498556695de7ddb1eb", "web/src/viewers/viewer-tools.ts": "7db4587ad1410cf21364b1121454e0520fd515c82b63916d31a5fdc1443615b4", "web/src/voice.ts": "f401f1d5bd1685c7d7270fc02a8ff16f54bde7ae98aee21b4e802f0357063345", - "web/src/ws.ts": "9fdd6388ad44277dbd8e1e702c5d623a4159238bf0338e282a1f56c7493355fe", + "web/src/ws.ts": "b8d433e2902d91c72563c304bbb8a609e242e4884074399a12f792f0f47db3a4", "web/vendor/xterm/LICENSE": "b569f629d00f2626a8100df2a1798210535621e42164dfd426a6fe5aac7b0ccd", "web/vendor/xterm/VERSION": "d8a60d9ace43d33ee184e5679b0b6815e8c6750331b6e6787b98e6f03d77180c", "web/vendor/xterm/addon-fit.js": "bdaefa370b1bfc42ee88d46fe6072400902a4d4b2d45cd93438dda9b23c97089", "web/vendor/xterm/xterm.css": "ba8e6985669488981ccf40c0cefe3aba80722cb6c92de7ad628b0bd717faf2b6", "web/vendor/xterm/xterm.js": "1f991ac3b4b283ebf96e60ae23a00a52765dd3a2e46fa6fdda9f1aab032f7495", - "web/build.ts": "ca51d13a44473f40f3af33d4c3ba928117613d15c9dda59abefd2c418d088426", + "web/build.ts": "40f837b7c23440ec7675bd5b7a472549c5a39eacc8fd2f2c2fe5abf1884d82c9", "assets/web/favicon.svg": "5b0f22a3329f59809216aabe58d8dbbedbd46d29e4a2373a727529daa2441a2c", "assets/web/favicon-light.svg": "9aa4fb973f8a719c602e351c84d3344bac377db049f59eaa52d617e84eada5b6" }, "outputs": { "assets/app.js": { - "bytes": 345371, - "gzipBytes": 97244, - "sha256": "38e41ef2564d036ec8450bf3305c4562bbed7044b6f41735e419b5eec6cb972d" + "bytes": 346991, + "gzipBytes": 97681, + "sha256": "c6179c60edbcfad8f39144b4fcc09d57ffbf6ddef039b22f55d18acc751a2889" }, "assets/favicon-light.svg": { "bytes": 1207, @@ -346,9 +347,9 @@ "sha256": "123b6a27f255d339b505c8fd83609674f0bddf9b46c0e907fce23befa96b1eec" }, "assets/pair.js": { - "bytes": 53024, - "gzipBytes": 16152, - "sha256": "4485eb13b87c0267e74385a82adb5f4de89b586e82ba34f4c8ecf20ad9d89fca" + "bytes": 53636, + "gzipBytes": 16213, + "sha256": "790192a8e58e5806615ed6ffeeb521e812bb44aaeca6e4e51c00f048a86f3cc7" }, "assets/style.css": { "bytes": 73359, diff --git a/web/src/app.ts b/web/src/app.ts index f45d09501d..01afa32957 100644 --- a/web/src/app.ts +++ b/web/src/app.ts @@ -10,7 +10,7 @@ import { onLocaleChange, setLocale, t } from "./i18n"; import { signOut } from "./logout"; import { MgmtStrip } from "./mgmt"; import { CommandPalette, type PaletteAction, type PaletteSearchResult } from "./palette"; -import { isNoProviderError, parseNoProvider, type NoProviderNotice } from "./provider-notice"; +import { isLocalNoProviderError, parseNoProvider, type NoProviderNotice } from "./provider-notice"; import { RailView, type RailEntry } from "./rail"; import { needAfter, needPress } from "./swarm-need"; import { SettingsModal, type SettingsRow } from "./settings"; @@ -27,7 +27,7 @@ import { type ThreadItem, } from "./sidebar"; import { VoiceController } from "./voice"; -import { HubClient, type DataPush, type HelloFrame, type HomeInfo } from "./ws"; +import { HubClient, HubRpcError, type DataPush, type HelloFrame, type HomeInfo } from "./ws"; // eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-ignore resolved by web/build.ts to ./viewers/viewer-pane.ts when present import { mountViewerPane } from "virtual:viewer-pane"; @@ -630,10 +630,22 @@ function mountApp(): void { void settings.openToAccounts(); } function showSendError(err: unknown, fallback: string): void { - const msg = err instanceof Error ? err.message : fallback; + const rawMsg = err instanceof Error ? err.message : fallback; + const rpcErr = err instanceof HubRpcError ? err : null; + const code = rpcErr?.code; + const machine = rpcErr?.machine; + const msg = + code === "no_provider_remote" && machine + ? t( + "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}", machine) + : rawMsg; composer.showError( msg, - isNoProviderError(msg) ? { label: t("provider.notice.button", "Open Settings → Accounts"), onClick: openAccounts } : undefined, + isLocalNoProviderError(rawMsg, code) + ? { label: t("provider.notice.button", "Open Settings → Accounts"), onClick: openAccounts } + : undefined, ); } @@ -1414,14 +1426,16 @@ function mountApp(): void { const gen = threadGen; const threadId = selectedThreadId; try { - const res = await hub.rpc<{ kind?: string; text?: string; repo?: string; error?: string }>("composer.run", { + const res = await hub.rpc<{ kind?: string; q?: string; a?: string; text?: string; repo?: string; error?: string; errorCode?: string; machine?: string }>("composer.run", { thread: threadId, text, }); if (gen !== threadGen || selectedThreadId !== threadId) return; if (res.error) { composer.setDraft(text); - showSendError(new Error(res.error), res.error); + showSendError(new HubRpcError(res.error, { code: res.errorCode, machine: res.machine }), res.error); + } else if (res.kind === "btw" && typeof res.a === "string") { + chat.showBtw(res.q ?? "", res.a); } else if (res.kind === "edit" && typeof res.text === "string") { composer.setDraft(res.text); } else if (res.kind === "project") { diff --git a/web/src/provider-notice.ts b/web/src/provider-notice.ts index 84687872a2..b5bb44ec40 100644 --- a/web/src/provider-notice.ts +++ b/web/src/provider-notice.ts @@ -35,5 +35,11 @@ export function parseNoProvider(raw: unknown): NoProviderNotice | null { } export function isNoProviderError(msg: string): boolean { - return msg.includes("No AI provider connected"); + return msg.startsWith("No AI provider connected yet."); +} + +export function isLocalNoProviderError(msg: string, code?: string): boolean { + if (code === "no_provider") return true; + if (code) return false; + return isNoProviderError(msg); } diff --git a/web/src/settings.ts b/web/src/settings.ts index e81b9abd56..62314e58a1 100644 --- a/web/src/settings.ts +++ b/web/src/settings.ts @@ -35,6 +35,7 @@ export class SettingsModal { private bodyEl: HTMLElement; private cb: SettingsCallbacks; private openState = false; + private forceProviders = false; private providersEl: HTMLElement | null = null; constructor(root: HTMLElement, cb: SettingsCallbacks) { @@ -81,12 +82,14 @@ export class SettingsModal { } public async openToAccounts(): Promise { + this.forceProviders = true; await this.open(); this.providersEl?.scrollIntoView({ block: "nearest" }); } public close(): void { this.openState = false; + this.forceProviders = false; this.backdrop.classList.add("bp-hidden"); } @@ -101,7 +104,7 @@ export class SettingsModal { this.providersEl = null; const noProvider = this.cb.onGetNoProvider?.() ?? null; - if (noProvider) { + if (noProvider || this.forceProviders) { const provSec = document.createElement("section"); provSec.className = "bp-set-section"; provSec.setAttribute("data-testid", "settings-providers"); @@ -113,7 +116,7 @@ export class SettingsModal { const info = document.createElement("div"); info.className = "bp-set-info"; const title = document.createElement("div"); - title.textContent = trs(noProvider.head); + title.textContent = noProvider ? trs(noProvider.head) : t("provider.notice.head", "No AI provider connected"); const sub = document.createElement("div"); sub.className = "bp-dim"; sub.textContent = t( @@ -125,9 +128,9 @@ export class SettingsModal { btns.className = "bp-set-btns"; const link = document.createElement("a"); link.className = "bp-link-btn primary"; - link.href = noProvider.url || "backplane://settings/accounts"; + link.href = noProvider?.url || "backplane://settings/accounts"; link.setAttribute("data-testid", "settings-open-accounts"); - link.textContent = trs(noProvider.button); + link.textContent = noProvider ? trs(noProvider.button) : t("provider.notice.button", "Open Settings → Accounts"); btns.appendChild(link); provRow.append(info, btns); provSec.append(provHead, provRow); diff --git a/web/src/ws.ts b/web/src/ws.ts index 4615fb9b51..d41c1f1a48 100644 --- a/web/src/ws.ts +++ b/web/src/ws.ts @@ -49,6 +49,19 @@ export interface DataPush { export type JsonFrame = HelloFrame | DataPush | { t: string; [key: string]: unknown }; export type ConnState = "connecting" | "connected" | "reconnecting" | "revoked"; +export class HubRpcError extends Error { + public code?: string; + public machine?: string; + public thread?: string; + constructor(message: string, opts?: { code?: string; machine?: string; thread?: string }) { + super(message); + this.name = "HubRpcError"; + this.code = opts?.code; + this.machine = opts?.machine; + this.thread = opts?.thread; + } +} + interface PendingCall { resolve: (v: unknown) => void; reject: (e: Error) => void; @@ -187,7 +200,10 @@ export class HubClient { : (errObj && typeof errObj === "object" && "message" in errObj) ? String((errObj as { message: unknown }).message) : "Request failed"; - call.reject(new Error(msg)); + const code = typeof frame.errorCode === "string" ? frame.errorCode : undefined; + const machine = typeof frame.machine === "string" ? frame.machine : undefined; + const thread = typeof frame.thread === "string" ? frame.thread : undefined; + call.reject(new HubRpcError(msg, { code, machine, thread })); } } return; diff --git a/web/test/provider-notice.test.ts b/web/test/provider-notice.test.ts index 4442225dbe..f28371d21b 100644 --- a/web/test/provider-notice.test.ts +++ b/web/test/provider-notice.test.ts @@ -1,5 +1,5 @@ import { describe, expect, test } from "bun:test"; -import { isNoProviderError, parseNoProvider } from "../src/provider-notice"; +import { isLocalNoProviderError, isNoProviderError, parseNoProvider } from "../src/provider-notice"; describe("provider-notice", () => { test("parses hello object and info JSON string payloads", () => { @@ -22,8 +22,17 @@ describe("provider-notice", () => { expect(parseNoProvider({ head: " " })).toBeNull(); }); - test("detects no-provider send guard errors", () => { - expect(isNoProviderError("No AI provider connected yet. Open Settings → Accounts to connect Claude, Codex, Antigravity, or another provider.")).toBe(true); + test("detects local vs remote no-provider send guard errors", () => { + const localMsg = "No AI provider connected yet. Open Settings → Accounts to connect Claude, Codex, Antigravity, or another provider."; + const remoteMsg = "No AI provider connected on boat-hub. Open Settings → Accounts on boat-hub to connect Claude, Codex, Antigravity, or another provider."; + expect(isNoProviderError(localMsg)).toBe(true); + expect(isNoProviderError(remoteMsg)).toBe(false); expect(isNoProviderError("Network timeout")).toBe(false); + + expect(isLocalNoProviderError(localMsg, "no_provider")).toBe(true); + expect(isLocalNoProviderError(remoteMsg, "no_provider_remote")).toBe(false); + expect(isLocalNoProviderError(localMsg, "no_provider_remote")).toBe(false); + expect(isLocalNoProviderError(localMsg)).toBe(true); + expect(isLocalNoProviderError(remoteMsg)).toBe(false); }); });