From a4b4a6baa64031e6b02d586817b5904c839d5789 Mon Sep 17 00:00:00 2001 From: i2cjak Date: Tue, 24 Nov 2026 02:29:14 -0500 Subject: [PATCH] =?UTF-8?q?web:=20Project=20Home,=20Settings=20=E2=80=BA?= =?UTF-8?q?=20Ring,=20and=20estimate=20lead=20time=20on=20the=20To=20order?= =?UTF-8?q?=20card?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A project's name in the web sidebar opens its home (goal and notes, mechanical models, parts to order with the last estimate's lead time and warnings, boards, threads, New thread); the chevron beside it folds its threads. Settings gains Ring: the Pebble ring's recordings listed, searched, played and heard again, their rows changed in place so a recording that plays keeps playing. Hub: data/1 `project.home` (feature `projecthome`), readable by a browser, read off the folder only (no git or gh). The browser policy lets a paired browser read the ring's recordings and have one heard again (`ring.list`, which also says `busy`, and `ring.hear`; feature `ringnotes`) and fetch a recording on its own origin behind its cookie, with byte ranges; the ring's webhook, token and delivery stay native. The project card carries the lead time and warnings of the card of the thread it buys from. Co-Authored-By: Claude Fable 5.2 --- docs/PARITY.md | 6 +- docs/PHONE-DATA.md | 2 + i18n/en.msg | 23 ++ i18n/es.msg | 23 ++ i18n/ja.msg | 23 ++ .../src/main/java/dev/backplane/mobile/Msg.kt | 139 +++++++- mobile/ios/Shared/TrCatalog.swift | 38 +++ native/host/src/bots/ring.rs | 24 +- native/host/src/bots/tests.rs | 7 + native/host/src/commands/home.rs | 5 + native/host/src/data/ext.rs | 33 ++ native/host/src/data/mod.rs | 2 +- native/host/src/data/tests.rs | 21 +- native/host/src/data/webpolicy.rs | 13 +- native/host/src/net/webingress.rs | 13 +- native/host/src/settings/fab.rs | 3 + test/web/home.mjs | 322 ++++++++++++++++++ web/build.ts | 14 + web/dist/assets/app.js | 37 +- web/dist/assets/pair.js | 2 +- web/dist/assets/style.css | 207 +++++++++++ web/dist/manifest.json | 77 ++++- web/src/app.ts | 112 +++++- web/src/project-home-model.ts | 112 ++++++ web/src/project-home.ts | 287 ++++++++++++++++ web/src/ring-model.ts | 109 ++++++ web/src/settings-model.ts | 12 +- web/src/settings.ts | 308 ++++++++++++++++- web/src/shell.css | 207 +++++++++++ web/src/sidebar.ts | 55 ++- web/test/project-home.test.ts | 68 ++++ web/test/ring.test.ts | 67 ++++ web/test/settings.test.ts | 4 +- 33 files changed, 2310 insertions(+), 65 deletions(-) create mode 100644 test/web/home.mjs create mode 100644 web/src/project-home-model.ts create mode 100644 web/src/project-home.ts create mode 100644 web/src/ring-model.ts create mode 100644 web/test/project-home.test.ts create mode 100644 web/test/ring.test.ts diff --git a/docs/PARITY.md b/docs/PARITY.md index 0974c72ef6..5a8bc40b3f 100644 --- a/docs/PARITY.md +++ b/docs/PARITY.md @@ -38,7 +38,7 @@ Each lane updates its own rows in the commit that lands the work. | **Voice** | | | | Dictation from the mic, desktop: the GPUI `Dictate` chip starts a hub session (`bots.voice` start/stop/view/act), draws the strip, level and fix chips, applies the hub's edits (`screens/voice.rs`, `voice_mic.rs`); the Rust `backplane-voice` helper is built and shipped beside the hub; a whole session through the hub is not yet driven end to end | partial | voice | | Dictation from the phones: the hub serves `/voice/in` and pipes the phone's audio to the helper; the Rust `backplane-voice` helper is built and shipped beside the hub. iOS: the composer's mic (`voice.start`, 16 kHz s16le in ~200 ms POSTs, `voice.stop`), the strip (status and level, never the words), fix chips, the ask card with its field, `edit`/`draft` applied with the mark rule, `voice-clear` on Send, `voice.view` after a reconnect, Settings → Voice from `voice.page`; driven on a simulator against a hub and the mock OpenAI (a test tone for the microphone, `BACKPLANE_VOICE_FAKE=1`, debug builds only); not yet heard through a real microphone. Android: the same (`DataVoice.kt`, `DataVoiceViews.kt`, `VoiceRecorder.kt`; RECORD_AUDIO asked at the first press, a refusal says so plainly); driven on an emulator against a hub and the mock OpenAI (a 440 Hz test tone when `/data/local/tmp/voice-fake` exists, debug builds only); edit and shift logic (`VoiceText`) checked against `test/fixtures/voice-edits.json`; not yet heard through a real microphone | partial | voice | -| Whole recordings and Pebble ring notes (Nov 10: docs/ring.md): the ring's form is kept with its M4A under `/ring//`, de-duplicated by the app's `X-Index-Delivery` (a retry is a 2xx), heard one at a time by the engine Settings, Voice picks with the dictionary (local segments with times and confidence), given to the Pebble bot (`ring.setup`: Pebble, its webhook and token, #ring-requests) as the person's words, notes the hub stopped on taken up again after a restart; Settings → Ring lists, searches, plays, hears again (local or OpenAI) and links to where a note went. Hub tests drive token, signature, retry, test event, playback; Android (`DataRing.kt`) and iOS (dedicated `Settings → Ring` page in `DataSettings.swift` / `DataRing.swift`) wire the same `ring.page` / `ring.page.act` list, search, clear, playback, re-transcribe, and thread jump | done | voice | +| Whole recordings and Pebble ring notes (Nov 10: docs/ring.md): the ring's form is kept with its M4A under `/ring//`, de-duplicated by the app's `X-Index-Delivery` (a retry is a 2xx), heard one at a time by the engine Settings, Voice picks with the dictionary (local segments with times and confidence), given to the Pebble bot (`ring.setup`: Pebble, its webhook and token, #ring-requests) as the person's words, notes the hub stopped on taken up again after a restart; Settings → Ring lists, searches, plays, hears again (local or OpenAI) and links to where a note went. Hub tests drive token, signature, retry, test event, playback; Android (`DataRing.kt`) and iOS (dedicated `Settings → Ring` page in `DataSettings.swift` / `DataRing.swift`) wire the same `ring.page` / `ring.page.act` list, search, clear, playback, re-transcribe, and thread jump. Web: Settings › Ring lists the recordings, finds them by their words, plays one from the page's own origin and hears it again (local or OpenAI), and opens where a note went (feature `ringnotes`: `ring.list` and `ring.hear` allowed to a browser, `/ring/audio/` behind its cookie); the ring's setup, webhook token and Send again stay native. Driven headless against a temp hub with a note delivered through the ring's webhook (`test/web/home.mjs`) | done | voice | | Voice ops of `bots.voice`: status, key, unkey, add, start, stop, view, act, page, page-act, install, remove, api-add, api-del (`voice/session.rs`) | done | voice | | Settings: Voice page (engine, model, mic, key, dictionary, learned fixes; `voice/page.rs`, in `PAGES`) | done | voice | | Personal dictionary, learned words, `voice_dictionary_add`: `voice.e.`/`voice.l.` settings, the correction pass and settle as pure Rust with 0.14's test vectors (`voice/vdict.rs`, `words.rs`), the bot tool writes a `voice.e.` entry | done | voice | @@ -50,7 +50,7 @@ Each lane updates its own rows in the commit that lands the work. | Local engine on macOS and Windows: `local-install` and real-audio decode (`native/voice/tests/local_e2e.rs`; sherpa-onnx's C API symbols there are unchecked) | needs a person or another machine | voice | | Android pairing through the pairing screen with dictation after it (the rig paired by writing the app's link preference with `run-as`) | needs a person or another machine | voice | | **Commerce** | | | -| Card and Ready to order data (`fab.look`, `fab.intent`): the answer matches 0.14's twelve keys and adds `lead_days`, `estimate_warnings` from the estimate; the bar itself is dropped (row below). Audit and fixes in `docs/COMMERCE-AUDIT.md`. GPUI, iOS, and Android render `lead_days` and `estimate_warnings` on Order cards and project fab cards. Open: the hub cannot see a paused server (needs a `paused` field from the order server); the deployed server's version and `DEFAULT_SERVER` need Bub | partial | commerce | +| Card and Ready to order data (`fab.look`, `fab.intent`): the answer matches 0.14's twelve keys and adds `lead_days`, `estimate_warnings` from the estimate; the bar itself is dropped (row below). Audit and fixes in `docs/COMMERCE-AUDIT.md`. GPUI, iOS, and Android render `lead_days` and `estimate_warnings` on Order cards and project fab cards. The web client draws them on its Project Home's To order card (`project.home` `leadDays`, `warnings`; the project's card takes them from the card of the thread it buys from). Open: the hub cannot see a paused server (needs a `paused` field from the order server); the deployed server's version and `DEFAULT_SERVER` need Bub | partial | commerce | | Buy it: `order.buy` starts a buy thread in the source's folder, "Buy: · 2" naming, the person's Buy it as its first message; only for fab files or a KiCad project's own board. Driven live in the window (test/order/live_e2e.sh): Buy it in the header, the window goes to the buy thread | done | commerce | | Buy threads: `order_ask` (its answer is the person's message), `order_quote` (the upload waits behind its approval card; nothing leaves before the person's Send, and a copy sends nothing), `order_status`, `order.wait`; order tokens only in `/orders/`. Tested on the hub with stand-ins, and once against the real `order/fabsrv` on loopback with a Stripe double (`test/order/local_server.py`), pilot and paid | done | commerce | | `order_review` check and record work for every agent (`settings/order.rs`; the design hash matches 0.14's, so a review it recorded stays current). The gate is in, tested through the agent's MCP path with stand-ins, but needs a buy thread to be reached: not driven on a client | partial | commerce | @@ -181,7 +181,7 @@ Driven in one thread with the stand-in's `stream` mode (`tools:`, `todos:`, `age | # | Row | Status | What was driven | |---|---|---|---| -| 98 | Project home (goal, intent, parts, boards) | partial | GPUI: clicking the project opens its home, which asks the hub `project.home {project}` and `fab.look {project}` (the card by project, with no estimate asked). Driven with `.backplane/intent.md` and `board.fab.json`: the home showed Goal & notes (goal, parts and notes as written), To order (LED board · pcb · board.fab.json), Boards (board.kicad_pcb), New thread and the threads. It has no Ready to order bar, Buy it or price, on purpose (row 56: Buy it is a thread's tool). Not ported from 0.14's web home: the embedded board viewer, the DRC/ERC chips, the README panel and the intent editor. Phones have no project home: **not planned** (the person's decision); a project row only folds its threads. | +| 98 | Project home (goal, intent, parts, boards) | partial | GPUI: clicking the project opens its home, which asks the hub `project.home {project}` and `fab.look {project}` (the card by project, with no estimate asked). Driven with `.backplane/intent.md` and `board.fab.json`: the home showed Goal & notes (goal, parts and notes as written), To order (LED board · pcb · board.fab.json), Boards (board.kicad_pcb), New thread and the threads. It has no Ready to order bar, Buy it or price, on purpose (row 56: Buy it is a thread's tool). Not ported from 0.14's web home: the embedded board viewer, the DRC/ERC chips, the README panel and the intent editor. Phones have no project home: **not planned** (the person's decision); a project row only folds its threads. Web: a project's name in the sidebar opens its home (the chevron beside it folds its threads), from data/1 `project.home` (feature `projecthome`) and `threads.list`: New thread, the threads, Goal & notes, Mechanical, To order with the last estimate's lead time and warnings, Boards (a row opens Board on the project's newest thread). Not on the web home: Open folder, the README, Buy it and Push (ordering and git stay native), Edit goal & notes (`/intent` in a thread's composer does it). Driven headless against a temp hub (`test/web/home.mjs`). | | 99 | Ready to order bar | dropped | Dropped on purpose (see the Commerce section: Buy it is the first of the thread's tools instead). | | 100 | Order progress | done | The Order card and its steps, driven live in the window, on the Android emulator and the iOS simulator against the local order server and a Stripe double (6508e65764, 1c1fa2a9f6; `test/order/live_e2e.sh`, `live_android.sh`, `live_ios.sh`). | | 101 | Manufacturing review | partial | `order_review` check and record work for every agent and the gate is tested through the agent's MCP path; the live buy-thread runs (6508e65764, 1c1fa2a9f6) do not drive a review, so it is not driven on a client. | diff --git a/docs/PHONE-DATA.md b/docs/PHONE-DATA.md index 5c3552d1f1..90cc1b6849 100644 --- a/docs/PHONE-DATA.md +++ b/docs/PHONE-DATA.md @@ -79,6 +79,8 @@ On reconnect the app resubscribes and re-reads lists and the open thread (no res - Feature `replyImages`: an assistant entry carries `images` (paths, in the message's spelling): the images it names, the desktop's own list (`files/mimg.rs` `paths`: a path on a line, in backticks, a list or bold, `~/`, `![alt](path)`, a folder then its files). The phone draws each under the first block that names it (the rest after the text) and reads it with `message.image {entry, path}` → `{mime, data}` (base64; the snapshot `/message-image` serves, so it works over the relay; at most 8 MiB). A tap on the path opens it full size. - Feature `fileLinks` (docs/file-links.md): an assistant entry carries `files: [{path, name, size, open}]`, the files its text names that the hub serves. The phones (`FileFetch.kt`/`.swift`, `Downloads.kt`, `DataDownloads.swift`) download a tapped `download` one (and a `view` one link.resolve cannot open) with `GET /file?path=` (`&thread=` for `~`), `Authorization: Bearer `, into a `.part` file resumed with `Range`/`If-Range`; a `/s//` share in a message is fetched the same way. Done: Android copies it to Downloads (MediaStore) and offers Open/Share (FileProvider); iOS brings up the share sheet. The Files tab's preview has Download (`/files/get`). - Feature `projectcard`: `project.card {project}` → `{goal, boards}`: the top of a project's page, its goal (from `.backplane/intent.md`) and its boards by name, from the hub's own `fab.look` card. +- Feature `projecthome`: `project.home {project}` → `{project, root, intent, parts, boards, mech, leadDays, warnings}`: a project's home page as the desktop's opens (the web client draws it when a project's name is pressed): `intent` the goal and notes as written (`.backplane/intent.md`), `parts` what there is to order (`name`, `kind`, `path` of the fab file), `boards` the board files (paths from the project's root, 12 at most), `mech` the models (`path`, `name`, `size`; biggest first: the assembly), and what the last estimate said beyond a price: `leadDays` (the longest lead time in days, 0 for none) and `warnings` (each once). They come from the card of the thread the project buys from (`fab.look`); the home itself never asks the order server. Nothing is priced or bought from it; a browser may read it (`data/webpolicy.rs`). +- Feature `ringnotes`: a paired browser may read the ring's recordings and have one heard again: `ring.list {q?}` and `ring.hear {note, engine}` are allowed to it, and `GET /ring/audio/?k=` answers on the browser's own origin behind its cookie (the key is the one in the note's `play` link; the page's CSP has `media-src 'self'`). `ring.list` also says `busy`: the note being heard now ("" for none). The recording answers a `Range: bytes=a-b` with that part (206), for players that ask in parts. The ring's webhook, token and delivery stay native: `ring.page`, `ring.page.act`, `ring.setup`, `ring.send`, `ring.get` and `ring.search` are refused to a browser. - Pictures: the agents' `turn.start` keeps `attachments` (a `MessageAttached` event in the same commit) and `agentText`; the message's text carries the `[Attached image: ]` lines for the agent and the phone data API strips them from what it shows. Viewer, files and browser requests are not here: the lanes adding them in `native/host` (viewers, files, cef) define them; the phones will take them as further features. diff --git a/i18n/en.msg b/i18n/en.msg index 12e3ffe9a7..9be5322dda 100644 --- a/i18n/en.msg +++ b/i18n/en.msg @@ -5075,3 +5075,26 @@ web.settings.providers = AI providers web.settings.providers.browser = Connect a provider in the Backplane desktop or mobile app under Settings → Accounts. order.lead.days = {days, plural, one {Est. lead time: 1 day} other {Est. lead time: {days} days}} order.estimate.warnings = Warning: {warnings} +web.home.open = Open project home +web.home.fold = Hide threads +web.home.unfold = Show threads +web.home.loading = Loading project… +web.home.error = Could not load this project. +web.home.lead = Lead time: {n} days +web.home.lead.one = Lead time: 1 day +web.ring.unavailable = This hub does not show ring notes to a browser yet. Update it, or open Settings › Ring in the desktop app. +web.ring.loading = Loading recordings… +web.ring.error = Could not load recordings. +web.ring.count = {n} recordings +web.ring.count.one = 1 recording +web.ring.found = {found} of {total} have “{q}”. +web.ring.not.heard = Not heard +web.ring.app.words = The Pebble app's words +web.ring.heard.by = Heard by {model} +web.ring.heard.by.sure = Heard by {model}, {conf}% sure +web.ring.state.sent = given to Pebble +web.ring.state.new = waiting to be heard +web.ring.state.heard = waiting to go to Pebble +web.ring.state.failed = not given to Pebble +web.ring.state.busy = being heard now +web.ring.no.words = (no words) diff --git a/i18n/es.msg b/i18n/es.msg index 3a27f829ae..cfa5cc21cd 100644 --- a/i18n/es.msg +++ b/i18n/es.msg @@ -5075,3 +5075,26 @@ 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. order.lead.days = {days, plural, one {Plazo estimado: 1 día} other {Plazo estimado: {days} días}} order.estimate.warnings = Aviso: {warnings} +web.home.open = Abrir la página del proyecto +web.home.fold = Ocultar hilos +web.home.unfold = Mostrar hilos +web.home.loading = Cargando el proyecto… +web.home.error = No se pudo cargar este proyecto. +web.home.lead = Plazo de entrega: {n} días +web.home.lead.one = Plazo de entrega: 1 día +web.ring.unavailable = Este hub aún no muestra las notas del anillo en un navegador. Actualízalo o abre Configuración › Anillo en la aplicación de escritorio. +web.ring.loading = Cargando grabaciones… +web.ring.error = No se pudieron cargar las grabaciones. +web.ring.count = {n} grabaciones +web.ring.count.one = 1 grabación +web.ring.found = {found} de {total} contienen “{q}”. +web.ring.not.heard = Sin transcribir +web.ring.app.words = Las palabras de la aplicación Pebble +web.ring.heard.by = Transcrito por {model} +web.ring.heard.by.sure = Transcrito por {model}, {conf}% de certeza +web.ring.state.sent = entregada a Pebble +web.ring.state.new = en espera de transcripción +web.ring.state.heard = en espera de entrega a Pebble +web.ring.state.failed = no entregada a Pebble +web.ring.state.busy = transcribiéndose ahora +web.ring.no.words = (sin palabras) diff --git a/i18n/ja.msg b/i18n/ja.msg index 7097af92b0..d49ecfb29c 100644 --- a/i18n/ja.msg +++ b/i18n/ja.msg @@ -5098,3 +5098,26 @@ web.settings.providers = AI プロバイダー web.settings.providers.browser = Backplane のデスクトップまたはモバイルアプリの設定 → アカウントからプロバイダーを接続してください。 order.lead.days = {days, plural, one {目安納期: 1日} other {目安納期: {days}日}} order.estimate.warnings = 警告: {warnings} +web.home.open = プロジェクトホームを開く +web.home.fold = スレッドを隠す +web.home.unfold = スレッドを表示 +web.home.loading = プロジェクトを読み込み中… +web.home.error = このプロジェクトを読み込めませんでした。 +web.home.lead = リードタイム: {n} 日 +web.home.lead.one = リードタイム: 1 日 +web.ring.unavailable = このハブはまだブラウザーにリングのメモを表示しません。ハブを更新するか、デスクトップアプリの設定 › リングを開いてください。 +web.ring.loading = 録音を読み込み中… +web.ring.error = 録音を読み込めませんでした。 +web.ring.count = 録音 {n} 件 +web.ring.count.one = 録音 1 件 +web.ring.found = {total} 件中 {found} 件に「{q}」があります。 +web.ring.not.heard = 未認識 +web.ring.app.words = Pebble アプリの文字起こし +web.ring.heard.by = {model} が認識 +web.ring.heard.by.sure = {model} が認識、確度 {conf}% +web.ring.state.sent = Pebble に渡しました +web.ring.state.new = 認識待ち +web.ring.state.heard = Pebble への受け渡し待ち +web.ring.state.failed = Pebble に渡せませんでした +web.ring.state.busy = 認識中 +web.ring.no.words = (言葉なし) 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 e3d26f0571..64275e2ecc 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 @@ -4974,6 +4974,29 @@ object Msg { "web.settings.providers.browser", "order.lead.days", "order.estimate.warnings", + "web.home.open", + "web.home.fold", + "web.home.unfold", + "web.home.loading", + "web.home.error", + "web.home.lead", + "web.home.lead.one", + "web.ring.unavailable", + "web.ring.loading", + "web.ring.error", + "web.ring.count", + "web.ring.count.one", + "web.ring.found", + "web.ring.not.heard", + "web.ring.app.words", + "web.ring.heard.by", + "web.ring.heard.by.sure", + "web.ring.state.sent", + "web.ring.state.new", + "web.ring.state.heard", + "web.ring.state.failed", + "web.ring.state.busy", + "web.ring.no.words", ) 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( @@ -9947,6 +9970,29 @@ object Msg { "Connect a provider in the Backplane desktop or mobile app under Settings → Accounts.", "{days, plural, one {Est. lead time: 1 day} other {Est. lead time: {days} days}}", "Warning: {warnings}", + "Open project home", + "Hide threads", + "Show threads", + "Loading project…", + "Could not load this project.", + "Lead time: {n} days", + "Lead time: 1 day", + "This hub does not show ring notes to a browser yet. Update it, or open Settings › Ring in the desktop app.", + "Loading recordings…", + "Could not load recordings.", + "{n} recordings", + "1 recording", + "{found} of {total} have “{q}”.", + "Not heard", + "The Pebble app's words", + "Heard by {model}", + "Heard by {model}, {conf}% sure", + "given to Pebble", + "waiting to be heard", + "waiting to go to Pebble", + "not given to Pebble", + "being heard now", + "(no words)", ) 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( @@ -14920,6 +14966,29 @@ object Msg { "Backplane のデスクトップまたはモバイルアプリの設定 → アカウントからプロバイダーを接続してください。", "{days, plural, one {目安納期: 1日} other {目安納期: {days}日}}", "警告: {warnings}", + "プロジェクトホームを開く", + "スレッドを隠す", + "スレッドを表示", + "プロジェクトを読み込み中…", + "このプロジェクトを読み込めませんでした。", + "リードタイム: {n} 日", + "リードタイム: 1 日", + "このハブはまだブラウザーにリングのメモを表示しません。ハブを更新するか、デスクトップアプリの設定 › リングを開いてください。", + "録音を読み込み中…", + "録音を読み込めませんでした。", + "録音 {n} 件", + "録音 1 件", + "{total} 件中 {found} 件に「{q}」があります。", + "未認識", + "Pebble アプリの文字起こし", + "{model} が認識", + "{model} が認識、確度 {conf}%", + "Pebble に渡しました", + "認識待ち", + "Pebble への受け渡し待ち", + "Pebble に渡せませんでした", + "認識中", + "(言葉なし)", ) 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( @@ -19893,6 +19962,29 @@ object Msg { "Conecta un proveedor en la aplicación de escritorio o móvil de Backplane en Configuración → Cuentas.", "{days, plural, one {Plazo estimado: 1 día} other {Plazo estimado: {days} días}}", "Aviso: {warnings}", + "Abrir la página del proyecto", + "Ocultar hilos", + "Mostrar hilos", + "Cargando el proyecto…", + "No se pudo cargar este proyecto.", + "Plazo de entrega: {n} días", + "Plazo de entrega: 1 día", + "Este hub aún no muestra las notas del anillo en un navegador. Actualízalo o abre Configuración › Anillo en la aplicación de escritorio.", + "Cargando grabaciones…", + "No se pudieron cargar las grabaciones.", + "{n} grabaciones", + "1 grabación", + "{found} de {total} contienen “{q}”.", + "Sin transcribir", + "Las palabras de la aplicación Pebble", + "Transcrito por {model}", + "Transcrito por {model}, {conf}% de certeza", + "entregada a Pebble", + "en espera de transcripción", + "en espera de entrega a Pebble", + "no entregada a Pebble", + "transcribiéndose ahora", + "(sin palabras)", ) 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( @@ -23311,11 +23403,29 @@ object Msg { "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.", + "Open project home", + "Hide threads", + "Show threads", + "Loading project…", + "Could not load this project.", + "Lead time: 1 day", + "This hub does not show ring notes to a browser yet. Update it, or open Settings › Ring in the desktop app.", + "Loading recordings…", + "Could not load recordings.", + "1 recording", + "Not heard", + "The Pebble app's words", + "given to Pebble", + "waiting to be heard", + "waiting to go to Pebble", + "not given to Pebble", + "being heard now", + "(no words)", ) 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, 3163, 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, 3731, 61, 62, 63, 64, 66, 68, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 84, 85, 3770, 87, 88, 98, 99, 3092, 3769, 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, 3212, 165, 166, 3214, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 3173, 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, 2979, 237, 238, 239, 240, 3730, 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, 3184, 305, 306, 307, 308, 309, 310, 311, 313, 314, 315, 317, 319, 333, 3778, 336, 3777, 3780, 340, 3790, 342, 343, 344, 345, 354, 3161, 357, 358, 359, 360, 361, 362, 363, 364, 365, 366, 367, 368, 369, 370, 371, 372, 373, 2982, 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, 2974, 2975, 432, 433, 434, 435, 436, 437, 438, 439, 440, 441, 442, 443, 444, 445, 446, 447, 448, 449, 450, 451, 453, 454, 455, 3191, 457, 458, 459, 460, 461, 2964, 463, 464, 465, 3094, 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, 3199, 3200, 636, 637, 638, 639, 640, 641, 642, 643, 644, 645, 646, 647, 651, 652, 3843, 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, 3775, 734, 735, 736, 737, 3198, 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, 3758, 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, 3194, 850, 852, 853, 854, 857, 858, 859, 860, 861, 862, 863, 864, 865, 866, 867, 3768, 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, 3845, 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, 3164, 964, 965, 966, 967, 968, 969, 3793, 971, 3019, 3076, 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, 3796, 1020, 1021, 1022, 1025, 1029, 1030, 1031, 2971, 3045, 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, 3810, 1094, 1095, 1098, 1099, 1100, 3193, 1102, 1103, 1104, 1105, 1106, 1107, 1108, 1110, 1111, 1112, 1113, 1114, 1115, 1116, 3795, 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, 2973, 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, 3508, 1361, 1362, 1363, 1364, 1365, 1366, 3575, 1373, 1375, 1380, 1384, 1385, 3049, 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, 2976, 1417, 1418, 1419, 1420, 1421, 1422, 1423, 1424, 1425, 1426, 1427, 1428, 1429, 1430, 1431, 1432, 1433, 3093, 3586, 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, 3588, 1473, 1474, 1475, 1477, 1478, 1479, 1480, 1481, 1482, 1483, 1484, 1485, 1486, 1487, 1488, 1489, 1490, 1493, 1494, 3733, 1496, 1497, 1498, 3745, 3751, 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, 1567, 1568, 1569, 1570, 1571, 1573, 1574, 1575, 1576, 1578, 1579, 1580, 1581, 1582, 1585, 1586, 1587, 1588, 1589, 1590, 1591, 1592, 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, 1621, 1622, 1623, 1624, 1625, 1627, 1628, 1629, 1630, 1631, 1632, 1633, 1634, 3052, 1636, 1637, 1638, 1639, 1640, 1641, 1642, 1643, 1644, 1645, 1646, 1647, 1648, 1650, 1651, 1652, 1653, 1654, 1655, 1656, 1661, 1662, 1663, 1664, 1665, 1666, 1667, 1668, 3462, 1670, 1671, 1672, 1673, 3463, 1675, 1676, 1677, 1678, 1679, 1680, 1681, 1682, 1683, 1684, 1685, 1686, 2985, 1692, 1694, 1696, 1698, 1702, 1706, 1712, 1714, 1715, 1716, 1718, 1719, 1720, 1721, 1722, 1723, 1725, 1727, 1728, 1729, 1730, 1731, 1733, 1734, 3757, 1736, 1737, 1738, 1739, 1740, 1741, 1742, 1744, 1745, 1747, 1748, 1749, 1750, 1751, 1752, 1753, 1754, 1755, 1756, 1757, 1758, 1759, 1760, 1761, 1762, 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, 1820, 1821, 1822, 1823, 1824, 1826, 1827, 3028, 1836, 1838, 1842, 3010, 1844, 1845, 3011, 1847, 1848, 1852, 3075, 1854, 1855, 1856, 1857, 1858, 1859, 1860, 1861, 1862, 1864, 1869, 1871, 1872, 1873, 1874, 1875, 1876, 3090, 1878, 1879, 1882, 1883, 1893, 1894, 1898, 1899, 1900, 1901, 1902, 1903, 1904, 1905, 1907, 1908, 1909, 1910, 1911, 1912, 1913, 1914, 1915, 1916, 1917, 1918, 1919, 1920, 1921, 1922, 1927, 1928, 1929, 1930, 1931, 1932, 1933, 1934, 1935, 1936, 1937, 1938, 1939, 1940, 1942, 1943, 1945, 1946, 1956, 1958, 1959, 1962, 1963, 1966, 1967, 1968, 1970, 1971, 1972, 1973, 1974, 1975, 1976, 1977, 1978, 1979, 1980, 1981, 1982, 1983, 1984, 1985, 1986, 1988, 1994, 1995, 1996, 1997, 2001, 3151, 2007, 2008, 2010, 2011, 2012, 2013, 3803, 3804, 2022, 2024, 2025, 2026, 2028, 2029, 2030, 2031, 2032, 2033, 2034, 2035, 2036, 2039, 2040, 2042, 2043, 2046, 2047, 3136, 3137, 3138, 2055, 3364, 2057, 2059, 2060, 2061, 2062, 2063, 2064, 2065, 2066, 2067, 2068, 2069, 2070, 2071, 2074, 2075, 2076, 2077, 2078, 2079, 2083, 2084, 2085, 2086, 2087, 2088, 2089, 2090, 2091, 2092, 2093, 2094, 2095, 2096, 2097, 2098, 2099, 2100, 2102, 2103, 2104, 2105, 2106, 2107, 2108, 2109, 2110, 2112, 2118, 2119, 2120, 2121, 2122, 2123, 2124, 2125, 2127, 2128, 2129, 3078, 2133, 2134, 2135, 2137, 2139, 2140, 2141, 2142, 3001, 3126, 3127, 3128, 3129, 3130, 2149, 2150, 2151, 2153, 3003, 3004, 2994, 2993, 2159, 2995, 2161, 2999, 2163, 3362, 2168, 2172, 2174, 2175, 2176, 2177, 2178, 2179, 2180, 2181, 2182, 2183, 2184, 3029, 2188, 2189, 2190, 2191, 3062, 2193, 2194, 2195, 2196, 2197, 2198, 2199, 2200, 2201, 2204, 3375, 2206, 2207, 2208, 2209, 3044, 2211, 2212, 2213, 2214, 2992, 2216, 3107, 2219, 2223, 2224, 3652, 2226, 2227, 3739, 3740, 2231, 3189, 2234, 3728, 2237, 2238, 2239, 2240, 2241, 3788, 2243, 3159, 2245, 3158, 2247, 2249, 2251, 2252, 2253, 2257, 2260, 2262, 2264, 2265, 2266, 2267, 2268, 2269, 2270, 2271, 2272, 2273, 2274, 2275, 2276, 2277, 2279, 2280, 2281, 3746, 2283, 2284, 2286, 3036, 3034, 3038, 2292, 2294, 2295, 2301, 2302, 2303, 2304, 3074, 2309, 2310, 2312, 2317, 2318, 3018, 3587, 2981, 2980, 2983, 3103, 3106, 2331, 2332, 2334, 2335, 2337, 2338, 2339, 2340, 2341, 2342, 2343, 2344, 2345, 3807, 2349, 2350, 2351, 2352, 2353, 2354, 2355, 2356, 2357, 2358, 2359, 2360, 2361, 2362, 2363, 2368, 2370, 2371, 2372, 2376, 2377, 2380, 2381, 2388, 2389, 2390, 2391, 2392, 2393, 2394, 2395, 2396, 2397, 2398, 2399, 2400, 2402, 2403, 2404, 2405, 2406, 2407, 2429, 2430, 2433, 2434, 2435, 2436, 2437, 2438, 2439, 2449, 2453, 2454, 2455, 2456, 2457, 2458, 2459, 2460, 2461, 2463, 2464, 2465, 2466, 2468, 2469, 2470, 2472, 2475, 2476, 2477, 2480, 2481, 2482, 2483, 2484, 2485, 2486, 2487, 2493, 2494, 2495, 2496, 2497, 2498, 2499, 2500, 2501, 2502, 2503, 2504, 2505, 2506, 2507, 2508, 2509, 2510, 2511, 2512, 2513, 2514, 2515, 2517, 2518, 2519, 2520, 2521, 2522, 2523, 2524, 2525, 2526, 2527, 2528, 2529, 2530, 2531, 2532, 2533, 2534, 2535, 2536, 2537, 2538, 2540, 2541, 2542, 2543, 3140, 2545, 2547, 2548, 2550, 2551, 2552, 2553, 2554, 2555, 2556, 2559, 2560, 2561, 2562, 2565, 2566, 2567, 2568, 2569, 2570, 2571, 2572, 2573, 2581, 2582, 2583, 2584, 2587, 2588, 2589, 2590, 2591, 2592, 2593, 2594, 2595, 2597, 2598, 2599, 2600, 2601, 2602, 2603, 2604, 2605, 2608, 2610, 2611, 2614, 2615, 2616, 2617, 2618, 2619, 2620, 2621, 2622, 2624, 2625, 2627, 2628, 2629, 2630, 2631, 2632, 2633, 2634, 2635, 2636, 2637, 2639, 2641, 2644, 2646, 3736, 2651, 2652, 2653, 2654, 2655, 2656, 2657, 2661, 2662, 2664, 2665, 2666, 2667, 2668, 2669, 2670, 2672, 2673, 2674, 2679, 2680, 2681, 2683, 2684, 2685, 2686, 2688, 2689, 2690, 2691, 2692, 2693, 2694, 2695, 2696, 2697, 2698, 2699, 2700, 3709, 2702, 2703, 2705, 3706, 2707, 2708, 3710, 3707, 2720, 2724, 3717, 3213, 3718, 2728, 3719, 2730, 2732, 3721, 2734, 3722, 2736, 2738, 3726, 3704, 3697, 3705, 2757, 2758, 2760, 2761, 2771, 2772, 2774, 2775, 2776, 2777, 2778, 2779, 2780, 2781, 2782, 2786, 2789, 2792, 2794, 2796, 2802, 2803, 2804, 2805, 2806, 2807, 2808, 2809, 2810, 2811, 2812, 2813, 2814, 3384, 2816, 2817, 2818, 2819, 2820, 2822, 2824, 2825, 3416, 2831, 2832, 2833, 2834, 2835, 2836, 2837, 2838, 2839, 2840, 2841, 2842, 2844, 2845, 2846, 2847, 2850, 2851, 2853, 2854, 2855, 2856, 3008, 2858, 2860, 2861, 2863, 2864, 2865, 2866, 2867, 2869, 2870, 2874, 2877, 2878, 2879, 2881, 2882, 2883, 2885, 2886, 2887, 2888, 2890, 2891, 2894, 2897, 2898, 2899, 2900, 2901, 2903, 2905, 2906, 2908, 2909, 2910, 2911, 2912, 2913, 2914, 2915, 2917, 2918, 2919, 2920, 2921, 2922, 2923, 2924, 2925, 2926, 2927, 2928, 2929, 2930, 2931, 2932, 2933, 2934, 2935, 2936, 2942, 2943, 2944, 2946, 2947, 2948, 2952, 2953, 2954, 2955, 2956, 2960, 2961, 2965, 2966, 2967, 2968, 2969, 2970, 2972, 2977, 2978, 2984, 2989, 2991, 2996, 2997, 2998, 3000, 3002, 3005, 3006, 3007, 3009, 3013, 3020, 3021, 3022, 3023, 3024, 3025, 3026, 3027, 3030, 3031, 3032, 3033, 3037, 3039, 3040, 3041, 3042, 3046, 3047, 3051, 3053, 3054, 3055, 3057, 3058, 3059, 3060, 3061, 3064, 3065, 3066, 3067, 3068, 3069, 3070, 3071, 3072, 3079, 3080, 3081, 3082, 3087, 3088, 3089, 3091, 3095, 3096, 3097, 3098, 3099, 3102, 3104, 3105, 3108, 3109, 3110, 3111, 3112, 3113, 3114, 3115, 3116, 3118, 3120, 3121, 3122, 3123, 3124, 3125, 3131, 3132, 3133, 3134, 3135, 3139, 3141, 3142, 3143, 3144, 3145, 3146, 3147, 3149, 3150, 3153, 3155, 3156, 3157, 3160, 3165, 3166, 3167, 3169, 3172, 3174, 3175, 3177, 3178, 3179, 3181, 3182, 3183, 3185, 3186, 3187, 3188, 3192, 3197, 3202, 3203, 3204, 3205, 3206, 3207, 3208, 3210, 3215, 3216, 3217, 3218, 3219, 3220, 3221, 3222, 3223, 3224, 3225, 3226, 3227, 3230, 3231, 3234, 3235, 3236, 3237, 3238, 3239, 3240, 3241, 3244, 3245, 3246, 3247, 3248, 3249, 3250, 3251, 3252, 3253, 3254, 3257, 3258, 3260, 3261, 3262, 3263, 3264, 3265, 3266, 3267, 3268, 3269, 3270, 3271, 3272, 3273, 3274, 3275, 3276, 3277, 3278, 3279, 3280, 3281, 3282, 3283, 3284, 3285, 3286, 3289, 3290, 3291, 3292, 3293, 3294, 3295, 3296, 3297, 3298, 3300, 3301, 3302, 3303, 3304, 3305, 3306, 3307, 3308, 3309, 3310, 3311, 3312, 3313, 3314, 3315, 3316, 3317, 3318, 3319, 3320, 3321, 3322, 3323, 3324, 3325, 3326, 3327, 3328, 3329, 3330, 3331, 3332, 3335, 3336, 3337, 3338, 3339, 3340, 3341, 3342, 3343, 3344, 3345, 3346, 3347, 3348, 3349, 3350, 3351, 3352, 3353, 3354, 3355, 3356, 3358, 3359, 3363, 3365, 3366, 3367, 3369, 3370, 3371, 3374, 3376, 3377, 3378, 3379, 3380, 3383, 3385, 3388, 3390, 3391, 3396, 3397, 3398, 3399, 3402, 3409, 3410, 3411, 3412, 3413, 3414, 3417, 3418, 3419, 3420, 3423, 3424, 3425, 3426, 3427, 3428, 3429, 3430, 3431, 3432, 3434, 3435, 3436, 3437, 3438, 3439, 3441, 3442, 3444, 3445, 3446, 3447, 3448, 3454, 3455, 3456, 3457, 3458, 3459, 3460, 3461, 3464, 3467, 3470, 3471, 3472, 3473, 3474, 3475, 3476, 3477, 3478, 3479, 3480, 3481, 3482, 3483, 3484, 3485, 3486, 3487, 3488, 3490, 3491, 3492, 3493, 3494, 3495, 3496, 3498, 3499, 3500, 3501, 3502, 3503, 3504, 3505, 3507, 3512, 3518, 3520, 3521, 3522, 3523, 3524, 3525, 3526, 3527, 3528, 3529, 3530, 3531, 3532, 3533, 3534, 3536, 3537, 3538, 3539, 3540, 3541, 3545, 3546, 3550, 3551, 3557, 3558, 3559, 3560, 3561, 3562, 3563, 3564, 3565, 3567, 3568, 3569, 3570, 3573, 3574, 3576, 3577, 3589, 3590, 3591, 3592, 3593, 3594, 3595, 3596, 3597, 3598, 3599, 3600, 3601, 3602, 3603, 3604, 3605, 3606, 3608, 3609, 3610, 3614, 3615, 3616, 3617, 3623, 3624, 3625, 3626, 3630, 3632, 3633, 3634, 3636, 3639, 3640, 3644, 3651, 3653, 3656, 3658, 3659, 3660, 3661, 3662, 3663, 3665, 3666, 3667, 3668, 3669, 3670, 3671, 3672, 3673, 3674, 3675, 3676, 3677, 3678, 3679, 3680, 3681, 3682, 3683, 3684, 3685, 3686, 3687, 3688, 3689, 3690, 3691, 3692, 3693, 3694, 3695, 3696, 3714, 3729, 3732, 3734, 3735, 3737, 3741, 3743, 3747, 3756, 3759, 3760, 3761, 3762, 3763, 3764, 3766, 3772, 3773, 3776, 3779, 3781, 3782, 3783, 3784, 3785, 3786, 3789, 3792, 3794, 3798, 3799, 3800, 3801, 3802, 3805, 3806, 3808, 3809, 3811, 3812, 3813, 3814, 3815, 3816, 3817, 3818, 3820, 3821, 3822, 3823, 3824, 3825, 3826, 3827, 3828, 3829, 3830, 3831, 3832, 3833, 3834, 3835, 3836, 3837, 3840, 3842, 3844, 3853, 3854, 3856, 3857, 3866, 3872, 3878, 3887, 3889, 3890, 3891, 3892, 3895, 3896, 3898, 3904, 3908, 3912, 3917, 3918, 3920, 3921, 3922, 3924, 3925, 3926, 3931, 3932, 3933, 3934, 3935, 3936, 3937, 3938, 3939, 3942, 3943, 3944, 3989, 3990, 3995, 3997, 3998, 4000, 4006, 4009, 4024, 4025, 4026, 4027, 4028, 4029, 4031, 4032, 4034, 4035, 4037, 4039, 4040, 4053, 4056, 4057, 4059, 4060, 4064, 4069, 4072, 4073, 4075, 4076, 4082, 4084, 4085, 4088, 4090, 4095, 4096, 4097, 4102, 4113, 4136, 4152, 4160, 4169, 4170, 4174, 4179, 4195, 4196, 4197, 4198, 4200, 4202, 4203, 4205, 4208, 4212, 4215, 4218, 4219, 4220, 4221, 4225, 4226, 4227, 4228, 4231, 4232, 4233, 4234, 4235, 4236, 4237, 4238, 4239, 4240, 4241, 4242, 4243, 4244, 4245, 4246, 4247, 4248, 4249, 4250, 4251, 4252, 4253, 4254, 4262, 4265, 4266, 4272, 4277, 4278, 4279, 4280, 4284, 4288, 4290, 4291, 4292, 4293, 4294, 4295, 4296, 4297, 4299, 4300, 4301, 4302, 4304, 4305, 4306, 4307, 4308, 4309, 4310, 4320, 4329, 4330, 4331, 4332, 4333, 4334, 4335, 4336, 4337, 4338, 4340, 4341, 4345, 4346, 4348, 4349, 4350, 4351, 4355, 4356, 4357, 4358, 4359, 4360, 4362, 4363, 4364, 4370, 4371, 4372, 4373, 4374, 4375, 4379, 4383, 4384, 4386, 4387, 4388, 4389, 4390, 4392, 4402, 4404, 4409, 4410, 4411, 4412, 4413, 4414, 4415, 4416, 4417, 4418, 4419, 4420, 4421, 4422, 4423, 4424, 4426, 4427, 4428, 4429, 4430, 4431, 4432, 4437, 4440, 4441, 4442, 4443, 4444, 4445, 4446, 4447, 4448, 4449, 4450, 4451, 4452, 4453, 4454, 4455, 4456, 4457, 4458, 4459, 4460, 4462, 4463, 4464, 4466, 4467, 4468, 4469, 4472, 4473, 4474, 4476, 4477, 4478, 4480, 4481, 4482, 4483, 4484, 4485, 4487, 4489, 4492, 4493, 4494, 4495, 4497, 4498, 4499, 4500, 4501, 4502, 4503, 4504, 4505, 4506, 4507, 4511, 4513, 4514, 4515, 4516, 4517, 4521, 4522, 4526, 4527, 4528, 4530, 4532, 4533, 4534, 4535, 4536, 4537, 4538, 4540, 4541, 4542, 4543, 4544, 4545, 4546, 4553, 4554, 4555, 4556, 4557, 4558, 4559, 4560, 4561, 4562, 4563, 4564, 4570, 4571, 4573, 4574, 4575, 4576, 4577, 4578, 4579, 4580, 4581, 4582, 4583, 4584, 4585, 4586, 4587, 4588, 4592, 4593, 4594, 4595, 4596, 4597, 4598, 4599, 4600, 4605, 4606, 4609, 4610, 4611, 4612, 4613, 4614, 4615, 4616, 4617, 4618, 4619, 4620, 4621, 4622, 4624, 4625, 4626, 4627, 4636, 4637, 4638, 4639, 4640, 4641, 4643, 4646, 4647, 4648, 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, 4728, 4729, 4730, 4731, 4732, 4733, 4734, 4735, 4736, 4737, 4738, 4739, 4740, 4741, 4742, 4743, 4744, 4745, 4746, 4747, 4748, 4749, 4750, 4751, 4756, 4757, 4758, 4764, 4777, 4781, 4782, 4783, 4784, 4785, 4786, 4787, 4788, 4789, 4790, 4791, 4792, 4793, 4794, 4795, 4796, 4798, 4799, 4800, 4801, 4802, 4804, 4805, 4806, 4807, 4808, 4809, 4810, 4813, 4814, 4816, 4817, 4818, 4821, 4822, 4823, 4824, 4825, 4826, 4827, 4828, 4829, 4830, 4831, 4832, 4833, 4834, 4835, 4836, 4837, 4838, 4839, 4840, 4841, 4842, 4843, 4844, 4845, 4846, 4847, 4849, 4850, 4851, 4852, 4853, 4854, 4855, 4856, 4857, 4858, 4859, 4860, 4861, 4862, 4863, 4864, 4865, 4866, 4867, 4868, 4869, 4870, 4871, 4872, 4873, 4874, 4875, 4876, 4877, 4878, 4879, 4880, 4882, 4883, 4884, 4886, 4888, 4890, 4891, 4892, 4893, 4896, 4898, 4899, 4900, 4901, 4903, 4904, 4905, 4906, 4907, 4908, 4909, 4910, 4913, 4917, 4918, 4922, 4923, 4924, 4925, 4926, 4928, 4929) } - internal val templates: IntArray by lazy { intArrayOf(2369, 2848, 2660, 2659, 2658, 2880, 2902, 3382, 2623, 418, 2793, 2791, 2687, 2378, 2384, 2795, 2892, 2607, 2606, 285, 2336, 2797, 2904, 3232, 4184, 2546, 4927, 2596, 2050, 2374, 3716, 2115, 2723, 2379, 3233, 1336, 4204, 4224, 3715, 2564, 2721, 1867, 4199, 2126, 2167, 2173, 4566, 283, 2116, 4508, 3394, 3415, 2073, 2347, 3712, 452, 2755, 2787, 2788, 3395, 3711, 2756, 3643, 609, 1711, 3720, 1868, 2731, 3723, 2737, 3386, 616, 617, 2773, 3084, 3698, 1659, 2790, 3642, 303, 614, 69, 711, 621, 2346, 4222, 1121, 2488, 3465, 3838, 1242, 2202, 2575, 3387, 2165, 3727, 714, 1763, 1964, 2743, 2752, 2963, 4229, 3389, 3401, 136, 594, 596, 2563, 2718, 1865, 4217, 3035, 610, 2289, 2586, 3875, 1302, 4216, 3511, 3648, 3649, 158, 2080, 2082, 2117, 2843, 4365, 2171, 2373, 2516, 3637, 214, 284, 1276, 2014, 4797, 3506, 3515, 3516, 67, 83, 218, 619, 4602, 3535, 1360, 4311, 3360, 3725, 726, 1023, 1372, 2387, 2479, 2741, 4367, 89, 2386, 2401, 2916, 624, 1657, 1954, 2830, 4496, 3408, 1577, 2101, 2293, 2577, 4548, 3403, 3469, 3519, 650, 1888, 3930, 3168, 3510, 3556, 3620, 3839, 1317, 1866, 2045, 2425, 2712, 3858, 4567, 3422, 3468, 1841, 1863, 3357, 593, 1292, 1346, 1371, 1953, 3497, 3699, 221, 1701, 2744, 2941, 3086, 3154, 3443, 258, 591, 1026, 1379, 1965, 1989, 4137, 3440, 3566, 655, 1342, 1717, 2051, 3162, 3361, 3622, 3641, 710, 1283, 1370, 1382, 1658, 1732, 1895, 2375, 2478, 2576, 3945, 4223, 4433, 3421, 3489, 3635, 649, 699, 1044, 2612, 3180, 3299, 3702, 108, 184, 606, 721, 1081, 1969, 2049, 2111, 2169, 2411, 2492, 2748, 2784, 2828, 3950, 4479, 4820, 3381, 3452, 3613, 160, 623, 701, 1332, 1333, 1345, 1520, 1660, 2166, 2170, 2263, 2410, 2638, 4192, 4509, 3117, 3209, 3256, 3334, 3548, 3703, 3713, 703, 1183, 1572, 1897, 2258, 2261, 2491, 2749, 2769, 2770, 2938, 2939, 3960, 3980, 4213, 4470, 4803, 4819, 3621, 3638, 3744, 1378, 1492, 1584, 1703, 1955, 2431, 2443, 2768, 4156, 4214, 4510, 4601, 3083, 3085, 3100, 3618, 3631, 3797, 723, 1024, 1832, 2138, 2203, 2421, 2764, 2765, 3965, 4211, 4287, 4298, 3287, 3407, 91, 93, 595, 715, 1027, 1350, 1355, 2020, 2333, 2426, 2711, 2763, 2767, 3927, 4549, 4881, 3014, 3015, 3517, 3581, 3724, 94, 1251, 1259, 1353, 1377, 1519, 1583, 1880, 2186, 2218, 2471, 2489, 2739, 3867, 3868, 4210, 4376, 4439, 4885, 3333, 3372, 3373, 3451, 3607, 299, 599, 618, 700, 1109, 1117, 1175, 1367, 1518, 1626, 1948, 2130, 2136, 2154, 2221, 2441, 2446, 2448, 2671, 2704, 2762, 2940, 2957, 2958, 4181, 4207, 4324, 3016, 3170, 3547, 3580, 3749, 211, 585, 590, 605, 717, 720, 906, 990, 1084, 1159, 1334, 1470, 1524, 1705, 1886, 1906, 1926, 1961, 1991, 2072, 2316, 2424, 2490, 2945, 3894, 3946, 4164, 4550, 4568, 4569, 4768, 4930, 3077, 3433, 3628, 3629, 92, 96, 269, 603, 648, 712, 980, 1331, 1707, 1887, 1944, 2114, 2419, 2445, 2447, 2450, 2539, 2677, 2713, 2895, 2907, 4255, 4552, 4780, 2990, 3255, 3288, 3368, 3466, 3585, 3619, 208, 277, 316, 329, 330, 1287, 1352, 1376, 1521, 1522, 1949, 2019, 2044, 2113, 2220, 2248, 2299, 2413, 2428, 2440, 2714, 2717, 2798, 2799, 3865, 4565, 4763, 3012, 3400, 3404, 3453, 3509, 3664, 3701, 3754, 6, 244, 304, 600, 604, 1047, 1221, 1286, 1354, 1359, 1708, 1709, 1884, 1957, 1960, 2018, 2021, 2152, 2187, 2235, 2412, 2420, 2640, 2746, 2785, 2862, 3862, 3863, 3923, 4180, 4766, 4778, 4779, 3450, 3572, 3579, 3584, 3646, 3654, 268, 318, 322, 331, 583, 707, 722, 1076, 1160, 1164, 1284, 1285, 1312, 1517, 1710, 1828, 1889, 2009, 2222, 2228, 2383, 2409, 2415, 2442, 2574, 2675, 3928, 4153, 4206, 4269, 4368, 4438, 4649, 4767, 3063, 3148, 3513, 3514, 3612, 3645, 65, 210, 274, 587, 608, 613, 708, 713, 984, 1075, 1167, 1369, 1713, 1743, 1829, 1834, 1849, 1885, 2048, 2081, 2278, 2296, 2305, 2408, 2462, 2474, 2766, 4191, 3043, 3393, 3578, 3647, 3655, 3700, 90, 207, 288, 320, 323, 324, 349, 597, 607, 709, 855, 905, 1166, 1169, 1252, 1437, 1890, 2005, 2015, 2414, 2423, 2467, 2745, 2783, 2937, 2951, 3900, 4811, 4812, 4815, 4911, 3017, 3048, 3101, 3171, 3229, 3242, 3243, 3406, 3554, 3555, 3627, 3650, 3657, 3708, 110, 186, 190, 191, 212, 321, 327, 328, 352, 375, 580, 582, 589, 625, 727, 851, 977, 1077, 1118, 1147, 1243, 1304, 1314, 1746, 1830, 1831, 1839, 1950, 1951, 1952, 2041, 2254, 2256, 2285, 2297, 2298, 2320, 2382, 2416, 2417, 2473, 2579, 2580, 2663, 2678, 2710, 2715, 2716, 2753, 2800, 2801, 3846, 3864, 3910, 3964, 4209, 4303, 4321, 4339, 4366, 4436, 4471, 4523, 4547, 4608, 4848, 4931, 3050, 3152, 3176, 3190, 3211, 3392, 3405, 3549, 3553, 3583, 3611, 3742, 3752, 3753, 3765, 3767, 3774, 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, 1649, 1693, 1704, 1850, 1881, 1947, 1993, 2006, 2027, 2250, 2255, 2308, 2314, 2315, 2322, 2427, 2613, 2649, 2823, 3911, 3919, 3949, 3966, 4133, 4168, 4182, 4230, 4270, 4322, 4361, 4524, 4551, 3073, 3119, 3195, 3196, 3201, 3259, 3543, 154, 259, 261, 347, 350, 353, 579, 602, 612, 702, 706, 982, 1078, 1381, 1593, 1833, 1925, 1987, 1990, 2306, 2319, 2385, 2432, 2578, 2626, 2868, 3869, 3916, 3982, 4149, 4520, 4607, 3449, 3542, 3544, 3552, 3571, 3582, 3750, 3771, 3791, 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, 1688, 1689, 1691, 1726, 1851, 1891, 2233, 2311, 2321, 2422, 2444, 2452, 2959, 4135, 4165, 4166, 4256, 4281, 4319, 4434, 4490, 4531, 4887, 4912) } - 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"), 1572 to arrayOf("why"), 1577 to arrayOf("e"), 1583 to arrayOf("max"), 1584 to arrayOf("secs", "max", "mib"), 1593 to arrayOf("path"), 1626 to arrayOf("secs"), 1649 to arrayOf("pct", "scope"), 1657 to arrayOf("n"), 1658 to arrayOf("n"), 1659 to arrayOf("n"), 1660 to arrayOf("n"), 1688 to arrayOf("d", "h"), 1689 to arrayOf("h", "m"), 1690 to arrayOf("m"), 1691 to arrayOf("window", "pct"), 1693 to arrayOf("when"), 1695 to arrayOf("label", "e"), 1697 to arrayOf("from", "to", "total"), 1701 to arrayOf("messages", "lines", "left"), 1703 to arrayOf("pct", "view", "max"), 1704 to arrayOf("pct"), 1705 to arrayOf("done", "total"), 1707 to arrayOf("n"), 1708 to arrayOf("n"), 1709 to arrayOf("time"), 1710 to arrayOf("view", "max"), 1711 to arrayOf("view", "max"), 1713 to arrayOf("more"), 1717 to arrayOf("n"), 1726 to arrayOf("n"), 1732 to arrayOf("page"), 1743 to arrayOf("title"), 1746 to arrayOf("n"), 1763 to arrayOf("name"), 1828 to arrayOf("line"), 1829 to arrayOf("quote"), 1830 to arrayOf("n"), 1831 to arrayOf("n"), 1832 to arrayOf("n"), 1833 to arrayOf("n"), 1834 to arrayOf("n"), 1839 to arrayOf("held"), 1840 to arrayOf("machine"), 1841 to arrayOf("machine"), 1849 to arrayOf("count", "total"), 1850 to arrayOf("count"), 1851 to arrayOf("n"), 1863 to arrayOf("name"), 1865 to arrayOf("n", "c", "total"), 1866 to arrayOf("n", "c"), 1867 to arrayOf("n", "c", "total", "before"), 1868 to arrayOf("n", "c", "before"), 1880 to arrayOf("name"), 1881 to arrayOf("path"), 1884 to arrayOf("file"), 1885 to arrayOf("path", "n"), 1886 to arrayOf("why"), 1887 to arrayOf("n"), 1888 to arrayOf("name"), 1889 to arrayOf("name"), 1890 to arrayOf("name"), 1891 to arrayOf("n"), 1892 to arrayOf("shown", "n"), 1895 to arrayOf("path"), 1897 to arrayOf("n"), 1906 to arrayOf("status"), 1923 to arrayOf("name", "pct"), 1924 to arrayOf("name", "mb"), 1925 to arrayOf("name"), 1926 to arrayOf("name", "why"), 1944 to arrayOf("machine"), 1947 to arrayOf("n"), 1948 to arrayOf("ref"), 1949 to arrayOf("ref", "sheet"), 1950 to arrayOf("name"), 1951 to arrayOf("name"), 1952 to arrayOf("file", "folder"), 1953 to arrayOf("name", "error"), 1954 to arrayOf("name", "status"), 1955 to arrayOf("name", "error"), 1957 to arrayOf("name"), 1960 to arrayOf("code"), 1961 to arrayOf("error"), 1964 to arrayOf("error"), 1965 to arrayOf("error"), 1969 to arrayOf("error"), 1987 to arrayOf("done", "of"), 1989 to arrayOf("why"), 1990 to arrayOf("path"), 1991 to arrayOf("error"), 1992 to arrayOf("secs"), 1993 to arrayOf("secs"), 2005 to arrayOf("code"), 2006 to arrayOf("code"), 2009 to arrayOf("state"), 2014 to arrayOf("hide", "copy", "paste"), 2015 to arrayOf("n"), 2018 to arrayOf("name"), 2019 to arrayOf("name", "folder"), 2020 to arrayOf("name"), 2021 to arrayOf("name", "percent"), 2027 to arrayOf("folder"), 2037 to arrayOf("w", "h"), 2041 to arrayOf("path"), 2044 to arrayOf("why"), 2045 to arrayOf("mb"), 2048 to arrayOf("n"), 2049 to arrayOf("delete", "undo"), 2050 to arrayOf("delete", "undo"), 2051 to arrayOf("undo"), 2072 to arrayOf("what", "secs"), 2073 to arrayOf("file", "holder"), 2080 to arrayOf("what"), 2081 to arrayOf("what"), 2082 to arrayOf("editor", "why"), 2101 to arrayOf("files"), 2111 to arrayOf("why"), 2113 to arrayOf("title"), 2114 to arrayOf("title"), 2115 to arrayOf("version"), 2116 to arrayOf("version", "size", "folder"), 2117 to arrayOf("version", "size", "folder"), 2126 to arrayOf("title"), 2130 to arrayOf("dir", "files"), 2136 to arrayOf("why"), 2138 to arrayOf("code"), 2152 to arrayOf("origin"), 2154 to arrayOf("why"), 2165 to arrayOf("dir"), 2166 to arrayOf("path"), 2167 to arrayOf("home", "other"), 2169 to arrayOf("path"), 2170 to arrayOf("code", "log"), 2171 to arrayOf("log"), 2173 to arrayOf("addr"), 2186 to arrayOf("home"), 2187 to arrayOf("addr"), 2202 to arrayOf("dir", "why"), 2203 to arrayOf("dir"), 2218 to arrayOf("phase"), 2220 to arrayOf("why"), 2221 to arrayOf("what"), 2222 to arrayOf("code"), 2228 to arrayOf("label"), 2233 to arrayOf("kind"), 2235 to arrayOf("project"), 2248 to arrayOf("what"), 2250 to arrayOf("when"), 2254 to arrayOf("n"), 2255 to arrayOf("n"), 2256 to arrayOf("n"), 2258 to arrayOf("agent"), 2259 to arrayOf("effort"), 2261 to arrayOf("n"), 2263 to arrayOf("model"), 2278 to arrayOf("word"), 2285 to arrayOf("more", "step"), 2289 to arrayOf("name"), 2293 to arrayOf("max", "skipped"), 2296 to arrayOf("name"), 2297 to arrayOf("n"), 2298 to arrayOf("name"), 2299 to arrayOf("name"), 2305 to arrayOf("n"), 2306 to arrayOf("name"), 2308 to arrayOf("price"), 2311 to arrayOf("name"), 2313 to arrayOf("name"), 2314 to arrayOf("name"), 2315 to arrayOf("name"), 2316 to arrayOf("text"), 2319 to arrayOf("key"), 2320 to arrayOf("key"), 2321 to arrayOf("pct"), 2322 to arrayOf("when"), 2333 to arrayOf("n", "upstream"), 2336 to arrayOf("mb"), 2346 to arrayOf("path"), 2347 to arrayOf("path"), 2369 to arrayOf("id"), 2373 to arrayOf("model"), 2374 to arrayOf("platform"), 2375 to arrayOf("version"), 2378 to arrayOf("version", "from", "into"), 2379 to arrayOf("version", "from"), 2382 to arrayOf("version", "path"), 2383 to arrayOf("version", "path"), 2384 to arrayOf("version", "pin", "from"), 2385 to arrayOf("path"), 2386 to arrayOf("version", "path"), 2387 to arrayOf("version", "path", "set"), 2401 to arrayOf("turns", "input", "cread", "cwrite", "output", "cost"), 2408 to arrayOf("tool"), 2409 to arrayOf("tool"), 2410 to arrayOf("tool", "word"), 2411 to arrayOf("tool", "word"), 2412 to arrayOf("tool"), 2413 to arrayOf("tool"), 2414 to arrayOf("due"), 2415 to arrayOf("due"), 2416 to arrayOf("due"), 2417 to arrayOf("due"), 2418 to arrayOf("zone"), 2419 to arrayOf("zone"), 2420 to arrayOf("zone"), 2421 to arrayOf("zone"), 2422 to arrayOf("n"), 2423 to arrayOf("who"), 2424 to arrayOf("n", "who"), 2425 to arrayOf("harness"), 2426 to arrayOf("path"), 2427 to arrayOf("path"), 2428 to arrayOf("path"), 2431 to arrayOf("error", "line"), 2432 to arrayOf("label"), 2440 to arrayOf("who"), 2441 to arrayOf("who"), 2442 to arrayOf("label", "left", "when"), 2443 to arrayOf("left"), 2444 to arrayOf("name", "left"), 2445 to arrayOf("used"), 2446 to arrayOf("used", "limit"), 2447 to arrayOf("used", "reason"), 2448 to arrayOf("used", "limit", "reason"), 2450 to arrayOf("provider"), 2451 to arrayOf("used", "window", "pct"), 2452 to arrayOf("rate"), 2462 to arrayOf("n", "r"), 2467 to arrayOf("time", "n"), 2471 to arrayOf("n", "m"), 2473 to arrayOf("pct"), 2474 to arrayOf("cost", "n"), 2478 to arrayOf("in", "out", "cread", "cwrite"), 2479 to arrayOf("in", "out", "cread", "cwrite", "n"), 2488 to arrayOf("turns", "input", "cread", "cwrite", "output"), 2489 to arrayOf("left", "when"), 2490 to arrayOf("left", "when"), 2491 to arrayOf("left", "when"), 2492 to arrayOf("left", "when"), 2516 to arrayOf("n"), 2539 to arrayOf("when"), 2546 to arrayOf("phrase", "now"), 2557 to arrayOf("s"), 2563 to arrayOf("now"), 2564 to arrayOf("now", "nudge", "sent", "undone"), 2574 to arrayOf("e"), 2575 to arrayOf("a", "ams", "b", "bms"), 2576 to arrayOf("ms"), 2577 to arrayOf("e"), 2578 to arrayOf("t"), 2579 to arrayOf("t"), 2580 to arrayOf("t"), 2586 to arrayOf("why"), 2596 to arrayOf("apps"), 2606 to arrayOf("n"), 2607 to arrayOf("n", "k"), 2612 to arrayOf("stt", "conf"), 2613 to arrayOf("words"), 2623 to arrayOf("into"), 2626 to arrayOf("origin"), 2638 to arrayOf("url"), 2640 to arrayOf("url"), 2648 to arrayOf("i", "n"), 2649 to arrayOf("d", "n"), 2658 to arrayOf("version"), 2659 to arrayOf("version"), 2660 to arrayOf("version"), 2663 to arrayOf("path"), 2671 to arrayOf("addr"), 2675 to arrayOf("label"), 2677 to arrayOf("label"), 2678 to arrayOf("label"), 2682 to arrayOf("label"), 2687 to arrayOf("from"), 2704 to arrayOf("done", "of"), 2710 to arrayOf("n"), 2711 to arrayOf("t", "m"), 2712 to arrayOf("m"), 2713 to arrayOf("b", "m"), 2714 to arrayOf("r", "p"), 2715 to arrayOf("n"), 2716 to arrayOf("n"), 2717 to arrayOf("n"), 2718 to arrayOf("n"), 2721 to arrayOf("n"), 2723 to arrayOf("n"), 2731 to arrayOf("n"), 2737 to arrayOf("name", "gb", "path"), 2739 to arrayOf("path", "why"), 2741 to arrayOf("names"), 2743 to arrayOf("why"), 2744 to arrayOf("p", "pn", "t", "tn", "e", "en"), 2745 to arrayOf("done", "total"), 2746 to arrayOf("n"), 2747 to arrayOf("what"), 2748 to arrayOf("n"), 2749 to arrayOf("n"), 2752 to arrayOf("what"), 2753 to arrayOf("n"), 2755 to arrayOf("why", "from"), 2756 to arrayOf("why"), 2762 to arrayOf("path"), 2763 to arrayOf("path", "who"), 2764 to arrayOf("path"), 2765 to arrayOf("path", "cmd"), 2766 to arrayOf("version", "path"), 2767 to arrayOf("version", "path"), 2768 to arrayOf("version", "path", "who"), 2769 to arrayOf("version", "path"), 2770 to arrayOf("version", "path", "cmd"), 2773 to arrayOf("cmd"), 2783 to arrayOf("name", "version", "path"), 2784 to arrayOf("path", "why"), 2785 to arrayOf("name"), 2787 to arrayOf("version", "cli"), 2788 to arrayOf("cli"), 2790 to arrayOf("version"), 2791 to arrayOf("version"), 2793 to arrayOf("version"), 2795 to arrayOf("version"), 2797 to arrayOf("computer"), 2798 to arrayOf("version", "cli"), 2799 to arrayOf("cli"), 2800 to arrayOf("version", "cli"), 2801 to arrayOf("cli"), 2823 to arrayOf("n"), 2828 to arrayOf("code"), 2830 to arrayOf("e"), 2843 to arrayOf("n"), 2848 to arrayOf("channel"), 2862 to arrayOf("project"), 2868 to arrayOf("n"), 2880 to arrayOf("m"), 2892 to arrayOf("m"), 2895 to arrayOf("m"), 2902 to arrayOf("pages"), 2904 to arrayOf("name"), 2907 to arrayOf("name"), 2916 to arrayOf("d", "n"), 2937 to arrayOf("n", "tools"), 2938 to arrayOf("n", "tools", "d"), 2939 to arrayOf("n", "d"), 2940 to arrayOf("n", "what"), 2941 to arrayOf("n", "d", "what"), 2945 to arrayOf("head"), 2951 to arrayOf("name", "path"), 2957 to arrayOf("page", "net", "near"), 2958 to arrayOf("page", "what"), 2959 to arrayOf("ref"), 2963 to arrayOf("page"), 2986 to arrayOf("n"), 2987 to arrayOf("n"), 2988 to arrayOf("n"), 2990 to arrayOf("hub"), 3012 to arrayOf("project"), 3014 to arrayOf("n"), 3015 to arrayOf("n"), 3016 to arrayOf("word"), 3017 to arrayOf("n"), 3035 to arrayOf("name"), 3043 to arrayOf("answer"), 3048 to arrayOf("why"), 3050 to arrayOf("hub"), 3056 to arrayOf("from", "to"), 3063 to arrayOf("project"), 3073 to arrayOf("name"), 3077 to arrayOf("n"), 3083 to arrayOf("code"), 3084 to arrayOf("hub"), 3085 to arrayOf("hub"), 3086 to arrayOf("hub"), 3100 to arrayOf("n"), 3101 to arrayOf("n"), 3117 to arrayOf("status"), 3119 to arrayOf("status"), 3148 to arrayOf("project"), 3152 to arrayOf("code"), 3154 to arrayOf("why"), 3162 to arrayOf("title"), 3168 to arrayOf("title"), 3170 to arrayOf("q"), 3171 to arrayOf("title"), 3176 to arrayOf("room"), 3180 to arrayOf("q"), 3190 to arrayOf("title"), 3195 to arrayOf("n"), 3196 to arrayOf("n"), 3201 to arrayOf("at"), 3209 to arrayOf("size"), 3211 to arrayOf("n", "total"), 3228 to arrayOf("n"), 3229 to arrayOf("what"), 3232 to arrayOf("device"), 3233 to arrayOf("device"), 3242 to arrayOf("word", "count"), 3243 to arrayOf("heard"), 3255 to arrayOf("files"), 3256 to arrayOf("files"), 3259 to arrayOf("name"), 3287 to arrayOf("n"), 3288 to arrayOf("n"), 3299 to arrayOf("n"), 3333 to arrayOf("root"), 3334 to arrayOf("path"), 3357 to arrayOf("name"), 3360 to arrayOf("until"), 3361 to arrayOf("error"), 3368 to arrayOf("url"), 3372 to arrayOf("name"), 3373 to arrayOf("name"), 3381 to arrayOf("code", "hub", "until"), 3382 to arrayOf("url"), 3386 to arrayOf("kinds"), 3387 to arrayOf("address"), 3389 to arrayOf("address"), 3392 to arrayOf("url"), 3393 to arrayOf("url"), 3394 to arrayOf("url"), 3395 to arrayOf("url", "via"), 3400 to arrayOf("name"), 3401 to arrayOf("url", "check", "left"), 3403 to arrayOf("check"), 3404 to arrayOf("address"), 3405 to arrayOf("name"), 3406 to arrayOf("error"), 3407 to arrayOf("url"), 3408 to arrayOf("url"), 3415 to arrayOf("code", "address", "left"), 3421 to arrayOf("name"), 3422 to arrayOf("name"), 3433 to arrayOf("address"), 3440 to arrayOf("code", "body"), 3443 to arrayOf("code", "body"), 3449 to arrayOf("window", "used"), 3450 to arrayOf("window", "used", "when"), 3451 to arrayOf("window", "used"), 3452 to arrayOf("window", "used", "when"), 3453 to arrayOf("provider"), 3465 to arrayOf("label"), 3466 to arrayOf("when"), 3468 to arrayOf("provider"), 3469 to arrayOf("provider", "title", "why"), 3489 to arrayOf("reason"), 3497 to arrayOf("code"), 3506 to arrayOf("name"), 3509 to arrayOf("version"), 3510 to arrayOf("version"), 3511 to arrayOf("version"), 3513 to arrayOf("version"), 3514 to arrayOf("version"), 3515 to arrayOf("version"), 3516 to arrayOf("version", "why"), 3517 to arrayOf("version"), 3519 to arrayOf("code"), 3535 to arrayOf("name"), 3542 to arrayOf("count"), 3543 to arrayOf("title"), 3544 to arrayOf("name"), 3547 to arrayOf("n", "holder"), 3548 to arrayOf("n", "title"), 3549 to arrayOf("title"), 3552 to arrayOf("n"), 3553 to arrayOf("n"), 3554 to arrayOf("n"), 3555 to arrayOf("n"), 3556 to arrayOf("harness", "typed", "type", "remote", "host", "wt", "branch"), 3566 to arrayOf("pid"), 3571 to arrayOf("left"), 3572 to arrayOf("left"), 3578 to arrayOf("left"), 3579 to arrayOf("left"), 3580 to arrayOf("left"), 3581 to arrayOf("left"), 3582 to arrayOf("label", "left"), 3583 to arrayOf("when"), 3584 to arrayOf("used"), 3585 to arrayOf("used", "limit"), 3607 to arrayOf("tracking"), 3611 to arrayOf("total"), 3612 to arrayOf("price"), 3613 to arrayOf("price"), 3618 to arrayOf("n"), 3619 to arrayOf("parts"), 3620 to arrayOf("note"), 3621 to arrayOf("error"), 3622 to arrayOf("error", "parts"), 3627 to arrayOf("state"), 3628 to arrayOf("name", "path"), 3629 to arrayOf("name", "path", "why"), 3631 to arrayOf("code"), 3635 to arrayOf("detail"), 3637 to arrayOf("why"), 3638 to arrayOf("parts"), 3641 to arrayOf("build", "to"), 3642 to arrayOf("build"), 3643 to arrayOf("build", "skip"), 3645 to arrayOf("why"), 3646 to arrayOf("why"), 3647 to arrayOf("build"), 3648 to arrayOf("build", "why"), 3649 to arrayOf("build"), 3650 to arrayOf("build"), 3654 to arrayOf("build"), 3655 to arrayOf("build"), 3657 to arrayOf("build"), 3664 to arrayOf("build"), 3698 to arrayOf("step"), 3699 to arrayOf("p", "pt", "t", "tt", "e", "et"), 3700 to arrayOf("done", "total"), 3701 to arrayOf("n"), 3702 to arrayOf("n"), 3703 to arrayOf("n"), 3708 to arrayOf("n"), 3711 to arrayOf("why"), 3712 to arrayOf("why", "from"), 3713 to arrayOf("error"), 3715 to arrayOf("n"), 3716 to arrayOf("n"), 3720 to arrayOf("n"), 3723 to arrayOf("name", "gb", "path"), 3724 to arrayOf("path", "why"), 3725 to arrayOf("names"), 3727 to arrayOf("why"), 3738 to arrayOf("n", "total"), 3742 to arrayOf("title"), 3744 to arrayOf("n"), 3748 to arrayOf("name"), 3749 to arrayOf("title"), 3750 to arrayOf("note"), 3752 to arrayOf("machine"), 3753 to arrayOf("machines"), 3754 to arrayOf("machine"), 3765 to arrayOf("n"), 3767 to arrayOf("n"), 3771 to arrayOf("name"), 3774 to arrayOf("name"), 3791 to arrayOf("why"), 3797 to arrayOf("project"), 3838 to arrayOf("path"), 3839 to arrayOf("path"), 3841 to arrayOf("have", "total"), 3846 to arrayOf("n"), 3855 to arrayOf("hub"), 3858 to arrayOf("title"), 3862 to arrayOf("project"), 3863 to arrayOf("project"), 3864 to arrayOf("n"), 3865 to arrayOf("hub"), 3867 to arrayOf("n"), 3868 to arrayOf("n"), 3869 to arrayOf("model"), 3875 to arrayOf("name"), 3894 to arrayOf("word"), 3900 to arrayOf("answer"), 3910 to arrayOf("version", "build"), 3911 to arrayOf("hub"), 3916 to arrayOf("name"), 3919 to arrayOf("when", "who", "mark"), 3923 to arrayOf("who"), 3927 to arrayOf("time"), 3928 to arrayOf("address"), 3930 to arrayOf("kind", "name"), 3945 to arrayOf("title"), 3946 to arrayOf("query"), 3949 to arrayOf("room"), 3950 to arrayOf("query"), 3952 to arrayOf("n"), 3953 to arrayOf("n"), 3954 to arrayOf("n"), 3960 to arrayOf("size"), 3964 to arrayOf("n"), 3965 to arrayOf("n"), 3966 to arrayOf("n"), 3980 to arrayOf("status"), 3982 to arrayOf("status"), 4133 to arrayOf("code"), 4135 to arrayOf("n"), 4137 to arrayOf("why"), 4149 to arrayOf("done", "of"), 4153 to arrayOf("thread"), 4156 to arrayOf("n"), 4164 to arrayOf("title"), 4165 to arrayOf("note"), 4166 to arrayOf("label"), 4167 to arrayOf("machine"), 4168 to arrayOf("machine"), 4175 to arrayOf("at", "total"), 4176 to arrayOf("at", "total"), 4180 to arrayOf("machine"), 4181 to arrayOf("machine"), 4182 to arrayOf("machines"), 4184 to arrayOf("device"), 4191 to arrayOf("price"), 4192 to arrayOf("price"), 4199 to arrayOf("home"), 4204 to arrayOf("from"), 4206 to arrayOf("note"), 4207 to arrayOf("note"), 4209 to arrayOf("v"), 4210 to arrayOf("v"), 4211 to arrayOf("v", "who"), 4213 to arrayOf("who"), 4214 to arrayOf("v"), 4216 to arrayOf("v", "cmd"), 4217 to arrayOf("cmd"), 4222 to arrayOf("v", "path"), 4223 to arrayOf("v", "note"), 4224 to arrayOf("v"), 4229 to arrayOf("tool"), 4230 to arrayOf("tool"), 4255 to arrayOf("n", "w"), 4256 to arrayOf("why"), 4257 to arrayOf("state", "why"), 4269 to arrayOf("project"), 4270 to arrayOf("n"), 4281 to arrayOf("why"), 4287 to arrayOf("name"), 4298 to arrayOf("project"), 4303 to arrayOf("n"), 4311 to arrayOf("names"), 4319 to arrayOf("dest"), 4321 to arrayOf("repo"), 4322 to arrayOf("repo"), 4324 to arrayOf("url"), 4339 to arrayOf("time"), 4361 to arrayOf("group"), 4365 to arrayOf("project"), 4366 to arrayOf("n"), 4367 to arrayOf("n"), 4368 to arrayOf("n"), 4376 to arrayOf("n"), 4433 to arrayOf("n"), 4434 to arrayOf("n"), 4435 to arrayOf("a", "b"), 4436 to arrayOf("n"), 4438 to arrayOf("parts", "lines"), 4439 to arrayOf("n"), 4470 to arrayOf("what", "project", "fab"), 4471 to arrayOf("rev", "day"), 4479 to arrayOf("n"), 4490 to arrayOf("layer"), 4491 to arrayOf("n"), 4496 to arrayOf("board"), 4508 to arrayOf("others"), 4509 to arrayOf("must", "should", "notes"), 4510 to arrayOf("id", "w"), 4520 to arrayOf("what"), 4523 to arrayOf("why"), 4524 to arrayOf("why"), 4531 to arrayOf("n"), 4547 to arrayOf("price", "n"), 4548 to arrayOf("n", "need"), 4549 to arrayOf("n"), 4550 to arrayOf("n"), 4551 to arrayOf("cost"), 4552 to arrayOf("cost"), 4565 to arrayOf("day", "n"), 4566 to arrayOf("day"), 4567 to arrayOf("cost", "n", "lines"), 4568 to arrayOf("stock", "price"), 4569 to arrayOf("lines"), 4590 to arrayOf("host"), 4601 to arrayOf("n"), 4602 to arrayOf("a", "b"), 4603 to arrayOf("n"), 4604 to arrayOf("n"), 4607 to arrayOf("day"), 4608 to arrayOf("n"), 4649 to arrayOf("turn"), 4763 to arrayOf("text"), 4766 to arrayOf("repo", "dest"), 4767 to arrayOf("repo", "dest"), 4768 to arrayOf("repo"), 4773 to arrayOf("dir"), 4774 to arrayOf("dir"), 4778 to arrayOf("editor", "job", "secs"), 4779 to arrayOf("editor", "secs"), 4780 to arrayOf("editor"), 4797 to arrayOf("time"), 4803 to arrayOf("status"), 4811 to arrayOf("time"), 4812 to arrayOf("time", "dur"), 4815 to arrayOf("answer"), 4819 to arrayOf("type"), 4820 to arrayOf("max"), 4848 to arrayOf("bytes", "tokens"), 4881 to arrayOf("what"), 4885 to arrayOf("n"), 4887 to arrayOf("n"), 4911 to arrayOf("n"), 4912 to arrayOf("done", "total"), 4920 to arrayOf("v"), 4921 to arrayOf("x", "y"), 4927 to arrayOf("machine"), 4930 to arrayOf("days"), 4931 to arrayOf("warnings")) } + 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, 3163, 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, 3731, 61, 62, 63, 64, 66, 68, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 84, 85, 3770, 87, 88, 98, 99, 3092, 3769, 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, 3212, 165, 166, 3214, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 3173, 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, 2979, 237, 238, 239, 240, 3730, 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, 3184, 305, 306, 307, 308, 309, 310, 311, 313, 314, 315, 317, 319, 333, 3778, 336, 3777, 3780, 340, 3790, 342, 343, 344, 345, 354, 3161, 357, 358, 359, 360, 361, 362, 363, 364, 365, 366, 367, 368, 369, 370, 371, 372, 373, 2982, 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, 2974, 2975, 432, 433, 434, 435, 436, 437, 438, 439, 440, 441, 442, 443, 444, 445, 446, 447, 448, 449, 450, 451, 453, 454, 455, 3191, 457, 458, 459, 460, 461, 2964, 463, 464, 465, 3094, 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, 3199, 3200, 636, 637, 638, 639, 640, 641, 642, 643, 644, 645, 646, 647, 651, 652, 3843, 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, 3775, 734, 735, 736, 737, 3198, 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, 3758, 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, 3194, 850, 852, 853, 854, 857, 858, 859, 860, 861, 862, 863, 864, 865, 866, 867, 3768, 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, 3845, 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, 3164, 964, 965, 966, 967, 968, 969, 3793, 971, 3019, 3076, 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, 3796, 1020, 1021, 1022, 1025, 1029, 1030, 1031, 2971, 3045, 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, 3810, 1094, 1095, 1098, 1099, 1100, 3193, 1102, 1103, 1104, 1105, 1106, 1107, 1108, 1110, 1111, 1112, 1113, 1114, 1115, 1116, 3795, 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, 2973, 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, 3508, 1361, 1362, 1363, 1364, 1365, 1366, 3575, 1373, 1375, 1380, 1384, 1385, 3049, 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, 2976, 1417, 1418, 1419, 1420, 1421, 1422, 1423, 1424, 1425, 1426, 1427, 1428, 1429, 1430, 1431, 1432, 1433, 3093, 3586, 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, 3588, 1473, 1474, 1475, 1477, 1478, 1479, 1480, 1481, 1482, 1483, 1484, 1485, 1486, 1487, 1488, 1489, 1490, 1493, 1494, 3733, 1496, 1497, 1498, 3745, 3751, 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, 1567, 1568, 1569, 1570, 1571, 1573, 1574, 1575, 1576, 1578, 1579, 1580, 1581, 1582, 1585, 1586, 1587, 1588, 1589, 1590, 1591, 1592, 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, 1621, 1622, 1623, 1624, 1625, 1627, 1628, 1629, 1630, 1631, 1632, 1633, 1634, 3052, 1636, 1637, 1638, 1639, 1640, 1641, 1642, 1643, 1644, 1645, 1646, 1647, 1648, 1650, 1651, 1652, 1653, 1654, 1655, 1656, 1661, 1662, 1663, 1664, 1665, 1666, 1667, 1668, 3462, 1670, 1671, 1672, 1673, 3463, 1675, 1676, 1677, 1678, 1679, 1680, 1681, 1682, 1683, 1684, 1685, 1686, 2985, 1692, 1694, 1696, 1698, 1702, 1706, 1712, 1714, 1715, 1716, 1718, 1719, 1720, 1721, 1722, 1723, 1725, 1727, 1728, 1729, 1730, 1731, 1733, 1734, 3757, 1736, 1737, 1738, 1739, 1740, 1741, 1742, 1744, 1745, 1747, 1748, 1749, 1750, 1751, 1752, 1753, 1754, 1755, 1756, 1757, 1758, 1759, 1760, 1761, 1762, 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, 1820, 1821, 1822, 1823, 1824, 1826, 1827, 3028, 1836, 1838, 1842, 3010, 1844, 1845, 3011, 1847, 1848, 1852, 3075, 1854, 1855, 1856, 1857, 1858, 1859, 1860, 1861, 1862, 1864, 1869, 1871, 1872, 1873, 1874, 1875, 1876, 3090, 1878, 1879, 1882, 1883, 1893, 1894, 1898, 1899, 1900, 1901, 1902, 1903, 1904, 1905, 1907, 1908, 1909, 1910, 1911, 1912, 1913, 1914, 1915, 1916, 1917, 1918, 1919, 1920, 1921, 1922, 1927, 1928, 1929, 1930, 1931, 1932, 1933, 1934, 1935, 1936, 1937, 1938, 1939, 1940, 1942, 1943, 1945, 1946, 1956, 1958, 1959, 1962, 1963, 1966, 1967, 1968, 1970, 1971, 1972, 1973, 1974, 1975, 1976, 1977, 1978, 1979, 1980, 1981, 1982, 1983, 1984, 1985, 1986, 1988, 1994, 1995, 1996, 1997, 2001, 3151, 2007, 2008, 2010, 2011, 2012, 2013, 3803, 3804, 2022, 2024, 2025, 2026, 2028, 2029, 2030, 2031, 2032, 2033, 2034, 2035, 2036, 2039, 2040, 2042, 2043, 2046, 2047, 3136, 3137, 3138, 2055, 3364, 2057, 2059, 2060, 2061, 2062, 2063, 2064, 2065, 2066, 2067, 2068, 2069, 2070, 2071, 2074, 2075, 2076, 2077, 2078, 2079, 2083, 2084, 2085, 2086, 2087, 2088, 2089, 2090, 2091, 2092, 2093, 2094, 2095, 2096, 2097, 2098, 2099, 2100, 2102, 2103, 2104, 2105, 2106, 2107, 2108, 2109, 2110, 2112, 2118, 2119, 2120, 2121, 2122, 2123, 2124, 2125, 2127, 2128, 2129, 3078, 2133, 2134, 2135, 2137, 2139, 2140, 2141, 2142, 3001, 3126, 3127, 3128, 3129, 3130, 2149, 2150, 2151, 2153, 3003, 3004, 2994, 2993, 2159, 2995, 2161, 2999, 2163, 3362, 2168, 2172, 2174, 2175, 2176, 2177, 2178, 2179, 2180, 2181, 2182, 2183, 2184, 3029, 2188, 2189, 2190, 2191, 3062, 2193, 2194, 2195, 2196, 2197, 2198, 2199, 2200, 2201, 2204, 3375, 2206, 2207, 2208, 2209, 3044, 2211, 2212, 2213, 2214, 2992, 2216, 3107, 2219, 2223, 2224, 3652, 2226, 2227, 3739, 3740, 2231, 3189, 2234, 3728, 2237, 2238, 2239, 2240, 2241, 3788, 2243, 3159, 2245, 3158, 2247, 2249, 2251, 2252, 2253, 2257, 2260, 2262, 2264, 2265, 2266, 2267, 2268, 2269, 2270, 2271, 2272, 2273, 2274, 2275, 2276, 2277, 2279, 2280, 2281, 3746, 2283, 2284, 2286, 3036, 3034, 3038, 2292, 2294, 2295, 2301, 2302, 2303, 2304, 3074, 2309, 2310, 2312, 2317, 2318, 3018, 3587, 2981, 2980, 2983, 3103, 3106, 2331, 2332, 2334, 2335, 2337, 2338, 2339, 2340, 2341, 2342, 2343, 2344, 2345, 3807, 2349, 2350, 2351, 2352, 2353, 2354, 2355, 2356, 2357, 2358, 2359, 2360, 2361, 2362, 2363, 2368, 2370, 2371, 2372, 2376, 2377, 2380, 2381, 2388, 2389, 2390, 2391, 2392, 2393, 2394, 2395, 2396, 2397, 2398, 2399, 2400, 2402, 2403, 2404, 2405, 2406, 2407, 2429, 2430, 2433, 2434, 2435, 2436, 2437, 2438, 2439, 2449, 2453, 2454, 2455, 2456, 2457, 2458, 2459, 2460, 2461, 2463, 2464, 2465, 2466, 2468, 2469, 2470, 2472, 2475, 2476, 2477, 2480, 2481, 2482, 2483, 2484, 2485, 2486, 2487, 2493, 2494, 2495, 2496, 2497, 2498, 2499, 2500, 2501, 2502, 2503, 2504, 2505, 2506, 2507, 2508, 2509, 2510, 2511, 2512, 2513, 2514, 2515, 2517, 2518, 2519, 2520, 2521, 2522, 2523, 2524, 2525, 2526, 2527, 2528, 2529, 2530, 2531, 2532, 2533, 2534, 2535, 2536, 2537, 2538, 2540, 2541, 2542, 2543, 3140, 2545, 2547, 2548, 2550, 2551, 2552, 2553, 2554, 2555, 2556, 2559, 2560, 2561, 2562, 2565, 2566, 2567, 2568, 2569, 2570, 2571, 2572, 2573, 2581, 2582, 2583, 2584, 2587, 2588, 2589, 2590, 2591, 2592, 2593, 2594, 2595, 2597, 2598, 2599, 2600, 2601, 2602, 2603, 2604, 2605, 2608, 2610, 2611, 2614, 2615, 2616, 2617, 2618, 2619, 2620, 2621, 2622, 2624, 2625, 2627, 2628, 2629, 2630, 2631, 2632, 2633, 2634, 2635, 2636, 2637, 2639, 2641, 2644, 2646, 3736, 2651, 2652, 2653, 2654, 2655, 2656, 2657, 2661, 2662, 2664, 2665, 2666, 2667, 2668, 2669, 2670, 2672, 2673, 2674, 2679, 2680, 2681, 2683, 2684, 2685, 2686, 2688, 2689, 2690, 2691, 2692, 2693, 2694, 2695, 2696, 2697, 2698, 2699, 2700, 3709, 2702, 2703, 2705, 3706, 2707, 2708, 3710, 3707, 2720, 2724, 3717, 3213, 3718, 2728, 3719, 2730, 2732, 3721, 2734, 3722, 2736, 2738, 3726, 3704, 3697, 3705, 2757, 2758, 2760, 2761, 2771, 2772, 2774, 2775, 2776, 2777, 2778, 2779, 2780, 2781, 2782, 2786, 2789, 2792, 2794, 2796, 2802, 2803, 2804, 2805, 2806, 2807, 2808, 2809, 2810, 2811, 2812, 2813, 2814, 3384, 2816, 2817, 2818, 2819, 2820, 2822, 2824, 2825, 3416, 2831, 2832, 2833, 2834, 2835, 2836, 2837, 2838, 2839, 2840, 2841, 2842, 2844, 2845, 2846, 2847, 2850, 2851, 2853, 2854, 2855, 2856, 3008, 2858, 2860, 2861, 2863, 2864, 2865, 2866, 2867, 2869, 2870, 2874, 2877, 2878, 2879, 2881, 2882, 2883, 2885, 2886, 2887, 2888, 2890, 2891, 2894, 2897, 2898, 2899, 2900, 2901, 2903, 2905, 2906, 2908, 2909, 2910, 2911, 2912, 2913, 2914, 2915, 2917, 2918, 2919, 2920, 2921, 2922, 2923, 2924, 2925, 2926, 2927, 2928, 2929, 2930, 2931, 2932, 2933, 2934, 2935, 2936, 2942, 2943, 2944, 2946, 2947, 2948, 2952, 2953, 2954, 2955, 2956, 2960, 2961, 2965, 2966, 2967, 2968, 2969, 2970, 2972, 2977, 2978, 2984, 2989, 2991, 2996, 2997, 2998, 3000, 3002, 3005, 3006, 3007, 3009, 3013, 3020, 3021, 3022, 3023, 3024, 3025, 3026, 3027, 3030, 3031, 3032, 3033, 3037, 3039, 3040, 3041, 3042, 3046, 3047, 3051, 3053, 3054, 3055, 3057, 3058, 3059, 3060, 3061, 3064, 3065, 3066, 3067, 3068, 3069, 3070, 3071, 3072, 3079, 3080, 3081, 3082, 3087, 3088, 3089, 3091, 3095, 3096, 3097, 3098, 3099, 3102, 3104, 3105, 3108, 3109, 3110, 3111, 3112, 3113, 3114, 3115, 3116, 3118, 3120, 3121, 3122, 3123, 3124, 3125, 3131, 3132, 3133, 3134, 3135, 3139, 3141, 3142, 3143, 3144, 3145, 3146, 3147, 3149, 3150, 3153, 3155, 3156, 3157, 3160, 3165, 3166, 3167, 3169, 3172, 3174, 3175, 3177, 3178, 3179, 3181, 3182, 3183, 3185, 3186, 3187, 3188, 3192, 3197, 3202, 3203, 3204, 3205, 3206, 3207, 3208, 3210, 3215, 3216, 3217, 3218, 3219, 3220, 3221, 3222, 3223, 3224, 3225, 3226, 3227, 3230, 3231, 3234, 3235, 3236, 3237, 3238, 3239, 3240, 3241, 3244, 3245, 3246, 3247, 3248, 3249, 3250, 3251, 3252, 3253, 3254, 3257, 3258, 3260, 3261, 3262, 3263, 3264, 3265, 3266, 3267, 3268, 3269, 3270, 3271, 3272, 3273, 3274, 3275, 3276, 3277, 3278, 3279, 3280, 3281, 3282, 3283, 3284, 3285, 3286, 3289, 3290, 3291, 3292, 3293, 3294, 3295, 3296, 3297, 3298, 3300, 3301, 3302, 3303, 3304, 3305, 3306, 3307, 3308, 3309, 3310, 3311, 3312, 3313, 3314, 3315, 3316, 3317, 3318, 3319, 3320, 3321, 3322, 3323, 3324, 3325, 3326, 3327, 3328, 3329, 3330, 3331, 3332, 3335, 3336, 3337, 3338, 3339, 3340, 3341, 3342, 3343, 3344, 3345, 3346, 3347, 3348, 3349, 3350, 3351, 3352, 3353, 3354, 3355, 3356, 3358, 3359, 3363, 3365, 3366, 3367, 3369, 3370, 3371, 3374, 3376, 3377, 3378, 3379, 3380, 3383, 3385, 3388, 3390, 3391, 3396, 3397, 3398, 3399, 3402, 3409, 3410, 3411, 3412, 3413, 3414, 3417, 3418, 3419, 3420, 3423, 3424, 3425, 3426, 3427, 3428, 3429, 3430, 3431, 3432, 3434, 3435, 3436, 3437, 3438, 3439, 3441, 3442, 3444, 3445, 3446, 3447, 3448, 3454, 3455, 3456, 3457, 3458, 3459, 3460, 3461, 3464, 3467, 3470, 3471, 3472, 3473, 3474, 3475, 3476, 3477, 3478, 3479, 3480, 3481, 3482, 3483, 3484, 3485, 3486, 3487, 3488, 3490, 3491, 3492, 3493, 3494, 3495, 3496, 3498, 3499, 3500, 3501, 3502, 3503, 3504, 3505, 3507, 3512, 3518, 3520, 3521, 3522, 3523, 3524, 3525, 3526, 3527, 3528, 3529, 3530, 3531, 3532, 3533, 3534, 3536, 3537, 3538, 3539, 3540, 3541, 3545, 3546, 3550, 3551, 3557, 3558, 3559, 3560, 3561, 3562, 3563, 3564, 3565, 3567, 3568, 3569, 3570, 3573, 3574, 3576, 3577, 3589, 3590, 3591, 3592, 3593, 3594, 3595, 3596, 3597, 3598, 3599, 3600, 3601, 3602, 3603, 3604, 3605, 3606, 3608, 3609, 3610, 3614, 3615, 3616, 3617, 3623, 3624, 3625, 3626, 3630, 3632, 3633, 3634, 3636, 3639, 3640, 3644, 3651, 3653, 3656, 3658, 3659, 3660, 3661, 3662, 3663, 3665, 3666, 3667, 3668, 3669, 3670, 3671, 3672, 3673, 3674, 3675, 3676, 3677, 3678, 3679, 3680, 3681, 3682, 3683, 3684, 3685, 3686, 3687, 3688, 3689, 3690, 3691, 3692, 3693, 3694, 3695, 3696, 3714, 3729, 3732, 3734, 3735, 3737, 3741, 3743, 3747, 3756, 3759, 3760, 3761, 3762, 3763, 3764, 3766, 3772, 3773, 3776, 3779, 3781, 3782, 3783, 3784, 3785, 3786, 3789, 3792, 3794, 3798, 3799, 3800, 3801, 3802, 3805, 3806, 3808, 3809, 3811, 3812, 3813, 3814, 3815, 3816, 3817, 3818, 3820, 3821, 3822, 3823, 3824, 3825, 3826, 3827, 3828, 3829, 3830, 3831, 3832, 3833, 3834, 3835, 3836, 3837, 3840, 3842, 3844, 3853, 3854, 3856, 3857, 3866, 3872, 3878, 3887, 3889, 3890, 3891, 3892, 3895, 3896, 3898, 3904, 3908, 3912, 3917, 3918, 3920, 3921, 3922, 3924, 3925, 3926, 3931, 3932, 3933, 3934, 3935, 3936, 3937, 3938, 3939, 3942, 3943, 3944, 3989, 3990, 3995, 3997, 3998, 4000, 4006, 4009, 4024, 4025, 4026, 4027, 4028, 4029, 4031, 4032, 4034, 4035, 4037, 4039, 4040, 4053, 4056, 4057, 4059, 4060, 4064, 4069, 4072, 4073, 4075, 4076, 4082, 4084, 4085, 4088, 4090, 4095, 4096, 4097, 4102, 4113, 4136, 4152, 4160, 4169, 4170, 4174, 4179, 4195, 4196, 4197, 4198, 4200, 4202, 4203, 4205, 4208, 4212, 4215, 4218, 4219, 4220, 4221, 4225, 4226, 4227, 4228, 4231, 4232, 4233, 4234, 4235, 4236, 4237, 4238, 4239, 4240, 4241, 4242, 4243, 4244, 4245, 4246, 4247, 4248, 4249, 4250, 4251, 4252, 4253, 4254, 4262, 4265, 4266, 4272, 4277, 4278, 4279, 4280, 4284, 4288, 4290, 4291, 4292, 4293, 4294, 4295, 4296, 4297, 4299, 4300, 4301, 4302, 4304, 4305, 4306, 4307, 4308, 4309, 4310, 4320, 4329, 4330, 4331, 4332, 4333, 4334, 4335, 4336, 4337, 4338, 4340, 4341, 4345, 4346, 4348, 4349, 4350, 4351, 4355, 4356, 4357, 4358, 4359, 4360, 4362, 4363, 4364, 4370, 4371, 4372, 4373, 4374, 4375, 4379, 4383, 4384, 4386, 4387, 4388, 4389, 4390, 4392, 4402, 4404, 4409, 4410, 4411, 4412, 4413, 4414, 4415, 4416, 4417, 4418, 4419, 4420, 4421, 4422, 4423, 4424, 4426, 4427, 4428, 4429, 4430, 4431, 4432, 4437, 4440, 4441, 4442, 4443, 4444, 4445, 4446, 4447, 4448, 4449, 4450, 4451, 4452, 4453, 4454, 4455, 4456, 4457, 4458, 4459, 4460, 4462, 4463, 4464, 4466, 4467, 4468, 4469, 4472, 4473, 4474, 4476, 4477, 4478, 4480, 4481, 4482, 4483, 4484, 4485, 4487, 4489, 4492, 4493, 4494, 4495, 4497, 4498, 4499, 4500, 4501, 4502, 4503, 4504, 4505, 4506, 4507, 4511, 4513, 4514, 4515, 4516, 4517, 4521, 4522, 4526, 4527, 4528, 4530, 4532, 4533, 4534, 4535, 4536, 4537, 4538, 4540, 4541, 4542, 4543, 4544, 4545, 4546, 4553, 4554, 4555, 4556, 4557, 4558, 4559, 4560, 4561, 4562, 4563, 4564, 4570, 4571, 4573, 4574, 4575, 4576, 4577, 4578, 4579, 4580, 4581, 4582, 4583, 4584, 4585, 4586, 4587, 4588, 4592, 4593, 4594, 4595, 4596, 4597, 4598, 4599, 4600, 4605, 4606, 4609, 4610, 4611, 4612, 4613, 4614, 4615, 4616, 4617, 4618, 4619, 4620, 4621, 4622, 4624, 4625, 4626, 4627, 4636, 4637, 4638, 4639, 4640, 4641, 4643, 4646, 4647, 4648, 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, 4728, 4729, 4730, 4731, 4732, 4733, 4734, 4735, 4736, 4737, 4738, 4739, 4740, 4741, 4742, 4743, 4744, 4745, 4746, 4747, 4748, 4749, 4750, 4751, 4756, 4757, 4758, 4764, 4777, 4781, 4782, 4783, 4784, 4785, 4786, 4787, 4788, 4789, 4790, 4791, 4792, 4793, 4794, 4795, 4796, 4798, 4799, 4800, 4801, 4802, 4804, 4805, 4806, 4807, 4808, 4809, 4810, 4813, 4814, 4816, 4817, 4818, 4821, 4822, 4823, 4824, 4825, 4826, 4827, 4828, 4829, 4830, 4831, 4832, 4833, 4834, 4835, 4836, 4837, 4838, 4839, 4840, 4841, 4842, 4843, 4844, 4845, 4846, 4847, 4849, 4850, 4851, 4852, 4853, 4854, 4855, 4856, 4857, 4858, 4859, 4860, 4861, 4862, 4863, 4864, 4865, 4866, 4867, 4868, 4869, 4870, 4871, 4872, 4873, 4874, 4875, 4876, 4877, 4878, 4879, 4880, 4882, 4883, 4884, 4886, 4888, 4890, 4891, 4892, 4893, 4896, 4898, 4899, 4900, 4901, 4903, 4904, 4905, 4906, 4907, 4908, 4909, 4910, 4913, 4917, 4918, 4922, 4923, 4924, 4925, 4926, 4928, 4929, 4932, 4933, 4934, 4935, 4936, 4938, 4939, 4940, 4941, 4943, 4945, 4946, 4949, 4950, 4951, 4952, 4953, 4954) } + internal val templates: IntArray by lazy { intArrayOf(2369, 2848, 2660, 2659, 2658, 2880, 2902, 3382, 2623, 418, 2793, 2791, 2687, 2378, 2384, 2795, 2892, 2607, 2606, 285, 2336, 2797, 2904, 3232, 4184, 2546, 4927, 2596, 2050, 2374, 3716, 2115, 2723, 2379, 3233, 1336, 4204, 4224, 3715, 2564, 2721, 1867, 4199, 2126, 2167, 2173, 4566, 283, 2116, 4508, 3394, 3415, 2073, 2347, 3712, 452, 2755, 2787, 2788, 3395, 3711, 2756, 3643, 609, 1711, 3720, 1868, 2731, 3723, 2737, 3386, 616, 617, 2773, 3084, 3698, 1659, 2790, 3642, 303, 614, 69, 711, 621, 2346, 4222, 1121, 2488, 3465, 3838, 1242, 2202, 2575, 3387, 2165, 3727, 714, 1763, 1964, 2743, 2752, 2963, 4229, 3389, 3401, 136, 594, 596, 2563, 2718, 1865, 4217, 3035, 610, 2289, 2586, 3875, 1302, 4216, 3511, 3648, 3649, 158, 2080, 2082, 2117, 2843, 4365, 2171, 2373, 2516, 3637, 214, 284, 1276, 2014, 4797, 3506, 3515, 3516, 67, 83, 218, 619, 4602, 3535, 1360, 4311, 3360, 3725, 726, 1023, 1372, 2387, 2479, 2741, 4367, 89, 2386, 2401, 2916, 624, 1657, 1954, 2830, 4496, 3408, 1577, 2101, 2293, 2577, 4548, 3403, 3469, 3519, 650, 1888, 3930, 3168, 3510, 3556, 3620, 3839, 1317, 1866, 2045, 2425, 2712, 3858, 4567, 3422, 3468, 1841, 1863, 3357, 593, 1292, 1346, 1371, 1953, 3497, 3699, 221, 1701, 2744, 2941, 3086, 3154, 3443, 258, 591, 1026, 1379, 1965, 1989, 4137, 3440, 3566, 655, 1342, 1717, 2051, 3162, 3361, 3622, 3641, 710, 1283, 1370, 1382, 1658, 1732, 1895, 2375, 2478, 2576, 3945, 4223, 4433, 3421, 3489, 3635, 649, 699, 1044, 2612, 3180, 3299, 3702, 108, 184, 606, 721, 1081, 1969, 2049, 2111, 2169, 2411, 2492, 2748, 2784, 2828, 3950, 4479, 4820, 3381, 3452, 3613, 160, 623, 701, 1332, 1333, 1345, 1520, 1660, 2166, 2170, 2263, 2410, 2638, 4192, 4509, 3117, 3209, 3256, 3334, 3548, 3703, 3713, 703, 1183, 1572, 1897, 2258, 2261, 2491, 2749, 2769, 2770, 2938, 2939, 3960, 3980, 4213, 4470, 4803, 4819, 3621, 3638, 3744, 1378, 1492, 1584, 1703, 1955, 2431, 2443, 2768, 4156, 4214, 4510, 4601, 3083, 3085, 3100, 3618, 3631, 3797, 723, 1024, 1832, 2138, 2203, 2421, 2764, 2765, 3965, 4211, 4287, 4298, 3287, 3407, 91, 93, 595, 715, 1027, 1350, 1355, 2020, 2333, 2426, 2711, 2763, 2767, 3927, 4549, 4881, 3014, 3015, 3517, 3581, 3724, 94, 1251, 1259, 1353, 1377, 1519, 1583, 1880, 2186, 2218, 2471, 2489, 2739, 3867, 3868, 4210, 4376, 4439, 4885, 3333, 3372, 3373, 3451, 3607, 299, 599, 618, 700, 1109, 1117, 1175, 1367, 1518, 1626, 1948, 2130, 2136, 2154, 2221, 2441, 2446, 2448, 2671, 2704, 2762, 2940, 2957, 2958, 4181, 4207, 4324, 3016, 3170, 3547, 3580, 3749, 211, 585, 590, 605, 717, 720, 906, 990, 1084, 1159, 1334, 1470, 1524, 1705, 1886, 1906, 1926, 1961, 1991, 2072, 2316, 2424, 2490, 2945, 3894, 3946, 4164, 4550, 4568, 4569, 4768, 4930, 3077, 3433, 3628, 3629, 92, 96, 269, 603, 648, 712, 980, 1331, 1707, 1887, 1944, 2114, 2419, 2445, 2447, 2450, 2539, 2677, 2713, 2895, 2907, 4255, 4552, 4780, 2990, 3255, 3288, 3368, 3466, 3585, 3619, 208, 277, 316, 329, 330, 1287, 1352, 1376, 1521, 1522, 1949, 2019, 2044, 2113, 2220, 2248, 2299, 2413, 2428, 2440, 2714, 2717, 2798, 2799, 3865, 4565, 4763, 4937, 3012, 3400, 3404, 3453, 3509, 3664, 3701, 3754, 6, 244, 304, 600, 604, 1047, 1221, 1286, 1354, 1359, 1708, 1709, 1884, 1957, 1960, 2018, 2021, 2152, 2187, 2235, 2412, 2420, 2640, 2746, 2785, 2862, 3862, 3863, 3923, 4180, 4766, 4778, 4779, 4948, 3450, 3572, 3579, 3584, 3646, 3654, 268, 318, 322, 331, 583, 707, 722, 1076, 1160, 1164, 1284, 1285, 1312, 1517, 1710, 1828, 1889, 2009, 2222, 2228, 2383, 2409, 2415, 2442, 2574, 2675, 3928, 4153, 4206, 4269, 4368, 4438, 4649, 4767, 4942, 3063, 3148, 3513, 3514, 3612, 3645, 65, 210, 274, 587, 608, 613, 708, 713, 984, 1075, 1167, 1369, 1713, 1743, 1829, 1834, 1849, 1885, 2048, 2081, 2278, 2296, 2305, 2408, 2462, 2474, 2766, 4191, 3043, 3393, 3578, 3647, 3655, 3700, 90, 207, 288, 320, 323, 324, 349, 597, 607, 709, 855, 905, 1166, 1169, 1252, 1437, 1890, 2005, 2015, 2414, 2423, 2467, 2745, 2783, 2937, 2951, 3900, 4811, 4812, 4815, 4911, 3017, 3048, 3101, 3171, 3229, 3242, 3243, 3406, 3554, 3555, 3627, 3650, 3657, 3708, 110, 186, 190, 191, 212, 321, 327, 328, 352, 375, 580, 582, 589, 625, 727, 851, 977, 1077, 1118, 1147, 1243, 1304, 1314, 1746, 1830, 1831, 1839, 1950, 1951, 1952, 2041, 2254, 2256, 2285, 2297, 2298, 2320, 2382, 2416, 2417, 2473, 2579, 2580, 2663, 2678, 2710, 2715, 2716, 2753, 2800, 2801, 3846, 3864, 3910, 3964, 4209, 4303, 4321, 4339, 4366, 4436, 4471, 4523, 4547, 4608, 4848, 4931, 4947, 3050, 3152, 3176, 3190, 3211, 3392, 3405, 3549, 3553, 3583, 3611, 3742, 3752, 3753, 3765, 3767, 3774, 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, 1649, 1693, 1704, 1850, 1881, 1947, 1993, 2006, 2027, 2250, 2255, 2308, 2314, 2315, 2322, 2427, 2613, 2649, 2823, 3911, 3919, 3949, 3966, 4133, 4168, 4182, 4230, 4270, 4322, 4361, 4524, 4551, 4944, 3073, 3119, 3195, 3196, 3201, 3259, 3543, 154, 259, 261, 347, 350, 353, 579, 602, 612, 702, 706, 982, 1078, 1381, 1593, 1833, 1925, 1987, 1990, 2306, 2319, 2385, 2432, 2578, 2626, 2868, 3869, 3916, 3982, 4149, 4520, 4607, 3449, 3542, 3544, 3552, 3571, 3582, 3750, 3771, 3791, 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, 1688, 1689, 1691, 1726, 1851, 1891, 2233, 2311, 2321, 2422, 2444, 2452, 2959, 4135, 4165, 4166, 4256, 4281, 4319, 4434, 4490, 4531, 4887, 4912) } + 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"), 1572 to arrayOf("why"), 1577 to arrayOf("e"), 1583 to arrayOf("max"), 1584 to arrayOf("secs", "max", "mib"), 1593 to arrayOf("path"), 1626 to arrayOf("secs"), 1649 to arrayOf("pct", "scope"), 1657 to arrayOf("n"), 1658 to arrayOf("n"), 1659 to arrayOf("n"), 1660 to arrayOf("n"), 1688 to arrayOf("d", "h"), 1689 to arrayOf("h", "m"), 1690 to arrayOf("m"), 1691 to arrayOf("window", "pct"), 1693 to arrayOf("when"), 1695 to arrayOf("label", "e"), 1697 to arrayOf("from", "to", "total"), 1701 to arrayOf("messages", "lines", "left"), 1703 to arrayOf("pct", "view", "max"), 1704 to arrayOf("pct"), 1705 to arrayOf("done", "total"), 1707 to arrayOf("n"), 1708 to arrayOf("n"), 1709 to arrayOf("time"), 1710 to arrayOf("view", "max"), 1711 to arrayOf("view", "max"), 1713 to arrayOf("more"), 1717 to arrayOf("n"), 1726 to arrayOf("n"), 1732 to arrayOf("page"), 1743 to arrayOf("title"), 1746 to arrayOf("n"), 1763 to arrayOf("name"), 1828 to arrayOf("line"), 1829 to arrayOf("quote"), 1830 to arrayOf("n"), 1831 to arrayOf("n"), 1832 to arrayOf("n"), 1833 to arrayOf("n"), 1834 to arrayOf("n"), 1839 to arrayOf("held"), 1840 to arrayOf("machine"), 1841 to arrayOf("machine"), 1849 to arrayOf("count", "total"), 1850 to arrayOf("count"), 1851 to arrayOf("n"), 1863 to arrayOf("name"), 1865 to arrayOf("n", "c", "total"), 1866 to arrayOf("n", "c"), 1867 to arrayOf("n", "c", "total", "before"), 1868 to arrayOf("n", "c", "before"), 1880 to arrayOf("name"), 1881 to arrayOf("path"), 1884 to arrayOf("file"), 1885 to arrayOf("path", "n"), 1886 to arrayOf("why"), 1887 to arrayOf("n"), 1888 to arrayOf("name"), 1889 to arrayOf("name"), 1890 to arrayOf("name"), 1891 to arrayOf("n"), 1892 to arrayOf("shown", "n"), 1895 to arrayOf("path"), 1897 to arrayOf("n"), 1906 to arrayOf("status"), 1923 to arrayOf("name", "pct"), 1924 to arrayOf("name", "mb"), 1925 to arrayOf("name"), 1926 to arrayOf("name", "why"), 1944 to arrayOf("machine"), 1947 to arrayOf("n"), 1948 to arrayOf("ref"), 1949 to arrayOf("ref", "sheet"), 1950 to arrayOf("name"), 1951 to arrayOf("name"), 1952 to arrayOf("file", "folder"), 1953 to arrayOf("name", "error"), 1954 to arrayOf("name", "status"), 1955 to arrayOf("name", "error"), 1957 to arrayOf("name"), 1960 to arrayOf("code"), 1961 to arrayOf("error"), 1964 to arrayOf("error"), 1965 to arrayOf("error"), 1969 to arrayOf("error"), 1987 to arrayOf("done", "of"), 1989 to arrayOf("why"), 1990 to arrayOf("path"), 1991 to arrayOf("error"), 1992 to arrayOf("secs"), 1993 to arrayOf("secs"), 2005 to arrayOf("code"), 2006 to arrayOf("code"), 2009 to arrayOf("state"), 2014 to arrayOf("hide", "copy", "paste"), 2015 to arrayOf("n"), 2018 to arrayOf("name"), 2019 to arrayOf("name", "folder"), 2020 to arrayOf("name"), 2021 to arrayOf("name", "percent"), 2027 to arrayOf("folder"), 2037 to arrayOf("w", "h"), 2041 to arrayOf("path"), 2044 to arrayOf("why"), 2045 to arrayOf("mb"), 2048 to arrayOf("n"), 2049 to arrayOf("delete", "undo"), 2050 to arrayOf("delete", "undo"), 2051 to arrayOf("undo"), 2072 to arrayOf("what", "secs"), 2073 to arrayOf("file", "holder"), 2080 to arrayOf("what"), 2081 to arrayOf("what"), 2082 to arrayOf("editor", "why"), 2101 to arrayOf("files"), 2111 to arrayOf("why"), 2113 to arrayOf("title"), 2114 to arrayOf("title"), 2115 to arrayOf("version"), 2116 to arrayOf("version", "size", "folder"), 2117 to arrayOf("version", "size", "folder"), 2126 to arrayOf("title"), 2130 to arrayOf("dir", "files"), 2136 to arrayOf("why"), 2138 to arrayOf("code"), 2152 to arrayOf("origin"), 2154 to arrayOf("why"), 2165 to arrayOf("dir"), 2166 to arrayOf("path"), 2167 to arrayOf("home", "other"), 2169 to arrayOf("path"), 2170 to arrayOf("code", "log"), 2171 to arrayOf("log"), 2173 to arrayOf("addr"), 2186 to arrayOf("home"), 2187 to arrayOf("addr"), 2202 to arrayOf("dir", "why"), 2203 to arrayOf("dir"), 2218 to arrayOf("phase"), 2220 to arrayOf("why"), 2221 to arrayOf("what"), 2222 to arrayOf("code"), 2228 to arrayOf("label"), 2233 to arrayOf("kind"), 2235 to arrayOf("project"), 2248 to arrayOf("what"), 2250 to arrayOf("when"), 2254 to arrayOf("n"), 2255 to arrayOf("n"), 2256 to arrayOf("n"), 2258 to arrayOf("agent"), 2259 to arrayOf("effort"), 2261 to arrayOf("n"), 2263 to arrayOf("model"), 2278 to arrayOf("word"), 2285 to arrayOf("more", "step"), 2289 to arrayOf("name"), 2293 to arrayOf("max", "skipped"), 2296 to arrayOf("name"), 2297 to arrayOf("n"), 2298 to arrayOf("name"), 2299 to arrayOf("name"), 2305 to arrayOf("n"), 2306 to arrayOf("name"), 2308 to arrayOf("price"), 2311 to arrayOf("name"), 2313 to arrayOf("name"), 2314 to arrayOf("name"), 2315 to arrayOf("name"), 2316 to arrayOf("text"), 2319 to arrayOf("key"), 2320 to arrayOf("key"), 2321 to arrayOf("pct"), 2322 to arrayOf("when"), 2333 to arrayOf("n", "upstream"), 2336 to arrayOf("mb"), 2346 to arrayOf("path"), 2347 to arrayOf("path"), 2369 to arrayOf("id"), 2373 to arrayOf("model"), 2374 to arrayOf("platform"), 2375 to arrayOf("version"), 2378 to arrayOf("version", "from", "into"), 2379 to arrayOf("version", "from"), 2382 to arrayOf("version", "path"), 2383 to arrayOf("version", "path"), 2384 to arrayOf("version", "pin", "from"), 2385 to arrayOf("path"), 2386 to arrayOf("version", "path"), 2387 to arrayOf("version", "path", "set"), 2401 to arrayOf("turns", "input", "cread", "cwrite", "output", "cost"), 2408 to arrayOf("tool"), 2409 to arrayOf("tool"), 2410 to arrayOf("tool", "word"), 2411 to arrayOf("tool", "word"), 2412 to arrayOf("tool"), 2413 to arrayOf("tool"), 2414 to arrayOf("due"), 2415 to arrayOf("due"), 2416 to arrayOf("due"), 2417 to arrayOf("due"), 2418 to arrayOf("zone"), 2419 to arrayOf("zone"), 2420 to arrayOf("zone"), 2421 to arrayOf("zone"), 2422 to arrayOf("n"), 2423 to arrayOf("who"), 2424 to arrayOf("n", "who"), 2425 to arrayOf("harness"), 2426 to arrayOf("path"), 2427 to arrayOf("path"), 2428 to arrayOf("path"), 2431 to arrayOf("error", "line"), 2432 to arrayOf("label"), 2440 to arrayOf("who"), 2441 to arrayOf("who"), 2442 to arrayOf("label", "left", "when"), 2443 to arrayOf("left"), 2444 to arrayOf("name", "left"), 2445 to arrayOf("used"), 2446 to arrayOf("used", "limit"), 2447 to arrayOf("used", "reason"), 2448 to arrayOf("used", "limit", "reason"), 2450 to arrayOf("provider"), 2451 to arrayOf("used", "window", "pct"), 2452 to arrayOf("rate"), 2462 to arrayOf("n", "r"), 2467 to arrayOf("time", "n"), 2471 to arrayOf("n", "m"), 2473 to arrayOf("pct"), 2474 to arrayOf("cost", "n"), 2478 to arrayOf("in", "out", "cread", "cwrite"), 2479 to arrayOf("in", "out", "cread", "cwrite", "n"), 2488 to arrayOf("turns", "input", "cread", "cwrite", "output"), 2489 to arrayOf("left", "when"), 2490 to arrayOf("left", "when"), 2491 to arrayOf("left", "when"), 2492 to arrayOf("left", "when"), 2516 to arrayOf("n"), 2539 to arrayOf("when"), 2546 to arrayOf("phrase", "now"), 2557 to arrayOf("s"), 2563 to arrayOf("now"), 2564 to arrayOf("now", "nudge", "sent", "undone"), 2574 to arrayOf("e"), 2575 to arrayOf("a", "ams", "b", "bms"), 2576 to arrayOf("ms"), 2577 to arrayOf("e"), 2578 to arrayOf("t"), 2579 to arrayOf("t"), 2580 to arrayOf("t"), 2586 to arrayOf("why"), 2596 to arrayOf("apps"), 2606 to arrayOf("n"), 2607 to arrayOf("n", "k"), 2612 to arrayOf("stt", "conf"), 2613 to arrayOf("words"), 2623 to arrayOf("into"), 2626 to arrayOf("origin"), 2638 to arrayOf("url"), 2640 to arrayOf("url"), 2648 to arrayOf("i", "n"), 2649 to arrayOf("d", "n"), 2658 to arrayOf("version"), 2659 to arrayOf("version"), 2660 to arrayOf("version"), 2663 to arrayOf("path"), 2671 to arrayOf("addr"), 2675 to arrayOf("label"), 2677 to arrayOf("label"), 2678 to arrayOf("label"), 2682 to arrayOf("label"), 2687 to arrayOf("from"), 2704 to arrayOf("done", "of"), 2710 to arrayOf("n"), 2711 to arrayOf("t", "m"), 2712 to arrayOf("m"), 2713 to arrayOf("b", "m"), 2714 to arrayOf("r", "p"), 2715 to arrayOf("n"), 2716 to arrayOf("n"), 2717 to arrayOf("n"), 2718 to arrayOf("n"), 2721 to arrayOf("n"), 2723 to arrayOf("n"), 2731 to arrayOf("n"), 2737 to arrayOf("name", "gb", "path"), 2739 to arrayOf("path", "why"), 2741 to arrayOf("names"), 2743 to arrayOf("why"), 2744 to arrayOf("p", "pn", "t", "tn", "e", "en"), 2745 to arrayOf("done", "total"), 2746 to arrayOf("n"), 2747 to arrayOf("what"), 2748 to arrayOf("n"), 2749 to arrayOf("n"), 2752 to arrayOf("what"), 2753 to arrayOf("n"), 2755 to arrayOf("why", "from"), 2756 to arrayOf("why"), 2762 to arrayOf("path"), 2763 to arrayOf("path", "who"), 2764 to arrayOf("path"), 2765 to arrayOf("path", "cmd"), 2766 to arrayOf("version", "path"), 2767 to arrayOf("version", "path"), 2768 to arrayOf("version", "path", "who"), 2769 to arrayOf("version", "path"), 2770 to arrayOf("version", "path", "cmd"), 2773 to arrayOf("cmd"), 2783 to arrayOf("name", "version", "path"), 2784 to arrayOf("path", "why"), 2785 to arrayOf("name"), 2787 to arrayOf("version", "cli"), 2788 to arrayOf("cli"), 2790 to arrayOf("version"), 2791 to arrayOf("version"), 2793 to arrayOf("version"), 2795 to arrayOf("version"), 2797 to arrayOf("computer"), 2798 to arrayOf("version", "cli"), 2799 to arrayOf("cli"), 2800 to arrayOf("version", "cli"), 2801 to arrayOf("cli"), 2823 to arrayOf("n"), 2828 to arrayOf("code"), 2830 to arrayOf("e"), 2843 to arrayOf("n"), 2848 to arrayOf("channel"), 2862 to arrayOf("project"), 2868 to arrayOf("n"), 2880 to arrayOf("m"), 2892 to arrayOf("m"), 2895 to arrayOf("m"), 2902 to arrayOf("pages"), 2904 to arrayOf("name"), 2907 to arrayOf("name"), 2916 to arrayOf("d", "n"), 2937 to arrayOf("n", "tools"), 2938 to arrayOf("n", "tools", "d"), 2939 to arrayOf("n", "d"), 2940 to arrayOf("n", "what"), 2941 to arrayOf("n", "d", "what"), 2945 to arrayOf("head"), 2951 to arrayOf("name", "path"), 2957 to arrayOf("page", "net", "near"), 2958 to arrayOf("page", "what"), 2959 to arrayOf("ref"), 2963 to arrayOf("page"), 2986 to arrayOf("n"), 2987 to arrayOf("n"), 2988 to arrayOf("n"), 2990 to arrayOf("hub"), 3012 to arrayOf("project"), 3014 to arrayOf("n"), 3015 to arrayOf("n"), 3016 to arrayOf("word"), 3017 to arrayOf("n"), 3035 to arrayOf("name"), 3043 to arrayOf("answer"), 3048 to arrayOf("why"), 3050 to arrayOf("hub"), 3056 to arrayOf("from", "to"), 3063 to arrayOf("project"), 3073 to arrayOf("name"), 3077 to arrayOf("n"), 3083 to arrayOf("code"), 3084 to arrayOf("hub"), 3085 to arrayOf("hub"), 3086 to arrayOf("hub"), 3100 to arrayOf("n"), 3101 to arrayOf("n"), 3117 to arrayOf("status"), 3119 to arrayOf("status"), 3148 to arrayOf("project"), 3152 to arrayOf("code"), 3154 to arrayOf("why"), 3162 to arrayOf("title"), 3168 to arrayOf("title"), 3170 to arrayOf("q"), 3171 to arrayOf("title"), 3176 to arrayOf("room"), 3180 to arrayOf("q"), 3190 to arrayOf("title"), 3195 to arrayOf("n"), 3196 to arrayOf("n"), 3201 to arrayOf("at"), 3209 to arrayOf("size"), 3211 to arrayOf("n", "total"), 3228 to arrayOf("n"), 3229 to arrayOf("what"), 3232 to arrayOf("device"), 3233 to arrayOf("device"), 3242 to arrayOf("word", "count"), 3243 to arrayOf("heard"), 3255 to arrayOf("files"), 3256 to arrayOf("files"), 3259 to arrayOf("name"), 3287 to arrayOf("n"), 3288 to arrayOf("n"), 3299 to arrayOf("n"), 3333 to arrayOf("root"), 3334 to arrayOf("path"), 3357 to arrayOf("name"), 3360 to arrayOf("until"), 3361 to arrayOf("error"), 3368 to arrayOf("url"), 3372 to arrayOf("name"), 3373 to arrayOf("name"), 3381 to arrayOf("code", "hub", "until"), 3382 to arrayOf("url"), 3386 to arrayOf("kinds"), 3387 to arrayOf("address"), 3389 to arrayOf("address"), 3392 to arrayOf("url"), 3393 to arrayOf("url"), 3394 to arrayOf("url"), 3395 to arrayOf("url", "via"), 3400 to arrayOf("name"), 3401 to arrayOf("url", "check", "left"), 3403 to arrayOf("check"), 3404 to arrayOf("address"), 3405 to arrayOf("name"), 3406 to arrayOf("error"), 3407 to arrayOf("url"), 3408 to arrayOf("url"), 3415 to arrayOf("code", "address", "left"), 3421 to arrayOf("name"), 3422 to arrayOf("name"), 3433 to arrayOf("address"), 3440 to arrayOf("code", "body"), 3443 to arrayOf("code", "body"), 3449 to arrayOf("window", "used"), 3450 to arrayOf("window", "used", "when"), 3451 to arrayOf("window", "used"), 3452 to arrayOf("window", "used", "when"), 3453 to arrayOf("provider"), 3465 to arrayOf("label"), 3466 to arrayOf("when"), 3468 to arrayOf("provider"), 3469 to arrayOf("provider", "title", "why"), 3489 to arrayOf("reason"), 3497 to arrayOf("code"), 3506 to arrayOf("name"), 3509 to arrayOf("version"), 3510 to arrayOf("version"), 3511 to arrayOf("version"), 3513 to arrayOf("version"), 3514 to arrayOf("version"), 3515 to arrayOf("version"), 3516 to arrayOf("version", "why"), 3517 to arrayOf("version"), 3519 to arrayOf("code"), 3535 to arrayOf("name"), 3542 to arrayOf("count"), 3543 to arrayOf("title"), 3544 to arrayOf("name"), 3547 to arrayOf("n", "holder"), 3548 to arrayOf("n", "title"), 3549 to arrayOf("title"), 3552 to arrayOf("n"), 3553 to arrayOf("n"), 3554 to arrayOf("n"), 3555 to arrayOf("n"), 3556 to arrayOf("harness", "typed", "type", "remote", "host", "wt", "branch"), 3566 to arrayOf("pid"), 3571 to arrayOf("left"), 3572 to arrayOf("left"), 3578 to arrayOf("left"), 3579 to arrayOf("left"), 3580 to arrayOf("left"), 3581 to arrayOf("left"), 3582 to arrayOf("label", "left"), 3583 to arrayOf("when"), 3584 to arrayOf("used"), 3585 to arrayOf("used", "limit"), 3607 to arrayOf("tracking"), 3611 to arrayOf("total"), 3612 to arrayOf("price"), 3613 to arrayOf("price"), 3618 to arrayOf("n"), 3619 to arrayOf("parts"), 3620 to arrayOf("note"), 3621 to arrayOf("error"), 3622 to arrayOf("error", "parts"), 3627 to arrayOf("state"), 3628 to arrayOf("name", "path"), 3629 to arrayOf("name", "path", "why"), 3631 to arrayOf("code"), 3635 to arrayOf("detail"), 3637 to arrayOf("why"), 3638 to arrayOf("parts"), 3641 to arrayOf("build", "to"), 3642 to arrayOf("build"), 3643 to arrayOf("build", "skip"), 3645 to arrayOf("why"), 3646 to arrayOf("why"), 3647 to arrayOf("build"), 3648 to arrayOf("build", "why"), 3649 to arrayOf("build"), 3650 to arrayOf("build"), 3654 to arrayOf("build"), 3655 to arrayOf("build"), 3657 to arrayOf("build"), 3664 to arrayOf("build"), 3698 to arrayOf("step"), 3699 to arrayOf("p", "pt", "t", "tt", "e", "et"), 3700 to arrayOf("done", "total"), 3701 to arrayOf("n"), 3702 to arrayOf("n"), 3703 to arrayOf("n"), 3708 to arrayOf("n"), 3711 to arrayOf("why"), 3712 to arrayOf("why", "from"), 3713 to arrayOf("error"), 3715 to arrayOf("n"), 3716 to arrayOf("n"), 3720 to arrayOf("n"), 3723 to arrayOf("name", "gb", "path"), 3724 to arrayOf("path", "why"), 3725 to arrayOf("names"), 3727 to arrayOf("why"), 3738 to arrayOf("n", "total"), 3742 to arrayOf("title"), 3744 to arrayOf("n"), 3748 to arrayOf("name"), 3749 to arrayOf("title"), 3750 to arrayOf("note"), 3752 to arrayOf("machine"), 3753 to arrayOf("machines"), 3754 to arrayOf("machine"), 3765 to arrayOf("n"), 3767 to arrayOf("n"), 3771 to arrayOf("name"), 3774 to arrayOf("name"), 3791 to arrayOf("why"), 3797 to arrayOf("project"), 3838 to arrayOf("path"), 3839 to arrayOf("path"), 3841 to arrayOf("have", "total"), 3846 to arrayOf("n"), 3855 to arrayOf("hub"), 3858 to arrayOf("title"), 3862 to arrayOf("project"), 3863 to arrayOf("project"), 3864 to arrayOf("n"), 3865 to arrayOf("hub"), 3867 to arrayOf("n"), 3868 to arrayOf("n"), 3869 to arrayOf("model"), 3875 to arrayOf("name"), 3894 to arrayOf("word"), 3900 to arrayOf("answer"), 3910 to arrayOf("version", "build"), 3911 to arrayOf("hub"), 3916 to arrayOf("name"), 3919 to arrayOf("when", "who", "mark"), 3923 to arrayOf("who"), 3927 to arrayOf("time"), 3928 to arrayOf("address"), 3930 to arrayOf("kind", "name"), 3945 to arrayOf("title"), 3946 to arrayOf("query"), 3949 to arrayOf("room"), 3950 to arrayOf("query"), 3952 to arrayOf("n"), 3953 to arrayOf("n"), 3954 to arrayOf("n"), 3960 to arrayOf("size"), 3964 to arrayOf("n"), 3965 to arrayOf("n"), 3966 to arrayOf("n"), 3980 to arrayOf("status"), 3982 to arrayOf("status"), 4133 to arrayOf("code"), 4135 to arrayOf("n"), 4137 to arrayOf("why"), 4149 to arrayOf("done", "of"), 4153 to arrayOf("thread"), 4156 to arrayOf("n"), 4164 to arrayOf("title"), 4165 to arrayOf("note"), 4166 to arrayOf("label"), 4167 to arrayOf("machine"), 4168 to arrayOf("machine"), 4175 to arrayOf("at", "total"), 4176 to arrayOf("at", "total"), 4180 to arrayOf("machine"), 4181 to arrayOf("machine"), 4182 to arrayOf("machines"), 4184 to arrayOf("device"), 4191 to arrayOf("price"), 4192 to arrayOf("price"), 4199 to arrayOf("home"), 4204 to arrayOf("from"), 4206 to arrayOf("note"), 4207 to arrayOf("note"), 4209 to arrayOf("v"), 4210 to arrayOf("v"), 4211 to arrayOf("v", "who"), 4213 to arrayOf("who"), 4214 to arrayOf("v"), 4216 to arrayOf("v", "cmd"), 4217 to arrayOf("cmd"), 4222 to arrayOf("v", "path"), 4223 to arrayOf("v", "note"), 4224 to arrayOf("v"), 4229 to arrayOf("tool"), 4230 to arrayOf("tool"), 4255 to arrayOf("n", "w"), 4256 to arrayOf("why"), 4257 to arrayOf("state", "why"), 4269 to arrayOf("project"), 4270 to arrayOf("n"), 4281 to arrayOf("why"), 4287 to arrayOf("name"), 4298 to arrayOf("project"), 4303 to arrayOf("n"), 4311 to arrayOf("names"), 4319 to arrayOf("dest"), 4321 to arrayOf("repo"), 4322 to arrayOf("repo"), 4324 to arrayOf("url"), 4339 to arrayOf("time"), 4361 to arrayOf("group"), 4365 to arrayOf("project"), 4366 to arrayOf("n"), 4367 to arrayOf("n"), 4368 to arrayOf("n"), 4376 to arrayOf("n"), 4433 to arrayOf("n"), 4434 to arrayOf("n"), 4435 to arrayOf("a", "b"), 4436 to arrayOf("n"), 4438 to arrayOf("parts", "lines"), 4439 to arrayOf("n"), 4470 to arrayOf("what", "project", "fab"), 4471 to arrayOf("rev", "day"), 4479 to arrayOf("n"), 4490 to arrayOf("layer"), 4491 to arrayOf("n"), 4496 to arrayOf("board"), 4508 to arrayOf("others"), 4509 to arrayOf("must", "should", "notes"), 4510 to arrayOf("id", "w"), 4520 to arrayOf("what"), 4523 to arrayOf("why"), 4524 to arrayOf("why"), 4531 to arrayOf("n"), 4547 to arrayOf("price", "n"), 4548 to arrayOf("n", "need"), 4549 to arrayOf("n"), 4550 to arrayOf("n"), 4551 to arrayOf("cost"), 4552 to arrayOf("cost"), 4565 to arrayOf("day", "n"), 4566 to arrayOf("day"), 4567 to arrayOf("cost", "n", "lines"), 4568 to arrayOf("stock", "price"), 4569 to arrayOf("lines"), 4590 to arrayOf("host"), 4601 to arrayOf("n"), 4602 to arrayOf("a", "b"), 4603 to arrayOf("n"), 4604 to arrayOf("n"), 4607 to arrayOf("day"), 4608 to arrayOf("n"), 4649 to arrayOf("turn"), 4763 to arrayOf("text"), 4766 to arrayOf("repo", "dest"), 4767 to arrayOf("repo", "dest"), 4768 to arrayOf("repo"), 4773 to arrayOf("dir"), 4774 to arrayOf("dir"), 4778 to arrayOf("editor", "job", "secs"), 4779 to arrayOf("editor", "secs"), 4780 to arrayOf("editor"), 4797 to arrayOf("time"), 4803 to arrayOf("status"), 4811 to arrayOf("time"), 4812 to arrayOf("time", "dur"), 4815 to arrayOf("answer"), 4819 to arrayOf("type"), 4820 to arrayOf("max"), 4848 to arrayOf("bytes", "tokens"), 4881 to arrayOf("what"), 4885 to arrayOf("n"), 4887 to arrayOf("n"), 4911 to arrayOf("n"), 4912 to arrayOf("done", "total"), 4920 to arrayOf("v"), 4921 to arrayOf("x", "y"), 4927 to arrayOf("machine"), 4930 to arrayOf("days"), 4931 to arrayOf("warnings"), 4937 to arrayOf("n"), 4942 to arrayOf("n"), 4944 to arrayOf("found", "total", "q"), 4947 to arrayOf("model"), 4948 to arrayOf("model", "conf")) } val common_cancel: String get() = Tr.s(0) val common_delete: String get() = Tr.s(1) @@ -28249,4 +28359,27 @@ object Msg { val web_settings_providers_browser: String get() = Tr.s(4929) fun order_lead_days(days: Number): String = Tr.f(4930, arrayOf(days)) fun order_estimate_warnings(warnings: Any): String = Tr.f(4931, arrayOf(warnings)) + val web_home_open: String get() = Tr.s(4932) + val web_home_fold: String get() = Tr.s(4933) + val web_home_unfold: String get() = Tr.s(4934) + val web_home_loading: String get() = Tr.s(4935) + val web_home_error: String get() = Tr.s(4936) + fun web_home_lead(n: Any): String = Tr.f(4937, arrayOf(n)) + val web_home_lead_one: String get() = Tr.s(4938) + val web_ring_unavailable: String get() = Tr.s(4939) + val web_ring_loading: String get() = Tr.s(4940) + val web_ring_error: String get() = Tr.s(4941) + fun web_ring_count(n: Any): String = Tr.f(4942, arrayOf(n)) + val web_ring_count_one: String get() = Tr.s(4943) + fun web_ring_found(found: Any, total: Any, q: Any): String = Tr.f(4944, arrayOf(found, total, q)) + val web_ring_not_heard: String get() = Tr.s(4945) + val web_ring_app_words: String get() = Tr.s(4946) + fun web_ring_heard_by(model: Any): String = Tr.f(4947, arrayOf(model)) + fun web_ring_heard_by_sure(model: Any, conf: Any): String = Tr.f(4948, arrayOf(model, conf)) + val web_ring_state_sent: String get() = Tr.s(4949) + val web_ring_state_new: String get() = Tr.s(4950) + val web_ring_state_heard: String get() = Tr.s(4951) + val web_ring_state_failed: String get() = Tr.s(4952) + val web_ring_state_busy: String get() = Tr.s(4953) + val web_ring_no_words: String get() = Tr.s(4954) } diff --git a/mobile/ios/Shared/TrCatalog.swift b/mobile/ios/Shared/TrCatalog.swift index b0b6aafb40..e6c119a819 100644 --- a/mobile/ios/Shared/TrCatalog.swift +++ b/mobile/ios/Shared/TrCatalog.swift @@ -4935,6 +4935,29 @@ 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. order.lead.days {days, plural, one {Est. lead time: 1 day} other {Est. lead time: {days} days}} {days, plural, one {目安納期: 1日} other {目安納期: {days}日}} {days, plural, one {Plazo estimado: 1 día} other {Plazo estimado: {days} días}} order.estimate.warnings Warning: {warnings} 警告: {warnings} Aviso: {warnings} +web.home.open Open project home プロジェクトホームを開く Abrir la página del proyecto +web.home.fold Hide threads スレッドを隠す Ocultar hilos +web.home.unfold Show threads スレッドを表示 Mostrar hilos +web.home.loading Loading project… プロジェクトを読み込み中… Cargando el proyecto… +web.home.error Could not load this project. このプロジェクトを読み込めませんでした。 No se pudo cargar este proyecto. +web.home.lead Lead time: {n} days リードタイム: {n} 日 Plazo de entrega: {n} días +web.home.lead.one Lead time: 1 day リードタイム: 1 日 Plazo de entrega: 1 día +web.ring.unavailable This hub does not show ring notes to a browser yet. Update it, or open Settings › Ring in the desktop app. このハブはまだブラウザーにリングのメモを表示しません。ハブを更新するか、デスクトップアプリの設定 › リングを開いてください。 Este hub aún no muestra las notas del anillo en un navegador. Actualízalo o abre Configuración › Anillo en la aplicación de escritorio. +web.ring.loading Loading recordings… 録音を読み込み中… Cargando grabaciones… +web.ring.error Could not load recordings. 録音を読み込めませんでした。 No se pudieron cargar las grabaciones. +web.ring.count {n} recordings 録音 {n} 件 {n} grabaciones +web.ring.count.one 1 recording 録音 1 件 1 grabación +web.ring.found {found} of {total} have “{q}”. {total} 件中 {found} 件に「{q}」があります。 {found} de {total} contienen “{q}”. +web.ring.not.heard Not heard 未認識 Sin transcribir +web.ring.app.words The Pebble app's words Pebble アプリの文字起こし Las palabras de la aplicación Pebble +web.ring.heard.by Heard by {model} {model} が認識 Transcrito por {model} +web.ring.heard.by.sure Heard by {model}, {conf}% sure {model} が認識、確度 {conf}% Transcrito por {model}, {conf}% de certeza +web.ring.state.sent given to Pebble Pebble に渡しました entregada a Pebble +web.ring.state.new waiting to be heard 認識待ち en espera de transcripción +web.ring.state.heard waiting to go to Pebble Pebble への受け渡し待ち en espera de entrega a Pebble +web.ring.state.failed not given to Pebble Pebble に渡せませんでした no entregada a Pebble +web.ring.state.busy being heard now 認識中 transcribiéndose ahora +web.ring.no.words (no words) (言葉なし) (sin palabras) """# /// thread.count = {n, plural, one {# thread} other {# threads}} @@ -7924,4 +7947,19 @@ order.estimate.warnings Warning: {warnings} 警告: {warnings} Aviso: {warnings} /// order.estimate.warnings = Warning: {warnings} static func order_estimate_warnings(warnings: String) -> String { f("order.estimate.warnings", ["warnings": warnings]) } + + /// web.home.lead = Lead time: {n} days + static func web_home_lead(n: String) -> String { f("web.home.lead", ["n": n]) } + + /// web.ring.count = {n} recordings + static func web_ring_count(n: String) -> String { f("web.ring.count", ["n": n]) } + + /// web.ring.found = {found} of {total} have “{q}”. + static func web_ring_found(found: String, total: String, q: String) -> String { f("web.ring.found", ["found": found, "total": total, "q": q]) } + + /// web.ring.heard.by = Heard by {model} + static func web_ring_heard_by(model: String) -> String { f("web.ring.heard.by", ["model": model]) } + + /// web.ring.heard.by.sure = Heard by {model}, {conf}% sure + static func web_ring_heard_by_sure(model: String, conf: String) -> String { f("web.ring.heard.by.sure", ["model": model, "conf": conf]) } } diff --git a/native/host/src/bots/ring.rs b/native/host/src/bots/ring.rs index 937630fbc6..a6a5b219c1 100644 --- a/native/host/src/bots/ring.rs +++ b/native/host/src/bots/ring.rs @@ -246,6 +246,8 @@ impl RpcHandler for RingRpc { if m == "ring.search" { if let Some(q) = p.get("q").and_then(Value::as_str) { *QUERY.lock().unwrap() = q.chars().take(200).collect(); } b.ring_publish().await; } let (q, base) = (gs(p, "q").to_string(), base(hub).await); let v = blocking(move || { let all = ringbox::list(&home); let key = ringbox::link_key(&home); let f = ringbox::search(&all, &q); json!({"total": all.len(), "notes": f.iter().take(200).map(|n| ringbox::summary(n, &base, &key)).collect::>()}) }).await.unwrap_or(Value::Null); + // `busy`: the note being heard now ("" for none), as the desktop's page has it from the `ring.busy` info + let mut v = v; if v.is_object() { v["busy"] = json!(hub.info_now()["ring.busy"].as_str().unwrap_or("")); } ok(v) } "ring.get" => { let i = gs(p, "note").to_string(); match blocking(move || ringbox::load(&home, &i)).await.flatten() { Some(n) => ok(json!({"note": n})), None => no("no such ring note".into()) } } @@ -258,6 +260,18 @@ impl RpcHandler for RingRpc { } } +/// One `Range: bytes=a-b` (or `a-`, or `-n` for the last n) over `len` bytes: the first and last byte to send. None: no range asked, or one this does +/// not read (several ranges, another unit: the whole is sent, as HTTP allows). Err: a range outside the bytes. +pub fn byte_range(header: &str, len: usize) -> Option> { + let spec = header.trim().strip_prefix("bytes=")?; if spec.contains(',') { return None } + let (a, b) = spec.split_once('-')?; let (a, b) = (a.trim(), b.trim()); + if len == 0 { return Some(Err(())) } + if a.is_empty() { let n: usize = b.parse().ok()?; if n == 0 { return Some(Err(())) } return Some(Ok((len.saturating_sub(n), len - 1))) } + let from: usize = a.parse().ok()?; if from >= len { return Some(Err(())) } + let to = if b.is_empty() { len - 1 } else { b.parse::().ok()?.min(len - 1) }; + if to < from { return None } + Some(Ok((from, to))) +} /// `GET /ring/audio/?k=`: one recording, to whoever holds its link (a browser or a phone's player cannot send the hub's token). pub struct RingAudio; impl HttpHandler for RingAudio { @@ -270,7 +284,15 @@ impl HttpHandler for RingAudio { let home = hub.cfg.home.clone(); let got = blocking(move || { if !ringbox::cap_ok(&ringbox::link_key(&home), &id, &k) { return None } ringbox::audio_path(&home, &id).and_then(|p| std::fs::read(p).ok()).map(|b| (id, b)) }).await.flatten(); match got { - Some((id, b)) => HttpReply { status: "200 OK", ctype: "audio/mp4".into(), extra: format!("Cache-Control: private, max-age=3600\r\nContent-Disposition: inline; filename=\"{id}.m4a\"\r\nX-Content-Type-Options: nosniff\r\nReferrer-Policy: no-referrer\r\n"), body: b }, + Some((id, b)) => { + let head = format!("Cache-Control: private, max-age=3600\r\nAccept-Ranges: bytes\r\nContent-Disposition: inline; filename=\"{id}.m4a\"\r\nX-Content-Type-Options: nosniff\r\nReferrer-Policy: no-referrer\r\n"); + // a player that asks for a part (Safari plays nothing it cannot ask in parts) gets that part + match byte_range(req.header("range"), b.len()) { + Some(Ok((from, to))) => HttpReply { status: "206 Partial Content", ctype: "audio/mp4".into(), extra: format!("{head}Content-Range: bytes {from}-{to}/{}\r\n", b.len()), body: b[from..=to].to_vec() }, + Some(Err(())) => HttpReply { status: "416 Range Not Satisfiable", ctype: "text/plain; charset=utf-8".into(), extra: format!("Content-Range: bytes */{}\r\n", b.len()), body: vec![] }, + None => HttpReply { status: "200 OK", ctype: "audio/mp4".into(), extra: head, body: b }, + } + } None => HttpReply::text("404 Not Found", "no such recording"), } }) diff --git a/native/host/src/bots/tests.rs b/native/host/src/bots/tests.rs index 1b1d2c6361..43241a0110 100644 --- a/native/host/src/bots/tests.rs +++ b/native/host/src/bots/tests.rs @@ -1580,6 +1580,13 @@ fn ring_form(words: &str, audio: &[u8], at: u64) -> Vec { let play = l["notes"][1]["play"].as_str().unwrap().to_string(); let path = &play[play.find("/ring/audio/").unwrap()..]; let get = |p: &str| { let hub = hub.clone(); let p = p.to_string(); async move { let h = hub.http_for(&p).unwrap(); let r = crate::auth::Req::new("GET", &p, vec![]); let a = h.call(&hub, &r).await; (a.status.to_string(), a.body) } }; assert_eq!(get(path).await, ("200 OK".to_string(), audio.to_vec())); assert_eq!(get(&format!("/ring/audio/{id}?k=00")).await.0, "404 Not Found"); + // a player asks in parts (Safari plays nothing else): that part, and where it lies; the list says which note is being heard (none now) + { let h = hub.http_for(path).unwrap(); let r = crate::auth::Req::new("GET", path, vec![("Range".to_string(), "bytes=4-7".to_string())]); let a = h.call(&hub, &r).await; + assert_eq!((a.status, a.body.as_slice()), ("206 Partial Content", &audio[4..8])); assert!(a.extra.contains(&format!("Content-Range: bytes 4-7/{}", audio.len())) && a.extra.contains("Accept-Ranges: bytes"), "{}", a.extra); } + use crate::bots::ring::byte_range as br; + assert_eq!((br("", 10), br("bytes=0-", 10), br("bytes=2-99", 10), br("bytes=-3", 10)), (None, Some(Ok((0, 9))), Some(Ok((2, 9))), Some(Ok((7, 9))))); + assert_eq!((br("bytes=10-", 10), br("bytes=-0", 10), br("bytes=0-1,4-5", 10), br("lines=0-1", 10), br("bytes=5-2", 10), br("bytes=0-", 0)), (Some(Err(())), Some(Err(())), None, None, None, Some(Err(())))); + assert_eq!(l["busy"], "", "{l}"); assert_eq!(rpc(&hub, "ring.hear", json!({"note":"../x"})).await["ok"], false); // the phones' page: the same rows, the test event's time, a search typed on the phone, and a press the phone does itself refused here let pg = rpc(&hub, "ring.page", json!({})).await; let rows = pg["rows"].as_array().unwrap().clone(); diff --git a/native/host/src/commands/home.rs b/native/host/src/commands/home.rs index d11b8b3ece..d970dde63d 100644 --- a/native/host/src/commands/home.rs +++ b/native/host/src/commands/home.rs @@ -226,6 +226,11 @@ fn read_files(root: &str, req: &Value) -> (Value, bool, PathBuf) { (snapshot, git, real) } +/// The snapshot alone, read off the folder: no git rows (recent changes, pull requests), so no `git` or `gh` is run for it. +pub async fn read_plain(root: &str, req: &Value) -> Value { + let (r, rq) = (root.to_string(), req.clone()); + tokio::task::spawn_blocking(move || read_files(&r, &rq).0).await.unwrap_or_else(|_| json!({"error": "the project home could not be read"})) +} /// The request's answer: the snapshot (with the git rows: recent changes, open pull requests), or the document window. pub async fn read(root: &str, req: &Value) -> Value { let (r, rq) = (root.to_string(), req.clone()); diff --git a/native/host/src/data/ext.rs b/native/host/src/data/ext.rs index fb34aafd58..3870015447 100644 --- a/native/host/src/data/ext.rs +++ b/native/host/src/data/ext.rs @@ -308,6 +308,18 @@ pub async fn call(hub: &Arc, c: &mut Conn, m: &str, p: &Value, is_browser: "project.card" => { let pr = s(p, "project"); if pr.is_empty() { return Some(Err(err("project"))) } let card = rpc(hub, c, "fab.look", json!({"project":pr})).await.map(|r| r["result"].clone()).unwrap_or(Value::Null); Ok(project_card(&card)) } + // feature "projecthome": a project's home page for the browser, as the desktop's opens (`project.home` and `fab.look {project}` there): `project.home {project}` → + // `{project, root, intent, parts, boards, mech, leadDays, warnings}` (`project_home` below); nothing is priced or bought from it + "project.home" => { let pr = s(p, "project"); if pr.is_empty() { return Some(Err(err("project"))) } + // a linked machine's project is read there; this hub's own from its folder, as the desktop's request reads it (commands/mod.rs) + let snap = if pr.contains('~') { match rpc(hub, c, "project.home", json!({"project":pr})).await { Ok(r) => r["result"].clone(), Err(e) => return Some(Err(e)) } } else { + let root = { let m = hub.model().await; m.projects.get(pr).filter(|x| !x.removed).map(|x| x.root.clone()).unwrap_or_default() }; + if root.is_empty() { return Some(Err(err("Choose an existing project."))) } + // the files only: the page draws no git rows, so no `git log` or `gh pr list` runs for it + // (a folder that cannot be read answers an empty page, as the desktop's does: the error is inside the snapshot) + crate::commands::home::read_plain(&root, &json!({"project":pr})).await }; + let card = rpc(hub, c, "fab.look", json!({"project":pr})).await.map(|r| r["result"].clone()).unwrap_or(Value::Null); + Ok(project_home(pr, &snap, &card)) } "thread.buy" if s(p, "thread").is_empty() && !s(p, "project").is_empty() => { let card = rpc(hub, c, "fab.look", json!({"project":s(p, "project")})).await.map(|r| r["result"].clone()).unwrap_or(Value::Null); let b = &card["buy"]; @@ -524,6 +536,27 @@ pub fn project_card(card: &Value) -> Value { if let Some(w) = card["estimate_warnings"].as_str().filter(|w| !w.is_empty()) { out["estimate_warnings"] = json!(w); } out } +/// The project's home page (feature "projecthome"), from the hub's own snapshot (`commands/home.rs`) and project card (`settings/fab.rs` `look_project`): +/// the goal and notes as written, the parts to order (name, kind, fab file), the boards (the snapshot's, then the card's board files, paths from the +/// project's root, 12 at most), the mechanical models (biggest first: the assembly), and what the last estimate said beyond a price: `leadDays` +/// (0: none) and `warnings`, each once. +pub fn project_home(project: &str, snap: &Value, card: &Value) -> Value { + let root = snap["root"].as_str().unwrap_or(""); + let rel = |p: &str| p.strip_prefix(root).filter(|_| !root.is_empty()).map(|r| r.trim_start_matches('/').to_string()).unwrap_or_else(|| p.to_string()); + let arts = |kind: &'static str| snap["artifacts"].as_array().into_iter().flatten().filter(move |a| a["kind"] == kind); + let ci = card["intent"].as_str().unwrap_or(""); + let intent = if ci.trim().is_empty() && arts("intent").next().is_some() { snap["intent"].as_str().unwrap_or("") } else { ci }; + let mut boards: Vec = arts("board").map(|a| rel(a["path"].as_str().unwrap_or(""))).filter(|p| !p.is_empty()).collect(); + for b in card["board_files"].as_array().into_iter().flatten().filter_map(Value::as_str) { if !boards.iter().any(|o| o == b) { boards.push(b.to_string()); } } + boards.truncate(12); + let mut mech: Vec<(String, String, u64)> = arts("mech").map(|a| { let p = rel(a["path"].as_str().unwrap_or("")); let n = p.rsplit('/').next().unwrap_or("").to_string(); (p, n, a["size"].as_u64().unwrap_or(0)) }).collect(); + mech.sort_by(|a, b| b.2.cmp(&a.2).then(a.1.cmp(&b.1))); + let parts: Vec = card["parts"].as_array().into_iter().flatten().map(|x| json!({"name": x["name"].as_str().unwrap_or(""), "kind": x["kind"].as_str().unwrap_or(""), "path": x["path"].as_str().unwrap_or("")})).collect(); + let warnings: Vec<&str> = card["estimate_warnings"].as_str().unwrap_or("").split("; ").map(str::trim).filter(|w| !w.is_empty()).collect(); + json!({"project": project, "root": root, "intent": intent, "parts": parts, "boards": boards, + "mech": mech.iter().map(|(p, n, z)| json!({"path": p, "name": n, "size": z})).collect::>(), + "leadDays": card["lead_days"].as_u64().unwrap_or(0), "warnings": warnings}) +} // ---- viewers, files, browser (each the hub's own request, for the folder of the thread) ---- pub(super) async fn root_of(hub: &Arc, thread: &str) -> Result { // a thread of a linked machine: the folder over there (its mirror holds the project's root and the thread's worktree) diff --git a/native/host/src/data/mod.rs b/native/host/src/data/mod.rs index 613ad5006e..f367ac1a0c 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", "noProvider"]; +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", "projecthome", "ringnotes"]; const PREVIEW: usize = 140; const ASK_SCAN: usize = 4000; diff --git a/native/host/src/data/tests.rs b/native/host/src/data/tests.rs index b2d33ac024..9c44dffec5 100644 --- a/native/host/src/data/tests.rs +++ b/native/host/src/data/tests.rs @@ -69,10 +69,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", "noProvider"])); + 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", "projecthome", "ringnotes"])); 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", "noProvider"]), "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", "projecthome", "ringnotes"]), "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"); @@ -685,6 +685,23 @@ impl RpcHandler for FakeStar { let r = ask(&mut ws, 10, "project.card", json!({})).await; assert_eq!(r["ok"], false, "{r}"); assert_eq!(super::ext::project_card(&json!({"goal":"A gimbal node","board_files":["Nodes/A/A.kicad_pcb","B.kicad_pcb"]})), json!({"goal":"A gimbal node","boards":["A","B"]})); assert_eq!(super::ext::project_card(&json!({"goal":"A gimbal node","board_files":["B.kicad_pcb"],"lead_days":9,"estimate_warnings":"thin board"})), json!({"goal":"A gimbal node","boards":["B"],"lead_days":9,"estimate_warnings":"thin board"})); + // the browser's project home: the project's own page, never an error for one with no design yet; a project is needed, and one that exists + let r = ask(&mut ws, 11, "project.home", json!({"project":"p1"})).await; + assert_eq!((r["ok"].as_bool(), &r["result"]["project"], &r["result"]["boards"], &r["result"]["parts"], &r["result"]["leadDays"]), (Some(true), &json!("p1"), &json!([]), &json!([]), &json!(0)), "{r}"); + assert!(r["result"]["root"].is_string() && r["result"]["intent"].is_string() && r["result"]["warnings"].is_array(), "{r}"); + let r = ask(&mut ws, 12, "project.home", json!({})).await; assert_eq!(r["ok"], false, "{r}"); + let r = ask(&mut ws, 13, "project.home", json!({"project":"no-such"})).await; assert_eq!(r["ok"], false, "{r}"); + let snap = json!({"root":"/home/user/lamp","intent":"# Goal\n\nfrom the snapshot\n","artifacts":[ + {"kind":"board","path":"/home/user/lamp/boards/led/led.kicad_pcb"},{"kind":"intent","path":"/home/user/lamp/.backplane/intent.md"}, + {"kind":"mech","path":"/home/user/lamp/mech/shade.step","size":10},{"kind":"mech","path":"/home/user/lamp/mech/lamp.step","size":90}]}); + let card = json!({"intent":"# Goal\n\nA lamp.\n","parts":[{"name":"LED board","kind":"pcb","path":"boards/led/led.fab.json","qty":5}], + "board_files":["boards/led/led.kicad_pcb","boards/psu/psu.kicad_pcb"],"lead_days":9,"estimate_warnings":"thin board; fragile"}); + assert_eq!(super::ext::project_home("p1", &snap, &card), json!({"project":"p1","root":"/home/user/lamp","intent":"# Goal\n\nA lamp.\n", + "parts":[{"name":"LED board","kind":"pcb","path":"boards/led/led.fab.json"}],"boards":["boards/led/led.kicad_pcb","boards/psu/psu.kicad_pcb"], + "mech":[{"path":"mech/lamp.step","name":"lamp.step","size":90},{"path":"mech/shade.step","name":"shade.step","size":10}],"leadDays":9,"warnings":["thin board","fragile"]})); + // the card had no intent of its own: the snapshot's is shown; no estimate: no lead time and no warnings + let bare = super::ext::project_home("p1", &snap, &json!({})); + assert_eq!((&bare["intent"], &bare["leadDays"], &bare["warnings"], &bare["parts"]), (&json!("# Goal\n\nfrom the snapshot\n"), &json!(0), &json!([]), &json!([]))); let r = ask(&mut ws, 7, "threads.list", json!({"project":"p1"})).await; assert!(r["result"]["threads"].as_array().unwrap().iter().all(|t| t["status"].is_string()), "every thread says its dot's word: {r}"); } diff --git a/native/host/src/data/webpolicy.rs b/native/host/src/data/webpolicy.rs index fcce4fda00..42f4af94d0 100644 --- a/native/host/src/data/webpolicy.rs +++ b/native/host/src/data/webpolicy.rs @@ -101,6 +101,7 @@ fn classify(method: &str, params: &Value) -> Option { | "models.list" | "plan.get" | "project.card" + | "project.home" | "projects.list" | "review.list" | "review.page" @@ -179,10 +180,11 @@ fn classify(method: &str, params: &Value) -> Option { // Initiates an order or checkout. "order.buy" | "thread.buy" => Denied, - // Native ring transport setup and delivery. + // The ring's recordings: listed and found (their words, where each went, the link that plays one), and heard again. + "ring.list" => Passive, + "ring.hear" => Activity, + // Native ring transport setup and delivery: the webhook's token (on `ring.page`), a note's raw form, sending to the bot, the desktop's own search. "ring.get" - | "ring.hear" - | "ring.list" | "ring.page" | "ring.page.act" | "ring.search" @@ -223,6 +225,11 @@ mod tests { assert_eq!(policy("models.favorite", &json!({"provider":"claude","model":"opus"})), Policy::Activity); assert!(!allowed("composer.run", &json!({"text":"/secret example"}))); assert!(allowed("composer.run", &json!({"text":"/settle"}))); + // the ring's recordings are read and heard again; its webhook, token and delivery stay native + assert_eq!(policy("ring.list", &json!({"q":"sam"})), Policy::Passive); + assert_eq!(policy("ring.hear", &json!({"note":"n1","engine":"local"})), Policy::Activity); + for m in ["ring.page", "ring.page.act", "ring.setup", "ring.send", "ring.get", "ring.search"] { assert_eq!(policy(m, &Value::Null), Policy::Denied, "{m}"); } + assert_eq!(policy("project.home", &json!({"project":"p1"})), Policy::Passive); assert_eq!(policy("devices.page", &Value::Null), Policy::Devices); assert_eq!(policy("devices.page.act", &Value::Null), Policy::Denied); } diff --git a/native/host/src/net/webingress.rs b/native/host/src/net/webingress.rs index debf5c5581..2917c40e66 100644 --- a/native/host/src/net/webingress.rs +++ b/native/host/src/net/webingress.rs @@ -42,6 +42,12 @@ impl BrowserIngress<'_> { mod tests { use super::*; + #[test] + fn a_ring_recording_is_a_protected_asset_by_its_own_id_only() { + assert!(super::is_protected_asset("/ring/audio/n0123456789abcdef") && super::is_protected_asset("/ring/audio/n0123456789abcdef.m4a")); + for no in ["/ring/audio/", "/ring/audio/../x", "/ring/audio/n0123456789ABCDEF", "/ring/audio/n0123456789abcdef/x", "/ring/hook", "/ring"] { assert!(!super::is_protected_asset(no), "{no}"); } + assert!(super::SECURITY_HEADERS.contains("media-src 'self'"), "the page may play a recording from its own origin, and from nowhere else"); + } #[test] fn terminal_lazy_assets_require_paired_session() { for path in ["/assets/terminal.js", "/assets/xterm.css"] { @@ -367,7 +373,7 @@ mod tests { const SECURITY_HEADERS: &str = concat!( "Cache-Control: private, no-store\r\n", "Content-Security-Policy: default-src 'none'; script-src 'self'; style-src 'self'; ", - "img-src 'self' blob: data:; font-src 'self'; worker-src 'self'; connect-src 'self'; ", + "img-src 'self' blob: data:; media-src 'self'; font-src 'self'; worker-src 'self'; connect-src 'self'; ", "object-src 'none'; frame-ancestors 'none'; base-uri 'none'; form-action 'self'\r\n", "X-Content-Type-Options: nosniff\r\nReferrer-Policy: no-referrer\r\n", ); @@ -613,7 +619,8 @@ where S: tokio::io::AsyncRead + tokio::io::AsyncWrite + Unpin + Send { ); for line in result.extra.lines() { let lower = line.to_ascii_lowercase(); - if lower.starts_with("content-disposition:") || (is_blob && lower.starts_with("etag:")) { + let is_ring = req.route().starts_with("/ring/audio/"); + if lower.starts_with("content-disposition:") || (is_blob && lower.starts_with("etag:")) || (is_ring && (lower.starts_with("accept-ranges:") || lower.starts_with("content-range:"))) { headers.push_str(line.trim_end()); headers.push_str("\r\n"); } @@ -680,6 +687,8 @@ fn is_browser_ws_target(target: &str) -> bool { fn is_protected_asset(path: &str) -> bool { matches!(path, "/files/get" | "/message-image") || path.strip_prefix("/blob/").is_some_and(|h| h.len() == 64 && h.bytes().all(|b| matches!(b, b'0'..=b'9' | b'a'..=b'f'))) || + // a ring recording (Settings › Ring): its handler still wants the link's own key (bots/ring.rs `RingAudio`) + path.strip_prefix("/ring/audio/").is_some_and(|id| crate::voice::ringbox::id_ok(id.trim_end_matches(".m4a"))) || path.strip_prefix("/bots/").and_then(|p| p.strip_suffix("/screen.jpg")) .is_some_and(|id| !id.is_empty() && id.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_')) } diff --git a/native/host/src/settings/fab.rs b/native/host/src/settings/fab.rs index fcc2ad4f77..be5c5f4099 100644 --- a/native/host/src/settings/fab.rs +++ b/native/host/src/settings/fab.rs @@ -264,6 +264,9 @@ pub async fn look_project(hub: &Arc, project: &str) -> Value { let src = crate::statehost::policies().and_then(|q| q.with_state(|st| crate::present::ready::page_source(st, project))).flatten(); if let Some(th) = src { let tc = look(hub, &th).await; + // what the last estimate said beyond a price (the thread's card asked for it; this one never asks the order server) + if tc["lead_days"].as_u64().unwrap_or(0) > 0 { c["lead_days"] = tc["lead_days"].clone(); } + if !tc["estimate_warnings"].as_str().unwrap_or("").is_empty() { c["estimate_warnings"] = tc["estimate_warnings"].clone(); } if let Some(b) = crate::statehost::policies().and_then(|q| q.with_state(|st| crate::present::ready::page_button(st, &th, &tc))).flatten() { c["buy"] = b; } } c diff --git a/test/web/home.mjs b/test/web/home.mjs new file mode 100644 index 0000000000..81228860b9 --- /dev/null +++ b/test/web/home.mjs @@ -0,0 +1,322 @@ +// The web client's Project Home and Settings › Ring, driven headless against the disposable browser hub of rig.mjs. +// Run with bun test/web/home.mjs , after cargo-q test --bin backplane-hub --no-run in +// native/host. A project with a goal, a fab file, a board and two models: its name opens the home (goal and notes, To order, Boards, +// Mechanical, threads, New thread), a thread row and New thread leave it. One ring note is delivered through the ring's own webhook; +// Settings › Ring lists it, finds it, plays it from the page's origin and asks for it to be heard again, while the ring's setup stays +// refused to a browser. Stand-in agents only; no order server is reachable, so the estimate's lead time and warnings are put into the +// hub's `project.home` answer on its way to the page (a drawing check: the hub's own test covers where they come from). +import assert from 'node:assert/strict'; +import { withBrowser, withTestTls } from './rig.mjs'; + +async function main(binary, output) { + const fs = await import('node:fs/promises'); + const path = await import('node:path'); + const { spawn } = await import('node:child_process'); + const { once } = await import('node:events'); + const { createServer } = await import('node:net'); + assert.ok(binary && output && process.env.BP_TMP && process.versions.bun); + const temp = await fs.mkdtemp(path.join(process.env.BP_TMP, 'web-home-')); + const home = path.join(temp, 'hub'); + const agents = path.join(temp, 'agents'); + const project = path.join(temp, 'project'); + await fs.mkdir(agents); + await fs.mkdir(path.join(project, '.backplane'), { recursive: true }); + await fs.mkdir(path.join(project, 'mech')); + await fs.writeFile(path.join(temp, 'registry-clock'), String(Date.now())); // the fixture hub's pairing clock (rig.mjs) + await fs.mkdir(output, { recursive: true }); + await fs.writeFile(path.join(project, 'ecc83-pp.kicad_pro'), '{}'); + await fs.writeFile(path.join(project, 'ecc83-pp.kicad_pcb'), '(kicad_pcb (version 20240108) (generator "fixture"))\n'); + await fs.writeFile(path.join(project, '.backplane', 'intent.md'), '# Goal\n\nA push-pull amplifier for the bench.\n\n# Parts\n\n- Amp board: the PCB, to order\n- Lid: printed\n\n# Notes\n\nKeep it under 100 mm wide.\n'); + await fs.writeFile(path.join(project, 'amp.fab.json'), JSON.stringify({ name: 'Amp board', kind: 'pcb', source: 'ecc83-pp.kicad_pcb', qty: 5, options: {}, features: {} })); + await fs.writeFile(path.join(project, 'mech', 'lid.step'), 'ISO-10303-21;\n'); + await fs.writeFile(path.join(project, 'mech', 'amp-assembly.step'), 'ISO-10303-21;\n' + 'x'.repeat(4000)); + const standin = new URL('../tools/claude_standin.ts', import.meta.url).pathname; + await fs.writeFile(path.join(agents, 'claude'), '#!/bin/sh\nexec bun "$BP_WEB_STANDIN" "$@"\n', { mode: 0o700 }); + + const native = createServer(); + native.listen(0, '127.0.0.1'); + await once(native, 'listening'); + const nativePort = native.address().port; + await new Promise(resolve => native.close(resolve)); + assert.ok(nativePort >= 3799); + + try { + await withTestTls(path.join(home, 'browser.sock'), async tls => { + const env = { PATH: process.env.PATH, HOME: temp, TMPDIR: temp, BP_TMP: temp, BACKPLANE_VAULT_KEYRING: 'file', + BP_WEB_MASK_FIXTURE: 'fixture-mask-home', BP_WEB_STANDIN: standin, BP_WEB_FIXTURE: temp, BACKPLANE_AGENTS: agents, + BP_WEB_NATIVE_PORT: String(nativePort), BP_WEB_TLS_PORT: String(tls.port), + BACKPLANE_NO_UPDATE: '1', BACKPLANE_ORDER_SERVER: 'http://127.0.0.1:9' }; + const child = spawn(binary, ['--ignored', '--exact', 'net::listener::webingress::isolated_browser_hub'], { + env, stdio: ['ignore', 'pipe', 'pipe'], detached: true, + }); + const logs = []; + for (const stream of [child.stdout, child.stderr]) stream.on('data', chunk => logs.push(chunk)); + const exited = once(child, 'exit'); + try { + for (let i = 0; ; ++i) { + if (await fs.stat(path.join(home, 'browser.sock')).then(s => s.isSocket(), () => false)) break; + assert.ok(child.exitCode === null && i < 400, 'fixture failed to start: ' + Buffer.concat(logs).toString().slice(-2000)); + await Bun.sleep(50); + } + const credential = (await fs.readFile(path.join(home, 'token'), 'utf8')).trim(); + const ws = new WebSocket('ws://127.0.0.1:' + nativePort + '/ws?data=1&enc=json', { headers: { Authorization: 'Bearer ' + credential } }); + const replies = new Map(); + let next = 0; + ws.onmessage = event => { + if (typeof event.data !== 'string') return; + const frame = JSON.parse(event.data); + if (frame.t === 'reply') replies.get(frame.id)?.(frame); + }; + await new Promise((resolve, reject) => { ws.onopen = resolve; ws.onerror = () => reject(Error('native fixture connection failed')); }); + const rpc = async (method, params) => { + const id = ++next; + try { + const frame = await new Promise((resolve, reject) => { + const timer = setTimeout(() => reject(Error(method + ' timed out')), 10000); + replies.set(id, frame => { clearTimeout(timer); resolve(frame); }); + ws.send(JSON.stringify({ id, m: method, p: params })); + }); + assert.equal(frame.ok, true, method + ' failed: ' + JSON.stringify(frame.error)); + return frame.result; + } finally { replies.delete(id); } + }; + try { + await rpc('devices.page.act', { action: 'device-web-access', value: '1' }); + + // one ring note, through the ring's own webhook: set up natively (a browser may not), then the Pebble app's form + const ring = await rpc('ring.setup', {}); + assert.ok(ring.hook && ring.token, 'ring.setup: ' + JSON.stringify(ring)); + const audio = Buffer.from('\x00\x00\x00\x18ftypM4A fixture-recording', 'latin1'); + const said = Date.now() - 3600_000; + const form = Buffer.concat([ + Buffer.from('--bnd\r\nContent-Disposition: form-data; name="audio"; filename="rec-1.m4a"\r\nContent-Type: audio/mp4\r\n\r\n'), audio, + Buffer.from('\r\n--bnd\r\nContent-Disposition: form-data; name="transcription"\r\n\r\nRemind me to order the amp boards\r\n' + + '--bnd\r\nContent-Disposition: form-data; name="recordedAt"\r\n\r\n' + said + '\r\n' + + '--bnd\r\nContent-Disposition: form-data; name="client"\r\n\r\nring\r\n--bnd--\r\n'), + ]); + const posted = await fetch('http://127.0.0.1:' + nativePort + '/hook/' + ring.hook, { method: 'POST', body: form, headers: { + 'Content-Type': 'multipart/form-data; boundary=bnd', Authorization: 'Bearer ' + ring.token, + 'X-Index-Webhook-Version': '1', 'X-Index-Delivery': 'd-home-1', 'X-Index-Trigger': 'single-click-hold' } }); + assert.equal(posted.status, 200, 'the ring webhook: ' + await posted.text()); + let noteId = ''; + for (let i = 0; i < 100 && !noteId; ++i) { + noteId = (await rpc('ring.list', {})).notes?.[0]?.id ?? ''; + if (!noteId) await Bun.sleep(100); + } + assert.match(noteId, /^n[0-9a-f]{16}$/, 'the note is kept'); + + await withBrowser(tls, async (context, origin) => { + // the estimate's lead time and warnings, put into `project.home`'s answer (no order server here); the page's own requests, + // by method, for the checks below. The page asks for plain frames here (no &z=deflate), so they can be read + await context.addInitScript(() => { + const Native = window.WebSocket; + window.bpCalls = []; + window.WebSocket = class extends Native { + constructor(url, protocols) { super(String(url).replace('&z=deflate', ''), protocols); this.homeIds = new Set(); window.bpSocket = this; } + send(data) { + try { const f = JSON.parse(data); if (f.m) window.bpCalls.push(f.m); if (f.m === 'project.home') this.homeIds.add(f.id); } catch { /* binary */ } + return super.send(data); + } + addEventListener(type, fn, opts) { + if (type !== 'message') return super.addEventListener(type, fn, opts); + return super.addEventListener(type, ev => { + let f = null; + if (typeof ev.data === 'string') { try { f = JSON.parse(ev.data); } catch { /* not JSON */ } } + if (f && f.t === 'reply' && f.ok && this.homeIds.has(f.id) && window.bpEstimate) { + window.bpHomeRaw = JSON.parse(JSON.stringify(f.result)); + Object.assign(f.result, window.bpEstimate); + fn.call(this, new MessageEvent('message', { data: JSON.stringify(f) })); + return; + } + if (f && f.t === 'reply' && f.ok && this.homeIds.has(f.id)) window.bpHomeRaw = f.result; + fn.call(this, ev); + }, opts); + } + }; + }); + const page = await context.newPage(); + const errors = []; + page.on('pageerror', e => errors.push(String(e))); + if (process.env.BP_HOME_DEBUG) { + page.on('console', m => console.error('console', m.type(), m.text())); + page.on('response', r => { if (r.status() >= 400) console.error('http', r.status(), r.url()); }); + } + const testId = id => page.getByTestId(id); + const shot = name => page.screenshot({ path: path.join(output, name + '.png') }); + await page.setViewportSize({ width: 1280, height: 860 }); + await page.goto(origin); + await testId('pair-card').waitFor(); + const name = 'Home browser'; + await testId('pair-name').fill(name); + await testId('pair-request-btn').click(); + await testId('pair-code').waitFor(); + const { rows } = await rpc('devices.page', {}); + const row = rows.find(r => r.label === name && r.buttons?.some(b => b.action === 'device-web-approve')); + assert.ok(row, 'no approval row'); + await rpc('devices.page.act', row.buttons.find(b => b.action === 'device-web-approve')); + await testId('composer-input').waitFor(); + await testId('timeline').waitFor(); + + // 1. the project's name opens its home: the hub's own answer first, as it is + // (the fixture's project has had no turn: it is under the Quiet fold until that is opened) + await testId('sidebar-list').waitFor(); + if (await page.locator('[data-testid^="project-open-"]').count() === 0) await testId('section-toggle-quiet').click(); + const open = page.locator('[data-testid^="project-open-"]').first(); + await open.waitFor(); + await open.click(); + await testId('project-home').waitFor(); + await testId('project-home-intent').waitFor(); + assert.equal(await testId('project-home-title').innerText(), 'Browser fixture'); + const intent = await testId('project-home-intent').innerText(); + assert.match(intent, /Goal\s+A push-pull amplifier for the bench\./); + assert.match(intent, /Amp board: the PCB, to order/); + assert.match(intent, /Keep it under 100 mm wide\./); + assert.match(await testId('project-home-part-0').innerText(), /Amp board\s+pcb\s+amp\.fab\.json/); + assert.match(await testId('project-home-board-0').innerText(), /ecc83-pp\.kicad_pcb/); + assert.match(await testId('project-home-mech-0').innerText(), /amp-assembly\.step\s+Assembly/); + assert.match(await testId('project-home-mech-1').innerText(), /lid\.step/); + await testId('project-home-thread-t1').waitFor(); + assert.equal(await testId('project-home-lead').count(), 0, 'no estimate, no lead time'); + assert.equal(await testId('project-home-warning').count(), 0); + const raw = await page.evaluate(() => window.bpHomeRaw); + assert.deepEqual(Object.keys(raw).sort(), ['boards', 'intent', 'leadDays', 'mech', 'parts', 'project', 'root', 'warnings']); + assert.equal(raw.leadDays, 0); + assert.equal(await testId('composer-input').isVisible(), false, 'the home covers the thread and its composer'); + assert.equal(await testId('thread-title').innerText(), '', 'the bar names the project, no thread'); + assert.equal(await page.locator('.bp-thread-row.active').count(), 0, 'no thread row is marked while the home is on show'); + await shot('home-1-project'); + + // 2. an estimate's lead time and warnings are drawn on the To order card + await page.evaluate(() => { window.bpEstimate = { leadDays: 9, warnings: ['thin board', 'fragile'] }; }); + await testId('thread-row-t1').click(); + await testId('project-home').waitFor({ state: 'hidden' }); + await open.click(); + await testId('project-home-lead').waitFor(); + assert.equal(await testId('project-home-lead').innerText(), 'Lead time: 9 days'); + assert.deepEqual(await testId('project-home-warning').allInnerTexts(), ['thin board', 'fragile']); + await shot('home-2-lead-and-warnings'); + await page.evaluate(() => { window.bpEstimate = null; }); + + // 3. the chevron folds the project's threads and leaves the home on show; again unfolds + const fold = page.locator('[data-testid^="project-fold-"]').first(); + if (await fold.isEnabled()) { + await fold.click(); + await page.waitForFunction(() => document.querySelector('[data-testid^="project-fold-"]')?.getAttribute('aria-expanded') === 'false'); + assert.ok(await testId('project-home').isVisible()); + await page.locator('[data-testid^="project-fold-"]').first().click(); + await page.waitForFunction(() => document.querySelector('[data-testid^="project-fold-"]')?.getAttribute('aria-expanded') === 'true'); + } + + // 4. a thread row opens the thread and the home is gone + await testId('project-home-thread-t1').click(); + await testId('project-home').waitFor({ state: 'hidden' }); + await testId('composer-input').waitFor(); + await page.waitForFunction(() => document.querySelector('[data-testid="thread-row-t1"]')?.classList.contains('active')); + assert.equal(await testId('thread-title').innerText(), 'Browser test'); + + // 5. New thread on the home makes a thread in the project and opens it + const before = (await rpc('threads.list', { project: 'p1' })).threads.length; + await open.click(); + await testId('project-home').waitFor(); + await testId('project-home-new-thread').click(); + await testId('project-home').waitFor({ state: 'hidden' }); + await testId('composer-input').waitFor(); + const after = (await rpc('threads.list', { project: 'p1' })).threads; + assert.equal(after.length, before + 1, 'New thread made one thread'); + await shot('home-3-new-thread'); + + // 6. a narrow screen: the home still reads + await page.setViewportSize({ width: 390, height: 780 }); + await page.evaluate(() => document.querySelector('.bp-side-toggle')?.click()); + await open.click(); + await testId('project-home-intent').waitFor(); + const wide = await page.evaluate(() => document.documentElement.scrollWidth > document.documentElement.clientWidth); + assert.equal(wide, false, 'nothing overflows sideways at 390 px'); + await shot('home-4-phone'); + await page.setViewportSize({ width: 1280, height: 860 }); + + // 7. Settings › Ring: the note, found by its words, played from this origin, heard again; the ring's setup stays native + await testId('settings-btn').click(); + await testId('settings-nav-ring').click(); + await testId('ring-note-' + noteId).waitFor(); + assert.match(await testId('ring-note-' + noteId).innerText(), /Remind me to order the amp boards/); + assert.equal(await testId('ring-count').innerText(), '1 recording'); + await shot('ring-1-list'); + await testId('ring-search').fill('zebra'); + await testId('ring-search').press('Enter'); + await page.waitForFunction(() => /0 of 1 have “zebra”\./.test(document.querySelector('[data-testid="ring-count"]')?.textContent || '')); + assert.equal(await testId('ring-note-' + noteId).count(), 0); + await testId('ring-search').fill('AMP boards'); + await testId('ring-search').press('Enter'); + await testId('ring-note-' + noteId).waitFor(); + const src = await testId('ring-audio-' + noteId).getAttribute('src'); + assert.match(src, new RegExp('^/ring/audio/' + noteId + '\\?k=[0-9a-f]+$')); + const played = await page.evaluate(async s => { + const r = await fetch(s); + return { status: r.status, type: r.headers.get('content-type'), bytes: Array.from(new Uint8Array(await r.arrayBuffer())) }; + }, src); + assert.equal(played.status, 200); + assert.equal(played.type, 'audio/mp4'); + assert.deepEqual(Buffer.from(played.bytes), audio, 'the recording as it came'); + const refused = await page.evaluate(async s => [ + (await fetch(s.replace(/k=.*/, 'k=00'))).status, + (await fetch('/ring/audio/nope?k=00')).status, + ], src); + assert.deepEqual(refused, [404, 404], 'a wrong key and a name that is no recording'); + const part = await page.evaluate(async s => { + const r = await fetch(s, { headers: { Range: 'bytes=4-7' } }); + return { status: r.status, range: r.headers.get('content-range'), bytes: Array.from(new Uint8Array(await r.arrayBuffer())) }; + }, src); + assert.deepEqual(part, { status: 206, range: 'bytes 4-7/' + audio.length, bytes: Array.from(audio.subarray(4, 8)) }, 'a player that asks in parts gets the part'); + const blocked = await page.evaluate(() => { + const violations = []; + document.addEventListener('securitypolicyviolation', e => violations.push(e.violatedDirective)); + return new Promise(resolve => { + const a = document.querySelector('audio.bp-ring-audio'); + a.load(); + setTimeout(() => resolve(violations), 600); + }); + }); + assert.deepEqual(blocked, [], 'the page may load the recording'); + // hearing again changes the row in place: the player on show is the same element (a recording that plays keeps playing) + await page.evaluate(() => { document.querySelector('audio.bp-ring-audio').dataset.kept = '1'; }); + await testId('ring-hear-local-' + noteId).click(); + await page.waitForFunction(() => window.bpCalls.includes('ring.hear')); + await page.waitForFunction(() => window.bpCalls.filter(m => m === 'ring.list').length >= 4, null, { timeout: 15000 }); + assert.equal(await page.evaluate(() => document.querySelector('audio.bp-ring-audio')?.dataset.kept), '1', 'the list read again did not rebuild the player'); + await shot('ring-2-heard-again'); + const calls = await page.evaluate(() => window.bpCalls); + assert.ok(calls.includes('ring.list') && calls.includes('ring.hear') && calls.includes('project.home')); + for (const m of ['ring.page', 'ring.setup', 'ring.send', 'ring.get', 'ring.search', 'ring.page.act']) assert.ok(!calls.includes(m), 'the page never asks ' + m); + const denied = await page.evaluate(() => new Promise((resolve, reject) => { + const out = {}; + const methods = ['ring.page', 'ring.setup', 'ring.send', 'ring.get', 'ring.search', 'ring.page.act', 'thread.buy', 'order.buy']; + const socket = new WebSocket('/ws?data=1&enc=json'); + const timer = setTimeout(() => { socket.close(); reject(Error('browser RPC timeout')); }, 5000); + socket.addEventListener('open', () => methods.forEach((m, i) => socket.send(JSON.stringify({ id: i + 1, m, p: { note: 'n0000000000000000', thread: 't1' } })))); + socket.addEventListener('message', ev => { + if (typeof ev.data !== 'string') return; + const f = JSON.parse(ev.data); + if (f.t !== 'reply') return; + out[methods[f.id - 1]] = f.ok ? 'ok' : f.error; + if (Object.keys(out).length === methods.length) { clearTimeout(timer); socket.close(); resolve(out); } + }); + })); + for (const [m, said] of Object.entries(denied)) assert.equal(said, 'not allowed for browser', m); + + assert.deepEqual(errors, [], 'page errors: ' + errors.join('\n')); + console.log('web home: ok', JSON.stringify({ note: noteId, threads: after.length })); + }); + } catch (e) { + await fs.writeFile(path.join(output, 'hub.log'), Buffer.concat(logs)); + throw e; + } finally { ws.close(); } + } finally { + if (child.pid && child.exitCode === null) { try { process.kill(-child.pid, 'SIGTERM'); } catch { /* already gone */ } } + await exited; + } + }); + } finally { await fs.rm(temp, { recursive: true, force: true }); } +} + +if (import.meta.main) await main(...process.argv.slice(2)); diff --git a/web/build.ts b/web/build.ts index 3c247d04fc..7f88e89235 100644 --- a/web/build.ts +++ b/web/build.ts @@ -127,6 +127,20 @@ function collectI18nKeys(tsFiles: string[]): string[] { "provider.notice.button", "provider.notice.senderr", "provider.notice.senderr.remote", + // Settings › Ring: texts the pure model names by key (ring-model.ts) + "ring.no.recordings.yet", + "web.ring.count", + "web.ring.count.one", + "web.ring.found", + "web.ring.not.heard", + "web.ring.app.words", + "web.ring.heard.by", + "web.ring.heard.by.sure", + "web.ring.state.sent", + "web.ring.state.new", + "web.ring.state.heard", + "web.ring.state.failed", + "web.ring.state.busy", ]); 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 54cf1c928e..4d8958236d 100644 --- a/web/dist/assets/app.js +++ b/web/dist/assets/app.js @@ -1,16 +1,17 @@ -function dn(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 ai(e){return e==="done"||e==="failed"||e==="cancelled"}function oi(e,t){if(!e||e.id!==t.id)return!0;let n=ai(e.state),i=ai(t.state);if(n!==i)return i;return(t.ended??0)>=(e.ended??0)}function li(e){if(e.state!=="done")return!1;if(typeof e.hold==="boolean")return!e.hold;return(e.notes??[]).length===0}var Mt={en:{"agy.signout":"Sign out","android.hub.machines.approve":"Approve","android.load.earlier":"load earlier","approval.dismiss":"Dismiss","approval.implement":"Implement","ask.plan":"Proposed plan","bots.new":"New bot","bots.rooms":"Rooms","bots.tab.browser":"Browser","common.cancel":"Cancel","common.close":"Close","common.copy":"Copy","common.delete":"Delete","common.refresh":"Refresh","common.remove":"Remove","common.save":"Save","composer.model.tip":"Choose the model and effort","composer.placeholder":"Ask anything: @bot, >thread, %project, #room, $skill, /btw","composer.send":"Send","composer.stop":"Stop","gpui.acct.connected":"Connected","gpui.acct.not.connected":"Not connected","gpui.acct.sign.in.expired":"Sign-in expired","gpui.ask.plan.ready":"Ready for review","gpui.ask.plan.revise":"Revise","gpui.ask.plan.reviseph":"What should change in the plan?","gpui.ask.plan.sendrev":"Send revision","gpui.b.in.reply.to":"↩ In reply to: {quote}","gpui.b.replying.to":"↩ Replying to: {line}","gpui.bots.recall.off":"Off","gpui.bots.recall.on":"On","gpui.c.solid.big.next":"Loading it may take a while and a lot of memory.","gpui.c.solid.load.big":"Load it anyway","gpui.c.solid.loading.big":"Loading it anyway…","gpui.c.term.collapse":"Collapse","gpui.c.term.expand":"Expand","gpui.commands":"Commands","gpui.e.open.folder":"Open folder","gpui.filter.projects.and.threads":"Filter projects and threads","gpui.fold.or.unfold.the.sidebar":"Fold or unfold the sidebar","gpui.follow.paused":"Following paused","gpui.follow.wait":"Following: waiting for the agent's next edit","gpui.gerbers":"Gerbers","gpui.improvements":"Improvements","gpui.jump.to.a.thread.run":"Jump to a thread, run a command or find what was said","gpui.mgmt.bom.dnp":"DNP","gpui.mgmt.bom.nompn":"no MPN","gpui.mgmt.checks.all":"All","gpui.mgmt.checks.fix":"Fix with agent","gpui.mgmt.checks.run":"Run","gpui.mgmt.close":"Close the panel","gpui.mgmt.fab.apply":"Apply","gpui.mgmt.fab.changed":"Changed since you last looked","gpui.mgmt.fab.derived":"* worked out from the fab's page (a mil in mm, a ring from a diameter). Dimmed: the rigid board's value, where this board's page says nothing else. A date opens the page it was read from.","gpui.mgmt.fab.extra":"Costs more","gpui.mgmt.fab.findings":"Findings","gpui.mgmt.fab.free":"Base price","gpui.mgmt.fab.judge":"Datasheets","gpui.mgmt.fab.limit":"Limit","gpui.mgmt.fab.readcol":"Read","gpui.mgmt.fab.refresh":"Refresh","gpui.mgmt.fab.reviewbtn":"Review","gpui.mgmt.fab.seen":"Seen","gpui.mgmt.fab.thefab":"The fab","gpui.mgmt.fab.use":"Use","gpui.mgmt.life.nopart":"No reading of this part yet.","gpui.mgmt.life.reading":"Reading its history…","gpui.mgmt.plan.addnote":"Add note","gpui.mgmt.plan.all":"Approve all","gpui.mgmt.plan.before":"Plan before routing","gpui.mgmt.plan.compact":"Compact","gpui.mgmt.plan.done":"done","gpui.mgmt.plan.drawn":"The plan's corridors and planes are drawn on the board while this panel is open. Close it to hide them.","gpui.mgmt.plan.edited":"Edited","gpui.mgmt.plan.elsewhere":"A routing plan for {board} awaits your approval","gpui.mgmt.plan.emptysub":"Layers, corridors, and planes appear here once a plan is proposed.","gpui.mgmt.plan.expand":"Expand","gpui.mgmt.plan.fit":"Fit","gpui.mgmt.plan.grid.all":"All layers","gpui.mgmt.plan.grid.pair":"Side by side","gpui.mgmt.plan.grid.single":"Single","gpui.mgmt.plan.hide":"Hide done","gpui.mgmt.plan.hint":"Drag waypoints to steer · Click + on edge to insert · Right-click vertex to remove","gpui.mgmt.plan.keysnote":"On this KiCad version, approve from this panel: in plan view KiCad's A, R and W keys aren't the plan's yet (A opens Add Footprint). Update KiCad.","gpui.mgmt.plan.layer":"Approve layer","gpui.mgmt.plan.layer.short":"Layer","gpui.mgmt.plan.lock":"Lock","gpui.mgmt.plan.locked":"Locked","gpui.mgmt.plan.noboard":"No routing plan for this board.","gpui.mgmt.plan.noitems":"No corridors or planes on this layer","gpui.mgmt.plan.note.placeholder":"Steering note for router…","gpui.mgmt.plan.nothing":"Nothing awaits your approval","gpui.mgmt.plan.offwords":"Agents route as you ask. Turn it on to have them propose a routing plan first and route only what you approve here.","gpui.mgmt.plan.onwords":"Before routing a board with 4 or more copper layers or more than 60 nets, the agent proposes corridors and plane regions here. It routes only what you approve.","gpui.mgmt.plan.reading":"Reading the routing plan…","gpui.mgmt.plan.reference":"over {layer}","gpui.mgmt.plan.refused":"KiCad refused","gpui.mgmt.plan.reject":"Reject","gpui.mgmt.plan.rejectlayer":"Reject layer","gpui.mgmt.plan.reqplain":"Approval requested","gpui.mgmt.plan.requested":"Approval requested: {what}","gpui.mgmt.plan.saved":"saved plan","gpui.mgmt.plan.show":"Show done","gpui.mgmt.plan.st.approved":"Approved","gpui.mgmt.plan.st.awaiting":"Awaiting review","gpui.mgmt.plan.st.blocked":"Blocked","gpui.mgmt.plan.st.empty":"Empty","gpui.mgmt.plan.st.partial":"Partial","gpui.mgmt.plan.st.rejected":"Rejected","gpui.mgmt.plan.st.routed":"Routed","gpui.mgmt.plan.st.routing":"Routing","gpui.mgmt.plan.st.verified":"Verified","gpui.mgmt.plan.stackup.short":"Stackup","gpui.mgmt.plan.stop":"Stop routing","gpui.mgmt.plan.sync":"Link zoom","gpui.mgmt.plan.tab":"Plan","gpui.mgmt.plan.unlock":"Unlock","gpui.mgmt.plan.verify":"Verify","gpui.mgmt.plan.view.canvas":"Canvas","gpui.mgmt.plan.view.list":"List","gpui.mgmt.plan.view.split":"Split","gpui.mgmt.plan.width":"Width","gpui.next.thread":"Next thread","gpui.no.models":"No models","gpui.nothing.matches":"Nothing matches","gpui.picker.favorite.add":"Add to favorites","gpui.picker.favorite.remove":"Remove from favorites","gpui.picker.favorites":"Favorites","gpui.planmode.bar.always":"Plan mode — explores and proposes a plan before editing","gpui.planmode.bar.executing":"Building the approved plan","gpui.planmode.bar.once":"Plan mode (1 turn) — explores and proposes a plan before editing","gpui.planmode.bar.pending":"Proposed plan awaits review below","gpui.planmode.bar.planning":"Planning — drafting a plan before edits","gpui.planmode.chip.building":"Building","gpui.planmode.chip.once":"Plan · 1t","gpui.planmode.scope.always":"Always","gpui.planmode.scope.once":"1 turn","gpui.planmode.tip":"Plan before acting (1 turn, always, or off)","gpui.planmode.top.executing":"Building plan","gpui.planmode.top.once":"Plan (1 turn)","gpui.planmode.top.pending":"Review plan","gpui.planmode.top.planning":"Planning","gpui.previous.thread":"Previous thread","gpui.rail.no.board":"No board in this project","gpui.rail.no.mech":"No mechanical parts in this project","gpui.rail.no.schematic":"No schematic in this project","gpui.rail.split.needs.both":"Split needs a board and a schematic","gpui.search.models":"Search models","gpui.settings.group.agents":"Agents and tools","gpui.settings.group.general":"General","home.away":"Home ({name}) is away","home.away.queued":"Home ({name}) is away · {n} queued","home.away.since":"Home ({name}) is away since {time}","home.away.since.queued":"Home ({name}) is away since {time} · {n} queued","home.machine":"Home machine","home.move.failed":"Home move failed","home.move.failed.note":"Home move failed: {note}","home.move.here":"Make this machine the home","home.moving":"Moving home to {to}…","home.moving.step":"Moving home to {to}: {step}","hub.back.crash":"Backplane is back after it stopped unexpectedly","hub.restarting":"Restarting Backplane…","hub.restarting.build":"Restarting Backplane… (new build {build})","hub.stopped":"Backplane stopped","ios.hub.address.field":"Hub address","menu.pin":"Pin","menu.settle":"Settle","menu.unpin":"Unpin","menu.wake":"Wake","model.col.agent":"Agent","model.col.effort":"Effort","native.pair.connect":"Connect","native.thread.model":"Model","notify.settled":"Settled","palette.archive":"Archive thread","palette.command.placeholder":"Type a command or a thread","palette.diff":"Diff: what this thread changed","palette.newthread":"New thread","palette.settings":"Settings","palette.terminal":"Terminal","palette.unarchive":"Unarchive thread","phone.unsettle":"Unsettle","provider.notice.button":"Open Settings → Accounts","provider.notice.head":"No AI provider connected","provider.notice.senderr":"No AI provider connected yet. Open Settings → Accounts to connect Claude, Codex, Antigravity, or another provider.","provider.notice.senderr.remote":"No AI provider connected on {machine}. Open Settings → Accounts on {machine} to connect Claude, Codex, Antigravity, or another provider.","provider.notice.text.none":"Connect Claude, Codex, Antigravity, or another provider to start chatting.","provider.notice.text.signedout":"Sign in to Claude, Codex, or another provider in Settings → Accounts to start chatting.","reply.action":"Reply","reply.cancel":"Cancel reply","reply.to":"In reply to:","rooms.new":"New room","secret.you":"You","settings.appearance":"Appearance","settings.lang":"Language","settings.lang.auto":"Automatic","settings.lang.en":"English","settings.lang.es":"Español","settings.lang.ja":"日本語","settings.theme":"Theme","settings.theme.dark":"Dark","settings.theme.light":"Light","sheet.rename":"Rename thread","sidebar.add.project":"Add project","sidebar.search.projects":"Search projects","thread.context.base":"Backplane","thread.context.copied":"Prompt copied.","thread.context.copy":"Copy prompt","thread.context.disable":"Disable","thread.context.enable":"Enable","thread.context.index":"Available skills index","thread.context.injected.label":"Injected project instructions","thread.context.instructions":"Instructions","thread.context.mcp":"Project MCPs","thread.context.native.note":"Backplane’s launch prompt. Native files are loaded by the provider.","thread.context.none.instructions":"No project instructions found.","thread.context.none.mcp":"No project MCP configurations found.","thread.context.reading":"Reading thread context…","thread.context.size":"{bytes} B · ≈{tokens} tokens","thread.context.skills":"Skills","thread.context.system":"System Prompt","thread.context.title":"Context & Prompt","thread.context.trust":"Trust and enable","thread.new":"New thread","tools.pinned":"Pinned","tools.retry":"Retry","tour.title.bots":"Bots","viewer.board":"Board","viewer.diff":"Diff","viewer.files":"Files","viewer.mech":"Mech","viewer.review":"Review","viewer.schematic":"Schematic","viewer.solid":"3D","web.chat.answer.btn":"Answer","web.chat.answer.placeholder":"Type answer…","web.chat.answered":"Answered: {answer}","web.chat.choose":"Choose a project thread on the left to begin.","web.chat.empty":"No messages yet. Type below to start a turn.","web.chat.finished":"Finished {time}","web.chat.finished.dur":"Finished {time} · {dur}","web.chat.loading":"Loading messages…","web.chat.review.mode":"Review mode","web.chat.streaming":"Streaming…","web.clone.add.dir":"Add {dir}","web.clone.back":"Back","web.clone.change.folder":"Change folder","web.clone.cloned":"Cloned {repo} into {dest}","web.clone.cloning":"Cloning {repo} into {dest}","web.clone.copied":"Copied","web.clone.first":"First message: {text}","web.clone.folder.name":"Folder name","web.clone.go":"Clone","web.clone.loading":"Loading…","web.clone.no.folders":"No folders here","web.clone.open.project":"Open the project","web.clone.open.thread":"Open the thread","web.clone.private":"private","web.clone.repo.placeholder":"https or ssh URL, or owner/repo","web.clone.retry":"Try again","web.clone.same":"Already cloned there: it is added as it is.","web.clone.signin":"Sign in to GitHub","web.clone.signin.done":"Signed in to GitHub","web.clone.signin.enter":"Enter this code on GitHub:","web.clone.signin.wait":"Starting GitHub sign-in…","web.clone.start.thread":"Start a thread","web.clone.stopped":"Stopped cloning {repo}","web.clone.tab":"Clone from git","web.clone.up":"Up","web.clone.use.dir":"Use {dir}","web.composer.attach":"Attach image","web.composer.maximages":"At most {max} images per message.","web.composer.unsupported":"Unsupported image type: {type}","web.composer.voice":"Voice dictation","web.logout.failed":"Could not confirm sign-out. Try again.","web.pair.approve.in":"Approve on desktop or paired phone · expires in {time}","web.pair.approved":"Approved. Opening Backplane…","web.pair.cancelled":"Cancelled.","web.pair.code":"Comparison code","web.pair.denied":"Pairing request was denied.","web.pair.expired":"Pairing code expired. Request a new code to try again.","web.pair.failed":"Pairing request failed ({status})","web.pair.name":"Browser name","web.pair.nocode":"Hub did not return a comparison code.","web.pair.ratelimited":"Too many pairing attempts. Wait a moment and try again.","web.pair.request":"Request pairing","web.pair.requesting":"Requesting pairing code…","web.pair.subtitle":"Pair this browser with your hub. Approve the 6-digit code in Backplane › Settings › Devices.","web.pair.unreachable":"Could not reach the hub. Check your tailnet connection.","web.plan.awaiting":"{n} awaiting approval","web.plan.net.one":"1 net","web.plan.nets":"{n} nets","web.settings.providers":"AI providers","web.settings.providers.browser":"Connect a provider in the Backplane desktop or mobile app under Settings → Accounts."},es:{"agy.signout":"Cerrar sesión","android.hub.machines.approve":"Aprobar","android.load.earlier":"cargar anteriores","approval.dismiss":"Descartar","approval.implement":"Implementar","ask.plan":"Plan propuesto","bots.new":"Nuevo bot","bots.rooms":"Salas","bots.tab.browser":"Navegador","common.cancel":"Cancelar","common.close":"Cerrar","common.copy":"Copiar","common.delete":"Eliminar","common.refresh":"Actualizar","common.remove":"Quitar","common.save":"Guardar","composer.model.tip":"Elegir el modelo y el esfuerzo","composer.placeholder":"Pregunta lo que sea: @bot, >hilo, %proyecto, #sala, $skill, /btw","composer.send":"Enviar","composer.stop":"Detener","gpui.acct.connected":"Conectado","gpui.acct.not.connected":"No conectado","gpui.acct.sign.in.expired":"Sesión caducada","gpui.ask.plan.ready":"Listo para revisar","gpui.ask.plan.revise":"Revisar","gpui.ask.plan.reviseph":"¿Qué debería cambiar en el plan?","gpui.ask.plan.sendrev":"Enviar revisión","gpui.b.in.reply.to":"↩ En respuesta a: {quote}","gpui.b.replying.to":"↩ Respondiendo a: {line}","gpui.bots.recall.off":"Desactivado","gpui.bots.recall.on":"Activado","gpui.c.solid.big.next":"Cargarlo puede tardar y usar mucha memoria.","gpui.c.solid.load.big":"Cargarlo de todos modos","gpui.c.solid.loading.big":"Cargándolo de todos modos…","gpui.c.term.collapse":"Contraer","gpui.c.term.expand":"Expandir","gpui.commands":"Comandos","gpui.e.open.folder":"Abrir carpeta","gpui.filter.projects.and.threads":"Filtrar proyectos e hilos","gpui.fold.or.unfold.the.sidebar":"Plegar o desplegar la barra lateral","gpui.follow.paused":"Seguimiento en pausa","gpui.follow.wait":"Siguiendo: esperando la próxima edición del agente","gpui.gerbers":"Gerbers","gpui.improvements":"Mejoras","gpui.jump.to.a.thread.run":"Saltar a un hilo, ejecutar un comando o buscar lo dicho","gpui.mgmt.bom.dnp":"DNP","gpui.mgmt.bom.nompn":"sin MPN","gpui.mgmt.checks.all":"Todas","gpui.mgmt.checks.fix":"Corregir con agente","gpui.mgmt.checks.run":"Ejecutar","gpui.mgmt.close":"Cerrar el panel","gpui.mgmt.fab.apply":"Aplicar","gpui.mgmt.fab.changed":"Cambió desde la última vez que miraste","gpui.mgmt.fab.derived":"* calculado desde la página del fabricante (un mil en mm, un anillo desde un diámetro). Atenuado: el valor de la placa rígida, cuando la página de esta placa no dice otra cosa. Una fecha abre la página de la que se leyó.","gpui.mgmt.fab.extra":"Cuesta más","gpui.mgmt.fab.findings":"Hallazgos","gpui.mgmt.fab.free":"Precio base","gpui.mgmt.fab.judge":"Hojas de datos","gpui.mgmt.fab.limit":"Límite","gpui.mgmt.fab.readcol":"Leído","gpui.mgmt.fab.refresh":"Actualizar","gpui.mgmt.fab.reviewbtn":"Revisar","gpui.mgmt.fab.seen":"Visto","gpui.mgmt.fab.thefab":"El fabricante","gpui.mgmt.fab.use":"Usar","gpui.mgmt.life.nopart":"Sin lectura de esta pieza aún.","gpui.mgmt.life.reading":"Leyendo su historial…","gpui.mgmt.plan.addnote":"Añadir nota","gpui.mgmt.plan.all":"Aprobar todo","gpui.mgmt.plan.before":"Planificar antes de rutear","gpui.mgmt.plan.compact":"Compacto","gpui.mgmt.plan.done":"hecho","gpui.mgmt.plan.drawn":"Los corredores y planos del plan se dibujan en la placa mientras este panel está abierto. Ciérralo para ocultarlos.","gpui.mgmt.plan.edited":"Editado","gpui.mgmt.plan.elsewhere":"Un plan de ruteo para {board} espera tu aprobación","gpui.mgmt.plan.emptysub":"Las capas, corredores y planos aparecerán aquí cuando se proponga un plan.","gpui.mgmt.plan.expand":"Expandir","gpui.mgmt.plan.fit":"Ajustar","gpui.mgmt.plan.grid.all":"Todas las capas","gpui.mgmt.plan.grid.pair":"Lado a lado","gpui.mgmt.plan.grid.single":"Única","gpui.mgmt.plan.hide":"Ocultar hechos","gpui.mgmt.plan.hint":"Arrastra vértices para guiar · Clic en + del borde para insertar · Clic derecho en vértice para quitar","gpui.mgmt.plan.keysnote":"En esta versión de KiCad, aprueba desde este panel: en la vista de plan las teclas A, R y W de KiCad aún no son del plan (A abre Añadir Huella). Actualiza KiCad.","gpui.mgmt.plan.layer":"Aprobar capa","gpui.mgmt.plan.layer.short":"Capa","gpui.mgmt.plan.lock":"Bloquear","gpui.mgmt.plan.locked":"Bloqueado","gpui.mgmt.plan.noboard":"No hay plan de ruteo para esta placa.","gpui.mgmt.plan.noitems":"Sin corredores ni planos en esta capa","gpui.mgmt.plan.note.placeholder":"Nota de guiado para el router…","gpui.mgmt.plan.nothing":"Nada espera tu aprobación","gpui.mgmt.plan.offwords":"Los agentes rutean como les pidas. Actívalo para que primero propongan un plan de ruteo y ruteen solo lo que apruebes aquí.","gpui.mgmt.plan.onwords":"Antes de rutear una placa con 4 o más capas de cobre o más de 60 redes, el agente propone aquí corredores y regiones de plano. Solo rutea lo que apruebes.","gpui.mgmt.plan.reading":"Leyendo el plan de ruteo…","gpui.mgmt.plan.reference":"sobre {layer}","gpui.mgmt.plan.refused":"KiCad lo rechazó","gpui.mgmt.plan.reject":"Rechazar","gpui.mgmt.plan.rejectlayer":"Rechazar capa","gpui.mgmt.plan.reqplain":"Aprobación solicitada","gpui.mgmt.plan.requested":"Aprobación solicitada: {what}","gpui.mgmt.plan.saved":"plan guardado","gpui.mgmt.plan.show":"Mostrar hechos","gpui.mgmt.plan.st.approved":"Aprobado","gpui.mgmt.plan.st.awaiting":"Esperando revisión","gpui.mgmt.plan.st.blocked":"Bloqueado","gpui.mgmt.plan.st.empty":"Vacío","gpui.mgmt.plan.st.partial":"Parcial","gpui.mgmt.plan.st.rejected":"Rechazado","gpui.mgmt.plan.st.routed":"Ruteado","gpui.mgmt.plan.st.routing":"Ruteando","gpui.mgmt.plan.st.verified":"Verificado","gpui.mgmt.plan.stackup.short":"Apilamiento","gpui.mgmt.plan.stop":"Detener ruteo","gpui.mgmt.plan.sync":"Vincular zoom","gpui.mgmt.plan.tab":"Plan","gpui.mgmt.plan.unlock":"Desbloquear","gpui.mgmt.plan.verify":"Verificar","gpui.mgmt.plan.view.canvas":"Lienzo","gpui.mgmt.plan.view.list":"Lista","gpui.mgmt.plan.view.split":"Dividido","gpui.mgmt.plan.width":"Ancho","gpui.next.thread":"Hilo siguiente","gpui.no.models":"Sin modelos","gpui.nothing.matches":"Nada coincide","gpui.picker.favorite.add":"Añadir a favoritos","gpui.picker.favorite.remove":"Quitar de favoritos","gpui.picker.favorites":"Favoritos","gpui.planmode.bar.always":"Modo plan — explora y propone un plan antes de editar","gpui.planmode.bar.executing":"Ejecutando el plan aprobado","gpui.planmode.bar.once":"Modo plan (1 turno) — explora y propone un plan antes de editar","gpui.planmode.bar.pending":"El plan propuesto espera revisión abajo","gpui.planmode.bar.planning":"Planificando — redactando un plan antes de editar","gpui.planmode.chip.building":"Ejecutando","gpui.planmode.chip.once":"Plan · 1t","gpui.planmode.scope.always":"Siempre","gpui.planmode.scope.once":"1 turno","gpui.planmode.tip":"Planificar antes de actuar (1 turno, siempre u off)","gpui.planmode.top.executing":"Ejecutando plan","gpui.planmode.top.once":"Plan (1 turno)","gpui.planmode.top.pending":"Revisar plan","gpui.planmode.top.planning":"Planificando","gpui.previous.thread":"Hilo anterior","gpui.rail.no.board":"Este proyecto no tiene placa","gpui.rail.no.mech":"Este proyecto no tiene piezas mecánicas","gpui.rail.no.schematic":"Este proyecto no tiene esquema","gpui.rail.split.needs.both":"La vista dividida requiere una placa y un esquema","gpui.search.models":"Buscar modelos","gpui.settings.group.agents":"Agentes y herramientas","gpui.settings.group.general":"General","home.away":"El inicio ({name}) no está disponible","home.away.queued":"El inicio ({name}) no está disponible · {n} en cola","home.away.since":"El inicio ({name}) no está disponible desde las {time}","home.away.since.queued":"El inicio ({name}) no está disponible desde las {time} · {n} en cola","home.machine":"Máquina de inicio","home.move.failed":"No se pudo mover el inicio","home.move.failed.note":"No se pudo mover el inicio: {note}","home.move.here":"Hacer de esta máquina el inicio","home.moving":"Moviendo el inicio a {to}…","home.moving.step":"Moviendo el inicio a {to}: {step}","hub.back.crash":"Backplane volvió tras detenerse de forma inesperada","hub.restarting":"Reiniciando Backplane…","hub.restarting.build":"Reiniciando Backplane… (nueva compilación {build})","hub.stopped":"Backplane se detuvo","ios.hub.address.field":"Dirección del hub","menu.pin":"Fijar","menu.settle":"Cerrar","menu.unpin":"Desfijar","menu.wake":"Despertar","model.col.agent":"Agente","model.col.effort":"Esfuerzo","native.pair.connect":"Conectar","native.thread.model":"Modelo","notify.settled":"Cerrado","palette.archive":"Archivar hilo","palette.command.placeholder":"Escribe un comando o un hilo","palette.diff":"Diff: qué cambió este hilo","palette.newthread":"Nuevo hilo","palette.settings":"Ajustes","palette.terminal":"Terminal","palette.unarchive":"Desarchivar hilo","phone.unsettle":"Reabrir","provider.notice.button":"Abrir Configuración → Cuentas","provider.notice.head":"No hay ningún proveedor de IA conectado","provider.notice.senderr":"Aún no hay ningún proveedor de IA conectado. Abre Configuración → Cuentas para conectar Claude, Codex, Antigravity u otro proveedor.","provider.notice.senderr.remote":"No hay ningún proveedor de IA conectado en {machine}. Abre Configuración → Cuentas en {machine} para conectar Claude, Codex, Antigravity u otro proveedor.","provider.notice.text.none":"Conecta Claude, Codex, Antigravity u otro proveedor para empezar a chatear.","provider.notice.text.signedout":"Inicia sesión en Claude, Codex u otro proveedor en Configuración → Cuentas para empezar a chatear.","reply.action":"Responder","reply.cancel":"Cancelar respuesta","reply.to":"En respuesta a:","rooms.new":"Nueva sala","secret.you":"Tú","settings.appearance":"Apariencia","settings.lang":"Idioma","settings.lang.auto":"Automático","settings.lang.en":"English","settings.lang.es":"Español","settings.lang.ja":"日本語","settings.theme":"Tema","settings.theme.dark":"Oscuro","settings.theme.light":"Claro","sheet.rename":"Renombrar hilo","sidebar.add.project":"Añadir proyecto","sidebar.search.projects":"Buscar proyectos","thread.context.base":"Backplane","thread.context.copied":"Se copiaron las instrucciones.","thread.context.copy":"Copiar instrucciones","thread.context.disable":"Desactivar","thread.context.enable":"Activar","thread.context.index":"Índice de habilidades disponibles","thread.context.injected.label":"Instrucciones del proyecto añadidas","thread.context.instructions":"Instrucciones","thread.context.mcp":"MCP del proyecto","thread.context.native.note":"Instrucciones de inicio de Backplane. El proveedor carga los archivos nativos.","thread.context.none.instructions":"No se encontraron instrucciones del proyecto.","thread.context.none.mcp":"No se encontraron configuraciones MCP del proyecto.","thread.context.reading":"Leyendo el contexto del hilo…","thread.context.size":"{bytes} B · ≈{tokens} tokens","thread.context.skills":"Habilidades","thread.context.system":"Instrucciones del sistema","thread.context.title":"Contexto e instrucciones","thread.context.trust":"Confiar y activar","thread.new":"Nuevo hilo","tools.pinned":"Fijado","tools.retry":"Reintentar","tour.title.bots":"Bots","viewer.board":"Placa","viewer.diff":"Diff","viewer.files":"Archivos","viewer.mech":"Mech","viewer.review":"Revisión","viewer.schematic":"Esquemático","viewer.solid":"3D","web.chat.answer.btn":"Responder","web.chat.answer.placeholder":"Escribe una respuesta…","web.chat.answered":"Respondido: {answer}","web.chat.choose":"Elige un hilo de proyecto a la izquierda para empezar.","web.chat.empty":"Aún no hay mensajes. Escribe abajo para iniciar un turno.","web.chat.finished":"Terminado {time}","web.chat.finished.dur":"Terminado {time} · {dur}","web.chat.loading":"Cargando mensajes…","web.chat.review.mode":"Modo de revisión","web.chat.streaming":"Transmitiendo…","web.clone.add.dir":"Añadir {dir}","web.clone.back":"Atrás","web.clone.change.folder":"Cambiar carpeta","web.clone.cloned":"{repo} clonado en {dest}","web.clone.cloning":"Clonando {repo} en {dest}","web.clone.copied":"Copiado","web.clone.first":"Primer mensaje: {text}","web.clone.folder.name":"Nombre de la carpeta","web.clone.go":"Clonar","web.clone.loading":"Cargando…","web.clone.no.folders":"No hay carpetas aquí","web.clone.open.project":"Abrir el proyecto","web.clone.open.thread":"Abrir el hilo","web.clone.private":"privado","web.clone.repo.placeholder":"URL https o ssh, o propietario/repositorio","web.clone.retry":"Reintentar","web.clone.same":"Ya está clonado ahí: se añade tal cual.","web.clone.signin":"Iniciar sesión en GitHub","web.clone.signin.done":"Sesión iniciada en GitHub","web.clone.signin.enter":"Introduce este código en GitHub:","web.clone.signin.wait":"Iniciando sesión en GitHub…","web.clone.start.thread":"Empezar un hilo","web.clone.stopped":"Se detuvo la clonación de {repo}","web.clone.tab":"Clonar desde git","web.clone.up":"Subir","web.clone.use.dir":"Usar {dir}","web.composer.attach":"Adjuntar imagen","web.composer.maximages":"Como máximo {max} imágenes por mensaje.","web.composer.unsupported":"Tipo de imagen no compatible: {type}","web.composer.voice":"Dictado por voz","web.logout.failed":"No se pudo confirmar el cierre de sesión. Inténtalo de nuevo.","web.pair.approve.in":"Aprueba en el escritorio o en un teléfono vinculado · caduca en {time}","web.pair.approved":"Aprobado. Abriendo Backplane…","web.pair.cancelled":"Cancelado.","web.pair.code":"Código de comparación","web.pair.denied":"Se rechazó la solicitud de vinculación.","web.pair.expired":"El código de vinculación caducó. Solicita uno nuevo para intentarlo otra vez.","web.pair.failed":"Falló la solicitud de vinculación ({status})","web.pair.name":"Nombre del navegador","web.pair.nocode":"El hub no devolvió un código de comparación.","web.pair.ratelimited":"Demasiados intentos de vinculación. Espera un momento e inténtalo de nuevo.","web.pair.request":"Solicitar vinculación","web.pair.requesting":"Solicitando código de vinculación…","web.pair.subtitle":"Vincula este navegador con tu hub. Aprueba el código de 6 dígitos en Backplane › Ajustes › Dispositivos.","web.pair.unreachable":"No se pudo conectar con el hub. Comprueba tu conexión de tailnet.","web.plan.awaiting":"{n} esperando aprobación","web.plan.net.one":"1 red","web.plan.nets":"{n} redes","web.settings.providers":"Proveedores de IA","web.settings.providers.browser":"Conecta un proveedor en la aplicación de escritorio o móvil de Backplane en Configuración → Cuentas."},ja:{"agy.signout":"サインアウト","android.hub.machines.approve":"承認","android.load.earlier":"以前のメッセージを読み込む","approval.dismiss":"閉じる","approval.implement":"実装","ask.plan":"提案されたプラン","bots.new":"新しいボット","bots.rooms":"ルーム","bots.tab.browser":"ブラウザ","common.cancel":"キャンセル","common.close":"閉じる","common.copy":"コピー","common.delete":"削除","common.refresh":"更新","common.remove":"削除","common.save":"保存","composer.model.tip":"モデルと推論の強さを選択","composer.placeholder":"何でも質問:@bot、>thread、%project、#room、$skill、/btw","composer.send":"送信","composer.stop":"停止","gpui.acct.connected":"接続済み","gpui.acct.not.connected":"未接続","gpui.acct.sign.in.expired":"サインインの期限切れ","gpui.ask.plan.ready":"確認待ち","gpui.ask.plan.revise":"修正","gpui.ask.plan.reviseph":"計画のどこを変更しますか?","gpui.ask.plan.sendrev":"修正を送る","gpui.b.in.reply.to":"↩ 返信先:{quote}","gpui.b.replying.to":"↩ 返信中:{line}","gpui.bots.recall.off":"オフ","gpui.bots.recall.on":"オン","gpui.c.solid.big.next":"読み込みには時間と多くのメモリがかかることがあります。","gpui.c.solid.load.big":"それでも読み込む","gpui.c.solid.loading.big":"それでも読み込み中…","gpui.c.term.collapse":"折りたたむ","gpui.c.term.expand":"展開","gpui.commands":"コマンド","gpui.e.open.folder":"フォルダを開く","gpui.filter.projects.and.threads":"プロジェクトとスレッドを絞り込む","gpui.fold.or.unfold.the.sidebar":"サイドバーを折りたたむ/開く","gpui.follow.paused":"追従を一時停止中","gpui.follow.wait":"追従中: エージェントの次の編集を待っています","gpui.gerbers":"ガーバー","gpui.improvements":"改善","gpui.jump.to.a.thread.run":"スレッドへ移動、コマンドを実行、または発言を検索","gpui.mgmt.bom.dnp":"実装しない","gpui.mgmt.bom.nompn":"MPNなし","gpui.mgmt.checks.all":"すべて","gpui.mgmt.checks.fix":"エージェントに直してもらう","gpui.mgmt.checks.run":"実行","gpui.mgmt.close":"パネルを閉じる","gpui.mgmt.fab.apply":"適用","gpui.mgmt.fab.changed":"前回見てから変わったところ","gpui.mgmt.fab.derived":"* 製造元のページから計算した値です(milをmmに、径からランドを)。薄い色の項目はリジッド基板の値です(この基板のページに記載がないもの)。日付を押すと読んだページが開きます。","gpui.mgmt.fab.extra":"追加料金","gpui.mgmt.fab.findings":"指摘","gpui.mgmt.fab.free":"基本料金","gpui.mgmt.fab.judge":"データシート","gpui.mgmt.fab.limit":"項目","gpui.mgmt.fab.readcol":"読んだ日","gpui.mgmt.fab.refresh":"再読み込み","gpui.mgmt.fab.reviewbtn":"レビュー","gpui.mgmt.fab.seen":"確認済み","gpui.mgmt.fab.thefab":"製造元","gpui.mgmt.fab.use":"使う","gpui.mgmt.life.nopart":"この部品の記録はまだありません。","gpui.mgmt.life.reading":"履歴を読んでいます…","gpui.mgmt.plan.addnote":"メモを追加","gpui.mgmt.plan.all":"すべて承認","gpui.mgmt.plan.before":"配線前に計画する","gpui.mgmt.plan.compact":"標準","gpui.mgmt.plan.done":"完了","gpui.mgmt.plan.drawn":"計画の配線経路とプレーンは、このパネルを開いている間だけ基板上に表示されます。閉じると消えます。","gpui.mgmt.plan.edited":"編集済み","gpui.mgmt.plan.elsewhere":"{board}の配線計画が承認を待っています","gpui.mgmt.plan.emptysub":"計画が提案されると、レイヤー・コリドー・ベタ領域がここに表示されます。","gpui.mgmt.plan.expand":"拡大","gpui.mgmt.plan.fit":"全体表示","gpui.mgmt.plan.grid.all":"全レイヤー","gpui.mgmt.plan.grid.pair":"並べて表示","gpui.mgmt.plan.grid.single":"単一","gpui.mgmt.plan.hide":"完了を隠す","gpui.mgmt.plan.hint":"頂点をドラッグして誘導 · 辺の + をクリックで追加 · 頂点を右クリックで削除","gpui.mgmt.plan.keysnote":"このバージョンのKiCadでは、このパネルから承認してください。プランビューでのKiCadのA・R・Wキーはまだ計画のものではありません(Aはフットプリントの追加を開きます)。KiCadを更新してください。","gpui.mgmt.plan.layer":"層を承認","gpui.mgmt.plan.layer.short":"レイヤー","gpui.mgmt.plan.lock":"ロック","gpui.mgmt.plan.locked":"ロック中","gpui.mgmt.plan.noboard":"この基板の配線計画はありません。","gpui.mgmt.plan.noitems":"このレイヤーにコリドーまたはプレーンがありません","gpui.mgmt.plan.note.placeholder":"ルーターへの指示メモ…","gpui.mgmt.plan.nothing":"承認待ちはありません","gpui.mgmt.plan.offwords":"エージェントは指示どおりに配線します。オンにすると、まず配線計画を提案し、ここで承認したものだけを配線します。","gpui.mgmt.plan.onwords":"銅箔層が4層以上、またはネットが60本を超える基板では、配線の前にエージェントがここで配線経路とプレーン領域を提案します。承認したものだけを配線します。","gpui.mgmt.plan.reading":"配線計画を読んでいます…","gpui.mgmt.plan.reference":"基準 {layer}","gpui.mgmt.plan.refused":"KiCad が拒否しました","gpui.mgmt.plan.reject":"却下","gpui.mgmt.plan.rejectlayer":"レイヤーを却下","gpui.mgmt.plan.reqplain":"承認が求められています","gpui.mgmt.plan.requested":"承認が求められています: {what}","gpui.mgmt.plan.saved":"保存された計画","gpui.mgmt.plan.show":"完了を表示","gpui.mgmt.plan.st.approved":"承認済み","gpui.mgmt.plan.st.awaiting":"承認待ち","gpui.mgmt.plan.st.blocked":"ブロック","gpui.mgmt.plan.st.empty":"空","gpui.mgmt.plan.st.partial":"一部完了","gpui.mgmt.plan.st.rejected":"却下","gpui.mgmt.plan.st.routed":"配線済み","gpui.mgmt.plan.st.routing":"配線中","gpui.mgmt.plan.st.verified":"検証済み","gpui.mgmt.plan.stackup.short":"スタックアップ","gpui.mgmt.plan.stop":"配線を止める","gpui.mgmt.plan.sync":"ズーム連動","gpui.mgmt.plan.tab":"計画","gpui.mgmt.plan.unlock":"ロック解除","gpui.mgmt.plan.verify":"検証","gpui.mgmt.plan.view.canvas":"キャンバス","gpui.mgmt.plan.view.list":"リスト","gpui.mgmt.plan.view.split":"分割","gpui.mgmt.plan.width":"幅","gpui.next.thread":"次のスレッド","gpui.no.models":"モデルがありません","gpui.nothing.matches":"一致するものはありません","gpui.picker.favorite.add":"お気に入りに追加","gpui.picker.favorite.remove":"お気に入りから外す","gpui.picker.favorites":"お気に入り","gpui.planmode.bar.always":"計画モード — 編集前に調査して計画を提案します","gpui.planmode.bar.executing":"承認された計画を実行しています","gpui.planmode.bar.once":"計画モード (1回) — 編集前に調査して計画を提案します","gpui.planmode.bar.pending":"提案された計画が下のレビューを待っています","gpui.planmode.bar.planning":"計画中 — 編集前の計画を作成しています","gpui.planmode.chip.building":"実行中","gpui.planmode.chip.once":"計画 · 1回","gpui.planmode.scope.always":"常時","gpui.planmode.scope.once":"1回","gpui.planmode.tip":"実行前に計画を作成 (1回・常時・オフ)","gpui.planmode.top.executing":"計画を実行中","gpui.planmode.top.once":"計画 (1回)","gpui.planmode.top.pending":"計画を確認","gpui.planmode.top.planning":"計画中","gpui.previous.thread":"前のスレッド","gpui.rail.no.board":"このプロジェクトには基板がありません","gpui.rail.no.mech":"このプロジェクトには機械部品がありません","gpui.rail.no.schematic":"このプロジェクトには回路図がありません","gpui.rail.split.needs.both":"分割表示には基板と回路図が必要です","gpui.search.models":"モデルを検索","gpui.settings.group.agents":"エージェントとツール","gpui.settings.group.general":"一般","home.away":"ホーム({name})はオフラインです","home.away.queued":"ホーム({name})はオフラインです · {n} 件待機中","home.away.since":"ホーム({name})は {time} からオフラインです","home.away.since.queued":"ホーム({name})は {time} からオフラインです · {n} 件待機中","home.machine":"ホームマシン","home.move.failed":"ホームの移動に失敗しました","home.move.failed.note":"ホームの移動に失敗しました: {note}","home.move.here":"このマシンをホームにする","home.moving":"ホームを {to} へ移動中…","home.moving.step":"ホームを {to} へ移動中: {step}","hub.back.crash":"予期せず停止したBackplaneが戻りました","hub.restarting":"Backplaneを再起動しています…","hub.restarting.build":"Backplaneを再起動しています…(新しいビルド {build})","hub.stopped":"Backplaneは停止しました","ios.hub.address.field":"ハブのアドレス","menu.pin":"ピン留め","menu.settle":"完了","menu.unpin":"ピン留めを解除","menu.wake":"再開","model.col.agent":"エージェント","model.col.effort":"推論の強さ","native.pair.connect":"接続","native.thread.model":"モデル","notify.settled":"完了","palette.archive":"スレッドをアーカイブ","palette.command.placeholder":"コマンドまたはスレッドを入力","palette.diff":"差分:このスレッドの変更","palette.newthread":"新しいスレッド","palette.settings":"設定","palette.terminal":"ターミナル","palette.unarchive":"スレッドのアーカイブを解除","phone.unsettle":"未完了に戻す","provider.notice.button":"設定 → アカウントを開く","provider.notice.head":"AI プロバイダーが接続されていません","provider.notice.senderr":"AI プロバイダーがまだ接続されていません。設定 → アカウントを開いて、Claude、Codex、Antigravity などのプロバイダーを接続してください。","provider.notice.senderr.remote":"{machine} に AI プロバイダーが接続されていません。{machine} で設定 → アカウントを開いて、Claude、Codex、Antigravity などのプロバイダーを接続してください。","provider.notice.text.none":"チャットを始めるには、Claude、Codex、Antigravity などのプロバイダーを接続してください。","provider.notice.text.signedout":"チャットを始めるには、設定 → アカウントで Claude、Codex などのプロバイダーにサインインしてください。","reply.action":"返信","reply.cancel":"返信をやめる","reply.to":"返信先:","rooms.new":"新しいルーム","secret.you":"あなた","settings.appearance":"外観","settings.lang":"言語","settings.lang.auto":"自動","settings.lang.en":"English","settings.lang.es":"Español","settings.lang.ja":"日本語","settings.theme":"テーマ","settings.theme.dark":"ダーク","settings.theme.light":"ライト","sheet.rename":"スレッド名を変更","sidebar.add.project":"プロジェクトを追加","sidebar.search.projects":"プロジェクトを検索","thread.context.base":"Backplane","thread.context.copied":"プロンプトをコピーしました。","thread.context.copy":"プロンプトをコピー","thread.context.disable":"無効にする","thread.context.enable":"有効にする","thread.context.index":"利用可能なスキルの一覧","thread.context.injected.label":"追加されたプロジェクトの指示","thread.context.instructions":"指示","thread.context.mcp":"プロジェクトの MCP","thread.context.native.note":"Backplane が起動時に渡すプロンプトです。ネイティブファイルはプロバイダーが読み込みます。","thread.context.none.instructions":"プロジェクトの指示が見つかりません。","thread.context.none.mcp":"プロジェクトの MCP 設定が見つかりません。","thread.context.reading":"スレッドのコンテキストを読み込み中…","thread.context.size":"{bytes} B・約{tokens}トークン","thread.context.skills":"スキル","thread.context.system":"システムプロンプト","thread.context.title":"コンテキストとプロンプト","thread.context.trust":"承認して有効にする","thread.new":"新しいスレッド","tools.pinned":"固定中","tools.retry":"再試行","tour.title.bots":"ボット","viewer.board":"基板","viewer.diff":"差分","viewer.files":"ファイル","viewer.mech":"Mech","viewer.review":"レビュー","viewer.schematic":"回路図","viewer.solid":"3D","web.chat.answer.btn":"回答","web.chat.answer.placeholder":"回答を入力…","web.chat.answered":"回答済み: {answer}","web.chat.choose":"左側からプロジェクトのスレッドを選んで開始してください。","web.chat.empty":"まだメッセージはありません。下に入力して開始してください。","web.chat.finished":"完了 {time}","web.chat.finished.dur":"完了 {time} · {dur}","web.chat.loading":"メッセージを読み込んでいます…","web.chat.review.mode":"レビューモード","web.chat.streaming":"受信中…","web.clone.add.dir":"{dir} を追加","web.clone.back":"戻る","web.clone.change.folder":"フォルダを変更","web.clone.cloned":"{repo} を {dest} にクローンしました","web.clone.cloning":"{repo} を {dest} にクローン中","web.clone.copied":"コピーしました","web.clone.first":"最初のメッセージ: {text}","web.clone.folder.name":"フォルダ名","web.clone.go":"クローン","web.clone.loading":"読み込み中…","web.clone.no.folders":"フォルダがありません","web.clone.open.project":"プロジェクトを開く","web.clone.open.thread":"スレッドを開く","web.clone.private":"非公開","web.clone.repo.placeholder":"https / ssh の URL、または owner/repo","web.clone.retry":"もう一度","web.clone.same":"すでにそこにクローンされています: そのまま追加します。","web.clone.signin":"GitHub にサインイン","web.clone.signin.done":"GitHub にサインインしました","web.clone.signin.enter":"このコードを GitHub に入力してください:","web.clone.signin.wait":"GitHub のサインインを開始しています…","web.clone.start.thread":"スレッドを開始","web.clone.stopped":"{repo} のクローンを中止しました","web.clone.tab":"git からクローン","web.clone.up":"上へ","web.clone.use.dir":"{dir} を使う","web.composer.attach":"画像を添付","web.composer.maximages":"1 件のメッセージに添付できる画像は最大 {max} 枚です。","web.composer.unsupported":"未対応の画像形式です: {type}","web.composer.voice":"音声入力","web.logout.failed":"サインアウトを確認できませんでした。もう一度お試しください。","web.pair.approve.in":"デスクトップまたはペアリング済みの端末で承認してください · 有効期限 {time}","web.pair.approved":"承認されました。Backplane を開いています…","web.pair.cancelled":"キャンセルしました。","web.pair.code":"確認コード","web.pair.denied":"ペアリングのリクエストが拒否されました。","web.pair.expired":"ペアリングコードの有効期限が切れました。新しいコードをリクエストしてください。","web.pair.failed":"ペアリングのリクエストに失敗しました ({status})","web.pair.name":"ブラウザー名","web.pair.nocode":"ハブから確認コードが返されませんでした。","web.pair.ratelimited":"ペアリングの試行回数が多すぎます。しばらく待ってからやり直してください。","web.pair.request":"ペアリングをリクエスト","web.pair.requesting":"ペアリングコードをリクエストしています…","web.pair.subtitle":"このブラウザーをハブとペアリングします。Backplane › 設定 › デバイス で 6 桁のコードを承認してください。","web.pair.unreachable":"ハブに接続できませんでした。tailnet の接続を確認してください。","web.plan.awaiting":"{n} 件が承認待ち","web.plan.net.one":"1 ネット","web.plan.nets":"{n} ネット","web.settings.providers":"AI プロバイダー","web.settings.providers.browser":"Backplane のデスクトップまたはモバイルアプリの設定 → アカウントからプロバイダーを接続してください。"}};function ci(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 Tt=tr(),pn=new Set,un=new Map;for(let[e,t]of Object.entries(Mt.en||{}))if(typeof t==="string"&&!un.has(t))un.set(t,e);function tr(){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 di(){if(typeof document<"u"&&document.documentElement)document.documentElement.lang=Tt}di();function Jt(e){return pn.add(e),()=>{pn.delete(e)}}function gt(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!==Tt;if(Tt=n,di(),i)for(let s of pn)s(Tt);return i}function h(e,t,n){let s=(Mt[Tt]||Mt.en||{})[e]??Mt.en?.[e]??t??e;return ci(s,n)}function pe(e){if(!e)return"";let t=un.get(e);if(!t)return e;return h(t,e)}function X(e,t="",n=""){let i=document.createElement(e);if(t)i.className=t;if(n)i.textContent=n;return i}function $e(e,t="",n){let i=X("button",t,e);if(i.type="button",n)i.addEventListener("click",n);return i}function nr(e){let t=e.replace(/[\\/]+$/,"");if(!t)return e||"/";let n=t.split(/[\\/]/);return n[n.length-1]||t}function ir(e,t){let n=e.includes("\\")&&!e.includes("/")?"\\":"/";return e.endsWith(n)?e+t:e+n+t}class mn{hub;actionLabel;action;root;pathInput;upBtn;listEl;errEl;actBtn;path="";parent=null;gen=0;busy=!1;constructor(e,t,n,i=[]){this.hub=e;this.actionLabel=t;this.action=n;this.root=X("div","bp-fb"),this.root.setAttribute("data-testid","folder-browser");let s=X("div","bp-fb-head");this.upBtn=$e("↑","bp-btn-ghost bp-fb-up",()=>{if(this.parent)this.go(this.parent)}),this.upBtn.title=h("web.clone.up","Up"),this.upBtn.setAttribute("aria-label",h("web.clone.up","Up")),this.pathInput=X("input","bp-input bp-fb-path"),this.pathInput.spellcheck=!1,this.pathInput.setAttribute("data-testid","folder-path"),this.pathInput.addEventListener("keydown",(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=X("div","bp-fb-list"),this.errEl=X("div","bp-ap-err bp-hidden");let r=X("div","bp-ap-foot");this.actBtn=$e("","primary",()=>{this.run()}),this.actBtn.setAttribute("data-testid","folder-act"),r.append(...i,this.actBtn),this.root.append(s,this.listEl,this.errEl,r)}currentPath(){return this.path}async go(e){let t=++this.gen;this.setError(""),this.listEl.replaceChildren(X("div","bp-fb-empty",h("web.clone.loading","Loading…")));try{let n=await this.hub.rpc("dirs.list",{path:e});if(t!==this.gen)return;this.path=n.path,this.parent=n.parent??null,this.render(n.dirs??[])}catch(n){if(t!==this.gen)return;this.setError(pe(n instanceof Error?n.message:String(n))),this.render(null)}}refreshLocale(){this.upBtn.title=h("web.clone.up","Up"),this.updateAct()}render(e){if(this.pathInput.value=this.path,this.upBtn.disabled=!this.parent,this.updateAct(),e===null){this.listEl.replaceChildren();return}if(e.length===0){this.listEl.replaceChildren(X("div","bp-fb-empty",h("web.clone.no.folders","No folders here")));return}let t=document.createDocumentFragment();for(let n of e){let i=$e("","bp-fb-row",()=>{this.go(ir(this.path,n))});i.append(X("span","bp-fb-icon","▸"),X("span","bp-fb-name",n)),t.appendChild(i)}this.listEl.replaceChildren(t),this.listEl.scrollTop=0}updateAct(){this.actBtn.textContent=this.path?this.actionLabel(nr(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 hn{container;host;backdrop=null;bodyEl=null;tabsEl=null;mode="folder";repoText="";repoValue="";firstText="";wantThread=!0;userParent="";nameText="";nameTouched=!1;dest=null;destGen=0;destPending=!1;destTimer=null;repos=null;reposGen=0;reposTimer=null;showSuggest=!1;suggestIdx=-1;startErr="";starting=!1;picking=!1;jobId="";job=null;specs=new Map;signin=null;copied=!1;repoInput=null;suggestEl=null;destEl=null;signinEl=null;cloneBtn=null;jobEl=null;constructor(e,t){this.container=e;this.host=t}isOpen(){return this.backdrop!==null}open(e={}){let t=this.host.hub.hasFeature("clone"),n=!e.repo&&Boolean(this.jobId)&&(!this.job||this.job.state==="running"||this.job.state==="done");if(!this.backdrop)this.build();if(!n)this.jobId="",this.job=null,this.resetForm();if(e.repo!==void 0||e.text!==void 0)this.repoText=(e.repo??"").trim(),this.repoValue="",this.firstText=(e.text??"").trim();if(this.mode=t&&(e.mode==="clone"||n)?"clone":"folder",this.render(),n){if(this.job)this.maybeGo(this.job);this.reconcile()}else if(this.mode==="clone"&&this.repoText)this.askDest()}reconcile(){let e=this.jobId;if(!e)return;this.host.hub.rpc("clone.status",{id:e}).then((t)=>this.apply(t)).catch(()=>{})}close(){if(this.reposTimer!==null)window.clearTimeout(this.reposTimer);if(this.destTimer!==null)window.clearTimeout(this.destTimer);this.reposTimer=null,this.destTimer=null,this.backdrop?.remove(),this.backdrop=null,this.bodyEl=null,this.tabsEl=null}escape(){if(this.picking){this.picking=!1,this.render();return}if(this.showSuggest){this.showSuggest=!1,this.renderSuggest();return}this.close()}refreshLocale(){if(this.backdrop)this.render()}handleFrame(e){if(e.k==="clone"){let t=e.clone;if(t)this.apply(t)}else if(e.k==="clone.repos"){if(this.isOpen()&&this.mode==="clone"&&!this.jobId)this.askRepos(0)}else if(e.k==="clone.signin"){if(!this.signin)return;let t=this.signin.state;if(this.signin=e.signin??null,this.signin?.state==="cancelled")this.signin=null;if(t!=="done"&&this.signin?.state==="done")this.askRepos(0);this.renderSignin()}}build(){let e=X("div","bp-modal-backdrop");e.setAttribute("data-testid","add-project");let t=X("div","bp-modal bp-ap"),n=X("div","bp-modal-head"),i=X("h2","",h("sidebar.add.project","Add project")),s=$e("×","icon",()=>this.close());s.title=h("common.close","Close"),s.setAttribute("aria-label",h("common.close","Close")),n.append(i,s),this.tabsEl=X("div","bp-ap-tabs"),this.bodyEl=X("div","bp-modal-body bp-ap-body"),t.append(n,this.tabsEl,this.bodyEl),e.appendChild(t),e.addEventListener("mousedown",(r)=>{if(r.target===e)this.close()}),this.container.appendChild(e),this.backdrop=e}resetForm(){this.repoText="",this.repoValue="",this.firstText="",this.wantThread=!0,this.userParent="",this.nameText="",this.nameTouched=!1,this.dest=null,this.destPending=!1,this.repos=null,this.showSuggest=!1,this.suggestIdx=-1,this.startErr="",this.starting=!1,this.picking=!1,this.signin=null,this.copied=!1}render(){if(!this.bodyEl||!this.tabsEl||!this.backdrop)return;let e=this.backdrop.querySelector(".bp-modal-head h2");if(e)e.textContent=h("sidebar.add.project","Add project");if(this.renderTabs(),this.repoInput=null,this.suggestEl=null,this.destEl=null,this.signinEl=null,this.cloneBtn=null,this.jobEl=null,this.mode==="folder")this.renderFolder();else if(this.jobId&&this.job)this.renderJobView();else if(this.picking)this.renderPickParent();else this.renderCloneForm()}renderTabs(){if(!this.tabsEl)return;if(!this.host.hub.hasFeature("clone")){this.tabsEl.classList.add("bp-hidden");return}this.tabsEl.classList.remove("bp-hidden");let e=(t,n)=>{let i=$e(n,"bp-ap-tab"+(this.mode===t?" on":""),()=>{if(this.mode===t)return;if(this.mode=t,this.render(),t==="clone"&&!this.jobId&&this.repos===null)this.askRepos(0)});return i.setAttribute("data-testid",`ap-tab-${t}`),i.setAttribute("aria-pressed",String(this.mode===t)),i};this.tabsEl.replaceChildren(e("folder",h("gpui.e.open.folder","Open folder")),e("clone",h("web.clone.tab","Clone from git")))}renderFolder(){let e=new mn(this.host.hub,(t)=>h("web.clone.add.dir","Add {dir}",{dir:t}),async(t)=>{let n=await this.host.hub.rpc("project.add",{path:t},30000);if(this.close(),n.project)this.host.onProjectAdded(n.project)});this.bodyEl.replaceChildren(e.root),e.go("")}renderCloneForm(){let e=this.bodyEl,t=X("div","bp-ap-form"),n=X("div","bp-ap-repo"),i=X("input","bp-input");i.type="text",i.spellcheck=!1,i.autocomplete="off",i.placeholder=h("web.clone.repo.placeholder","https or ssh URL, or owner/repo"),i.setAttribute("aria-label",h("web.clone.repo.placeholder","https or ssh URL, or owner/repo")),i.setAttribute("data-testid","clone-repo"),i.value=this.repoText,i.addEventListener("input",()=>{if(this.repoText=i.value,this.repoValue="",this.showSuggest=!0,this.suggestIdx=-1,this.startErr="",!this.nameTouched)this.nameText="";this.askRepos(200),this.askDest(250)}),i.addEventListener("focus",()=>{if(this.showSuggest=!0,this.repos===null)this.askRepos(0);else this.renderSuggest()}),i.addEventListener("blur",()=>{window.setTimeout(()=>{if(document.activeElement!==i)this.showSuggest=!1,this.renderSuggest()},120)}),i.addEventListener("keydown",(p)=>this.repoKey(p)),this.repoInput=i,this.suggestEl=X("div","bp-ap-suggest bp-hidden"),this.suggestEl.setAttribute("data-testid","clone-suggest"),n.append(i,this.suggestEl),this.signinEl=X("div","bp-ap-signin bp-hidden"),this.signinEl.setAttribute("data-testid","clone-signin"),this.destEl=X("div","bp-ap-dest"),this.destEl.setAttribute("data-testid","clone-dest");let s=X("label","bp-ap-check"),r=X("input");r.type="checkbox",r.checked=this.wantThread,r.setAttribute("data-testid","clone-thread"),r.addEventListener("change",()=>{this.wantThread=r.checked}),s.append(r,X("span","",h("web.clone.start.thread","Start a thread")));let a=[n,this.signinEl,this.destEl,s];if(this.firstText)a.push(X("div","bp-ap-first bp-dim",h("web.clone.first","First message: {text}",{text:this.firstText})));let o=X("div","bp-ap-err"+(this.startErr?"":" bp-hidden"),this.startErr);o.setAttribute("data-testid","clone-start-error");let c=X("div","bp-ap-foot");this.cloneBtn=$e(h("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=$e("","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=X("div","bp-ap-sug-top");if(o.append(X("span","bp-ap-sug-name",s.name)),s.private)o.append(X("span","bp-ap-tag",h("web.clone.private","private")));if(a.append(o),s.description)a.append(X("div","bp-ap-sug-desc",s.description));i.push(a)}),n.length===0&&t){if(t.loading)i.push(X("div","bp-ap-sug-note",h("web.clone.loading","Loading…")));else if(t.hint){let s=X("div","bp-ap-sug-note");if(s.append(X("span","",pe(t.hint))),t.state==="signedout"){let r=$e(h("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=X("div","bp-ap-where"),o=X("span","bp-ap-dest-path",t.destShown||t.dest||t.defaultParentShown||"");o.setAttribute("data-testid","clone-dest-shown");let c=$e(h("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 p=X("label","bp-ap-name");p.append(X("span","bp-ap-lbl",h("web.clone.folder.name","Folder name")));let l=X("input","bp-input");if(l.type="text",l.spellcheck=!1,l.value=this.nameText,l.setAttribute("data-testid","clone-name"),l.addEventListener("input",()=>{this.nameText=l.value,this.nameTouched=l.value.trim()!=="",this.startErr="",this.askDest(250)}),l.addEventListener("keydown",(u)=>{if(u.key==="Enter"&&this.canStart())u.preventDefault(),this.startClone()}),p.append(l),n.push(p),!t.ok&&t.error)n.push(this.errLine(pe(t.error)));else if(t.same)n.push(X("div","bp-ap-note bp-dim",h("web.clone.same","Already cloned there: it is added as it is.")))}let i=document.activeElement,s=i&&e.contains(i)&&i.getAttribute("data-testid")==="clone-name",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=X("div","bp-ap-err",e);return t.setAttribute("data-testid","clone-dest-error"),t}canStart(){return Boolean(this.dest?.ok&&this.dest.repo&&!this.destPending&&!this.starting&&this.repoArg())}updateCloneBtn(){if(this.cloneBtn)this.cloneBtn.disabled=!this.canStart()}renderPickParent(){let e=this.dest?.parent||this.userParent||this.dest?.defaultParent||"",t=$e(h("web.clone.back","Back"),"bp-btn-line",()=>{this.picking=!1,this.render()}),n=new mn(this.host.hub,(i)=>h("web.clone.use.dir","Use {dir}",{dir:i}),async(i)=>{this.userParent=i,this.picking=!1,this.render(),this.askDest()},[t]);this.bodyEl.replaceChildren(n.root),n.go(e)}async startClone(){if(!this.canStart()||!this.dest)return;this.starting=!0,this.startErr="",this.updateCloneBtn();let e={repo:this.repoArg(),thread:this.wantThread,text:this.firstText},t=dn();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=dn(),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(!oi(this.job,e))return;if(this.job=e,this.copied=!1,this.isOpen()&&this.mode==="clone")if(this.jobEl&&this.jobEl.isConnected)this.renderJob();else this.render();this.maybeGo(e)}maybeGo(e){if(this.isOpen()&&e.id===this.jobId&&li(e))this.goTo(e)}renderJobView(){this.jobEl=X("div","bp-ap-job"),this.jobEl.setAttribute("data-testid","clone-job"),this.signinEl=X("div","bp-ap-signin bp-hidden"),this.signinEl.setAttribute("data-testid","clone-signin"),this.bodyEl.replaceChildren(this.jobEl,this.signinEl),this.renderJob(),this.renderSignin()}renderJob(){let e=this.jobEl,t=this.job;if(!e||!t)return;let n=t.destShown||t.dest||"",i=t.repo||"",s=t.state==="done"?h("web.clone.cloned","Cloned {repo} into {dest}",{repo:i,dest:n}):t.state==="cancelled"?h("web.clone.stopped","Stopped cloning {repo}",{repo:i}):h("web.clone.cloning","Cloning {repo} into {dest}",{repo:i,dest:n}),r=[X("div","bp-ap-job-title",s)];if(t.state==="running"){let a=X("div","bp-ap-phase",pe(t.phase||""));a.setAttribute("data-testid","clone-phase");let o=X("div","bp-ap-bar"+(typeof t.pct==="number"?"":" indeterminate")),c=X("div","bp-ap-bar-fill");if(typeof t.pct==="number")c.style.width=`${Math.max(0,Math.min(100,t.pct))}%`;if(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(X("div","bp-ap-detail bp-dim",t.detail));let p=X("div","bp-ap-foot"),l=$e(h("common.cancel","Cancel"),"bp-btn-line",()=>{this.host.hub.rpc("clone.cancel",{id:t.id}).then((u)=>this.apply(u)).catch(()=>{})});l.setAttribute("data-testid","clone-cancel"),p.append(l),r.push(p)}else if(t.state==="failed"||t.state==="cancelled"){if(t.state==="failed"&&t.error){let p=X("div","bp-ap-err",pe(t.error));p.setAttribute("data-testid","clone-error"),r.push(p)}let a=X("div","bp-ap-foot"),o=$e(h("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 p=$e(h("web.clone.signin","Sign in to GitHub"),"bp-btn-line",()=>{this.startSignin()});p.setAttribute("data-testid","clone-signin-btn"),a.append(p)}let c=$e(h("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=X("ul","bp-ap-notes");l.setAttribute("data-testid","clone-notes");for(let u of a)l.appendChild(X("li","",pe(u)));r.push(l)}let o=X("div","bp-ap-foot"),c=t.thread?h("web.clone.open.thread","Open the thread"):h("web.clone.open.project","Open the project"),p=$e(c,"primary",()=>this.goTo(t));p.setAttribute("data-testid","clone-open"),o.append(p),r.push(o)}e.replaceChildren(...r)}showJobError(e){if(!this.jobEl)return;this.jobEl.querySelector(".bp-ap-job-err")?.remove();let t=X("div","bp-ap-err bp-ap-job-err",e);this.jobEl.appendChild(t)}goTo(e){this.jobId="",this.job=null,this.close(),this.host.onCloneDone(e)}async startSignin(){this.signin={state:"starting"},this.copied=!1,this.renderSignin();try{let e=await this.host.hub.rpc("clone.signin",{restart:!0},30000);if(!this.signin||this.signin.state==="starting")this.signin=e}catch(e){this.signin={state:"failed",error:e instanceof Error?e.message:String(e)}}if(this.signin?.state==="done")this.askRepos(0);this.renderSignin()}renderSignin(){let e=this.signinEl;if(!e)return;let t=this.signin,n=[];if(t&&t.state){if(t.state==="starting"||t.state==="waiting"&&!t.code)n.push(X("div","bp-dim",h("web.clone.signin.wait","Starting GitHub sign-in…")));else if(t.state==="waiting"){n.push(X("div","",h("web.clone.signin.enter","Enter this code on GitHub:")));let i=X("div","bp-ap-code-row"),s=X("span","bp-ap-code",t.code||"");s.setAttribute("data-testid","clone-signin-code");let r=$e(this.copied?h("web.clone.copied","Copied"):h("common.copy","Copy"),"bp-btn-line",()=>{navigator.clipboard?.writeText(t.code||"").then(()=>{this.copied=!0,this.renderSignin()}).catch(()=>{})});if(i.append(s,r),n.push(i),t.url){let a=X("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(X("div","bp-ok",h("web.clone.signin.done","Signed in to GitHub")));else if(t.state==="failed")n.push(X("div","bp-ap-err",pe(t.error||"")))}e.replaceChildren(...n),e.classList.toggle("bp-hidden",n.length===0)}}function sr(e){try{let t=new URL(e,window.location.origin);if(t.protocol==="https:"||t.protocol==="http:")return t.href}catch{}return null}function Bt(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=sr(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 Pi(e){if(e.state!=="done")return!1;if(typeof e.hold==="boolean")return!e.hold;return(e.notes??[]).length===0}var jt={en:{"agy.signout":"Sign out","android.hub.machines.approve":"Approve","android.load.earlier":"load earlier","approval.dismiss":"Dismiss","approval.implement":"Implement","ask.plan":"Proposed plan","bots.new":"New bot","bots.rooms":"Rooms","bots.tab.browser":"Browser","common.cancel":"Cancel","common.close":"Close","common.copy":"Copy","common.delete":"Delete","common.refresh":"Refresh","common.remove":"Remove","common.save":"Save","common.search":"Search","composer.model.tip":"Choose the model and effort","composer.placeholder":"Ask anything: @bot, >thread, %project, #room, $skill, /btw","composer.send":"Send","composer.stop":"Stop","gpui.acct.connected":"Connected","gpui.acct.not.connected":"Not connected","gpui.acct.sign.in.expired":"Sign-in expired","gpui.ask.plan.ready":"Ready for review","gpui.ask.plan.revise":"Revise","gpui.ask.plan.reviseph":"What should change in the plan?","gpui.ask.plan.sendrev":"Send revision","gpui.assembly":"Assembly","gpui.b.in.reply.to":"↩ In reply to: {quote}","gpui.b.replying.to":"↩ Replying to: {line}","gpui.bots.recall.off":"Off","gpui.bots.recall.on":"On","gpui.c.solid.big.next":"Loading it may take a while and a lot of memory.","gpui.c.solid.load.big":"Load it anyway","gpui.c.solid.loading.big":"Loading it anyway…","gpui.c.term.collapse":"Collapse","gpui.c.term.expand":"Expand","gpui.commands":"Commands","gpui.e.open.folder":"Open folder","gpui.filter.projects.and.threads":"Filter projects and threads","gpui.fold.or.unfold.the.sidebar":"Fold or unfold the sidebar","gpui.follow.paused":"Following paused","gpui.follow.wait":"Following: waiting for the agent's next edit","gpui.gerbers":"Gerbers","gpui.goal.notes":"GOAL & NOTES","gpui.improvements":"Improvements","gpui.jump.to.a.thread.run":"Jump to a thread, run a command or find what was said","gpui.mgmt.bom.dnp":"DNP","gpui.mgmt.bom.nompn":"no MPN","gpui.mgmt.checks.all":"All","gpui.mgmt.checks.fix":"Fix with agent","gpui.mgmt.checks.run":"Run","gpui.mgmt.close":"Close the panel","gpui.mgmt.fab.apply":"Apply","gpui.mgmt.fab.changed":"Changed since you last looked","gpui.mgmt.fab.derived":"* worked out from the fab's page (a mil in mm, a ring from a diameter). Dimmed: the rigid board's value, where this board's page says nothing else. A date opens the page it was read from.","gpui.mgmt.fab.extra":"Costs more","gpui.mgmt.fab.findings":"Findings","gpui.mgmt.fab.free":"Base price","gpui.mgmt.fab.judge":"Datasheets","gpui.mgmt.fab.limit":"Limit","gpui.mgmt.fab.readcol":"Read","gpui.mgmt.fab.refresh":"Refresh","gpui.mgmt.fab.reviewbtn":"Review","gpui.mgmt.fab.seen":"Seen","gpui.mgmt.fab.thefab":"The fab","gpui.mgmt.fab.use":"Use","gpui.mgmt.life.nopart":"No reading of this part yet.","gpui.mgmt.life.reading":"Reading its history…","gpui.mgmt.plan.addnote":"Add note","gpui.mgmt.plan.all":"Approve all","gpui.mgmt.plan.before":"Plan before routing","gpui.mgmt.plan.compact":"Compact","gpui.mgmt.plan.done":"done","gpui.mgmt.plan.drawn":"The plan's corridors and planes are drawn on the board while this panel is open. Close it to hide them.","gpui.mgmt.plan.edited":"Edited","gpui.mgmt.plan.elsewhere":"A routing plan for {board} awaits your approval","gpui.mgmt.plan.emptysub":"Layers, corridors, and planes appear here once a plan is proposed.","gpui.mgmt.plan.expand":"Expand","gpui.mgmt.plan.fit":"Fit","gpui.mgmt.plan.grid.all":"All layers","gpui.mgmt.plan.grid.pair":"Side by side","gpui.mgmt.plan.grid.single":"Single","gpui.mgmt.plan.hide":"Hide done","gpui.mgmt.plan.hint":"Drag waypoints to steer · Click + on edge to insert · Right-click vertex to remove","gpui.mgmt.plan.keysnote":"On this KiCad version, approve from this panel: in plan view KiCad's A, R and W keys aren't the plan's yet (A opens Add Footprint). Update KiCad.","gpui.mgmt.plan.layer":"Approve layer","gpui.mgmt.plan.layer.short":"Layer","gpui.mgmt.plan.lock":"Lock","gpui.mgmt.plan.locked":"Locked","gpui.mgmt.plan.noboard":"No routing plan for this board.","gpui.mgmt.plan.noitems":"No corridors or planes on this layer","gpui.mgmt.plan.note.placeholder":"Steering note for router…","gpui.mgmt.plan.nothing":"Nothing awaits your approval","gpui.mgmt.plan.offwords":"Agents route as you ask. Turn it on to have them propose a routing plan first and route only what you approve here.","gpui.mgmt.plan.onwords":"Before routing a board with 4 or more copper layers or more than 60 nets, the agent proposes corridors and plane regions here. It routes only what you approve.","gpui.mgmt.plan.reading":"Reading the routing plan…","gpui.mgmt.plan.reference":"over {layer}","gpui.mgmt.plan.refused":"KiCad refused","gpui.mgmt.plan.reject":"Reject","gpui.mgmt.plan.rejectlayer":"Reject layer","gpui.mgmt.plan.reqplain":"Approval requested","gpui.mgmt.plan.requested":"Approval requested: {what}","gpui.mgmt.plan.saved":"saved plan","gpui.mgmt.plan.show":"Show done","gpui.mgmt.plan.st.approved":"Approved","gpui.mgmt.plan.st.awaiting":"Awaiting review","gpui.mgmt.plan.st.blocked":"Blocked","gpui.mgmt.plan.st.empty":"Empty","gpui.mgmt.plan.st.partial":"Partial","gpui.mgmt.plan.st.rejected":"Rejected","gpui.mgmt.plan.st.routed":"Routed","gpui.mgmt.plan.st.routing":"Routing","gpui.mgmt.plan.st.verified":"Verified","gpui.mgmt.plan.stackup.short":"Stackup","gpui.mgmt.plan.stop":"Stop routing","gpui.mgmt.plan.sync":"Link zoom","gpui.mgmt.plan.tab":"Plan","gpui.mgmt.plan.unlock":"Unlock","gpui.mgmt.plan.verify":"Verify","gpui.mgmt.plan.view.canvas":"Canvas","gpui.mgmt.plan.view.list":"List","gpui.mgmt.plan.view.split":"Split","gpui.mgmt.plan.width":"Width","gpui.next.thread":"Next thread","gpui.no.goal.yet.ask.an":"No goal yet. Ask an agent to write what this project is for, or edit .backplane/intent.md.","gpui.no.models":"No models","gpui.no.threads.yet":"No threads yet.","gpui.nothing.matches":"Nothing matches","gpui.picker.favorite.add":"Add to favorites","gpui.picker.favorite.remove":"Remove from favorites","gpui.picker.favorites":"Favorites","gpui.planmode.bar.always":"Plan mode — explores and proposes a plan before editing","gpui.planmode.bar.executing":"Building the approved plan","gpui.planmode.bar.once":"Plan mode (1 turn) — explores and proposes a plan before editing","gpui.planmode.bar.pending":"Proposed plan awaits review below","gpui.planmode.bar.planning":"Planning — drafting a plan before edits","gpui.planmode.chip.building":"Building","gpui.planmode.chip.once":"Plan · 1t","gpui.planmode.scope.always":"Always","gpui.planmode.scope.once":"1 turn","gpui.planmode.tip":"Plan before acting (1 turn, always, or off)","gpui.planmode.top.executing":"Building plan","gpui.planmode.top.once":"Plan (1 turn)","gpui.planmode.top.pending":"Review plan","gpui.planmode.top.planning":"Planning","gpui.previous.thread":"Previous thread","gpui.projects.boards":"BOARDS ({n})","gpui.projects.mech":"MECHANICAL ({n})","gpui.projects.threads":"THREADS ({n})","gpui.projects.to.order":"TO ORDER ({n})","gpui.rail.no.board":"No board in this project","gpui.rail.no.mech":"No mechanical parts in this project","gpui.rail.no.schematic":"No schematic in this project","gpui.rail.split.needs.both":"Split needs a board and a schematic","gpui.search.models":"Search models","gpui.settings.group.agents":"Agents and tools","gpui.settings.group.general":"General","home.away":"Home ({name}) is away","home.away.queued":"Home ({name}) is away · {n} queued","home.away.since":"Home ({name}) is away since {time}","home.away.since.queued":"Home ({name}) is away since {time} · {n} queued","home.machine":"Home machine","home.move.failed":"Home move failed","home.move.failed.note":"Home move failed: {note}","home.move.here":"Make this machine the home","home.moving":"Moving home to {to}…","home.moving.step":"Moving home to {to}: {step}","hub.back.crash":"Backplane is back after it stopped unexpectedly","hub.restarting":"Restarting Backplane…","hub.restarting.build":"Restarting Backplane… (new build {build})","hub.stopped":"Backplane stopped","ios.hub.address.field":"Hub address","menu.pin":"Pin","menu.settle":"Settle","menu.unpin":"Unpin","menu.wake":"Wake","model.col.agent":"Agent","model.col.effort":"Effort","native.pair.connect":"Connect","native.thread.model":"Model","notify.settled":"Settled","palette.archive":"Archive thread","palette.command.placeholder":"Type a command or a thread","palette.diff":"Diff: what this thread changed","palette.newthread":"New thread","palette.settings":"Settings","palette.terminal":"Terminal","palette.unarchive":"Unarchive thread","phone.unsettle":"Unsettle","provider.notice.button":"Open Settings → Accounts","provider.notice.head":"No AI provider connected","provider.notice.senderr":"No AI provider connected yet. Open Settings → Accounts to connect Claude, Codex, Antigravity, or another provider.","provider.notice.senderr.remote":"No AI provider connected on {machine}. Open Settings → Accounts on {machine} to connect Claude, Codex, Antigravity, or another provider.","provider.notice.text.none":"Connect Claude, Codex, Antigravity, or another provider to start chatting.","provider.notice.text.signedout":"Sign in to Claude, Codex, or another provider in Settings → Accounts to start chatting.","reply.action":"Reply","reply.cancel":"Cancel reply","reply.to":"In reply to:","ring.hear.again.local":"Hear again (local)","ring.hear.again.openai":"Hear again (OpenAI)","ring.no.recordings.yet":"No recordings yet.","ring.recordings":"Recordings","ring.ring":"Ring","ring.search.what.you.said":"Search what you said","ring.show.all":"Show all","ring.what.happened":"What happened","rooms.new":"New room","secret.you":"You","settings.appearance":"Appearance","settings.lang":"Language","settings.lang.auto":"Automatic","settings.lang.en":"English","settings.lang.es":"Español","settings.lang.ja":"日本語","settings.theme":"Theme","settings.theme.dark":"Dark","settings.theme.light":"Light","sheet.rename":"Rename thread","sidebar.add.project":"Add project","sidebar.search.projects":"Search projects","thread.context.base":"Backplane","thread.context.copied":"Prompt copied.","thread.context.copy":"Copy prompt","thread.context.disable":"Disable","thread.context.enable":"Enable","thread.context.index":"Available skills index","thread.context.injected.label":"Injected project instructions","thread.context.instructions":"Instructions","thread.context.mcp":"Project MCPs","thread.context.native.note":"Backplane’s launch prompt. Native files are loaded by the provider.","thread.context.none.instructions":"No project instructions found.","thread.context.none.mcp":"No project MCP configurations found.","thread.context.reading":"Reading thread context…","thread.context.size":"{bytes} B · ≈{tokens} tokens","thread.context.skills":"Skills","thread.context.system":"System Prompt","thread.context.title":"Context & Prompt","thread.context.trust":"Trust and enable","thread.new":"New thread","tools.pinned":"Pinned","tools.retry":"Retry","tour.title.bots":"Bots","viewer.board":"Board","viewer.diff":"Diff","viewer.files":"Files","viewer.mech":"Mech","viewer.review":"Review","viewer.schematic":"Schematic","viewer.solid":"3D","web.chat.answer.btn":"Answer","web.chat.answer.placeholder":"Type answer…","web.chat.answered":"Answered: {answer}","web.chat.choose":"Choose a project thread on the left to begin.","web.chat.empty":"No messages yet. Type below to start a turn.","web.chat.finished":"Finished {time}","web.chat.finished.dur":"Finished {time} · {dur}","web.chat.loading":"Loading messages…","web.chat.review.mode":"Review mode","web.chat.streaming":"Streaming…","web.clone.add.dir":"Add {dir}","web.clone.back":"Back","web.clone.change.folder":"Change folder","web.clone.cloned":"Cloned {repo} into {dest}","web.clone.cloning":"Cloning {repo} into {dest}","web.clone.copied":"Copied","web.clone.first":"First message: {text}","web.clone.folder.name":"Folder name","web.clone.go":"Clone","web.clone.loading":"Loading…","web.clone.no.folders":"No folders here","web.clone.open.project":"Open the project","web.clone.open.thread":"Open the thread","web.clone.private":"private","web.clone.repo.placeholder":"https or ssh URL, or owner/repo","web.clone.retry":"Try again","web.clone.same":"Already cloned there: it is added as it is.","web.clone.signin":"Sign in to GitHub","web.clone.signin.done":"Signed in to GitHub","web.clone.signin.enter":"Enter this code on GitHub:","web.clone.signin.wait":"Starting GitHub sign-in…","web.clone.start.thread":"Start a thread","web.clone.stopped":"Stopped cloning {repo}","web.clone.tab":"Clone from git","web.clone.up":"Up","web.clone.use.dir":"Use {dir}","web.composer.attach":"Attach image","web.composer.maximages":"At most {max} images per message.","web.composer.unsupported":"Unsupported image type: {type}","web.composer.voice":"Voice dictation","web.home.error":"Could not load this project.","web.home.fold":"Hide threads","web.home.lead":"Lead time: {n} days","web.home.lead.one":"Lead time: 1 day","web.home.loading":"Loading project…","web.home.open":"Open project home","web.home.unfold":"Show threads","web.logout.failed":"Could not confirm sign-out. Try again.","web.pair.approve.in":"Approve on desktop or paired phone · expires in {time}","web.pair.approved":"Approved. Opening Backplane…","web.pair.cancelled":"Cancelled.","web.pair.code":"Comparison code","web.pair.denied":"Pairing request was denied.","web.pair.expired":"Pairing code expired. Request a new code to try again.","web.pair.failed":"Pairing request failed ({status})","web.pair.name":"Browser name","web.pair.nocode":"Hub did not return a comparison code.","web.pair.ratelimited":"Too many pairing attempts. Wait a moment and try again.","web.pair.request":"Request pairing","web.pair.requesting":"Requesting pairing code…","web.pair.subtitle":"Pair this browser with your hub. Approve the 6-digit code in Backplane › Settings › Devices.","web.pair.unreachable":"Could not reach the hub. Check your tailnet connection.","web.plan.awaiting":"{n} awaiting approval","web.plan.net.one":"1 net","web.plan.nets":"{n} nets","web.ring.app.words":"The Pebble app's words","web.ring.count":"{n} recordings","web.ring.count.one":"1 recording","web.ring.error":"Could not load recordings.","web.ring.found":"{found} of {total} have “{q}”.","web.ring.heard.by":"Heard by {model}","web.ring.heard.by.sure":"Heard by {model}, {conf}% sure","web.ring.loading":"Loading recordings…","web.ring.no.words":"(no words)","web.ring.not.heard":"Not heard","web.ring.state.busy":"being heard now","web.ring.state.failed":"not given to Pebble","web.ring.state.heard":"waiting to go to Pebble","web.ring.state.new":"waiting to be heard","web.ring.state.sent":"given to Pebble","web.ring.unavailable":"This hub does not show ring notes to a browser yet. Update it, or open Settings › Ring in the desktop app.","web.settings.providers":"AI providers","web.settings.providers.browser":"Connect a provider in the Backplane desktop or mobile app under Settings → Accounts."},es:{"agy.signout":"Cerrar sesión","android.hub.machines.approve":"Aprobar","android.load.earlier":"cargar anteriores","approval.dismiss":"Descartar","approval.implement":"Implementar","ask.plan":"Plan propuesto","bots.new":"Nuevo bot","bots.rooms":"Salas","bots.tab.browser":"Navegador","common.cancel":"Cancelar","common.close":"Cerrar","common.copy":"Copiar","common.delete":"Eliminar","common.refresh":"Actualizar","common.remove":"Quitar","common.save":"Guardar","common.search":"Buscar","composer.model.tip":"Elegir el modelo y el esfuerzo","composer.placeholder":"Pregunta lo que sea: @bot, >hilo, %proyecto, #sala, $skill, /btw","composer.send":"Enviar","composer.stop":"Detener","gpui.acct.connected":"Conectado","gpui.acct.not.connected":"No conectado","gpui.acct.sign.in.expired":"Sesión caducada","gpui.ask.plan.ready":"Listo para revisar","gpui.ask.plan.revise":"Revisar","gpui.ask.plan.reviseph":"¿Qué debería cambiar en el plan?","gpui.ask.plan.sendrev":"Enviar revisión","gpui.assembly":"Ensamblaje","gpui.b.in.reply.to":"↩ En respuesta a: {quote}","gpui.b.replying.to":"↩ Respondiendo a: {line}","gpui.bots.recall.off":"Desactivado","gpui.bots.recall.on":"Activado","gpui.c.solid.big.next":"Cargarlo puede tardar y usar mucha memoria.","gpui.c.solid.load.big":"Cargarlo de todos modos","gpui.c.solid.loading.big":"Cargándolo de todos modos…","gpui.c.term.collapse":"Contraer","gpui.c.term.expand":"Expandir","gpui.commands":"Comandos","gpui.e.open.folder":"Abrir carpeta","gpui.filter.projects.and.threads":"Filtrar proyectos e hilos","gpui.fold.or.unfold.the.sidebar":"Plegar o desplegar la barra lateral","gpui.follow.paused":"Seguimiento en pausa","gpui.follow.wait":"Siguiendo: esperando la próxima edición del agente","gpui.gerbers":"Gerbers","gpui.goal.notes":"OBJETIVO Y NOTAS","gpui.improvements":"Mejoras","gpui.jump.to.a.thread.run":"Saltar a un hilo, ejecutar un comando o buscar lo dicho","gpui.mgmt.bom.dnp":"DNP","gpui.mgmt.bom.nompn":"sin MPN","gpui.mgmt.checks.all":"Todas","gpui.mgmt.checks.fix":"Corregir con agente","gpui.mgmt.checks.run":"Ejecutar","gpui.mgmt.close":"Cerrar el panel","gpui.mgmt.fab.apply":"Aplicar","gpui.mgmt.fab.changed":"Cambió desde la última vez que miraste","gpui.mgmt.fab.derived":"* calculado desde la página del fabricante (un mil en mm, un anillo desde un diámetro). Atenuado: el valor de la placa rígida, cuando la página de esta placa no dice otra cosa. Una fecha abre la página de la que se leyó.","gpui.mgmt.fab.extra":"Cuesta más","gpui.mgmt.fab.findings":"Hallazgos","gpui.mgmt.fab.free":"Precio base","gpui.mgmt.fab.judge":"Hojas de datos","gpui.mgmt.fab.limit":"Límite","gpui.mgmt.fab.readcol":"Leído","gpui.mgmt.fab.refresh":"Actualizar","gpui.mgmt.fab.reviewbtn":"Revisar","gpui.mgmt.fab.seen":"Visto","gpui.mgmt.fab.thefab":"El fabricante","gpui.mgmt.fab.use":"Usar","gpui.mgmt.life.nopart":"Sin lectura de esta pieza aún.","gpui.mgmt.life.reading":"Leyendo su historial…","gpui.mgmt.plan.addnote":"Añadir nota","gpui.mgmt.plan.all":"Aprobar todo","gpui.mgmt.plan.before":"Planificar antes de rutear","gpui.mgmt.plan.compact":"Compacto","gpui.mgmt.plan.done":"hecho","gpui.mgmt.plan.drawn":"Los corredores y planos del plan se dibujan en la placa mientras este panel está abierto. Ciérralo para ocultarlos.","gpui.mgmt.plan.edited":"Editado","gpui.mgmt.plan.elsewhere":"Un plan de ruteo para {board} espera tu aprobación","gpui.mgmt.plan.emptysub":"Las capas, corredores y planos aparecerán aquí cuando se proponga un plan.","gpui.mgmt.plan.expand":"Expandir","gpui.mgmt.plan.fit":"Ajustar","gpui.mgmt.plan.grid.all":"Todas las capas","gpui.mgmt.plan.grid.pair":"Lado a lado","gpui.mgmt.plan.grid.single":"Única","gpui.mgmt.plan.hide":"Ocultar hechos","gpui.mgmt.plan.hint":"Arrastra vértices para guiar · Clic en + del borde para insertar · Clic derecho en vértice para quitar","gpui.mgmt.plan.keysnote":"En esta versión de KiCad, aprueba desde este panel: en la vista de plan las teclas A, R y W de KiCad aún no son del plan (A abre Añadir Huella). Actualiza KiCad.","gpui.mgmt.plan.layer":"Aprobar capa","gpui.mgmt.plan.layer.short":"Capa","gpui.mgmt.plan.lock":"Bloquear","gpui.mgmt.plan.locked":"Bloqueado","gpui.mgmt.plan.noboard":"No hay plan de ruteo para esta placa.","gpui.mgmt.plan.noitems":"Sin corredores ni planos en esta capa","gpui.mgmt.plan.note.placeholder":"Nota de guiado para el router…","gpui.mgmt.plan.nothing":"Nada espera tu aprobación","gpui.mgmt.plan.offwords":"Los agentes rutean como les pidas. Actívalo para que primero propongan un plan de ruteo y ruteen solo lo que apruebes aquí.","gpui.mgmt.plan.onwords":"Antes de rutear una placa con 4 o más capas de cobre o más de 60 redes, el agente propone aquí corredores y regiones de plano. Solo rutea lo que apruebes.","gpui.mgmt.plan.reading":"Leyendo el plan de ruteo…","gpui.mgmt.plan.reference":"sobre {layer}","gpui.mgmt.plan.refused":"KiCad lo rechazó","gpui.mgmt.plan.reject":"Rechazar","gpui.mgmt.plan.rejectlayer":"Rechazar capa","gpui.mgmt.plan.reqplain":"Aprobación solicitada","gpui.mgmt.plan.requested":"Aprobación solicitada: {what}","gpui.mgmt.plan.saved":"plan guardado","gpui.mgmt.plan.show":"Mostrar hechos","gpui.mgmt.plan.st.approved":"Aprobado","gpui.mgmt.plan.st.awaiting":"Esperando revisión","gpui.mgmt.plan.st.blocked":"Bloqueado","gpui.mgmt.plan.st.empty":"Vacío","gpui.mgmt.plan.st.partial":"Parcial","gpui.mgmt.plan.st.rejected":"Rechazado","gpui.mgmt.plan.st.routed":"Ruteado","gpui.mgmt.plan.st.routing":"Ruteando","gpui.mgmt.plan.st.verified":"Verificado","gpui.mgmt.plan.stackup.short":"Apilamiento","gpui.mgmt.plan.stop":"Detener ruteo","gpui.mgmt.plan.sync":"Vincular zoom","gpui.mgmt.plan.tab":"Plan","gpui.mgmt.plan.unlock":"Desbloquear","gpui.mgmt.plan.verify":"Verificar","gpui.mgmt.plan.view.canvas":"Lienzo","gpui.mgmt.plan.view.list":"Lista","gpui.mgmt.plan.view.split":"Dividido","gpui.mgmt.plan.width":"Ancho","gpui.next.thread":"Hilo siguiente","gpui.no.goal.yet.ask.an":"Sin objetivo aún. Pide a un agente que escriba para qué es este proyecto, o edita .backplane/intent.md.","gpui.no.models":"Sin modelos","gpui.no.threads.yet":"Sin hilos aún.","gpui.nothing.matches":"Nada coincide","gpui.picker.favorite.add":"Añadir a favoritos","gpui.picker.favorite.remove":"Quitar de favoritos","gpui.picker.favorites":"Favoritos","gpui.planmode.bar.always":"Modo plan — explora y propone un plan antes de editar","gpui.planmode.bar.executing":"Ejecutando el plan aprobado","gpui.planmode.bar.once":"Modo plan (1 turno) — explora y propone un plan antes de editar","gpui.planmode.bar.pending":"El plan propuesto espera revisión abajo","gpui.planmode.bar.planning":"Planificando — redactando un plan antes de editar","gpui.planmode.chip.building":"Ejecutando","gpui.planmode.chip.once":"Plan · 1t","gpui.planmode.scope.always":"Siempre","gpui.planmode.scope.once":"1 turno","gpui.planmode.tip":"Planificar antes de actuar (1 turno, siempre u off)","gpui.planmode.top.executing":"Ejecutando plan","gpui.planmode.top.once":"Plan (1 turno)","gpui.planmode.top.pending":"Revisar plan","gpui.planmode.top.planning":"Planificando","gpui.previous.thread":"Hilo anterior","gpui.projects.boards":"PLACAS ({n})","gpui.projects.mech":"MECÁNICO ({n})","gpui.projects.threads":"HILOS ({n})","gpui.projects.to.order":"POR PEDIR ({n})","gpui.rail.no.board":"Este proyecto no tiene placa","gpui.rail.no.mech":"Este proyecto no tiene piezas mecánicas","gpui.rail.no.schematic":"Este proyecto no tiene esquema","gpui.rail.split.needs.both":"La vista dividida requiere una placa y un esquema","gpui.search.models":"Buscar modelos","gpui.settings.group.agents":"Agentes y herramientas","gpui.settings.group.general":"General","home.away":"El inicio ({name}) no está disponible","home.away.queued":"El inicio ({name}) no está disponible · {n} en cola","home.away.since":"El inicio ({name}) no está disponible desde las {time}","home.away.since.queued":"El inicio ({name}) no está disponible desde las {time} · {n} en cola","home.machine":"Máquina de inicio","home.move.failed":"No se pudo mover el inicio","home.move.failed.note":"No se pudo mover el inicio: {note}","home.move.here":"Hacer de esta máquina el inicio","home.moving":"Moviendo el inicio a {to}…","home.moving.step":"Moviendo el inicio a {to}: {step}","hub.back.crash":"Backplane volvió tras detenerse de forma inesperada","hub.restarting":"Reiniciando Backplane…","hub.restarting.build":"Reiniciando Backplane… (nueva compilación {build})","hub.stopped":"Backplane se detuvo","ios.hub.address.field":"Dirección del hub","menu.pin":"Fijar","menu.settle":"Cerrar","menu.unpin":"Desfijar","menu.wake":"Despertar","model.col.agent":"Agente","model.col.effort":"Esfuerzo","native.pair.connect":"Conectar","native.thread.model":"Modelo","notify.settled":"Cerrado","palette.archive":"Archivar hilo","palette.command.placeholder":"Escribe un comando o un hilo","palette.diff":"Diff: qué cambió este hilo","palette.newthread":"Nuevo hilo","palette.settings":"Ajustes","palette.terminal":"Terminal","palette.unarchive":"Desarchivar hilo","phone.unsettle":"Reabrir","provider.notice.button":"Abrir Configuración → Cuentas","provider.notice.head":"No hay ningún proveedor de IA conectado","provider.notice.senderr":"Aún no hay ningún proveedor de IA conectado. Abre Configuración → Cuentas para conectar Claude, Codex, Antigravity u otro proveedor.","provider.notice.senderr.remote":"No hay ningún proveedor de IA conectado en {machine}. Abre Configuración → Cuentas en {machine} para conectar Claude, Codex, Antigravity u otro proveedor.","provider.notice.text.none":"Conecta Claude, Codex, Antigravity u otro proveedor para empezar a chatear.","provider.notice.text.signedout":"Inicia sesión en Claude, Codex u otro proveedor en Configuración → Cuentas para empezar a chatear.","reply.action":"Responder","reply.cancel":"Cancelar respuesta","reply.to":"En respuesta a:","ring.hear.again.local":"Escuchar de nuevo (local)","ring.hear.again.openai":"Escuchar de nuevo (OpenAI)","ring.no.recordings.yet":"Sin grabaciones aún.","ring.recordings":"Grabaciones","ring.ring":"Anillo","ring.search.what.you.said":"Buscar lo que dijiste","ring.show.all":"Mostrar todo","ring.what.happened":"Qué ocurrió","rooms.new":"Nueva sala","secret.you":"Tú","settings.appearance":"Apariencia","settings.lang":"Idioma","settings.lang.auto":"Automático","settings.lang.en":"English","settings.lang.es":"Español","settings.lang.ja":"日本語","settings.theme":"Tema","settings.theme.dark":"Oscuro","settings.theme.light":"Claro","sheet.rename":"Renombrar hilo","sidebar.add.project":"Añadir proyecto","sidebar.search.projects":"Buscar proyectos","thread.context.base":"Backplane","thread.context.copied":"Se copiaron las instrucciones.","thread.context.copy":"Copiar instrucciones","thread.context.disable":"Desactivar","thread.context.enable":"Activar","thread.context.index":"Índice de habilidades disponibles","thread.context.injected.label":"Instrucciones del proyecto añadidas","thread.context.instructions":"Instrucciones","thread.context.mcp":"MCP del proyecto","thread.context.native.note":"Instrucciones de inicio de Backplane. El proveedor carga los archivos nativos.","thread.context.none.instructions":"No se encontraron instrucciones del proyecto.","thread.context.none.mcp":"No se encontraron configuraciones MCP del proyecto.","thread.context.reading":"Leyendo el contexto del hilo…","thread.context.size":"{bytes} B · ≈{tokens} tokens","thread.context.skills":"Habilidades","thread.context.system":"Instrucciones del sistema","thread.context.title":"Contexto e instrucciones","thread.context.trust":"Confiar y activar","thread.new":"Nuevo hilo","tools.pinned":"Fijado","tools.retry":"Reintentar","tour.title.bots":"Bots","viewer.board":"Placa","viewer.diff":"Diff","viewer.files":"Archivos","viewer.mech":"Mech","viewer.review":"Revisión","viewer.schematic":"Esquemático","viewer.solid":"3D","web.chat.answer.btn":"Responder","web.chat.answer.placeholder":"Escribe una respuesta…","web.chat.answered":"Respondido: {answer}","web.chat.choose":"Elige un hilo de proyecto a la izquierda para empezar.","web.chat.empty":"Aún no hay mensajes. Escribe abajo para iniciar un turno.","web.chat.finished":"Terminado {time}","web.chat.finished.dur":"Terminado {time} · {dur}","web.chat.loading":"Cargando mensajes…","web.chat.review.mode":"Modo de revisión","web.chat.streaming":"Transmitiendo…","web.clone.add.dir":"Añadir {dir}","web.clone.back":"Atrás","web.clone.change.folder":"Cambiar carpeta","web.clone.cloned":"{repo} clonado en {dest}","web.clone.cloning":"Clonando {repo} en {dest}","web.clone.copied":"Copiado","web.clone.first":"Primer mensaje: {text}","web.clone.folder.name":"Nombre de la carpeta","web.clone.go":"Clonar","web.clone.loading":"Cargando…","web.clone.no.folders":"No hay carpetas aquí","web.clone.open.project":"Abrir el proyecto","web.clone.open.thread":"Abrir el hilo","web.clone.private":"privado","web.clone.repo.placeholder":"URL https o ssh, o propietario/repositorio","web.clone.retry":"Reintentar","web.clone.same":"Ya está clonado ahí: se añade tal cual.","web.clone.signin":"Iniciar sesión en GitHub","web.clone.signin.done":"Sesión iniciada en GitHub","web.clone.signin.enter":"Introduce este código en GitHub:","web.clone.signin.wait":"Iniciando sesión en GitHub…","web.clone.start.thread":"Empezar un hilo","web.clone.stopped":"Se detuvo la clonación de {repo}","web.clone.tab":"Clonar desde git","web.clone.up":"Subir","web.clone.use.dir":"Usar {dir}","web.composer.attach":"Adjuntar imagen","web.composer.maximages":"Como máximo {max} imágenes por mensaje.","web.composer.unsupported":"Tipo de imagen no compatible: {type}","web.composer.voice":"Dictado por voz","web.home.error":"No se pudo cargar este proyecto.","web.home.fold":"Ocultar hilos","web.home.lead":"Plazo de entrega: {n} días","web.home.lead.one":"Plazo de entrega: 1 día","web.home.loading":"Cargando el proyecto…","web.home.open":"Abrir la página del proyecto","web.home.unfold":"Mostrar hilos","web.logout.failed":"No se pudo confirmar el cierre de sesión. Inténtalo de nuevo.","web.pair.approve.in":"Aprueba en el escritorio o en un teléfono vinculado · caduca en {time}","web.pair.approved":"Aprobado. Abriendo Backplane…","web.pair.cancelled":"Cancelado.","web.pair.code":"Código de comparación","web.pair.denied":"Se rechazó la solicitud de vinculación.","web.pair.expired":"El código de vinculación caducó. Solicita uno nuevo para intentarlo otra vez.","web.pair.failed":"Falló la solicitud de vinculación ({status})","web.pair.name":"Nombre del navegador","web.pair.nocode":"El hub no devolvió un código de comparación.","web.pair.ratelimited":"Demasiados intentos de vinculación. Espera un momento e inténtalo de nuevo.","web.pair.request":"Solicitar vinculación","web.pair.requesting":"Solicitando código de vinculación…","web.pair.subtitle":"Vincula este navegador con tu hub. Aprueba el código de 6 dígitos en Backplane › Ajustes › Dispositivos.","web.pair.unreachable":"No se pudo conectar con el hub. Comprueba tu conexión de tailnet.","web.plan.awaiting":"{n} esperando aprobación","web.plan.net.one":"1 red","web.plan.nets":"{n} redes","web.ring.app.words":"Las palabras de la aplicación Pebble","web.ring.count":"{n} grabaciones","web.ring.count.one":"1 grabación","web.ring.error":"No se pudieron cargar las grabaciones.","web.ring.found":"{found} de {total} contienen “{q}”.","web.ring.heard.by":"Transcrito por {model}","web.ring.heard.by.sure":"Transcrito por {model}, {conf}% de certeza","web.ring.loading":"Cargando grabaciones…","web.ring.no.words":"(sin palabras)","web.ring.not.heard":"Sin transcribir","web.ring.state.busy":"transcribiéndose ahora","web.ring.state.failed":"no entregada a Pebble","web.ring.state.heard":"en espera de entrega a Pebble","web.ring.state.new":"en espera de transcripción","web.ring.state.sent":"entregada a Pebble","web.ring.unavailable":"Este hub aún no muestra las notas del anillo en un navegador. Actualízalo o abre Configuración › Anillo en la aplicación de escritorio.","web.settings.providers":"Proveedores de IA","web.settings.providers.browser":"Conecta un proveedor en la aplicación de escritorio o móvil de Backplane en Configuración → Cuentas."},ja:{"agy.signout":"サインアウト","android.hub.machines.approve":"承認","android.load.earlier":"以前のメッセージを読み込む","approval.dismiss":"閉じる","approval.implement":"実装","ask.plan":"提案されたプラン","bots.new":"新しいボット","bots.rooms":"ルーム","bots.tab.browser":"ブラウザ","common.cancel":"キャンセル","common.close":"閉じる","common.copy":"コピー","common.delete":"削除","common.refresh":"更新","common.remove":"削除","common.save":"保存","common.search":"検索","composer.model.tip":"モデルと推論の強さを選択","composer.placeholder":"何でも質問:@bot、>thread、%project、#room、$skill、/btw","composer.send":"送信","composer.stop":"停止","gpui.acct.connected":"接続済み","gpui.acct.not.connected":"未接続","gpui.acct.sign.in.expired":"サインインの期限切れ","gpui.ask.plan.ready":"確認待ち","gpui.ask.plan.revise":"修正","gpui.ask.plan.reviseph":"計画のどこを変更しますか?","gpui.ask.plan.sendrev":"修正を送る","gpui.assembly":"アセンブリ","gpui.b.in.reply.to":"↩ 返信先:{quote}","gpui.b.replying.to":"↩ 返信中:{line}","gpui.bots.recall.off":"オフ","gpui.bots.recall.on":"オン","gpui.c.solid.big.next":"読み込みには時間と多くのメモリがかかることがあります。","gpui.c.solid.load.big":"それでも読み込む","gpui.c.solid.loading.big":"それでも読み込み中…","gpui.c.term.collapse":"折りたたむ","gpui.c.term.expand":"展開","gpui.commands":"コマンド","gpui.e.open.folder":"フォルダを開く","gpui.filter.projects.and.threads":"プロジェクトとスレッドを絞り込む","gpui.fold.or.unfold.the.sidebar":"サイドバーを折りたたむ/開く","gpui.follow.paused":"追従を一時停止中","gpui.follow.wait":"追従中: エージェントの次の編集を待っています","gpui.gerbers":"ガーバー","gpui.goal.notes":"目標とメモ","gpui.improvements":"改善","gpui.jump.to.a.thread.run":"スレッドへ移動、コマンドを実行、または発言を検索","gpui.mgmt.bom.dnp":"実装しない","gpui.mgmt.bom.nompn":"MPNなし","gpui.mgmt.checks.all":"すべて","gpui.mgmt.checks.fix":"エージェントに直してもらう","gpui.mgmt.checks.run":"実行","gpui.mgmt.close":"パネルを閉じる","gpui.mgmt.fab.apply":"適用","gpui.mgmt.fab.changed":"前回見てから変わったところ","gpui.mgmt.fab.derived":"* 製造元のページから計算した値です(milをmmに、径からランドを)。薄い色の項目はリジッド基板の値です(この基板のページに記載がないもの)。日付を押すと読んだページが開きます。","gpui.mgmt.fab.extra":"追加料金","gpui.mgmt.fab.findings":"指摘","gpui.mgmt.fab.free":"基本料金","gpui.mgmt.fab.judge":"データシート","gpui.mgmt.fab.limit":"項目","gpui.mgmt.fab.readcol":"読んだ日","gpui.mgmt.fab.refresh":"再読み込み","gpui.mgmt.fab.reviewbtn":"レビュー","gpui.mgmt.fab.seen":"確認済み","gpui.mgmt.fab.thefab":"製造元","gpui.mgmt.fab.use":"使う","gpui.mgmt.life.nopart":"この部品の記録はまだありません。","gpui.mgmt.life.reading":"履歴を読んでいます…","gpui.mgmt.plan.addnote":"メモを追加","gpui.mgmt.plan.all":"すべて承認","gpui.mgmt.plan.before":"配線前に計画する","gpui.mgmt.plan.compact":"標準","gpui.mgmt.plan.done":"完了","gpui.mgmt.plan.drawn":"計画の配線経路とプレーンは、このパネルを開いている間だけ基板上に表示されます。閉じると消えます。","gpui.mgmt.plan.edited":"編集済み","gpui.mgmt.plan.elsewhere":"{board}の配線計画が承認を待っています","gpui.mgmt.plan.emptysub":"計画が提案されると、レイヤー・コリドー・ベタ領域がここに表示されます。","gpui.mgmt.plan.expand":"拡大","gpui.mgmt.plan.fit":"全体表示","gpui.mgmt.plan.grid.all":"全レイヤー","gpui.mgmt.plan.grid.pair":"並べて表示","gpui.mgmt.plan.grid.single":"単一","gpui.mgmt.plan.hide":"完了を隠す","gpui.mgmt.plan.hint":"頂点をドラッグして誘導 · 辺の + をクリックで追加 · 頂点を右クリックで削除","gpui.mgmt.plan.keysnote":"このバージョンのKiCadでは、このパネルから承認してください。プランビューでのKiCadのA・R・Wキーはまだ計画のものではありません(Aはフットプリントの追加を開きます)。KiCadを更新してください。","gpui.mgmt.plan.layer":"層を承認","gpui.mgmt.plan.layer.short":"レイヤー","gpui.mgmt.plan.lock":"ロック","gpui.mgmt.plan.locked":"ロック中","gpui.mgmt.plan.noboard":"この基板の配線計画はありません。","gpui.mgmt.plan.noitems":"このレイヤーにコリドーまたはプレーンがありません","gpui.mgmt.plan.note.placeholder":"ルーターへの指示メモ…","gpui.mgmt.plan.nothing":"承認待ちはありません","gpui.mgmt.plan.offwords":"エージェントは指示どおりに配線します。オンにすると、まず配線計画を提案し、ここで承認したものだけを配線します。","gpui.mgmt.plan.onwords":"銅箔層が4層以上、またはネットが60本を超える基板では、配線の前にエージェントがここで配線経路とプレーン領域を提案します。承認したものだけを配線します。","gpui.mgmt.plan.reading":"配線計画を読んでいます…","gpui.mgmt.plan.reference":"基準 {layer}","gpui.mgmt.plan.refused":"KiCad が拒否しました","gpui.mgmt.plan.reject":"却下","gpui.mgmt.plan.rejectlayer":"レイヤーを却下","gpui.mgmt.plan.reqplain":"承認が求められています","gpui.mgmt.plan.requested":"承認が求められています: {what}","gpui.mgmt.plan.saved":"保存された計画","gpui.mgmt.plan.show":"完了を表示","gpui.mgmt.plan.st.approved":"承認済み","gpui.mgmt.plan.st.awaiting":"承認待ち","gpui.mgmt.plan.st.blocked":"ブロック","gpui.mgmt.plan.st.empty":"空","gpui.mgmt.plan.st.partial":"一部完了","gpui.mgmt.plan.st.rejected":"却下","gpui.mgmt.plan.st.routed":"配線済み","gpui.mgmt.plan.st.routing":"配線中","gpui.mgmt.plan.st.verified":"検証済み","gpui.mgmt.plan.stackup.short":"スタックアップ","gpui.mgmt.plan.stop":"配線を止める","gpui.mgmt.plan.sync":"ズーム連動","gpui.mgmt.plan.tab":"計画","gpui.mgmt.plan.unlock":"ロック解除","gpui.mgmt.plan.verify":"検証","gpui.mgmt.plan.view.canvas":"キャンバス","gpui.mgmt.plan.view.list":"リスト","gpui.mgmt.plan.view.split":"分割","gpui.mgmt.plan.width":"幅","gpui.next.thread":"次のスレッド","gpui.no.goal.yet.ask.an":"目標はまだありません。このプロジェクトの目的をエージェントに書いてもらうか、.backplane/intent.md を編集してください。","gpui.no.models":"モデルがありません","gpui.no.threads.yet":"スレッドはまだありません。","gpui.nothing.matches":"一致するものはありません","gpui.picker.favorite.add":"お気に入りに追加","gpui.picker.favorite.remove":"お気に入りから外す","gpui.picker.favorites":"お気に入り","gpui.planmode.bar.always":"計画モード — 編集前に調査して計画を提案します","gpui.planmode.bar.executing":"承認された計画を実行しています","gpui.planmode.bar.once":"計画モード (1回) — 編集前に調査して計画を提案します","gpui.planmode.bar.pending":"提案された計画が下のレビューを待っています","gpui.planmode.bar.planning":"計画中 — 編集前の計画を作成しています","gpui.planmode.chip.building":"実行中","gpui.planmode.chip.once":"計画 · 1回","gpui.planmode.scope.always":"常時","gpui.planmode.scope.once":"1回","gpui.planmode.tip":"実行前に計画を作成 (1回・常時・オフ)","gpui.planmode.top.executing":"計画を実行中","gpui.planmode.top.once":"計画 (1回)","gpui.planmode.top.pending":"計画を確認","gpui.planmode.top.planning":"計画中","gpui.previous.thread":"前のスレッド","gpui.projects.boards":"基板({n})","gpui.projects.mech":"機構部品({n})","gpui.projects.threads":"スレッド({n})","gpui.projects.to.order":"注文するもの({n})","gpui.rail.no.board":"このプロジェクトには基板がありません","gpui.rail.no.mech":"このプロジェクトには機械部品がありません","gpui.rail.no.schematic":"このプロジェクトには回路図がありません","gpui.rail.split.needs.both":"分割表示には基板と回路図が必要です","gpui.search.models":"モデルを検索","gpui.settings.group.agents":"エージェントとツール","gpui.settings.group.general":"一般","home.away":"ホーム({name})はオフラインです","home.away.queued":"ホーム({name})はオフラインです · {n} 件待機中","home.away.since":"ホーム({name})は {time} からオフラインです","home.away.since.queued":"ホーム({name})は {time} からオフラインです · {n} 件待機中","home.machine":"ホームマシン","home.move.failed":"ホームの移動に失敗しました","home.move.failed.note":"ホームの移動に失敗しました: {note}","home.move.here":"このマシンをホームにする","home.moving":"ホームを {to} へ移動中…","home.moving.step":"ホームを {to} へ移動中: {step}","hub.back.crash":"予期せず停止したBackplaneが戻りました","hub.restarting":"Backplaneを再起動しています…","hub.restarting.build":"Backplaneを再起動しています…(新しいビルド {build})","hub.stopped":"Backplaneは停止しました","ios.hub.address.field":"ハブのアドレス","menu.pin":"ピン留め","menu.settle":"完了","menu.unpin":"ピン留めを解除","menu.wake":"再開","model.col.agent":"エージェント","model.col.effort":"推論の強さ","native.pair.connect":"接続","native.thread.model":"モデル","notify.settled":"完了","palette.archive":"スレッドをアーカイブ","palette.command.placeholder":"コマンドまたはスレッドを入力","palette.diff":"差分:このスレッドの変更","palette.newthread":"新しいスレッド","palette.settings":"設定","palette.terminal":"ターミナル","palette.unarchive":"スレッドのアーカイブを解除","phone.unsettle":"未完了に戻す","provider.notice.button":"設定 → アカウントを開く","provider.notice.head":"AI プロバイダーが接続されていません","provider.notice.senderr":"AI プロバイダーがまだ接続されていません。設定 → アカウントを開いて、Claude、Codex、Antigravity などのプロバイダーを接続してください。","provider.notice.senderr.remote":"{machine} に AI プロバイダーが接続されていません。{machine} で設定 → アカウントを開いて、Claude、Codex、Antigravity などのプロバイダーを接続してください。","provider.notice.text.none":"チャットを始めるには、Claude、Codex、Antigravity などのプロバイダーを接続してください。","provider.notice.text.signedout":"チャットを始めるには、設定 → アカウントで Claude、Codex などのプロバイダーにサインインしてください。","reply.action":"返信","reply.cancel":"返信をやめる","reply.to":"返信先:","ring.hear.again.local":"もう一度聞き取る (ローカル)","ring.hear.again.openai":"もう一度聞き取る (OpenAI)","ring.no.recordings.yet":"録音はまだありません。","ring.recordings":"録音","ring.ring":"リング","ring.search.what.you.said":"話した内容を検索","ring.show.all":"すべて表示","ring.what.happened":"どうなったか","rooms.new":"新しいルーム","secret.you":"あなた","settings.appearance":"外観","settings.lang":"言語","settings.lang.auto":"自動","settings.lang.en":"English","settings.lang.es":"Español","settings.lang.ja":"日本語","settings.theme":"テーマ","settings.theme.dark":"ダーク","settings.theme.light":"ライト","sheet.rename":"スレッド名を変更","sidebar.add.project":"プロジェクトを追加","sidebar.search.projects":"プロジェクトを検索","thread.context.base":"Backplane","thread.context.copied":"プロンプトをコピーしました。","thread.context.copy":"プロンプトをコピー","thread.context.disable":"無効にする","thread.context.enable":"有効にする","thread.context.index":"利用可能なスキルの一覧","thread.context.injected.label":"追加されたプロジェクトの指示","thread.context.instructions":"指示","thread.context.mcp":"プロジェクトの MCP","thread.context.native.note":"Backplane が起動時に渡すプロンプトです。ネイティブファイルはプロバイダーが読み込みます。","thread.context.none.instructions":"プロジェクトの指示が見つかりません。","thread.context.none.mcp":"プロジェクトの MCP 設定が見つかりません。","thread.context.reading":"スレッドのコンテキストを読み込み中…","thread.context.size":"{bytes} B・約{tokens}トークン","thread.context.skills":"スキル","thread.context.system":"システムプロンプト","thread.context.title":"コンテキストとプロンプト","thread.context.trust":"承認して有効にする","thread.new":"新しいスレッド","tools.pinned":"固定中","tools.retry":"再試行","tour.title.bots":"ボット","viewer.board":"基板","viewer.diff":"差分","viewer.files":"ファイル","viewer.mech":"Mech","viewer.review":"レビュー","viewer.schematic":"回路図","viewer.solid":"3D","web.chat.answer.btn":"回答","web.chat.answer.placeholder":"回答を入力…","web.chat.answered":"回答済み: {answer}","web.chat.choose":"左側からプロジェクトのスレッドを選んで開始してください。","web.chat.empty":"まだメッセージはありません。下に入力して開始してください。","web.chat.finished":"完了 {time}","web.chat.finished.dur":"完了 {time} · {dur}","web.chat.loading":"メッセージを読み込んでいます…","web.chat.review.mode":"レビューモード","web.chat.streaming":"受信中…","web.clone.add.dir":"{dir} を追加","web.clone.back":"戻る","web.clone.change.folder":"フォルダを変更","web.clone.cloned":"{repo} を {dest} にクローンしました","web.clone.cloning":"{repo} を {dest} にクローン中","web.clone.copied":"コピーしました","web.clone.first":"最初のメッセージ: {text}","web.clone.folder.name":"フォルダ名","web.clone.go":"クローン","web.clone.loading":"読み込み中…","web.clone.no.folders":"フォルダがありません","web.clone.open.project":"プロジェクトを開く","web.clone.open.thread":"スレッドを開く","web.clone.private":"非公開","web.clone.repo.placeholder":"https / ssh の URL、または owner/repo","web.clone.retry":"もう一度","web.clone.same":"すでにそこにクローンされています: そのまま追加します。","web.clone.signin":"GitHub にサインイン","web.clone.signin.done":"GitHub にサインインしました","web.clone.signin.enter":"このコードを GitHub に入力してください:","web.clone.signin.wait":"GitHub のサインインを開始しています…","web.clone.start.thread":"スレッドを開始","web.clone.stopped":"{repo} のクローンを中止しました","web.clone.tab":"git からクローン","web.clone.up":"上へ","web.clone.use.dir":"{dir} を使う","web.composer.attach":"画像を添付","web.composer.maximages":"1 件のメッセージに添付できる画像は最大 {max} 枚です。","web.composer.unsupported":"未対応の画像形式です: {type}","web.composer.voice":"音声入力","web.home.error":"このプロジェクトを読み込めませんでした。","web.home.fold":"スレッドを隠す","web.home.lead":"リードタイム: {n} 日","web.home.lead.one":"リードタイム: 1 日","web.home.loading":"プロジェクトを読み込み中…","web.home.open":"プロジェクトホームを開く","web.home.unfold":"スレッドを表示","web.logout.failed":"サインアウトを確認できませんでした。もう一度お試しください。","web.pair.approve.in":"デスクトップまたはペアリング済みの端末で承認してください · 有効期限 {time}","web.pair.approved":"承認されました。Backplane を開いています…","web.pair.cancelled":"キャンセルしました。","web.pair.code":"確認コード","web.pair.denied":"ペアリングのリクエストが拒否されました。","web.pair.expired":"ペアリングコードの有効期限が切れました。新しいコードをリクエストしてください。","web.pair.failed":"ペアリングのリクエストに失敗しました ({status})","web.pair.name":"ブラウザー名","web.pair.nocode":"ハブから確認コードが返されませんでした。","web.pair.ratelimited":"ペアリングの試行回数が多すぎます。しばらく待ってからやり直してください。","web.pair.request":"ペアリングをリクエスト","web.pair.requesting":"ペアリングコードをリクエストしています…","web.pair.subtitle":"このブラウザーをハブとペアリングします。Backplane › 設定 › デバイス で 6 桁のコードを承認してください。","web.pair.unreachable":"ハブに接続できませんでした。tailnet の接続を確認してください。","web.plan.awaiting":"{n} 件が承認待ち","web.plan.net.one":"1 ネット","web.plan.nets":"{n} ネット","web.ring.app.words":"Pebble アプリの文字起こし","web.ring.count":"録音 {n} 件","web.ring.count.one":"録音 1 件","web.ring.error":"録音を読み込めませんでした。","web.ring.found":"{total} 件中 {found} 件に「{q}」があります。","web.ring.heard.by":"{model} が認識","web.ring.heard.by.sure":"{model} が認識、確度 {conf}%","web.ring.loading":"録音を読み込み中…","web.ring.no.words":"(言葉なし)","web.ring.not.heard":"未認識","web.ring.state.busy":"認識中","web.ring.state.failed":"Pebble に渡せませんでした","web.ring.state.heard":"Pebble への受け渡し待ち","web.ring.state.new":"認識待ち","web.ring.state.sent":"Pebble に渡しました","web.ring.unavailable":"このハブはまだブラウザーにリングのメモを表示しません。ハブを更新するか、デスクトップアプリの設定 › リングを開いてください。","web.settings.providers":"AI プロバイダー","web.settings.providers.browser":"Backplane のデスクトップまたはモバイルアプリの設定 → アカウントからプロバイダーを接続してください。"}};function Si(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=Nr(),yn=new Set,wn=new Map;for(let[e,t]of Object.entries(jt.en||{}))if(typeof t==="string"&&!wn.has(t))wn.set(t,e);function Nr(){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 Li(){if(typeof document<"u"&&document.documentElement)document.documentElement.lang=ft}Li();function en(e){return yn.add(e),()=>{yn.delete(e)}}function vt(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,Li(),i)for(let s of yn)s(ft);return i}function Ai(){return ft}function m(e,t,n){let s=(jt[ft]||jt.en||{})[e]??jt.en?.[e]??t??e;return Si(s,n)}function pe(e){if(!e)return"";let t=wn.get(e);if(!t)return e;return m(t,e)}function X(e,t="",n=""){let i=document.createElement(e);if(t)i.className=t;if(n)i.textContent=n;return i}function We(e,t="",n){let i=X("button",t,e);if(i.type="button",n)i.addEventListener("click",n);return i}function Mr(e){let t=e.replace(/[\\/]+$/,"");if(!t)return e||"/";let n=t.split(/[\\/]/);return n[n.length-1]||t}function Tr(e,t){let n=e.includes("\\")&&!e.includes("/")?"\\":"/";return e.endsWith(n)?e+t:e+n+t}class En{hub;actionLabel;action;root;pathInput;upBtn;listEl;errEl;actBtn;path="";parent=null;gen=0;busy=!1;constructor(e,t,n,i=[]){this.hub=e;this.actionLabel=t;this.action=n;this.root=X("div","bp-fb"),this.root.setAttribute("data-testid","folder-browser");let s=X("div","bp-fb-head");this.upBtn=We("↑","bp-btn-ghost bp-fb-up",()=>{if(this.parent)this.go(this.parent)}),this.upBtn.title=m("web.clone.up","Up"),this.upBtn.setAttribute("aria-label",m("web.clone.up","Up")),this.pathInput=X("input","bp-input bp-fb-path"),this.pathInput.spellcheck=!1,this.pathInput.setAttribute("data-testid","folder-path"),this.pathInput.addEventListener("keydown",(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=X("div","bp-fb-list"),this.errEl=X("div","bp-ap-err bp-hidden");let r=X("div","bp-ap-foot");this.actBtn=We("","primary",()=>{this.run()}),this.actBtn.setAttribute("data-testid","folder-act"),r.append(...i,this.actBtn),this.root.append(s,this.listEl,this.errEl,r)}currentPath(){return this.path}async go(e){let t=++this.gen;this.setError(""),this.listEl.replaceChildren(X("div","bp-fb-empty",m("web.clone.loading","Loading…")));try{let n=await this.hub.rpc("dirs.list",{path:e});if(t!==this.gen)return;this.path=n.path,this.parent=n.parent??null,this.render(n.dirs??[])}catch(n){if(t!==this.gen)return;this.setError(pe(n instanceof Error?n.message:String(n))),this.render(null)}}refreshLocale(){this.upBtn.title=m("web.clone.up","Up"),this.updateAct()}render(e){if(this.pathInput.value=this.path,this.upBtn.disabled=!this.parent,this.updateAct(),e===null){this.listEl.replaceChildren();return}if(e.length===0){this.listEl.replaceChildren(X("div","bp-fb-empty",m("web.clone.no.folders","No folders here")));return}let t=document.createDocumentFragment();for(let n of e){let i=We("","bp-fb-row",()=>{this.go(Tr(this.path,n))});i.append(X("span","bp-fb-icon","▸"),X("span","bp-fb-name",n)),t.appendChild(i)}this.listEl.replaceChildren(t),this.listEl.scrollTop=0}updateAct(){this.actBtn.textContent=this.path?this.actionLabel(Mr(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 kn{container;host;backdrop=null;bodyEl=null;tabsEl=null;mode="folder";repoText="";repoValue="";firstText="";wantThread=!0;userParent="";nameText="";nameTouched=!1;dest=null;destGen=0;destPending=!1;destTimer=null;repos=null;reposGen=0;reposTimer=null;showSuggest=!1;suggestIdx=-1;startErr="";starting=!1;picking=!1;jobId="";job=null;specs=new Map;signin=null;copied=!1;repoInput=null;suggestEl=null;destEl=null;signinEl=null;cloneBtn=null;jobEl=null;constructor(e,t){this.container=e;this.host=t}isOpen(){return this.backdrop!==null}open(e={}){let t=this.host.hub.hasFeature("clone"),n=!e.repo&&Boolean(this.jobId)&&(!this.job||this.job.state==="running"||this.job.state==="done");if(!this.backdrop)this.build();if(!n)this.jobId="",this.job=null,this.resetForm();if(e.repo!==void 0||e.text!==void 0)this.repoText=(e.repo??"").trim(),this.repoValue="",this.firstText=(e.text??"").trim();if(this.mode=t&&(e.mode==="clone"||n)?"clone":"folder",this.render(),n){if(this.job)this.maybeGo(this.job);this.reconcile()}else if(this.mode==="clone"&&this.repoText)this.askDest()}reconcile(){let e=this.jobId;if(!e)return;this.host.hub.rpc("clone.status",{id:e}).then((t)=>this.apply(t)).catch(()=>{})}close(){if(this.reposTimer!==null)window.clearTimeout(this.reposTimer);if(this.destTimer!==null)window.clearTimeout(this.destTimer);this.reposTimer=null,this.destTimer=null,this.backdrop?.remove(),this.backdrop=null,this.bodyEl=null,this.tabsEl=null}escape(){if(this.picking){this.picking=!1,this.render();return}if(this.showSuggest){this.showSuggest=!1,this.renderSuggest();return}this.close()}refreshLocale(){if(this.backdrop)this.render()}handleFrame(e){if(e.k==="clone"){let t=e.clone;if(t)this.apply(t)}else if(e.k==="clone.repos"){if(this.isOpen()&&this.mode==="clone"&&!this.jobId)this.askRepos(0)}else if(e.k==="clone.signin"){if(!this.signin)return;let t=this.signin.state;if(this.signin=e.signin??null,this.signin?.state==="cancelled")this.signin=null;if(t!=="done"&&this.signin?.state==="done")this.askRepos(0);this.renderSignin()}}build(){let e=X("div","bp-modal-backdrop");e.setAttribute("data-testid","add-project");let t=X("div","bp-modal bp-ap"),n=X("div","bp-modal-head"),i=X("h2","",m("sidebar.add.project","Add project")),s=We("×","icon",()=>this.close());s.title=m("common.close","Close"),s.setAttribute("aria-label",m("common.close","Close")),n.append(i,s),this.tabsEl=X("div","bp-ap-tabs"),this.bodyEl=X("div","bp-modal-body bp-ap-body"),t.append(n,this.tabsEl,this.bodyEl),e.appendChild(t),e.addEventListener("mousedown",(r)=>{if(r.target===e)this.close()}),this.container.appendChild(e),this.backdrop=e}resetForm(){this.repoText="",this.repoValue="",this.firstText="",this.wantThread=!0,this.userParent="",this.nameText="",this.nameTouched=!1,this.dest=null,this.destPending=!1,this.repos=null,this.showSuggest=!1,this.suggestIdx=-1,this.startErr="",this.starting=!1,this.picking=!1,this.signin=null,this.copied=!1}render(){if(!this.bodyEl||!this.tabsEl||!this.backdrop)return;let e=this.backdrop.querySelector(".bp-modal-head h2");if(e)e.textContent=m("sidebar.add.project","Add project");if(this.renderTabs(),this.repoInput=null,this.suggestEl=null,this.destEl=null,this.signinEl=null,this.cloneBtn=null,this.jobEl=null,this.mode==="folder")this.renderFolder();else if(this.jobId&&this.job)this.renderJobView();else if(this.picking)this.renderPickParent();else this.renderCloneForm()}renderTabs(){if(!this.tabsEl)return;if(!this.host.hub.hasFeature("clone")){this.tabsEl.classList.add("bp-hidden");return}this.tabsEl.classList.remove("bp-hidden");let e=(t,n)=>{let i=We(n,"bp-ap-tab"+(this.mode===t?" on":""),()=>{if(this.mode===t)return;if(this.mode=t,this.render(),t==="clone"&&!this.jobId&&this.repos===null)this.askRepos(0)});return i.setAttribute("data-testid",`ap-tab-${t}`),i.setAttribute("aria-pressed",String(this.mode===t)),i};this.tabsEl.replaceChildren(e("folder",m("gpui.e.open.folder","Open folder")),e("clone",m("web.clone.tab","Clone from git")))}renderFolder(){let e=new En(this.host.hub,(t)=>m("web.clone.add.dir","Add {dir}",{dir:t}),async(t)=>{let n=await this.host.hub.rpc("project.add",{path:t},30000);if(this.close(),n.project)this.host.onProjectAdded(n.project)});this.bodyEl.replaceChildren(e.root),e.go("")}renderCloneForm(){let e=this.bodyEl,t=X("div","bp-ap-form"),n=X("div","bp-ap-repo"),i=X("input","bp-input");i.type="text",i.spellcheck=!1,i.autocomplete="off",i.placeholder=m("web.clone.repo.placeholder","https or ssh URL, or owner/repo"),i.setAttribute("aria-label",m("web.clone.repo.placeholder","https or ssh URL, or owner/repo")),i.setAttribute("data-testid","clone-repo"),i.value=this.repoText,i.addEventListener("input",()=>{if(this.repoText=i.value,this.repoValue="",this.showSuggest=!0,this.suggestIdx=-1,this.startErr="",!this.nameTouched)this.nameText="";this.askRepos(200),this.askDest(250)}),i.addEventListener("focus",()=>{if(this.showSuggest=!0,this.repos===null)this.askRepos(0);else this.renderSuggest()}),i.addEventListener("blur",()=>{window.setTimeout(()=>{if(document.activeElement!==i)this.showSuggest=!1,this.renderSuggest()},120)}),i.addEventListener("keydown",(p)=>this.repoKey(p)),this.repoInput=i,this.suggestEl=X("div","bp-ap-suggest bp-hidden"),this.suggestEl.setAttribute("data-testid","clone-suggest"),n.append(i,this.suggestEl),this.signinEl=X("div","bp-ap-signin bp-hidden"),this.signinEl.setAttribute("data-testid","clone-signin"),this.destEl=X("div","bp-ap-dest"),this.destEl.setAttribute("data-testid","clone-dest");let s=X("label","bp-ap-check"),r=X("input");r.type="checkbox",r.checked=this.wantThread,r.setAttribute("data-testid","clone-thread"),r.addEventListener("change",()=>{this.wantThread=r.checked}),s.append(r,X("span","",m("web.clone.start.thread","Start a thread")));let a=[n,this.signinEl,this.destEl,s];if(this.firstText)a.push(X("div","bp-ap-first bp-dim",m("web.clone.first","First message: {text}",{text:this.firstText})));let o=X("div","bp-ap-err"+(this.startErr?"":" bp-hidden"),this.startErr);o.setAttribute("data-testid","clone-start-error");let c=X("div","bp-ap-foot");this.cloneBtn=We(m("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=We("","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=X("div","bp-ap-sug-top");if(o.append(X("span","bp-ap-sug-name",s.name)),s.private)o.append(X("span","bp-ap-tag",m("web.clone.private","private")));if(a.append(o),s.description)a.append(X("div","bp-ap-sug-desc",s.description));i.push(a)}),n.length===0&&t){if(t.loading)i.push(X("div","bp-ap-sug-note",m("web.clone.loading","Loading…")));else if(t.hint){let s=X("div","bp-ap-sug-note");if(s.append(X("span","",pe(t.hint))),t.state==="signedout"){let r=We(m("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=X("div","bp-ap-where"),o=X("span","bp-ap-dest-path",t.destShown||t.dest||t.defaultParentShown||"");o.setAttribute("data-testid","clone-dest-shown");let c=We(m("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 p=X("label","bp-ap-name");p.append(X("span","bp-ap-lbl",m("web.clone.folder.name","Folder name")));let l=X("input","bp-input");if(l.type="text",l.spellcheck=!1,l.value=this.nameText,l.setAttribute("data-testid","clone-name"),l.addEventListener("input",()=>{this.nameText=l.value,this.nameTouched=l.value.trim()!=="",this.startErr="",this.askDest(250)}),l.addEventListener("keydown",(h)=>{if(h.key==="Enter"&&this.canStart())h.preventDefault(),this.startClone()}),p.append(l),n.push(p),!t.ok&&t.error)n.push(this.errLine(pe(t.error)));else if(t.same)n.push(X("div","bp-ap-note bp-dim",m("web.clone.same","Already cloned there: it is added as it is.")))}let i=document.activeElement,s=i&&e.contains(i)&&i.getAttribute("data-testid")==="clone-name",r=s?i.selectionStart:null;if(e.replaceChildren(...n),e.classList.toggle("bp-hidden",n.length===0),s){let a=e.querySelector('[data-testid="clone-name"]');if(a){if(a.focus(),r!==null)a.setSelectionRange(r,r)}}this.updateCloneBtn()}errLine(e){let t=X("div","bp-ap-err",e);return t.setAttribute("data-testid","clone-dest-error"),t}canStart(){return Boolean(this.dest?.ok&&this.dest.repo&&!this.destPending&&!this.starting&&this.repoArg())}updateCloneBtn(){if(this.cloneBtn)this.cloneBtn.disabled=!this.canStart()}renderPickParent(){let e=this.dest?.parent||this.userParent||this.dest?.defaultParent||"",t=We(m("web.clone.back","Back"),"bp-btn-line",()=>{this.picking=!1,this.render()}),n=new En(this.host.hub,(i)=>m("web.clone.use.dir","Use {dir}",{dir:i}),async(i)=>{this.userParent=i,this.picking=!1,this.render(),this.askDest()},[t]);this.bodyEl.replaceChildren(n.root),n.go(e)}async startClone(){if(!this.canStart()||!this.dest)return;this.starting=!0,this.startErr="",this.updateCloneBtn();let e={repo:this.repoArg(),thread:this.wantThread,text:this.firstText},t=vn();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=vn(),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(!xi(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&&Pi(e))this.goTo(e)}renderJobView(){this.jobEl=X("div","bp-ap-job"),this.jobEl.setAttribute("data-testid","clone-job"),this.signinEl=X("div","bp-ap-signin bp-hidden"),this.signinEl.setAttribute("data-testid","clone-signin"),this.bodyEl.replaceChildren(this.jobEl,this.signinEl),this.renderJob(),this.renderSignin()}renderJob(){let e=this.jobEl,t=this.job;if(!e||!t)return;let n=t.destShown||t.dest||"",i=t.repo||"",s=t.state==="done"?m("web.clone.cloned","Cloned {repo} into {dest}",{repo:i,dest:n}):t.state==="cancelled"?m("web.clone.stopped","Stopped cloning {repo}",{repo:i}):m("web.clone.cloning","Cloning {repo} into {dest}",{repo:i,dest:n}),r=[X("div","bp-ap-job-title",s)];if(t.state==="running"){let a=X("div","bp-ap-phase",pe(t.phase||""));a.setAttribute("data-testid","clone-phase");let o=X("div","bp-ap-bar"+(typeof t.pct==="number"?"":" indeterminate")),c=X("div","bp-ap-bar-fill");if(typeof t.pct==="number")c.style.width=`${Math.max(0,Math.min(100,t.pct))}%`;if(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(X("div","bp-ap-detail bp-dim",t.detail));let p=X("div","bp-ap-foot"),l=We(m("common.cancel","Cancel"),"bp-btn-line",()=>{this.host.hub.rpc("clone.cancel",{id:t.id}).then((h)=>this.apply(h)).catch(()=>{})});l.setAttribute("data-testid","clone-cancel"),p.append(l),r.push(p)}else if(t.state==="failed"||t.state==="cancelled"){if(t.state==="failed"&&t.error){let p=X("div","bp-ap-err",pe(t.error));p.setAttribute("data-testid","clone-error"),r.push(p)}let a=X("div","bp-ap-foot"),o=We(m("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 p=We(m("web.clone.signin","Sign in to GitHub"),"bp-btn-line",()=>{this.startSignin()});p.setAttribute("data-testid","clone-signin-btn"),a.append(p)}let c=We(m("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=X("ul","bp-ap-notes");l.setAttribute("data-testid","clone-notes");for(let h of a)l.appendChild(X("li","",pe(h)));r.push(l)}let o=X("div","bp-ap-foot"),c=t.thread?m("web.clone.open.thread","Open the thread"):m("web.clone.open.project","Open the project"),p=We(c,"primary",()=>this.goTo(t));p.setAttribute("data-testid","clone-open"),o.append(p),r.push(o)}e.replaceChildren(...r)}showJobError(e){if(!this.jobEl)return;this.jobEl.querySelector(".bp-ap-job-err")?.remove();let t=X("div","bp-ap-err bp-ap-job-err",e);this.jobEl.appendChild(t)}goTo(e){this.jobId="",this.job=null,this.close(),this.host.onCloneDone(e)}async startSignin(){this.signin={state:"starting"},this.copied=!1,this.renderSignin();try{let e=await this.host.hub.rpc("clone.signin",{restart:!0},30000);if(!this.signin||this.signin.state==="starting")this.signin=e}catch(e){this.signin={state:"failed",error:e instanceof Error?e.message:String(e)}}if(this.signin?.state==="done")this.askRepos(0);this.renderSignin()}renderSignin(){let e=this.signinEl;if(!e)return;let t=this.signin,n=[];if(t&&t.state){if(t.state==="starting"||t.state==="waiting"&&!t.code)n.push(X("div","bp-dim",m("web.clone.signin.wait","Starting GitHub sign-in…")));else if(t.state==="waiting"){n.push(X("div","",m("web.clone.signin.enter","Enter this code on GitHub:")));let i=X("div","bp-ap-code-row"),s=X("span","bp-ap-code",t.code||"");s.setAttribute("data-testid","clone-signin-code");let r=We(this.copied?m("web.clone.copied","Copied"):m("common.copy","Copy"),"bp-btn-line",()=>{navigator.clipboard?.writeText(t.code||"").then(()=>{this.copied=!0,this.renderSignin()}).catch(()=>{})});if(i.append(s,r),n.push(i),t.url){let a=X("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(X("div","bp-ok",m("web.clone.signin.done","Signed in to GitHub")));else if(t.state==="failed")n.push(X("div","bp-ap-err",pe(t.error||"")))}e.replaceChildren(...n),e.classList.toggle("bp-hidden",n.length===0)}}function Br(e){try{let t=new URL(e,window.location.origin);if(t.protocol==="https:"||t.protocol==="http:")return t.href}catch{}return null}function Ht(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=Br(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(()=>{f.textContent="✓",window.setTimeout(()=>{f.textContent=b},1200)}).catch(()=>{})}),d.append(m,f);let g=document.createElement("pre"),y=document.createElement("code");y.textContent=l,g.appendChild(y),u.append(d,g),t.appendChild(u);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",Bt(c,r[2]),t.appendChild(c),i++;continue}if(s.startsWith("> ")){let c=document.createElement("blockquote");c.className="bp-md-quote";let p=[];while(i "))p.push(n[i].slice(2)),i++;Bt(c,p.join(` -`)),t.appendChild(c);continue}if(/^\s*[-*]\s+/.test(s)){let c=document.createElement("ul");c.className="bp-md-list";while(i ")&&!/^\s*[-*]\s+/.test(n[i])&&!/^\s*\d+\.\s+/.test(n[i]))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"));Bt(o,a[c])}t.appendChild(o)}return t}var rr=new Set(["(","[",'"',"'","`"]);function ar(e){return/[\p{L}\p{N}\-_\/+\[]/u.test(e)}function or(e){return/[\p{L}\p{N}\-_\/]/u.test(e)}function lr(e){return/[\p{L}\p{N}]/u.test(e)}function pi(e,t){if(!e)return[];let n=(t??[]).filter((r)=>r.kind==="model"&&r.word&&r.label);if(n.length===0)return[{kind:"text",text:e}];let i=[],s=0;while(sa)r=l,a=u,o=c;break}p=l+1}}if(o===null)break;if(r>s)i.push({kind:"text",text:e.slice(s,r)});i.push({kind:"model",word:o.word,label:o.label}),s=a}if(s3600000)return"";let t=Math.max(1,Math.round(e/1000));if(t<60)return`${t}s`;let n=Math.floor(t/60),i=t%60;return i>0?`${n}m ${i}s`:`${n}m`}function pr(e,t){let n=document.createDocumentFragment(),i=pi(e,t),s=h("native.thread.model","Model").toLowerCase();for(let r of i){if(r.kind==="text"){n.appendChild(document.createTextNode(r.text));continue}let a=document.createElement("span");a.className="bp-ref-chip bp-ref-model",a.title=r.word,a.setAttribute("data-ref-word",r.word);let o=document.createElement("span");o.className="bp-ref-sigil",o.textContent="&";let c=document.createElement("span");c.className="bp-ref-label",c.textContent=r.label;let p=document.createElement("span");p.className="bp-ref-kind",p.textContent=s,a.append(o,c,p),n.appendChild(a)}return n}function ur(e){e.addEventListener("copy",(t)=>{let n=typeof window<"u"?window.getSelection():null;if(!n||n.rangeCount===0||n.isCollapsed)return;let i=n.getRangeAt(0);if(!e.contains(i.commonAncestorContainer))return;let s=i.commonAncestorContainer,o=(s.nodeType===Node.ELEMENT_NODE?s:s.parentElement)?.closest(".bp-ref-chip[data-ref-word]")?.getAttribute("data-ref-word"),c;if(o)c=o;else{let p=i.cloneContents(),l=p.querySelectorAll(".bp-ref-chip[data-ref-word]");if(l.length===0)return;for(let d of l){let m=d.getAttribute("data-ref-word")||d.textContent||"";d.replaceWith(document.createTextNode(m))}let u=p.querySelectorAll(".bp-entry");for(let d=1;d{if(!this.loadingOlder&&this.hasMore)this.loadingOlder=!0,this.cb.onLoadOlder()}),this.scrollEl.addEventListener("scroll",()=>{if(this.pinnedToBottom=this.isNearBottom(),this.hasMore&&!this.loadingOlder&&this.scrollEl.scrollTop<48)this.loadingOlder=!0,this.cb.onLoadOlder()}),typeof ResizeObserver<"u"){let n=0;new ResizeObserver(()=>{let s=this.scrollEl.clientHeight;if(n>0&&s!==n&&this.pinnedToBottom)this.scrollToBottom();n=s}).observe(this.scrollEl)}this.listEl=document.createElement("div"),this.listEl.className="bp-timeline-list",ur(this.scrollEl),this.scrollEl.append(this.olderBtn,this.listEl),e.append(this.bannerEl,this.scrollEl)}setLoading(e){this.thread=e,this.entries=[],this.hasMore=!1,this.loadingOlder=!1,this.review=null,this.unanswered=null,this.btwNote=null,this.liveNodes.clear(),this.planExpanded.clear(),this.planRevisingId="",this.planReviseDrafts.clear(),this.renderBanners(),this.olderBtn.classList.add("bp-hidden");let t=document.createElement("div");t.className="bp-empty-state",t.textContent=h("web.chat.loading","Loading messages…"),this.listEl.replaceChildren(t)}setError(e,t,n){this.thread=e,this.entries=[],this.hasMore=!1,this.loadingOlder=!1,this.review=null,this.unanswered=null,this.btwNote=null,this.liveNodes.clear(),this.planExpanded.clear(),this.planRevisingId="",this.planReviseDrafts.clear(),this.renderBanners(),this.olderBtn.classList.add("bp-hidden");let i=document.createElement("div");i.className="bp-empty-state";let s=document.createElement("div");s.className="bp-bad",s.textContent=t;let r=document.createElement("button");r.type="button",r.textContent=h("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=h("android.load.earlier","Load earlier"),this.renderBanners(),this.thread&&this.entries.length>0)this.renderEntries(!1);this.scrollEl.scrollTop=e}setThread(e,t,n,i,s){if((this.thread?.id??"")!==(e?.id??""))this.planExpanded.clear(),this.planRevisingId="",this.planReviseDrafts.clear();this.thread=e,this.entries=t.filter((r)=>!bn(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)=>!bn(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(bn(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(It(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||h("web.chat.review.mode","Review mode"),t.appendChild(n),this.review.button){let i=document.createElement("button");i.type="button",i.textContent=this.review.button,i.addEventListener("click",()=>this.cb.onToggleReview(!(this.review?.on??!0))),t.appendChild(i)}e.appendChild(t)}if(this.unanswered&&(this.unanswered.head||this.unanswered.text)){let t=document.createElement("div");t.className="bp-banner bp-unanswered",t.setAttribute("data-testid","unanswered-notice");let n=document.createElement("div");if(n.className="bp-unanswered-body",this.unanswered.head){let i=document.createElement("strong");i.textContent=this.unanswered.head,n.appendChild(i)}if(this.unanswered.text){let i=document.createElement("span");i.textContent=this.unanswered.text,n.appendChild(i)}if(t.appendChild(n),this.unanswered.buttons?.length){let i=document.createElement("div");i.className="bp-banner-actions";for(let s of this.unanswered.buttons){let 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(It(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=h("common.copy","Copy"),a=document.createElement("span");a.textContent=r,s.append(Rt(["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=h("reply.action","Reply"),o.append(Rt(["M9 17l-5-5 5-5","M20 18v-2a4 4 0 0 0-4-4H4"]),c),o.addEventListener("click",()=>this.cb.onReplyEntry(e));let p=!e.live&&!e.id.startsWith("local-")&&!e.id.startsWith("live:"),l=document.createElement("span");l.className="bp-entry-time";let u=cr(e.at);if(t)l.textContent=u,i.append(s,...p?[o]:[],l);else{let d=n&&e.at?dr(gn(e.at)-gn(n)):"",m=u?d?h("web.chat.finished.dur","Finished {time} · {dur}",{time:u,dur:d}):h("web.chat.finished","Finished {time}",{time:u}):"";l.textContent=e.live?h("web.chat.streaming","Streaming…"):m,i.append(l,s,...p?[o]:[])}return i}closePlanRevise(){let e=this.planRevisingId;if(!e)return!1;this.planRevisingId="";let t=this.scrollEl.scrollTop;return this.renderEntries(!1),this.scrollEl.scrollTop=t,this.listEl.querySelector(`[data-testid="ask-${CSS.escape(e)}"] [data-testid="plan-revise"]`)?.focus(),!0}renderEntries(e){let t=null,n=typeof document<"u"?document.activeElement:null;if(n instanceof HTMLTextAreaElement&&n.classList.contains("bp-plan-revise-input")&&this.listEl.contains(n)&&this.planRevisingId)this.planReviseDrafts.set(this.planRevisingId,n.value),t={askId:this.planRevisingId,start:n.selectionStart,end:n.selectionEnd,dir:n.selectionDirection};this.olderBtn.classList.toggle("bp-hidden",!this.hasMore),this.liveNodes.clear();let i=document.createDocumentFragment();if(!this.thread){let r=document.createElement("div");r.className="bp-empty-state",r.textContent=h("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=h("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 u=document.createElement("span");if(u.className="bp-tool-name",u.textContent=r.tool.name,l.appendChild(u),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 u=document.createElement("div");u.className="bp-ask-card",u.setAttribute("data-testid",`ask-${l.id}`);let d=document.createElement("div");if(d.className="bp-ask-q",d.textContent=l.question,u.appendChild(d),l.state==="open"){let m=document.createElement("div");if(m.className="bp-ask-opts",l.options&&l.options.length>0)for(let f of l.options){let b=document.createElement("button");b.type="button",b.textContent=f.label,b.addEventListener("click",()=>this.cb.onAnswerAsk(l.id,f.id)),m.appendChild(b)}else{let f=document.createElement("input");f.type="text",f.className="bp-input",f.placeholder=h("web.chat.answer.placeholder","Type answer…");let b=document.createElement("button");b.type="button",b.className="primary",b.textContent=h("web.chat.answer.btn","Answer"),b.addEventListener("click",()=>{if(f.value.trim())this.cb.onAnswerAsk(l.id,f.value.trim())}),m.append(f,b)}u.appendChild(m)}else{let m=document.createElement("div");m.className="bp-ask-answered",m.textContent=h("web.chat.answered","Answered: {answer}",{answer:l.answered??""}),u.appendChild(m)}a.appendChild(u),i.appendChild(a);continue}let o=Boolean(r.text&&r.text.trim().length>0),c=Boolean(r.images&&r.images.length>0),p=Boolean(r.attachments&&r.attachments.length>0);if(!o&&!c&&!p&&!r.live)continue;if(r.replyTo?.quote){let l=document.createElement("div");l.className="bp-reply-quote",l.textContent=h("gpui.b.in.reply.to","↩ In reply to: {quote}",{quote:r.replyTo.quote});let u=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(u);else this.goTo(u)};l.addEventListener("click",d),l.addEventListener("keydown",(m)=>{if(m.key==="Enter"||m.key===" ")m.preventDefault(),d()}),a.appendChild(l)}if(o||r.live){let l=document.createElement("div");if(l.className="bp-entry-body",r.kind==="user")l.appendChild(pr(r.text||"",r.refs));else l.appendChild(It(r.text||""));if(r.live)this.liveNodes.set(r.id,l);a.appendChild(l)}if(p&&r.attachments){let l=document.createElement("div");l.className="bp-entry-images";for(let u of r.attachments)if(u.previewUrl){let d=document.createElement("img");d.className="bp-reply-img",d.src=u.previewUrl,d.alt=u.name||"attachment",l.appendChild(d)}else if(u.path||u.name){let d=document.createElement("span");d.className="bp-tool-pill",d.textContent=u.name||u.path||"image",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 u of r.images){let d=document.createElement("img");d.className="bp-reply-img",d.alt=u;let m=`${r.id}|${u}`,f=this.imageCache.get(m);if(f)d.src=f;else this.cb.onLoadImage(r.id,u).then((b)=>{if(!b)return;let g=b.url??(b.mime&&b.data?`data:${b.mime};base64,${b.data}`:"");if(!g)return;this.imageCache.set(m,g),d.src=g});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=Rt(["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"?h("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=h("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 u=h("common.copy","Copy"),d=document.createElement("span");d.textContent=u,l.append(Rt(["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=h("web.clone.copied","Copied"),window.setTimeout(()=>{l.classList.remove("copied"),d.textContent=u},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?h("gpui.c.term.collapse","Collapse"):h("gpui.c.term.expand","Expand"),c.addEventListener("click",()=>{if(this.planExpanded.has(e.id))this.planExpanded.delete(e.id);else this.planExpanded.add(e.id);let l=this.scrollEl.scrollTop;this.renderEntries(!1),this.scrollEl.scrollTop=l}),s.appendChild(c),i.appendChild(s);let p=document.createElement("div");if(p.className="bp-plan-body"+(t?" is-expanded":""),p.setAttribute("data-testid","plan-body"),p.appendChild(It(e.question||"")),i.appendChild(p),e.state==="open"){let l=document.createElement("div");l.className="bp-plan-actions";let u=e.options?.find((b)=>b.id==="implement"||b.id.endsWith("|implement")),d=document.createElement("button");if(d.type="button",d.className="primary",d.setAttribute("data-testid","plan-implement"),d.textContent=u?.label&&u.label!=="Implement"?pe(u.label):h("approval.implement","Implement"),d.addEventListener("click",()=>{this.planRevisingId="",this.planReviseDrafts.delete(e.id),this.cb.onAnswerAsk(e.id,u?.id??"implement")}),l.appendChild(d),e.revise!==!1){let b=document.createElement("button");b.type="button",b.className="bp-plan-revise-btn"+(n?" active":""),b.setAttribute("data-testid","plan-revise"),b.append(Rt(["M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7","M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"]),document.createTextNode(h("gpui.ask.plan.revise","Revise"))),b.addEventListener("click",()=>{let g=this.planRevisingId!==e.id;this.planRevisingId=g?e.id:"";let y=this.scrollEl.scrollTop;if(this.renderEntries(!1),this.scrollEl.scrollTop=y,g)this.listEl.querySelector(`[data-testid="ask-${CSS.escape(e.id)}"] .bp-plan-revise-input`)?.focus()}),l.appendChild(b)}let m=e.options?.find((b)=>b.id==="dismiss"||b.id.endsWith("|dismiss")),f=document.createElement("button");if(f.type="button",f.className="bp-plan-dismiss-btn",f.setAttribute("data-testid","plan-dismiss"),f.textContent=m?.label&&m.label!=="Dismiss"?pe(m.label):h("approval.dismiss","Dismiss"),f.addEventListener("click",()=>{this.planRevisingId="",this.planReviseDrafts.delete(e.id),this.cb.onAnswerAsk(e.id,m?.id??"dismiss")}),l.appendChild(f),i.appendChild(l),n){let b=document.createElement("div");b.className="bp-plan-revise",b.setAttribute("data-testid","plan-revise-drawer");let g=document.createElement("textarea");g.rows=2,g.className="bp-input bp-plan-revise-input",g.placeholder=h("gpui.ask.plan.reviseph","What should change in the plan?"),g.value=this.planReviseDrafts.get(e.id)??"";let y=document.createElement("button");y.type="button",y.className="bp-plan-revise-send",y.setAttribute("data-testid","plan-revise-send"),y.textContent=h("gpui.ask.plan.sendrev","Send revision"),y.disabled=g.value.trim().length===0;let w=()=>{let S=g.value.trim();if(!S)return;this.planRevisingId="",this.planReviseDrafts.delete(e.id),this.cb.onAnswerAsk(e.id,`revise:${S}`)},C=()=>{this.closePlanRevise()};b.addEventListener("keydown",(S)=>{if(S.key==="Escape")S.preventDefault(),S.stopPropagation(),C()}),g.addEventListener("input",()=>{this.planReviseDrafts.set(e.id,g.value),y.disabled=g.value.trim().length===0}),g.addEventListener("keydown",(S)=>{if(S.key==="Enter"&&!S.shiftKey)S.preventDefault(),w()}),y.addEventListener("click",w);let A=document.createElement("button");A.type="button",A.className="bp-btn-ghost",A.textContent=h("common.cancel","Cancel"),A.addEventListener("click",C),b.append(g,y,A),i.appendChild(b)}}else{let l=document.createElement("div");l.className="bp-ask-answered",l.textContent=h("web.chat.answered","Answered: {answer}",{answer:e.answered??""}),i.appendChild(l)}return i}}var mr={claude:"Claude Code",codex:"Codex CLI",grok:"Grok CLI",muse:"Muse Code",antigravity:"Google Antigravity",opencode:"OpenCode",pi:"Pi",omp:"Oh My Pi"};var mi=/[\x00-\x1f\x7f]/,hr=/\s/;function vt(e){return e.trim().replace(/^@+/,"").toLowerCase()}function dt(e,t){if(mi.test(e)||mi.test(t))return"";let n=vt(e),i=t.trim();if(!n||!i||n.includes("/")||hr.test(n))return"";if(n.length+1+i.length>200)return"";return`${n}/${i}`}function hi(e){let t=e.indexOf("/");if(t<=0)return null;let n=e.slice(0,t),i=e.slice(t+1);if(!dt(n,i))return null;return{provider:vt(n),model:i.trim()}}function it(e){if(!Array.isArray(e))return[];let t=[],n=new Set;for(let i of e){if(typeof i!=="string")continue;let s=hi(i);if(!s)continue;let r=`${s.provider}/${s.model}`;if(!n.has(r)){if(n.add(r),t.push(r),t.length>=64)break}}return t}function vn(e,t,n,i){let s=dt(t,n),r=it(e);if(!s)return{keys:r,starred:!1};let a=r.indexOf(s),o=i!==void 0?i:a<0;if(o&&a<0){if(r.length>=64)return{keys:r,starred:!1};r.push(s)}else if(!o&&a>=0)r.splice(a,1);return{keys:r,starred:o}}function Qe(e){return e&&typeof e==="object"&&!Array.isArray(e)?e:null}function ft(e){return Array.isArray(e)?e:[]}function Se(e){return typeof e==="string"?e:""}function br(e){return mr[e]??e}function bi(e,t,n,i){let s=new Map;for(let a of e)s.set(a.provider,a);let r=[];for(let a of it(t)){let o=hi(a);if(!o)continue;let c=s.get(o.provider),p=Boolean(c&&c.models.some((m)=>m.value!=="")),l=c?.models.find((m)=>m.value===o.model),u=l?l.ok&&(c?.ok??!0):c?.ok??!0,d=l?.why||c?.why||"";if(u&&p&&!l)u=!1,d="not available on this machine";r.push({key:a,provider:o.provider,model:o.model,label:l?.label||o.model,note:l?.note||"",on:o.provider===n&&o.model===i,ok:u,why:d})}return r}function gi(e,t=[]){let n=Qe(e),i=Qe(n?.picker)??n??{},s=ft(i.sections).map(Qe).filter((L)=>Boolean(L)),r=(L)=>s.find((Y)=>Se(Y.action)===L),a=r("provider"),o=r("model"),c=r("effort"),p=ft(a?.choices).map(Qe).filter((L)=>Boolean(L)),l=ft(o?.choices).map(Qe).filter((L)=>Boolean(L)),u=ft(c?.choices).map(Qe).filter((L)=>Boolean(L)),d=Se(i.chip),m=Se(p.find((L)=>L.on===!0)?.value)||d.split("/")[0]?.trim()||"claude",f=vt(m)||"claude",b=Se(l.find((L)=>L.on===!0)?.value),g=Se(u.find((L)=>L.on===!0)?.value),y=u.map((L)=>({value:Se(L.value),label:Se(L.label)||"auto",on:L.on===!0})),w=Qe(i.agents),C=[],A=new Set,S=(L)=>{let Y=vt(L);if(Y&&!A.has(Y))A.add(Y),C.push(Y)};for(let L of p)S(Se(L.value)||Se(L.label));if(w)for(let L of Object.keys(w))S(L);S(f);let T=C.map((L)=>{let Y=p.find((ee)=>vt(Se(ee.value)||Se(ee.label))===L),re=Qe(w?.[L]),se=re?re.ok!==!1:Y?Y.ok!==!1:!0,be=Se(re?.why)||Se(Y?.why),Pe=ft(re?.models).map(Qe).filter((ee)=>Boolean(ee)),Ee;if(Pe.length>0)Ee=Pe.map((ee)=>{let ae=Se(ee.value),R=Se(ee.label)||(ae===""?"default":ae),ue=Se(ee.note);return{value:ae,label:R,note:ue,on:L===f&&ae===b,ok:ee.ok!==!1&&se,why:Se(ee.why)||be}});else if(L===f&&l.length>0)Ee=l.map((ee)=>{let ae=Se(ee.value),R=Se(ee.label);return{value:ae,label:ae===""?"default":ae,note:R&&R!==ae?R:"",on:ee.on===!0,ok:ee.ok!==!1&&se,why:Se(ee.why)||be}});else if(se)Ee=[{value:"",label:"default",note:"",on:L===f&&b==="",ok:!0,why:""}];else Ee=[];if(L===f&&b&&!Ee.some((ee)=>ee.value===b)){let ee=l.find((R)=>Se(R.value)===b),ae=Se(ee?.label);Ee.push({value:b,label:b,note:ae&&ae!==b?ae:"",on:!0,ok:!0,why:""})}return{provider:L,label:br(L),ok:se,why:be,models:Ee}}),I=Array.isArray(i.favoriteKeys),P=ft(i.favorites).map(Qe).filter((L)=>Boolean(L)),j=I?it(i.favoriteKeys):P.length>0?it(P.map((L)=>Se(L.key)||dt(Se(L.provider),Se(L.model)))):it(t),G=P.length>0?P.map((L)=>{let Y=vt(Se(L.provider)),re=Se(L.model).trim(),se=dt(Y,re);if(!se)return null;return{key:se,provider:Y,model:re,label:Se(L.label)||re,note:Se(L.note),on:L.on===!0||Y===f&&re===b,ok:L.ok!==!1,why:Se(L.why)}}).filter((L)=>Boolean(L)):bi(T,j,f,b);return{chip:d,provider:f,model:b,effort:g,efforts:y,providers:T,favoriteKeys:j,favorites:G}}function jt(e,t){let n=it(t);return{...e,favoriteKeys:n,favorites:bi(e.providers,n,e.provider,e.model)}}function fi(e,t){let n=t.trim().toLowerCase().split(/\s+/).filter(Boolean),i=(o)=>{if(n.length===0)return!0;let c=o.toLowerCase();return n.every((p)=>c.includes(p))},s=new Set(e.favoriteKeys),r=e.favorites.filter((o)=>i(`${o.provider} ${o.model} ${o.label} ${o.note}`)),a=[];for(let o of e.providers){let c=o.models.filter((p)=>i(`${o.provider} ${o.label} ${p.value} ${p.label} ${p.note}`)).map((p)=>{let l=p.value?dt(o.provider,p.value):"";return{...p,provider:o.provider,starrable:p.value!=="",starred:Boolean(l&&s.has(l))}});if(c.length>0||n.length===0&&!o.ok&&o.why)a.push({provider:o.provider,label:o.label,ok:o.ok,why:o.why,models:c})}return{favorites:r,groups:a,efforts:e.efforts}}var vi={claude:{viewBox:"0 0 24 24",d:"m4.7144 15.9555 4.7174-2.6471.079-.2307-.079-.1275h-.2307l-.7893-.0486-2.6956-.0729-2.3375-.0971-2.2646-.1214-.5707-.1215-.5343-.7042.0546-.3522.4797-.3218.686.0608 1.5179.1032 2.2767.1578 1.6514.0972 2.4468.255h.3886l.0546-.1579-.1336-.0971-.1032-.0972L6.973 9.8356l-2.55-1.6879-1.3356-.9714-.7225-.4918-.3643-.4614-.1578-1.0078.6557-.7225.8803.0607.2246.0607.8925.686 1.9064 1.4754 2.4893 1.8336.3643.3035.1457-.1032.0182-.0728-.164-.2733-1.3539-2.4467-1.445-2.4893-.6435-1.032-.17-.6194c-.0607-.255-.1032-.4674-.1032-.7285L6.287.1335 6.6997 0l.9957.1336.419.3642.6192 1.4147 1.0018 2.2282 1.5543 3.0296.4553.8985.2429.8318.091.255h.1579v-.1457l.1275-1.706.2368-2.0947.2307-2.6957.0789-.7589.3764-.9107.7468-.4918.5828.2793.4797.686-.0668.4433-.2853 1.8517-.5586 2.9021-.3643 1.9429h.2125l.2429-.2429.9835-1.3053 1.6514-2.0643.7286-.8196.85-.9046.5464-.4311h1.0321l.759 1.1293-.34 1.1657-1.0625 1.3478-.8804 1.1414-1.2628 1.7-.7893 1.36.0729.1093.1882-.0183 2.8535-.607 1.5421-.2794 1.8396-.3157.8318.3886.091.3946-.3278.8075-1.967.4857-2.3072.4614-3.4364.8136-.0425.0304.0486.0607 1.5482.1457.6618.0364h1.621l3.0175.2247.7892.522.4736.6376-.079.4857-1.2142.6193-1.6393-.3886-3.825-.9107-1.3113-.3279h-.1822v.1093l1.0929 1.0686 2.0035 1.8092 2.5075 2.3314.1275.5768-.3218.4554-.34-.0486-2.2039-1.6575-.85-.7468-1.9246-1.621h-.1275v.17l.4432.6496 2.3436 3.5214.1214 1.0807-.17.3521-.6071.2125-.6679-.1214-1.3721-1.9246L14.38 17.959l-1.1414-1.9428-.1397.079-.674 7.2552-.3156.3703-.7286.2793-.6071-.4614-.3218-.7468.3218-1.4753.3886-1.9246.3157-1.53.2853-1.9004.17-.6314-.0121-.0425-.1397.0182-1.4328 1.9672-2.1796 2.9446-1.7243 1.8456-.4128.164-.7164-.3704.0667-.6618.4008-.5889 2.386-3.0357 1.4389-1.882.929-1.0868-.0062-.1579h-.0546l-6.3385 4.1164-1.1293.1457-.4857-.4554.0608-.7467.2307-.2429 1.9064-1.3114Z"},codex:{viewBox:"0 0 256 260",d:"M239.184 106.203a64.716 64.716 0 0 0-5.576-53.103C219.452 28.459 191 15.784 163.213 21.74A65.586 65.586 0 0 0 52.096 45.22a64.716 64.716 0 0 0-43.23 31.36c-14.31 24.602-11.061 55.634 8.033 76.74a64.665 64.665 0 0 0 5.525 53.102c14.174 24.65 42.644 37.324 70.446 31.36a64.72 64.72 0 0 0 48.754 21.744c28.481.025 53.714-18.361 62.414-45.481a64.767 64.767 0 0 0 43.229-31.36c14.137-24.558 10.875-55.423-8.083-76.483Zm-97.56 136.338a48.397 48.397 0 0 1-31.105-11.255l1.535-.87l51.67-29.825a8.595 8.595 0 0 0 4.247-7.367v-72.85l21.845 12.636c.218.111.37.32.409.563v60.367c-.056 26.818-21.783 48.545-48.601 48.601Zm-104.466-44.61a48.345 48.345 0 0 1-5.781-32.589l1.534.921l51.722 29.826a8.339 8.339 0 0 0 8.441 0l63.181-36.425v25.221a.87.87 0 0 1-.358.665l-52.335 30.184c-23.257 13.398-52.97 5.431-66.404-17.803ZM23.549 85.38a48.499 48.499 0 0 1 25.58-21.333v61.39a8.288 8.288 0 0 0 4.195 7.316l62.874 36.272l-21.845 12.636a.819.819 0 0 1-.767 0L41.353 151.53c-23.211-13.454-31.171-43.144-17.804-66.405v.256Zm179.466 41.695l-63.08-36.63L161.73 77.86a.819.819 0 0 1 .768 0l52.233 30.184a48.6 48.6 0 0 1-7.316 87.635v-61.391a8.544 8.544 0 0 0-4.4-7.213Zm21.742-32.69l-1.535-.922l-51.619-30.081a8.39 8.39 0 0 0-8.492 0L99.98 99.808V74.587a.716.716 0 0 1 .307-.665l52.233-30.133a48.652 48.652 0 0 1 72.236 50.391v.205ZM88.061 139.097l-21.845-12.585a.87.87 0 0 1-.41-.614V65.685a48.652 48.652 0 0 1 79.757-37.346l-1.535.87l-51.67 29.825a8.595 8.595 0 0 0-4.246 7.367l-.051 72.697Zm11.868-25.58L128.067 97.3l28.188 16.218v32.434l-28.086 16.218l-28.188-16.218l-.052-32.434Z"},grok:{viewBox:"0 0 24 24",d:"M9.497 15.122 L16.811 9.491 C17.169 9.215 17.682 9.323 17.852 9.751 C18.752 12.013 18.35 14.73 16.561 16.596 C14.772 18.462 12.283 18.871 10.007 17.939 L7.522 19.139 C11.087 21.68 15.416 21.052 18.121 18.229 C20.267 15.991 20.931 12.941 20.31 10.19 L20.315 10.196 C19.414 6.155 20.537 4.54 22.837 1.237 C22.891 1.159 22.946 1.08 23 1 L19.974 4.156 L19.974 4.146 L9.495 15.124 M7.987 16.49 C5.429 13.941 5.87 9.996 8.053 7.721 C9.667 6.037 12.313 5.35 14.622 6.361 L17.102 5.166 C16.655 4.829 16.082 4.467 15.425 4.213 C12.455 2.938 8.9 3.573 6.485 6.088 C4.163 8.51 3.433 12.234 4.687 15.411 C5.624 17.786 4.088 19.466 2.541 21.162 C1.993 21.763 1.443 22.364 1 23 L7.985 16.492"},muse:{viewBox:"0 0 24 24",d:"M10.73.032c-1.333 0-2.032 1.016-2.032 2.285 0 2.223 2.127 4.953 4.318 4.953 1.301 0 2-.953 2-2.254 0-2.254-2.095-4.984-4.286-4.984m8.413 2.984c-1.968 0-3.397 2.73-3.397 4.825 0 1.556.794 3.016 2.254 3.016 2 0 3.365-2.762 3.365-4.794 0-1.523-.762-3.047-2.222-3.047M4.857 4.159c-1.968 0-3.778 1.016-3.778 2.54 0 1.65 2.16 2.793 4.254 2.793 1.873 0 3.778-.92 3.778-2.508 0-1.682-2.159-2.825-4.254-2.825m-.222 6.476C2.413 10.635 0 13.175 0 15.397c0 1.301.825 2.159 2.095 2.159 2.19 0 4.603-2.508 4.603-4.794 0-1.27-.761-2.127-2.063-2.127m16.667.698c-2.223 0-5.016 1.62-5.016 3.651 0 1.238 1.047 2.19 2.698 2.19 2.159 0 5.016-1.587 5.016-3.682 0-1.302-1.08-2.159-2.698-2.159M7.619 16c-1.524 0-2.38 1.746-2.38 3.429 0 2.063 1.269 4.54 3.047 4.54 1.524 0 2.38-1.81 2.38-3.461C10.667 18.57 9.46 16 7.62 16m6.571 1.016c-1.333 0-2.476.667-2.476 2.032 0 2.095 2.667 4.063 4.92 4.063 1.366 0 2.54-.73 2.54-2.063 0-2.032-2.698-4.032-4.984-4.032"},antigravity:{viewBox:"0 0 24 24",d:"M20.197 20.618 C21.318 21.459 23 20.898 21.459 19.357 C16.834 14.873 17.815 2.541 12.07 2.541 C6.325 2.541 7.306 14.873 2.682 19.357 C1 21.038 2.822 21.459 3.943 20.618 C8.287 17.675 8.006 12.49 12.07 12.49 C16.134 12.49 15.853 17.675 20.197 20.618 Z"},opencode:{viewBox:"0 0 24 24",d:"M22 24H2V0h20zM17 4.8H7v14.4h10z"},pi:{viewBox:"0 0 24 24",d:"M0 0v24h6v-6h6v-6H6V6h6v6h6V0Zm18 12v12h6V12Z"},omp:{viewBox:"0 0 24 24",d:"M1.44 3.86 L22.56 3.86 C23 3.86 23 3.86 23 4.3 L23 6.06 C23 6.5 23 6.5 22.56 6.5 L1.44 6.5 C1 6.5 1 6.5 1 6.06 L1 4.3 C1 3.86 1 3.86 1.44 3.86 Z M4.74 6.5 L6.5 6.5 C6.94 6.5 6.94 6.5 6.94 6.94 L6.94 19.7 C6.94 20.14 6.94 20.14 6.5 20.14 L4.74 20.14 C4.3 20.14 4.3 20.14 4.3 19.7 L4.3 6.94 C4.3 6.5 4.3 6.5 4.74 6.5 Z M15.74 6.5 L17.5 6.5 C17.94 6.5 17.94 6.5 17.94 6.94 L17.94 13.32 C17.94 13.76 17.94 13.76 17.5 13.76 L15.74 13.76 C15.3 13.76 15.3 13.76 15.3 13.32 L15.3 6.94 C15.3 6.5 15.3 6.5 15.74 6.5 Z M15.08 14.64 L18.16 14.64 C18.82 14.64 18.82 14.64 18.82 15.3 L18.82 17.5 C18.82 18.16 18.82 18.16 18.16 18.16 L15.08 18.16 C14.42 18.16 14.42 18.16 14.42 17.5 L14.42 15.3 C14.42 14.64 14.42 14.64 15.08 14.64 Z"}};var yt="http://www.w3.org/2000/svg",yi=4,wi=new Set(["image/png","image/jpeg","image/webp","image/gif"]);function Xt(e){let t=document.createElementNS(yt,"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(yt,"path");i.setAttribute("d",n),t.appendChild(i)}return t}function yn(){return Xt(["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 Ei(){return Xt(["M6 4l14 8-14 8z"])}function ki(e){let t=document.createElementNS(yt,"svg");t.setAttribute("viewBox","0 0 24 24"),t.setAttribute("width","13"),t.setAttribute("height","13"),t.setAttribute("fill",e?"currentColor":"none"),t.setAttribute("stroke","currentColor"),t.setAttribute("stroke-width","1.8"),t.setAttribute("stroke-linejoin","round"),t.setAttribute("aria-hidden","true");let n=document.createElementNS(yt,"path");return n.setAttribute("d","M12 2.5l2.9 6 6.6.9-4.8 4.6 1.2 6.5L12 17.4l-5.9 3.1 1.2-6.5-4.8-4.6 6.6-.9z"),t.appendChild(n),t}function Ci(e){let t=(e||"").toLowerCase();if(t.includes("claude")||t.includes("anthropic"))return{mark:"claude",glyph:"A",color:"#d97757",title:"Claude"};if(t.includes("codex")||t.includes("openai"))return{mark:"codex",glyph:"O",color:"#10a37f",title:"Codex"};if(t.includes("gemini")||t.includes("antigravity")||t==="agy")return{mark:"antigravity",glyph:"G",color:"#4285f4",title:"Antigravity"};if(t.includes("grok"))return{mark:"grok",glyph:"X",color:"#6b7280",title:"Grok"};if(t.includes("muse"))return{mark:"muse",glyph:"M",color:"#8b5cf6",title:"Muse"};if(t.includes("opencode"))return{mark:"opencode",glyph:"C",color:"#2563eb",title:"OpenCode"};if(t.includes("omp")||t.includes("oh-my-pi"))return{mark:"omp",glyph:"Ω",color:"#c026d3",title:"Oh My Pi"};if(t==="pi"||t.startsWith("pi/")||t.startsWith("@pi"))return{mark:"pi",glyph:"π",color:"#db2777",title:"Pi"};return{glyph:"●",color:"var(--accent)",title:e||"Model"}}function xi(e){let t=vi[e];if(!t||!t.d)return null;let n=document.createElementNS(yt,"svg");n.setAttribute("viewBox",t.viewBox||"0 0 24 24"),n.setAttribute("width","14"),n.setAttribute("height","14"),n.setAttribute("fill","currentColor"),n.setAttribute("aria-hidden","true");let i=document.createElementNS(yt,"path");return i.setAttribute("d",t.d),n.appendChild(i),n}class wn{popupEl;attachStripEl;planBarEl;fileInput;textarea;memoryEl;memoryFill;memoryText;modelBtn;providerMarkEl;modelTextEl;ctxEl;modelPickerEl;modelSearchInput;modelPickerBodyEl;modelPickerEffortsEl;modelPickerOpen=!1;modelPickerLoading=!1;modelPickerSnap=null;modelPickerQuery="";modelPickerFocusIdx=-1;onDocMouseDown;planChipBtn;planChipIconHost;planChipLbl;attachBtn;voiceBtn;sendBtn;stopBtn;errorEl;replyEl;cb;commands=[];popupMode="none";filteredSlash=[];mentionItems=[];popupIdx=0;enabled=!1;attachments=[];planMode=null;constructor(e,t){this.cb=t;let n=document.createElement("div");n.className="bp-composer",n.setAttribute("data-testid","composer");let i=document.createElement("div");i.className="bp-composer-inner",this.popupEl=document.createElement("div"),this.popupEl.className="bp-composer-popup bp-hidden",this.popupEl.setAttribute("data-testid","slash-menu"),this.errorEl=document.createElement("div"),this.errorEl.className="bp-composer-err bp-hidden",this.replyEl=document.createElement("div"),this.replyEl.className="bp-reply-strip bp-hidden",this.replyEl.setAttribute("data-testid","composer-reply"),this.attachStripEl=document.createElement("div"),this.attachStripEl.className="bp-attach-strip bp-hidden",this.attachStripEl.setAttribute("data-testid","composer-attachments"),this.planBarEl=document.createElement("div"),this.planBarEl.className="bp-plan-bar bp-hidden",this.planBarEl.setAttribute("data-testid","composer-plan-bar"),this.fileInput=document.createElement("input"),this.fileInput.type="file",this.fileInput.accept="image/png,image/jpeg,image/webp,image/gif",this.fileInput.multiple=!0,this.fileInput.className="bp-hidden",this.fileInput.setAttribute("data-testid","composer-file-input"),this.fileInput.addEventListener("change",()=>{if(this.fileInput.files)this.addFiles(Array.from(this.fileInput.files));this.fileInput.value=""}),this.textarea=document.createElement("textarea"),this.textarea.className="bp-composer-input",this.textarea.rows=2,this.textarea.placeholder=h("composer.placeholder","Ask anything: @bot, >thread, %project, #room, $skill, /btw"),this.textarea.setAttribute("data-testid","composer-input");let s=document.createElement("div");s.className="bp-composer-bar";let r=document.createElement("button");r.type="button",r.className="bp-composer-model",r.setAttribute("data-testid","composer-model-chip"),r.setAttribute("aria-haspopup","dialog"),r.setAttribute("aria-expanded","false"),r.title=h("composer.model.tip","Choose the model and effort"),this.modelBtn=r,this.providerMarkEl=document.createElement("span"),this.providerMarkEl.className="bp-provider-mark",this.providerMarkEl.textContent="●",this.modelTextEl=document.createElement("span"),this.modelTextEl.className="bp-model-text",this.modelTextEl.textContent="default",this.ctxEl=document.createElement("span"),this.ctxEl.className="bp-ctx-pct bp-hidden",this.ctxEl.setAttribute("data-testid","composer-ctx");let a=document.createElement("span");a.className="bp-model-caret",a.textContent="▾",r.append(this.providerMarkEl,this.modelTextEl,this.ctxEl,a),r.addEventListener("click",()=>{this.toggleModelPicker()}),this.modelPickerEl=document.createElement("div"),this.modelPickerEl.className="bp-model-picker bp-hidden",this.modelPickerEl.setAttribute("data-testid","model-picker"),this.modelPickerEl.setAttribute("role","dialog");let o=document.createElement("div");o.className="bp-mp-search-wrap",this.modelSearchInput=document.createElement("input"),this.modelSearchInput.type="search",this.modelSearchInput.className="bp-mp-search",this.modelSearchInput.placeholder=h("gpui.search.models","Search models"),this.modelSearchInput.setAttribute("data-testid","model-picker-search"),this.modelSearchInput.addEventListener("input",()=>{this.modelPickerQuery=this.modelSearchInput.value,this.modelPickerFocusIdx=-1,this.renderModelPicker()}),this.modelSearchInput.addEventListener("keydown",(l)=>{if(l.key==="Escape"){l.preventDefault(),l.stopPropagation(),this.closeModelPicker(),this.textarea.focus();return}if(l.key==="ArrowDown"||l.key==="ArrowUp"){let u=this.modelPickerFocusableButtons();if(u.length===0)return;l.preventDefault();let d=l.key==="ArrowDown"?1:-1;this.modelPickerFocusIdx=this.modelPickerFocusIdx<0?d>0?0:u.length-1:(this.modelPickerFocusIdx+d+u.length)%u.length,this.updateModelPickerKbdFocus(u);return}if(l.key==="Enter"){let u=this.modelPickerFocusableButtons(),d=this.modelPickerFocusIdx>=0&&this.modelPickerFocusIdxthis.cb.onCyclePlanMode?.()),this.memoryEl=document.createElement("div"),this.memoryEl.className="bp-composer-memory bp-hidden",this.memoryEl.setAttribute("data-testid","composer-memory");let c=document.createElement("div");c.className="bp-memory-meter",this.memoryFill=document.createElement("div"),this.memoryFill.className="bp-memory-fill",c.appendChild(this.memoryFill),this.memoryText=document.createElement("span"),this.memoryEl.append(c,this.memoryText);let p=document.createElement("div");p.className="bp-composer-btns",this.attachBtn=document.createElement("button"),this.attachBtn.type="button",this.attachBtn.className="icon bp-composer-tool",this.attachBtn.title=h("web.composer.attach","Attach image"),this.attachBtn.setAttribute("aria-label",h("web.composer.attach","Attach image")),this.attachBtn.setAttribute("data-testid","composer-attach"),this.attachBtn.appendChild(Xt(["M21.44 11.05l-9.19 9.19a6 6 0 0 1-8.49-8.49l9.19-9.19a4 4 0 0 1 5.66 5.66l-9.2 9.19a2 2 0 0 1-2.83-2.83l8.49-8.48"])),this.attachBtn.addEventListener("click",()=>this.fileInput.click()),this.voiceBtn=document.createElement("button"),this.voiceBtn.type="button",this.voiceBtn.className="icon bp-composer-tool",this.voiceBtn.title=h("web.composer.voice","Voice dictation"),this.voiceBtn.setAttribute("aria-label",h("web.composer.voice","Voice dictation")),this.voiceBtn.setAttribute("data-testid","composer-voice"),this.voiceBtn.appendChild(Xt(["M12 1a3 3 0 0 0-3 3v8a3 3 0 0 0 6 0V4a3 3 0 0 0-3-3z","M19 10v2a7 7 0 0 1-14 0v-2","M12 19v4","M8 23h8"])),this.voiceBtn.addEventListener("click",()=>this.cb.onToggleVoice?.()),this.stopBtn=document.createElement("button"),this.stopBtn.type="button",this.stopBtn.className="primary stop bp-hidden",this.stopBtn.textContent=h("composer.stop","Stop"),this.stopBtn.setAttribute("data-testid","composer-stop"),this.stopBtn.addEventListener("click",()=>this.cb.onInterrupt()),this.sendBtn=document.createElement("button"),this.sendBtn.type="button",this.sendBtn.className="primary bp-send-btn",this.sendBtn.textContent=h("composer.send","Send"),this.sendBtn.setAttribute("data-testid","composer-send"),this.sendBtn.addEventListener("click",()=>this.submit()),p.append(this.attachBtn,this.voiceBtn,this.stopBtn,this.sendBtn),s.append(r,this.planChipBtn,this.memoryEl,p),i.append(this.modelPickerEl,this.popupEl,this.errorEl,this.replyEl,this.attachStripEl,this.planBarEl,this.fileInput,this.textarea,s),n.appendChild(i),e.appendChild(n),this.onDocMouseDown=(l)=>{if(!this.modelPickerEl.isConnected){document.removeEventListener("mousedown",this.onDocMouseDown);return}if(!this.modelPickerOpen)return;let u=l.target;if(u&&(this.modelPickerEl.contains(u)||this.modelBtn.contains(u)))return;this.closeModelPicker()},document.addEventListener("mousedown",this.onDocMouseDown),this.textarea.addEventListener("paste",(l)=>{let u=l.clipboardData?.items;if(!u)return;let d=[];for(let m=0;m0)l.preventDefault(),this.addFiles(d)}),this.textarea.addEventListener("input",()=>{this.autoGrow(),this.clearError(),this.updatePopups()}),this.textarea.addEventListener("keydown",(l)=>{if(this.popupMode!=="none"){let u=this.popupMode==="slash"?this.filteredSlash.length:this.mentionItems.length;if(l.key==="ArrowDown"){l.preventDefault(),this.popupIdx=(this.popupIdx+1)%Math.max(1,u),this.renderPopup();return}if(l.key==="ArrowUp"){l.preventDefault(),this.popupIdx=(this.popupIdx-1+Math.max(1,u))%Math.max(1,u),this.renderPopup();return}if(l.key==="Tab"||l.key==="Enter"&&!l.shiftKey&&this.shouldCompleteOnEnter()){l.preventDefault(),this.applyPopupChoice(this.popupIdx);return}if(l.key==="Escape"){l.preventDefault(),this.closePopup();return}}if(l.key==="Tab"&&l.shiftKey&&this.planMode!==null){l.preventDefault(),this.cb.onCyclePlanMode?.();return}if(l.key==="Enter"&&!l.shiftKey)l.preventDefault(),this.submit()})}setCommands(e){this.commands=e.map((t)=>({...t,word:t.word.replace(/^\//,"")}))}setModelChip(e,t,n){let i=Ci(t),s=i.mark?xi(i.mark):null;if(s)this.providerMarkEl.replaceChildren(s);else this.providerMarkEl.textContent=i.glyph;if(this.providerMarkEl.style.color=i.color,this.providerMarkEl.title=i.title,this.modelTextEl.textContent=e||"default",typeof n==="number"&&Number.isFinite(n)&&n>=0)this.ctxEl.textContent=`ctx ${Math.round(n)}%`,this.ctxEl.classList.remove("bp-hidden");else this.ctxEl.textContent="",this.ctxEl.classList.add("bp-hidden")}setFeatures(e,t){this.attachBtn.classList.toggle("bp-hidden",!e),this.voiceBtn.classList.toggle("bp-hidden",!t)}setVoiceRecording(e){this.voiceBtn.classList.toggle("recording",e),this.voiceBtn.setAttribute("aria-pressed",e?"true":"false")}setVoiceLevel(e){this.voiceBtn.setAttribute("data-level",String(e))}getDraft(){return this.textarea.value}getCaret(){return this.textarea.selectionStart??this.textarea.value.length}setMemory(e){if(this.memoryEl.classList.toggle("bp-hidden",!e),!e)return;let t=e.total??0,n=t>0?Math.min(1,(e.done??0)/t):1;this.memoryFill.style.width=`${Math.round(n*100)}%`,this.memoryFill.dataset.state=e.state??"",this.memoryText.textContent=e.line??"",this.memoryEl.title=[e.status,e.lines,e.viewLine].filter(Boolean).join(` -`)}setPlanMode(e){if(this.planMode=e,this.textarea.classList.remove("is-plan","is-plan-exec"),this.sendBtn.classList.remove("is-plan","is-plan-exec"),this.planChipBtn.classList.remove("is-plan","is-exec"),this.planBarEl.classList.remove("is-exec"),!e){this.planChipBtn.classList.add("bp-hidden"),this.planChipBtn.setAttribute("aria-pressed","false"),this.planBarEl.classList.add("bp-hidden"),this.planBarEl.replaceChildren(),this.sendBtn.textContent=h("composer.send","Send");return}let t=e.phase,n=t!=="off",i=t==="armed"||t==="planning"||t==="pending",s=t==="executing";this.planChipBtn.classList.remove("bp-hidden"),this.planChipBtn.classList.toggle("is-plan",i),this.planChipBtn.classList.toggle("is-exec",s),this.planChipBtn.setAttribute("aria-pressed",n?"true":"false");let r=`${h("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?Ei():yn()),this.planChipLbl.textContent=s?h("gpui.planmode.chip.building","Building"):t==="pending"?h("gpui.mgmt.fab.reviewbtn","Review"):i&&e.once?h("gpui.planmode.chip.once","Plan · 1t"):h("gpui.mgmt.plan.tab","Plan"),this.textarea.classList.toggle("is-plan",i),this.textarea.classList.toggle("is-plan-exec",s),this.sendBtn.classList.toggle("is-plan",i),this.sendBtn.classList.toggle("is-plan-exec",s),this.sendBtn.textContent=i?h("gpui.mgmt.plan.tab","Plan"):h("composer.send","Send"),!n){this.planBarEl.classList.add("bp-hidden"),this.planBarEl.replaceChildren();return}this.planBarEl.classList.remove("bp-hidden"),this.planBarEl.classList.toggle("is-exec",s);let a=document.createElement("span");a.className="bp-plan-bar-ic",a.appendChild(s?Ei():yn());let o=document.createElement("span");o.className="bp-plan-bar-text",o.textContent=t==="armed"&&e.once?h("gpui.planmode.bar.once","Plan mode (1 turn) — explores and proposes a plan before editing"):t==="armed"?h("gpui.planmode.bar.always","Plan mode — explores and proposes a plan before editing"):t==="planning"?h("gpui.planmode.bar.planning","Planning — drafting a plan before edits"):t==="pending"?h("gpui.planmode.bar.pending","Proposed plan awaits review below"):h("gpui.planmode.bar.executing","Building the approved plan");let c=[a,o];if(t==="armed"||t==="planning"){let p=document.createElement("div");p.className="bp-plan-scopes";let l=(u,d,m,f)=>{let b=document.createElement("button");return b.type="button",b.className="bp-plan-scope-btn"+(d?" active":""),b.textContent=u,b.disabled=!this.enabled,b.setAttribute("data-testid",f),b.addEventListener("click",()=>this.cb.onSetPlanMode?.(m)),b};p.append(l(h("gpui.planmode.scope.once","1 turn"),e.once,"once","plan-scope-once"),l(h("gpui.planmode.scope.always","Always"),!e.once,"always","plan-scope-always"),l(h("gpui.bots.recall.off","Off"),!1,"off","plan-scope-off")),c.push(p)}this.planBarEl.replaceChildren(...c)}setState(e,t){if(this.enabled=e,this.textarea.disabled=!e,this.sendBtn.disabled=!e,this.attachBtn.disabled=!e,this.voiceBtn.disabled=!e,this.modelBtn.disabled=!e,!e)this.closeModelPicker();this.planChipBtn.disabled=!e,this.planBarEl.querySelectorAll(".bp-plan-scope-btn").forEach((n)=>{n.disabled=!e}),this.stopBtn.classList.toggle("bp-hidden",!t)}destroy(){document.removeEventListener("mousedown",this.onDocMouseDown)}isModelPickerOpen(){return this.modelPickerOpen}closeModelPicker(){if(!this.modelPickerOpen)return;this.modelPickerOpen=!1,this.modelPickerFocusIdx=-1,this.modelPickerEl.classList.add("bp-hidden"),this.modelBtn.classList.remove("is-open"),this.modelBtn.setAttribute("aria-expanded","false")}modelPickerFocusableButtons(){return Array.from(this.modelPickerBodyEl.querySelectorAll(".bp-mp-row-main:not(:disabled)"))}updateModelPickerKbdFocus(e){e.forEach((t,n)=>{let i=n===this.modelPickerFocusIdx;if(t.classList.toggle("is-kbd",i),i)t.scrollIntoView({block:"nearest"})})}updateFavoriteModels(e){if(!this.modelPickerSnap)return;if(this.modelPickerSnap=jt(this.modelPickerSnap,e),this.modelPickerOpen)this.renderModelPicker()}async toggleModelPicker(){if(!this.enabled)return;if(this.modelPickerOpen){this.closeModelPicker();return}this.closePopup(),this.modelPickerOpen=!0,this.modelPickerQuery="",this.modelPickerFocusIdx=-1,this.modelSearchInput.value="",this.modelPickerEl.classList.remove("bp-hidden"),this.modelBtn.classList.add("is-open"),this.modelBtn.setAttribute("aria-expanded","true"),this.modelPickerLoading=!0,this.renderModelPicker(),this.modelSearchInput.focus(),await this.reloadModelPicker()}async reloadModelPicker(){if(!this.cb.onLoadModelPicker){this.modelPickerLoading=!1,this.renderModelPicker();return}try{let e=await this.cb.onLoadModelPicker();if(!this.modelPickerOpen)return;this.modelPickerSnap=gi(e,this.cb.getFavoriteModels?.()??[])}catch{}finally{if(this.modelPickerLoading=!1,this.modelPickerOpen)this.renderModelPicker()}}async toggleFavoriteInPicker(e,t){if(!this.modelPickerSnap)return;let n=this.modelPickerSnap,i=dt(e,t);if(!i)return;let s=n.favoriteKeys.includes(i),r=vn(n.favoriteKeys,e,t);if(r.keys.length===n.favoriteKeys.length&&r.starred===s)return;if(this.modelPickerSnap=jt(n,r.keys),this.renderModelPicker(),!this.cb.onToggleFavorite)return;try{let a=await this.cb.onToggleFavorite(e,t,r.starred);if(Array.isArray(a)&&this.modelPickerSnap){if(this.modelPickerSnap=jt(this.modelPickerSnap,it(a)),this.modelPickerOpen)this.renderModelPicker()}}catch(a){if(this.modelPickerSnap){let o=this.cb.getFavoriteModels?.(),c=Array.isArray(o)?it(o):vn(this.modelPickerSnap.favoriteKeys,e,t,!r.starred).keys;if(this.modelPickerSnap=jt(this.modelPickerSnap,c),this.modelPickerOpen)this.renderModelPicker()}this.showError(a instanceof Error&&a.message?a.message:"Could not update favorite model")}}renderProviderGlyph(e){let t=Ci(e),n=document.createElement("span");n.className="bp-mp-mark",n.style.color=t.color,n.title=t.title;let i=t.mark?xi(t.mark):null;if(i)n.appendChild(i);else n.textContent=t.glyph;return n}makeStarButton(e,t,n,i="model-star"){let s=document.createElement("button");s.type="button",s.className="bp-mp-star"+(n?" is-starred":"");let r=n?h("gpui.picker.favorite.remove","Remove from favorites"):h("gpui.picker.favorite.add","Add to favorites");return s.title=r,s.setAttribute("aria-label",r),s.setAttribute("aria-pressed",n?"true":"false"),s.setAttribute("data-testid",`${i}-${e}-${t}`),s.appendChild(ki(n)),s.addEventListener("click",(a)=>{a.preventDefault(),a.stopPropagation(),this.toggleFavoriteInPicker(e,t)}),s}renderModelPicker(){if(!this.modelPickerOpen)return;if(this.modelPickerFocusIdx=-1,!this.modelPickerSnap){let i=document.createElement("div");i.className="bp-mp-empty",i.textContent=this.modelPickerLoading?"…":h("gpui.no.models","No models"),this.modelPickerBodyEl.replaceChildren(i),this.modelPickerEffortsEl.classList.add("bp-hidden"),this.modelPickerEffortsEl.replaceChildren();return}let e=fi(this.modelPickerSnap,this.modelPickerQuery),t=document.createDocumentFragment();if(e.favorites.length>0){let i=document.createElement("div");i.className="bp-mp-section bp-mp-favorites",i.setAttribute("data-testid","model-picker-favorites");let s=document.createElement("div");s.className="bp-mp-head";let r=document.createElement("span");r.className="bp-mp-head-star",r.appendChild(ki(!0));let a=document.createElement("span");a.textContent=h("gpui.picker.favorites","Favorites"),s.append(r,a),i.appendChild(s);for(let o of e.favorites){let c=document.createElement("div");c.className="bp-mp-row"+(o.on?" is-active":"")+(!o.ok?" is-disabled":""),c.setAttribute("data-testid",`model-fav-row-${o.provider}-${o.model}`);let p=document.createElement("button");if(p.type="button",p.className="bp-mp-row-main",p.disabled=!o.ok,!o.ok&&o.why)p.title=o.why;let l=document.createElement("span");l.className="bp-mp-check",l.textContent=o.on?"✓":"";let u=document.createElement("span");u.className="bp-mp-name",u.textContent=o.label;let d=document.createElement("span");d.className="bp-mp-note",d.textContent=!o.ok&&o.why?pe(o.why):o.note&&o.note!==o.label?pe(o.note):o.provider,p.append(l,this.renderProviderGlyph(o.provider),u,d),p.addEventListener("click",()=>{if(!o.ok)return;this.closeModelPicker(),this.textarea.focus(),this.cb.onSelectModel?.(o.provider,o.model)}),c.append(p,this.makeStarButton(o.provider,o.model,!0,"model-fav-star")),i.appendChild(c)}t.appendChild(i)}let n=document.createElement("div");if(n.className="bp-mp-groups",n.setAttribute("data-testid","model-picker-groups"),e.groups.length===0){let i=document.createElement("div");i.className="bp-mp-empty",i.textContent=this.modelPickerQuery.trim()?h("gpui.nothing.matches","Nothing matches"):h("gpui.no.models","No models"),n.appendChild(i)}else for(let i of e.groups){let s=document.createElement("div");s.className="bp-mp-group";let r=document.createElement("div");r.className="bp-mp-group-head";let a=document.createElement("span");if(a.className="bp-mp-group-title",a.textContent=i.label,r.append(this.renderProviderGlyph(i.provider),a),!i.ok&&i.why){let o=document.createElement("span");o.className="bp-mp-group-why",o.textContent=pe(i.why),r.appendChild(o)}s.appendChild(r);for(let o of i.models){let c=document.createElement("div");c.className="bp-mp-row"+(o.on?" is-active":"")+(!o.ok?" is-disabled":""),c.setAttribute("data-testid",`model-row-${i.provider}-${o.value||"default"}`);let p=document.createElement("button");if(p.type="button",p.className="bp-mp-row-main",p.disabled=!o.ok,!o.ok&&o.why)p.title=o.why;let l=document.createElement("span");l.className="bp-mp-check",l.textContent=o.on?"✓":"";let u=document.createElement("span");u.className="bp-mp-name",u.textContent=o.label;let d=document.createElement("span");if(d.className="bp-mp-note",d.textContent=o.note&&o.note!==o.label?pe(o.note):"",p.append(l,u,d),p.addEventListener("click",()=>{if(!o.ok)return;this.closeModelPicker(),this.textarea.focus(),this.cb.onSelectModel?.(i.provider,o.value)}),c.appendChild(p),o.starrable)c.appendChild(this.makeStarButton(i.provider,o.value,o.starred));s.appendChild(c)}n.appendChild(s)}if(t.appendChild(n),this.modelPickerBodyEl.replaceChildren(t),e.efforts.length>0){let i=document.createDocumentFragment(),s=document.createElement("span");s.className="bp-mp-efforts-lbl",s.textContent=h("model.col.effort","Effort"),i.appendChild(s);for(let r of e.efforts){let a=document.createElement("button");a.type="button",a.className="bp-mp-effort"+(r.on?" active":""),a.textContent=r.label,a.addEventListener("click",()=>{Promise.resolve(this.cb.onSelectEffort?.(r.value)).then(()=>{if(this.modelPickerOpen)this.reloadModelPicker()})}),i.appendChild(a)}this.modelPickerEffortsEl.replaceChildren(i),this.modelPickerEffortsEl.classList.remove("bp-hidden")}else this.modelPickerEffortsEl.classList.add("bp-hidden"),this.modelPickerEffortsEl.replaceChildren()}setDraft(e){this.textarea.value=e,this.autoGrow(),this.textarea.focus()}setReply(e,t,n){if(!e){this.replyEl.replaceChildren(),this.replyEl.classList.add("bp-hidden");return}let i=document.createElement("button");i.type="button",i.className="bp-reply-strip-body",i.setAttribute("data-testid","composer-reply-go");let s=document.createElement("span");s.className="bp-reply-strip-who",s.textContent=e.who;let r=document.createElement("span");if(r.className="bp-reply-strip-line",r.textContent=h("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=h("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(){if(this.textarea.placeholder=h("composer.placeholder","Ask anything: @bot, >thread, %project, #room, $skill, /btw"),this.attachBtn.title=h("web.composer.attach","Attach image"),this.attachBtn.setAttribute("aria-label",h("web.composer.attach","Attach image")),this.voiceBtn.title=h("web.composer.voice","Voice dictation"),this.voiceBtn.setAttribute("aria-label",h("web.composer.voice","Voice dictation")),this.modelBtn.title=h("composer.model.tip","Choose the model and effort"),this.modelSearchInput.placeholder=h("gpui.search.models","Search models"),this.sendBtn.textContent=h("composer.send","Send"),this.stopBtn.textContent=h("composer.stop","Stop"),this.setPlanMode(this.planMode),this.modelPickerOpen)this.renderModelPicker()}autoGrow(){this.textarea.style.height="auto",this.textarea.style.height=`${Math.min(180,Math.max(54,this.textarea.scrollHeight))}px`}shouldCompleteOnEnter(){if(this.popupMode==="mention")return!0;if(this.popupMode==="slash"){let e=this.textarea.value;return e.startsWith("/")&&!e.includes(" ")}return!1}updatePopups(){let e=this.textarea.value;if(e.startsWith("/")&&!e.includes(" ")&&!e.includes(` -`)){let n=e.slice(1).toLowerCase();if(this.filteredSlash=this.commands.filter((i)=>i.word.toLowerCase().startsWith(n)),this.filteredSlash.length>0){this.popupMode="slash",this.popupIdx=Math.min(this.popupIdx,this.filteredSlash.length-1),this.renderPopup();return}}let t=/(?:^|\s)([@>%#])([a-zA-Z0-9._-]{1,32})$/.exec(e.slice(0,this.textarea.selectionStart));if(t){let n=t[1],i=t[2];this.cb.onQueryMentions(i,n).then((s)=>{if(s.length>0)this.mentionItems=s,this.popupMode="mention",this.popupIdx=0,this.renderPopup();else if(this.popupMode==="mention")this.closePopup()});return}this.closePopup()}closePopup(){this.popupMode="none",this.popupEl.classList.add("bp-hidden"),this.popupEl.replaceChildren()}renderPopup(){let e=document.createDocumentFragment();if(this.popupMode==="slash")this.filteredSlash.forEach((t,n)=>{let i=document.createElement("button");i.type="button",i.className="bp-popup-row"+(n===this.popupIdx?" active":""),i.setAttribute("data-testid",`slash-item-${t.word}`);let s=document.createElement("span");s.className="bp-popup-name",s.textContent=`/${t.word}`;let r=document.createElement("span");r.className="bp-popup-desc",r.textContent=t.desc||t.label,i.append(s,r),i.addEventListener("mousedown",(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(!wi.has(t.type)){this.showError(h("web.composer.unsupported","Unsupported image type: {type}",{type:t.type||t.name}));continue}if(this.attachments.length>=yi){this.showError(h("web.composer.maximages","At most {max} images per message.",{max:yi}));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=h("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 Pi(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 gr=new Set(["bom","checks","life","plan","fab"]);function Yt(e){if(!e||!Array.isArray(e.panels))return[];return e.panels.filter((t)=>t&&typeof t.id==="string"&&gr.has(t.id))}function Ti(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 Zt(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 wt(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 Et(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 fr=new Set(["0201","0402","0603","0805","1206","1210","1812","2010","2512"]),vr=new Set(["QFN","DFN","SOT","SOIC","SOP","SSOP","TSSOP","MSOP","QFP","LQFP","TQFP","BGA","WLCSP","SOD","TO","SON","LGA"]);function Bi(e){if(!e)return"";let t=e.indexOf(":"),i=(t>=0?e.slice(t+1):e).split("_");for(let a of i)if(fr.has(a))return a;let s=i[0]??"",r=s.replace(/[^a-zA-Z].*$/,"").toUpperCase();if(vr.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 Ii(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 ${wt(Math.max(n,0))}`,tone:"bad"};if(t==="low")return{text:`low ${wt(n)}`,tone:"warn"};return{text:wt(n),tone:"ok"}}function Ri(e,t){let n=t.trim().toLowerCase().split(/\s+/).filter(Boolean);if(n.length===0)return e;return e.filter((i)=>{let s=[(i.refs??[]).join(" "),i.value??"",i.footprint??"",i.mpn??"",i.fab??""].join(" ").toLowerCase();return n.every((r)=>r==="dnp"&&Boolean(i.dnp)||s.includes(r))})}function ji(e,t){if(!t)return e;return e.filter((n)=>n.source===t)}function kn(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 Qt(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 Di(e){return e.state==="routed"||e.state==="verified"}function Hi(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 Fi(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 $i(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 Gi(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 Cn(e,t){return e.watchGen===t.watchGen&&e.editGen===t.editGen&&e.project!==""&&e.project===t.project&&e.editId!==""&&e.editId===t.editId}function Vi(e){return{project:e.project,refs:e.refs.slice(),field:e.field,value:e.was}}function xn(e,t){return e.watchGen===t.watchGen&&e.project!==""&&e.project===t.project&&e.threadId!==""&&e.threadId===t.threadId&&e.threadGen===t.threadGen}var Si=["#f59e0b","#38bdf8","#c084fc","#2dd4bf","#ef4444","#a3e635","#f97316","#ec4899"],Ai=["#14b8a6","#f59e0b","#c084fc","#22c55e","#38bdf8","#ef4444","#e879f9","#84cc16"];function Ui(e){let t=2166136261;for(let n=0;n>>0;return t}function Dt(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 Si[Ui(i)%Si.length]}function kt(e,t=""){let n=t.trim().toLowerCase();if(n&&n!=="#8a8a8a")return t;return Ai[Ui(e)%Ai.length]}function Wi(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 We(e,t,n,i,s){return[i*0.5+(t-e.cx)*e.scale,s*0.5+(n-e.cy)*e.scale]}function en(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 _i(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 zi(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)),[p,l]=en(e,n,i,s,r);return{...e,cx:p-(n-s*0.5)/c,cy:l-(i-r*0.5)/c,scale:c,touched:!0}}function qi(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 Pn(e,t,n){let i=n?3:2;if(e.length<=i||t<0||t>=e.length)return null;let s=e.map((r)=>[r[0],r[1]]);return s.splice(t,1),s}function yr(e,t,n,i,s,r){let 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 p=Math.max(0,Math.min(1,((e-n)*a+(t-i)*o)/c)),l=n+p*a,u=i+p*o;return(e-l)*(e-l)+(t-u)*(t-u)}function Li(e,t,n){if(n.length<3)return!1;let i=!1;for(let s=0,r=n.length-1;st!==p>t&&e<(c-a)*(t-o)/(p-o+0.000000000001)+a)i=!i}return i}function Sn(e,t){return Math.max(5,Math.min(32,e*t))}function tn(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 m=d.path??[];for(let f=0;f=3)for(let f=0;f=0;d--){let m=t[d];if(m.layer!==n)continue;let f=m.outline??[];if(!Li(l,u,f))continue;if(!(m.holes??[]).some((g)=>Li(l,u,g)))return{kind:"region",id:m.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((p)=>p.kind==="corridor").length,c=a.filter((p)=>p.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 Ni(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 pt(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 Ki(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 Mi(e,t,n){if(n.length<3)return!1;let i=!1;for(let s=0,r=n.length-1;st!==p>t&&e<(c-a)*(t-o)/(p-o+0.000000000001)+a)i=!i}return i}function Ji(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 p of e)n=Math.min(n,p[0]),i=Math.min(i,p[1]),s=Math.max(s,p[0]),r=Math.max(r,p[1]),a+=p[0],o+=p[1];let c=[[(n+s)*0.5,(i+r)*0.5],[a/e.length,o/e.length]];for(let p of[0.5,0.25,0.75,0.125,0.875])for(let l of[0.5,0.25,0.75,0.125,0.875])c.push([n+(s-n)*l,i+(r-i)*p]);for(let p of c)if(Mi(p[0],p[1],e)&&!t.some((l)=>Mi(p[0],p[1],l)))return p;return null}function Xi(e,t,n,i,s,r){let a=[];for(let l of e){let u=l.nets??0,d=l.path??[];if(u<=0||d.length<2)continue;let m=0;for(let f=1;f{let d=l.sel||l.hov?1:0,m=u.sel||u.hov?1:0;if(m!==d)return m-d;if(u.nets!==l.nets)return u.nets-l.nets;return l.b.id.localeCompare(u.b.id)});let o=[],c=[],p=(l,u,d,m,f)=>[l-d*0.5-f,u-m*0.5-f,l+d*0.5+f,u+m*0.5+f];for(let l of a){let u=l.b.name||"",d=String(l.nets),m=u?`${u} · ${l.nets}`:d,f=(l.sel||l.hov||l.pxLen>=95)&&u?[m,d]:[d],b=null,g=(w,C)=>Math.max(C*0.5+3,Math.min(Math.max(C*0.5+3,n-C*0.5-3),w)),y=(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 f){let C=Math.max(16,w.length*5.9+10),A=15;for(let S of[0.5,0.35,0.65,0.22,0.78]){let T=Ni(l.pts,S);if(!T)continue;let[I,P]=We(t,T[0],T[1],n,i),j=g(I,C),G=y(P,15),L=p(j,G,C,15,2);if(!o.some((Y)=>En(L,Y))){b={id:l.b.id,text:w,cx:j,cy:G,pw:C,ph:15,col:l.col,sel:l.sel};break e}}}if(!b){let w=Ni(l.pts,0.5);if(w){let[C,A]=We(t,w[0],w[1],n,i),S=Math.max(16,d.length*6.5+8),T=15,I=g(C,S);for(let P of[-18,18]){let j=y(A+P,15);if(!o.some((G)=>En(p(I,j,S,15,2),G))){b={id:l.b.id,text:d,cx:I,cy:j,pw:S,ph:15,col:l.col,sel:l.sel};break}}}}if(b)o.push(p(b.cx,b.cy,b.pw,b.ph,2)),c.push(b)}return c}function Yi(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[u,d]=We(t,l.b[0],l.b[1],n,i),[m,f]=We(t,l.b[2],l.b[3],n,i),b=Math.abs(m-u),g=Math.abs(f-d);if(b<13||g<9)continue;let y=(u+m)*0.5,w=(d+f)*0.5;if(y<8||y>n-8||w<8||w>i-8)continue;o.push({text:l.r,cx:y,cy:w,bw:l.r.length*5.8+4,bh:11,score:b*g+(a.has(l.r)?1e4:0)})}o.sort((l,u)=>u.score-l.score);let c=[...r],p=[];for(let l of o){let u=[l.cx-l.bw*0.5,l.cy-l.bh*0.5,l.cx+l.bw*0.5,l.cy+l.bh*0.5];if(!c.some((m)=>En(u,m)))c.push(u),p.push({text:l.text,cx:l.cx,cy:l.cy})}return p}function Zi(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 nn(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 Qi(e,t,n,i,s,r,a,o){return e===t&&n===i&&s===r&&(o===void 0||a>=o)}var es="#111917",wr="#16201d",Er="rgba(212, 224, 219, 0.92)",kr="rgba(61, 80, 73, 0.72)",Cr="rgba(82, 107, 97, 0.85)";var ts="#f59e0b",xr="#eef5f2",ns="#ef4444";function ut(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 Pr(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 Sr(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 Ar(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 An{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=nn(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 Wi(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=h("gpui.mgmt.plan.layer","Approve layer"),c.addEventListener("click",(w)=>{w.stopPropagation(),this.cb.onApproveLayer(e.layer,!0)});let p=document.createElement("button");p.type="button",p.className="bp-mgmt-btn bp-plan-mini-btn",p.textContent="✗",p.title=h("gpui.mgmt.plan.rejectlayer","Reject layer"),p.addEventListener("click",(w)=>{w.stopPropagation(),this.cb.onApproveLayer(e.layer,!1)}),i.append(s,a,o,c,p);let l=document.createElement("div");l.className="bp-plan-card-sub",n.append(i,l);let u=document.createElement("div");u.className="bp-plan-card-canvas-wrap";let d=document.createElement("canvas");d.className="bp-plan-card-canvas",d.setAttribute("data-testid",`mgmt-plan-canvas-${e.layer}`);let m=document.createElement("div");m.className="bp-plan-hover-hud bp-hidden",u.append(d,m);let f=document.createElement("div");f.className="bp-plan-legend bp-hidden",t.append(n,u,f);let b=d.getContext("2d"),g=new ResizeObserver(()=>this.scheduleDraw());g.observe(u),this.attachPointerListeners(d,e.layer);let y={layer:e.layer,el:t,canvas:d,ctx:b,legendEl:f,okBtn:c,noBtn:p,statusEl:o,titleEl:a,subtitleEl:l,hoverHudEl:m,ro:g};return this.syncCardHeaderAndLegend(y,e),y}syncCardHeaderAndLegend(e,t){e.titleEl.textContent=pt(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=Ar(t);e.statusEl.className=`bp-plan-card-status tone-${s.tone==="warn"?"dim":s.tone}`,e.statusEl.textContent=i.length>0?h(s.key,s.label):"",e.statusEl.classList.toggle("bp-hidden",i.length===0);let 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 p=document.createElement("button");p.type="button";let l=this.state?.selectedId===c.id;p.className="bp-plan-legend-chip"+(l?" active":"");let u=document.createElement("span");u.className="bp-plan-legend-sw",u.style.background=Dt(c.net||c.id,c.color||"");let d=document.createElement("span");d.textContent=c.net||c.id,p.append(u,d),p.addEventListener("click",()=>{this.cb.onSelect(c.id),this.cb.onFocusItem(c.id)}),o.appendChild(p)}e.legendEl.replaceChildren(o)}}attachPointerListeners(e,t){e.addEventListener("contextmenu",(i)=>i.preventDefault()),e.addEventListener("dblclick",()=>this.fitAll()),e.addEventListener("pointerdown",(i)=>{let s=this.state;if(!s)return;this.root.focus({preventScroll:!0});let r=e.getBoundingClientRect(),a=i.clientX-r.left,o=i.clientY-r.top,c=Math.max(1,r.width),p=Math.max(1,r.height),l=this.getCam(t,c,p),u=tn(s.bands,s.regions,t,s.selectedId,l,c,p,a,o);if(i.button===2){if(u?.kind==="vertex"){let d=this.getItemPts(u.id,u.isPlane),m=Pn(d,u.idx,u.isPlane);if(m)this.selectedVertex=null,this.cb.onCommitFields(u.id,{[u.isPlane?"outline":"path"]:m})}return}if(i.button!==0)return;if(e.setPointerCapture(i.pointerId),this.downPos={x:i.clientX,y:i.clientY},u?.kind==="vertex"){let d=this.getItemPts(u.id,u.isPlane),m=d.map((f)=>[f[0],f[1]]);this.selectedVertex={id:u.id,idx:u.idx},this.drag={layer:t,kind:"vertex",id:u.id,isPlane:u.isPlane,idx:u.idx,pts:d.map((f)=>[f[0],f[1]]),origPts:m,moved:!1},this.scheduleDraw()}else if(u?.kind==="midpoint"){let d=this.getItemPts(u.id,u.isPlane),m=d.map((g)=>[g[0],g[1]]),f=qi(d,u.segIdx,u.pos,u.isPlane),b=u.isPlane&&u.segIdx+1>=d.length?f.length-1:Math.min(u.segIdx+1,f.length-1);this.selectedVertex={id:u.id,idx:b},this.patchLocalItem(u.id,u.isPlane,f),this.drag={layer:t,kind:"vertex",id:u.id,isPlane:u.isPlane,idx:b,pts:f,origPts:m,moved:!0},this.scheduleDraw()}else this.selectedVertex=null,this.drag={layer:t,kind:"pan",lastX: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),p=Math.max(1,r.height);if(this.drag&&this.drag.layer===t){if(this.drag.kind==="pan"){let A=this.getCam(t,c,p);this.setCam(t,_i(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 b=this.getCam(t,c,p),[g,y]=en(b,a,o,c,p),w=[Math.round(g*1000)/1000,Math.round(y*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,p),u=tn(s.bands,s.regions,t,s.selectedId,l,c,p,a,o),d=this.hover?.hit?"id"in this.hover.hit?this.hover.hit.id:"":"",m=this.hover?.hit.kind??"",f=u?u.id:"";if(this.hover=u?{layer:t,hit:u}:null,e.style.cursor=u?"pointer":"crosshair",d!==f||(u?.kind??"")!==m)this.syncHoverHud(t),this.scheduleDraw()}),e.addEventListener("pointerleave",()=>{if(this.hover?.layer===t)this.hover=null,this.syncHoverHud(t),this.scheduleDraw()});let n=()=>{let i=this.drag;if(!i||i.layer!==t)return;if(this.drag=null,this.downPos=null,i.kind==="vertex"&&i.moved){let s=i.origPts.map((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,p=i.clientY-o.top,l=Math.max(1,o.width),u=Math.max(1,o.height),d=this.getCam(t,l,u),m=tn(s.bands,s.regions,t,s.selectedId,d,l,u,c,p);if(m&&(m.kind==="band"||m.kind==="region")){this.cb.onSelect(m.id),this.cb.onFocusItem(m.id);return}if(!m&&s.selectedId){this.cb.onSelect("");return}}this.cb.onDragEnd?.()}),e.addEventListener("wheel",(i)=>{i.preventDefault();let s=e.getBoundingClientRect(),r=i.clientX-s.left,a=i.clientY-s.top,o=Math.max(1,s.width),c=Math.max(1,s.height),p=this.getCam(t,o,c),l=Math.max(0.65,Math.min(1.55,1-i.deltaY*0.002));this.setCam(t,zi(p,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=Pn(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=(b,g)=>We(r,b,g,n,i);e.fillStyle=es,e.fillRect(0,0,n,i);let o=(s.board.outline??[]).filter((b)=>b.length>=3);if(e.fillStyle=wr,o.length>0){e.beginPath();for(let b of o){for(let g=0;gb.layer===t),p=this.hover?.layer===t?this.hover.hit:null;for(let b of c){let g=b.outline??[];if(g.length<3)continue;let y=s.selectedId===b.id,w=p?.id===b.id,C=Sr(b.state||"proposed",y,w),A=Dt(b.net||b.id,b.color||"");e.beginPath();for(let T=0;TP)P=L;if(Y>j)j=Y}if(Math.abs(P-T)>=38&&Math.abs(j-I)>=18){let G=Ji(g,b.holes??[]);if(G){let[L,Y]=a(G[0],G[1]);e.fillStyle=ut(A,y?0.91:0.67),e.font="bold 10px ui-monospace, 'SFMono-Regular', Menlo, monospace",e.textAlign="center",e.textBaseline="middle",e.fillText(S,L,Y)}}}}if(e.strokeStyle=Er,e.lineWidth=1.25,e.lineCap="round",e.lineJoin="round",o.length>0){e.beginPath();for(let b of o){for(let g=0;gb.layer===t),d=Xi(u,r,n,i,s.selectedId,p?.id??""),m=d.map((b)=>[b.cx-b.pw*0.5-1,b.cy-b.ph*0.5-1,b.cx+b.pw*0.5+1,b.cy+b.ph*0.5+1]),f=[];for(let b of u){for(let g of b.from??[])f.push(g);for(let g of b.to??[])f.push(g)}e.fillStyle="rgba(143, 163, 155, 0.72)",e.font="9.5px ui-monospace, 'SFMono-Regular', Menlo, monospace",e.textAlign="center",e.textBaseline="middle";for(let b of Yi(l,r,n,i,f,m))e.fillText(b.text,b.cx,b.cy);for(let b of u){let g=b.guides??[];if(g.length===0)continue;let y=s.selectedId===b.id||p?.id===b.id,w=kt(b.name||b.id,b.color||"");e.strokeStyle=ut(w,y?0.38:0.17),e.lineWidth=y?1:0.7,e.beginPath();for(let C of g){let[A,S]=a(C[0],C[1]),[T,I]=a(C[2],C[3]);e.moveTo(A,S),e.lineTo(T,I)}e.stroke()}for(let b of u){let g=b.path??[];if(g.length<2)continue;let y=s.selectedId===b.id,w=p?.id===b.id,C=Pr(b.state||"proposed",y,w),A=kt(b.name||b.id,b.color||""),S=Sn(b.width??1.5,r.scale),T=()=>{e.beginPath();for(let I=0;I{let w=y?g.length:Math.max(0,g.length-1);for(let C=0;Cn.id===e))return;if(this.openPanel!==e)this.togglePanel(e)}getTabs(){return Yt(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=Yt(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 p=document.createElement("span");p.textContent=pe(a.label),o.appendChild(p);let l=this.getPanelData(a.id),u=Ti(l);if(u){let d=document.createElement("span");d.className=`bp-mgmt-badge bp-tone-${u.tone}`,d.textContent=u.text,o.appendChild(d)}o.addEventListener("click",()=>this.togglePanel(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=h("gpui.mgmt.close","Close the panel"),a.setAttribute("aria-label",h("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 p=document.createElement("span");p.className="bp-dim",p.textContent=(t.priced??0)<(t.lookups??0)?`≥ ${Et(t.cost)}/board`:`${Et(t.cost)}/board`,i.appendChild(p)}if(t.paused){let p=document.createElement("span");p.className="bp-mgmt-faint",p.textContent="Stock check paused",i.appendChild(p)}if(e.appendChild(i),t.stock_note){let p=document.createElement("div");p.className="bp-mgmt-note bp-mgmt-faint",p.textContent=pe(t.stock_note),e.appendChild(p)}let o=this.bomEditingId?n.find((p)=>p.id===this.bomEditingId)??null:null;if(o)e.appendChild(this.renderBomEditor(o));else{let p=document.createElement("div");p.className="bp-mgmt-filter-row";let l=document.createElement("input");l.type="text",l.className="bp-mgmt-filter",l.placeholder="Filter BOM (ref, value, footprint, MPN, dnp)…",l.value=this.bomFilter,l.setAttribute("data-testid","mgmt-bom-filter"),l.addEventListener("input",()=>{this.bomFilter=l.value,this.renderBomRows(c,n)}),p.appendChild(l),e.appendChild(p)}let c=document.createElement("div");return c.className="bp-mgmt-rows",c.setAttribute("data-testid","mgmt-bom-rows"),this.renderBomRows(c,n),e.appendChild(c),e}renderBomRows(e,t){let n=Ri(t,this.bomFilter);if(n.length===0){e.replaceChildren(this.makeEmpty(t.length===0?"No parts found.":"No matching lines."));return}let i=t.some((r)=>Boolean(r.mpn)||Boolean(r.fab)),s=document.createDocumentFragment();for(let r of n){let a=Array.isArray(r.refs)?r.refs:[],o=document.createElement("div");o.className="bp-mgmt-row"+(this.bomSelectedId===r.id?" active":"")+(r.dnp?" faint":""),o.setAttribute("data-testid",`mgmt-bom-row-${r.id}`);let c=document.createElement("div");c.className="bp-mgmt-row-line";let p=document.createElement("span");if(p.className="bp-mgmt-strong bp-mgmt-flex1",p.textContent=Zt(a,24),c.appendChild(p),r.dnp){let b=document.createElement("span");b.className="bp-mgmt-pill",b.textContent=h("gpui.mgmt.bom.dnp","DNP"),c.appendChild(b)}else{let b=Ii(r.stock);if(b){let g=document.createElement("span");g.className=`bp-tone-${b.tone}`,g.textContent=b.text,c.appendChild(g)}}let l=document.createElement("button");l.type="button",l.className="bp-mgmt-btn",l.textContent="Edit",l.addEventListener("click",(b)=>{b.stopPropagation(),this.bomEditGen++,this.bomEditingId=r.id,this.bomEditDraft=r.mpn??"",this.bomEditStatus="",this.bomLastUndo=null,this.render()}),c.appendChild(l);let u=document.createElement("div");u.className="bp-mgmt-row-sub";let d=[`${r.qty??a.length}×`,r.value??"",Bi(r.footprint??"")].filter(Boolean).join(" · "),m=document.createElement("span");m.className="bp-dim",m.textContent=d;let f=document.createElement("span");if(f.className="bp-mgmt-flex1",r.mpn)f.textContent=r.mpn;else if(i&&!r.dnp)f.className+=" bp-tone-warn",f.textContent=h("gpui.mgmt.bom.nompn","no MPN");if(u.append(m,f),!r.dnp&&typeof r.stock?.price==="number"){let b=document.createElement("span");b.className="bp-dim",b.textContent=Et(r.stock.price),u.appendChild(b)}if(!r.dnp&&r.stock?.class){let b=document.createElement("span");b.className="bp-mgmt-faint",b.textContent=pe(r.stock.class),u.appendChild(b)}o.append(c,u),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=Zt(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,m=!1)=>{let f=o();this.bomEditStatus="Writing…",this.render();try{let b=await this.cb.hub.rpc("mgmt.bom.edit",d);if(!Cn(f,o()))return;this.bomLastUndo=!m&&(b.changed??0)>0?{project:d.project,editId:f.editId,refs:d.refs.slice(),field:d.field,was:typeof b.was==="string"?b.was:d.field==="mpn"?e.mpn??"":e.dnp?"yes":"no"}:null,this.bomEditStatus=m?"Restored":(b.changed??0)===0?"No change":b.via==="kicad"?"Updated in KiCad":"Saved to schematic"}catch(b){if(!Cn(f,o()))return;this.bomEditStatus=b instanceof Error?b.message:"Could not save edit"}this.render()},p=document.createElement("div");p.className="bp-mgmt-btn-row";let 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 u=document.createElement("button");if(u.type="button",u.className="bp-mgmt-btn",u.textContent=e.dnp?"Clear DNP":"Mark DNP",u.addEventListener("click",()=>{c({project:this.project,refs:n.slice(),field:"dnp",value:e.dnp?"no":"yes"})}),p.append(l,u),this.bomLastUndo&&this.bomLastUndo.project===this.project&&this.bomLastUndo.editId===this.bomEditingId){let d=this.bomLastUndo,m=document.createElement("button");m.type="button",m.className="bp-mgmt-btn",m.textContent="Undo",m.addEventListener("click",()=>{c(Vi(d),!0)}),p.appendChild(m)}if(t.append(i,a,p),this.bomEditStatus){let d=document.createElement("div");d.className="bp-mgmt-faint",d.textContent=this.bomEditStatus,t.appendChild(d)}return t}renderChecks(){let e=document.createElement("div");e.className="bp-mgmt-body";let t=this.getPanelData("checks");if(!t)return e.appendChild(this.makeEmpty("Reading checks…")),e;let n=Array.isArray(t.groups)?t.groups:[],i=Array.from(new Set(n.map((d)=>d.source).filter(Boolean))),s=(d)=>t.sources?.[d]?.label||d.toUpperCase(),r=(d)=>t.sources?.[d]?.judged===!0,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=h("gpui.mgmt.checks.all","All"),o.addEventListener("click",()=>{this.checksSource="",this.render()}),a.appendChild(o);for(let d of i){let m=document.createElement("button");m.type="button",m.className="bp-mgmt-btn"+(this.checksSource===d?" active":""),m.textContent=s(d)+(r(d)?" · judged":""),m.addEventListener("click",()=>{this.checksSource=this.checksSource===d?"":d,this.render()}),a.appendChild(m)}let c=document.createElement("span");c.className="bp-mgmt-flex1";let p=document.createElement("button");if(p.type="button",p.className="bp-mgmt-btn",p.textContent=h("gpui.mgmt.checks.run","Run"),p.addEventListener("click",()=>{let d=this.watchGen,m=this.project;this.checksStatus="Running checks…",this.render(),this.cb.hub.rpc("kicad.checks.run",{project:m}).then(()=>{if(d!==this.watchGen||m!==this.project)return;this.checksStatus="",this.render()}).catch((f)=>{if(d!==this.watchGen||m!==this.project)return;this.checksStatus=f instanceof Error?f.message:"Could not run checks",this.render()})}),a.append(c,p),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 u=ji(n,this.checksSource);if(u.length===0)l.appendChild(this.makeEmpty("No check findings."));else for(let d of u){let m=d.severity==="error"?"bad":d.severity==="warning"?"warn":"faint",f=document.createElement("div");f.className="bp-mgmt-group-head";let b=document.createElement("span");b.className=`bp-mgmt-dot bp-tone-bg-${m}`;let g=document.createElement("span");g.className="bp-mgmt-flex1",g.textContent=`${s(d.source)} · ${d.rule}`;let y=document.createElement("span");y.className=`bp-tone-${m}`,y.textContent=String(d.n),f.append(b,g,y),l.appendChild(f);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 S=document.createElement("div");S.className="bp-mgmt-row-sub";let T=document.createElement("span");if(T.className="bp-dim bp-mgmt-flex1",T.textContent=w.names??"",S.appendChild(T),this.checksSelectedId===w.id){let I=document.createElement("button");I.type="button",I.className="bp-mgmt-btn accent",I.textContent=h("gpui.mgmt.checks.fix","Fix with agent"),I.addEventListener("click",(P)=>{P.stopPropagation();let j={watchGen:this.watchGen,project:this.project,threadId:this.cb.getThreadId(),threadGen:this.cb.getThreadGen()};this.cb.hub.rpc("kicad.checks.fix",{project:j.project,id:w.id}).then((G)=>{let L={watchGen:this.watchGen,project:this.project,threadId:this.cb.getThreadId(),threadGen:this.cb.getThreadGen()};if(!xn(j,L))return;if(G.text)this.cb.onSendText(G.text),this.checksStatus="Sent to agent",this.render()}).catch((G)=>{let L={watchGen:this.watchGen,project:this.project,threadId:this.cb.getThreadId(),threadGen:this.cb.getThreadGen()};if(!xn(j,L))return;this.checksStatus=G instanceof Error?G.message:"Could not send finding",this.render()})}),S.appendChild(I)}C.appendChild(S)}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 p=i[c]??0,l=kn(c),u=document.createElement("span");u.className=p>0?`bp-tone-${l.tone}`:"bp-mgmt-faint",u.textContent=`${l.label} ${p}`,n.appendChild(u)}if((i.unknown??0)>0){let c=document.createElement("span");c.className="bp-mgmt-faint",c.textContent=`${i.unknown} unknown`,n.appendChild(c)}if(t.since){let c=document.createElement("span");c.className="bp-mgmt-flex1";let p=document.createElement("span");p.className="bp-mgmt-faint",p.textContent=`since ${Qt(t.since)} (${t.samples??0})`,n.append(c,p)}e.appendChild(n);let s=document.createElement("div");s.className="bp-mgmt-rows",s.setAttribute("data-testid","mgmt-life-rows");let r=t.bom?.cost??[],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],p=a[a.length-1],l=document.createElement("div");l.className="bp-mgmt-note bp-dim",l.textContent=`Parts/board: ${Et(c[1])} · ${Math.round(p?.[1]??0)}/${o} lines in stock (${Qt(c[0])})`,s.appendChild(l)}for(let c of t.parts??[]){let p=this.lifeSelectedKey===c.key,l=kn(c.lifecycle??"unknown"),u=document.createElement("div");u.className="bp-mgmt-row"+(p?" active":"");let d=document.createElement("div");d.className="bp-mgmt-row-line";let m=document.createElement("span");m.className="bp-mgmt-strong",m.textContent=Zt(c.refs??[],14);let f=document.createElement("span");f.className="bp-mgmt-flex1 bp-dim",f.textContent=c.mpn||c.key;let b=document.createElement("span");if(b.className=`bp-tone-${l.tone}`,b.textContent=l.label,d.append(m,f,b),typeof c.stock==="number"){let g=document.createElement("span");g.className="bp-dim",g.textContent=wt(c.stock),d.appendChild(g)}if(u.appendChild(d),p){let g=document.createElement("div");if(g.className="bp-mgmt-row-sub bp-mgmt-faint",this.lifePartLoading)g.textContent=h("gpui.mgmt.life.reading","Reading its history…");else if(this.lifePartSamples&&this.lifePartSamples.length>0){let y=this.lifePartSamples[this.lifePartSamples.length-1];g.textContent=`${this.lifePartSamples.length} samples · latest ${y.at?Qt(y.at):""}`+(typeof y.stock==="number"?` · stock ${wt(y.stock)}`:"")+(typeof y.price==="number"?` · ${Et(y.price)}`:"")}else g.textContent=h("gpui.mgmt.life.nopart","No reading of this part yet.");u.appendChild(g)}u.addEventListener("click",()=>{if(this.lifeSelectedKey===c.key){this.lifeSelectedKey="",this.lifePartSamples=null,this.render();return}this.lifeSelectedKey=c.key,this.lifePartSamples=null,this.lifePartLoading=!0,this.render(),this.cb.hub.rpc("mgmt.life.part",{project:this.project,key:c.key}).then((g)=>{if(this.lifeSelectedKey!==c.key)return;this.lifePartLoading=!1,this.lifePartSamples=Array.isArray(g.samples)?g.samples:[],this.render()}).catch(()=>{if(this.lifeSelectedKey!==c.key)return;this.lifePartLoading=!1,this.lifePartSamples=[],this.render()})}),s.appendChild(u)}return e.appendChild(s),e}renderPlan(){let e=document.createElement("div");e.className="bp-mgmt-body";let t=this.getPanelData("plan");if(!t)return e.appendChild(this.makeEmpty(h("gpui.mgmt.plan.reading","Reading the routing plan…"))),e;let n=(k,x)=>{let H=this.watchGen,B=this.project;this.planStatus="",this.cb.hub.rpc(k,{pro:B,...x}).catch((K)=>{if(H!==this.watchGen||B!==this.project)return;this.planOptimistic.clear(),this.planStatus=K instanceof Error?K.message:h("gpui.mgmt.plan.refused","KiCad refused"),this.render()})};if(t.revision!==this.planOptimisticRev)this.planOptimisticRev=t.revision,this.planOptimistic.clear();let i=`${this.project}:${t.revision??0}`;if(t.board_trimmed&&this.planHydrateAskedKey!==i&&this.project){this.planHydrateAskedKey=i;let k=this.watchGen,x=++this.planHydrateGen,H=this.project,B=t.revision??0;this.cb.hub.rpc("plan.get",{pro:H,board:!0}).then((K)=>{let ie=Zi(K);if(!ie)return;let we=typeof ie.revision==="number"?ie.revision:B;if(!Qi(k,this.watchGen,x,this.planHydrateGen,H,this.project,we,this.planHydratedRev))return;this.planHydratedRev=we,this.planHydratedKey=`${H}:${we}`,this.planHydratedBoard=ie.board??null,this.planHydratedDraw=ie.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=h("gpui.mgmt.plan.before","Plan before routing"),o.title=s?h("gpui.mgmt.plan.onwords","Before routing a board with 4 or more copper layers or more than 60 nets, the agent proposes corridors and plane regions here. It routes only what you approve."):h("gpui.mgmt.plan.offwords","Agents route as you ask. Turn it on to have them propose a routing plan first and route only what you approve here."),a.appendChild(o);let c=t.awaiting??0,p=t.blocked??0,l=t.done??0,u=t.total??0,d=t.revision??0,m=t.empty?[]:$i(t),f=m.reduce((k,x)=>k+x.count,0);if(!t.empty){let k=Fi(t),x=document.createElement("span");if(x.className=`bp-plan-status-badge tone-${k.tone}`,x.textContent=h(k.key,k.label),a.appendChild(x),d>0){let B=document.createElement("span");B.className="bp-dim",B.textContent=`v${d}`,a.appendChild(B)}let H=document.createElement("span");if(H.className="bp-plan-header-counts bp-mgmt-flex1 "+(c>0?"bp-tone-warn":p>0?"bp-tone-bad":"bp-dim"),H.textContent=u>0?`${l}/${u} ${h("gpui.mgmt.plan.done","done")}`:c>0?h("web.plan.awaiting","{n} awaiting approval",{n:c}):h("gpui.mgmt.plan.nothing","Nothing awaits your approval"),a.appendChild(H),!t.live){let B=document.createElement("span");B.className="bp-mgmt-pill",B.textContent=h("gpui.mgmt.plan.saved","saved plan"),a.appendChild(B)}}else{let k=document.createElement("span");k.className="bp-mgmt-flex1",a.appendChild(k)}let b=document.createElement("button");b.type="button",b.className="bp-mgmt-btn bp-plan-chip-btn"+(s?" active":""),b.setAttribute("data-testid","mgmt-plan-on"),b.setAttribute("aria-pressed",s?"true":"false"),b.textContent=h("gpui.bots.recall.on","On"),b.addEventListener("click",()=>n("plan.enable",{on:!0}));let g=document.createElement("button");if(g.type="button",g.className="bp-mgmt-btn bp-plan-chip-btn"+(!s?" active":""),g.setAttribute("data-testid","mgmt-plan-off"),g.setAttribute("aria-pressed",!s?"true":"false"),g.textContent=h("gpui.bots.recall.off","Off"),g.addEventListener("click",()=>n("plan.enable",{on:!1})),a.append(b,g),r.appendChild(a),f>0){let k=document.createElement("div");k.className="bp-plan-segbar";for(let x of m){if(x.count<=0)continue;let H=document.createElement("div");H.className=`bp-plan-seg bp-tone-bg-${x.tone}`,H.style.flexGrow=String(x.count),k.appendChild(H)}r.appendChild(k)}e.appendChild(r);for(let k of t.elsewhere??[]){let x=document.createElement("div");x.className="bp-plan-elsewhere";let H=document.createElement("span");H.className="bp-tone-warn bp-mgmt-flex1",H.textContent=h("gpui.mgmt.plan.elsewhere","A routing plan for {board} awaits your approval",{board:k.name||k.rel||""}),x.appendChild(H),e.appendChild(x)}if(t.empty){let k=document.createElement("div");k.className="bp-mgmt-note";let x=document.createElement("div");x.className="bp-dim",x.textContent=h("gpui.mgmt.plan.noboard","No routing plan for this board.");let H=document.createElement("div");return H.className="bp-mgmt-faint",H.textContent=h("gpui.mgmt.plan.emptysub","Layers, corridors, and planes appear here once a plan is proposed."),k.append(x,H),e.appendChild(k),e}let y=t.stackup_summary??"",w=Array.isArray(t.impedances)?t.impedances:[],C=Boolean(y)||w.length>0,A=document.createElement("div");if(A.className="bp-mgmt-head",c>0){let k=document.createElement("button");k.type="button",k.className="primary bp-mgmt-btn",k.setAttribute("data-testid","mgmt-plan-approve-all"),k.textContent=h("gpui.mgmt.plan.all","Approve all"),k.addEventListener("click",()=>n("plan.approve",{layer:"",ids:[],approve:!0})),A.appendChild(k)}if(t.routing){let k=document.createElement("button");k.type="button",k.className="bp-mgmt-btn",k.setAttribute("data-testid","mgmt-plan-stop"),k.textContent=h("gpui.mgmt.plan.stop","Stop routing"),k.addEventListener("click",()=>n("plan.stop",{})),A.appendChild(k)}if(t.live&&l>0){let k=document.createElement("button");k.type="button",k.className="bp-mgmt-btn",k.setAttribute("data-testid","mgmt-plan-verify"),k.textContent=h("gpui.mgmt.plan.verify","Verify"),k.addEventListener("click",()=>n("plan.verify",{})),A.appendChild(k)}let S=document.createElement("span");if(S.className="bp-mgmt-flex1",A.appendChild(S),C){let k=document.createElement("button");k.type="button",k.className="bp-mgmt-btn bp-plan-chip-btn"+(this.planStackupOpen?" active":""),k.setAttribute("data-testid","mgmt-plan-stackup-toggle"),k.setAttribute("aria-expanded",this.planStackupOpen?"true":"false"),k.textContent=`${h("gpui.mgmt.plan.stackup.short","Stackup")} ${this.planStackupOpen?"▾":"▸"}`,k.addEventListener("click",()=>{this.planStackupOpen=!this.planStackupOpen,this.render()}),A.appendChild(k)}let T=document.createElement("button");T.type="button",T.className="bp-mgmt-btn",T.setAttribute("data-testid","mgmt-plan-hide"),T.textContent=this.planHideDone?h("gpui.mgmt.plan.show","Show done"):h("gpui.mgmt.plan.hide","Hide done"),T.addEventListener("click",()=>{this.planHideDone=!this.planHideDone,this.render()}),A.appendChild(T),e.appendChild(A);let I=Array.isArray(t.asks)?t.asks:[];if(I.length>0){let k=I.map((ie)=>ie.what||"").filter(Boolean).join(", "),x=I[0]?.note||"",H=document.createElement("div");H.className="bp-plan-elsewhere";let B=document.createElement("div");B.className="bp-plan-ask-col";let K=document.createElement("div");if(K.className="bp-tone-warn",K.textContent=k?h("gpui.mgmt.plan.requested","Approval requested: {what}",{what:k}):h("gpui.mgmt.plan.reqplain","Approval requested"),B.appendChild(K),x){let ie=document.createElement("div");ie.className="bp-dim",ie.textContent=x,B.appendChild(ie)}H.appendChild(B),e.appendChild(H)}if(this.planStatus){let k=document.createElement("div");k.className="bp-mgmt-note bp-plan-err bp-tone-bad";let x=document.createElement("span");x.className="bp-mgmt-flex1",x.textContent=this.planStatus==="KiCad refused"?h("gpui.mgmt.plan.refused","KiCad refused"):pe(this.planStatus);let H=document.createElement("button");H.type="button",H.className="icon",H.textContent="×",H.title=h("common.close","Close"),H.addEventListener("click",()=>{this.planStatus="",this.render()}),k.append(x,H),e.appendChild(k)}if(t.keys_note){let k=document.createElement("div");k.className="bp-mgmt-note bp-dim";let x="On this KiCad version, approve from this panel: in plan view KiCad's A, R and W keys aren't the plan's yet (A opens Add Footprint). Update KiCad.";k.textContent=t.keys_note===x?h("gpui.mgmt.plan.keysnote",x):pe(t.keys_note),e.appendChild(k)}if(C&&this.planStackupOpen){let k=document.createElement("div");if(k.className="bp-plan-stackup-body",k.setAttribute("data-testid","mgmt-plan-stackup-body"),y){let x=document.createElement("div");x.className="bp-dim",x.textContent=y,k.appendChild(x)}for(let x of w){let H=document.createElement("div");H.className="bp-mgmt-faint",H.textContent=`· ${x}`,k.appendChild(H)}e.appendChild(k)}let P=(k,x,H,B)=>{let K=document.createElement("button");return K.type="button",K.className="bp-mgmt-btn bp-plan-chip-btn"+(x?" active":""),K.setAttribute("data-testid",H),K.setAttribute("aria-pressed",x?"true":"false"),K.textContent=k,K.addEventListener("click",B),K},j=document.createElement("div");if(j.className="bp-plan-viewbar",j.append(P(h("gpui.mgmt.plan.view.canvas","Canvas"),this.planViewMode==="canvas","mgmt-plan-view-canvas",()=>{this.planViewMode="canvas",this.render()}),P(h("gpui.mgmt.plan.view.split","Split"),this.planViewMode==="split","mgmt-plan-view-split",()=>{this.planViewMode="split",this.render()}),P(h("gpui.mgmt.plan.view.list","List"),this.planViewMode==="list","mgmt-plan-view-list",()=>{this.planViewMode="list",this.render()})),this.planViewMode!=="list"){let k=document.createElement("span");k.className="bp-plan-sep";let x=document.createElement("span");x.className="bp-plan-sep";let H=document.createElement("button");H.type="button",H.className="bp-mgmt-btn bp-plan-mini-btn",H.setAttribute("data-testid","mgmt-plan-fit"),H.textContent=h("gpui.mgmt.plan.fit","Fit"),H.addEventListener("click",()=>this.planCanvas?.fitAll()),j.append(k,P(h("gpui.mgmt.plan.grid.pair","Side by side"),this.planGridMode==="pair","mgmt-plan-grid-pair",()=>{this.planGridMode="pair",this.render()}),P(h("gpui.mgmt.plan.grid.all","All layers"),this.planGridMode==="all","mgmt-plan-grid-all",()=>{this.planGridMode="all",this.render()}),P(h("gpui.mgmt.plan.grid.single","Single"),this.planGridMode==="single","mgmt-plan-grid-single",()=>{this.planGridMode="single",this.render()}),x,P(h("gpui.mgmt.plan.sync","Link zoom"),this.planSyncZoom,"mgmt-plan-sync",()=>{this.planSyncZoom=!this.planSyncZoom,this.render()}),H)}let G=document.createElement("span");G.className="bp-mgmt-flex1";let L=document.createElement("button");L.type="button",L.className="bp-mgmt-btn bp-plan-mini-btn",L.setAttribute("data-testid","mgmt-plan-expand"),L.textContent=this.planExpanded?h("gpui.mgmt.plan.compact","Compact"):h("gpui.mgmt.plan.expand","Expand"),L.addEventListener("click",()=>{this.planExpanded=!this.planExpanded,this.render()}),j.append(G,L),e.appendChild(j);let Y=Boolean(this.planHydratedBoard)&&this.planHydratedKey.startsWith(`${this.project}:`)&&(this.planHydratedKey===i||this.planHydratedRev!==void 0&&this.planHydratedRev>=(t.revision??0)),re=Y&&this.planHydratedBoard?this.planHydratedBoard:t.board??{bbox:[0,0,100,70],outline:[],parts:[]},se=Y&&this.planHydratedDraw?this.planHydratedDraw:t.draw??{bands:[],regions:[]},be=(se.bands??[]).map((k)=>{let x=this.planOptimistic.get(k.id);if(!x)return{...k};return{...k,...x,edited:!0,state:k.state==="proposed"?"edited":k.state}}),Pe=(se.regions??[]).map((k)=>{let x=this.planOptimistic.get(k.id);if(!x)return{...k};return{...k,...x,edited:!0,state:k.state==="proposed"?"edited":k.state}}),Ee=[],ee=(t.layers??[]).map((k)=>{let x=[];for(let H of k.items??[]){let B=this.planOptimistic.get(H.id);if(!B){x.push(H);continue}let K={...H,width:typeof B.width==="number"?B.width:H.width,locked:typeof B.locked==="boolean"?B.locked:H.locked,edited:!0,state:H.state==="proposed"?"edited":H.state};if(typeof B.layer==="string"&&B.layer!==k.layer)Ee.push({target:B.layer,item:K});else x.push(K)}return{...k,items:x}});for(let k of Ee){let x=ee.find((H)=>H.layer===k.target);if(x)x.items=[...x.items??[],k.item]}let ae=nn(ee,t.copper_layers),R=this.planGridMode==="all"?ae.map((k)=>k.layer):this.planGridMode==="single"?[this.planShownLayers.find((k)=>ae.some((x)=>x.layer===k))??Ct(ae)[0]??ae[0]?.layer??""].filter(Boolean):this.planShownLayers.length>0&&this.planShownLayers.every((k)=>ae.some((x)=>x.layer===k))?this.planShownLayers.slice(0,2):Ct(ae);if(this.planViewMode!=="list"&&this.planGridMode!=="all"&&ae.length>1){let k=document.createElement("div");k.className="bp-plan-layerbar";for(let x of ae){let H=R.includes(x.layer),B=(x.items??[]).length,K=pt(x.layer,t.copper_layers,ae)||x.title||x.layer,ie=B>0?`${K} · ${B}`:K,we=P(ie,H,`mgmt-plan-layerpill-${x.layer}`,()=>{if(this.planGridMode==="single")this.planShownLayers=[x.layer];else if(this.planGridMode==="pair"){if(!R.includes(x.layer))this.planShownLayers=R.length>=2?[R[0],x.layer]:[...R,x.layer]}else this.planGridMode="single",this.planShownLayers=[x.layer];this.render()});if(B===0&&!H)we.classList.add("empty-layer");k.appendChild(we)}e.appendChild(k)}let ue=(k,x)=>{let H=this.planOptimistic.get(k)??{};if(this.planOptimistic.set(k,{...H,...x}),typeof x.layer==="string"){if(this.planGridMode==="single")this.planShownLayers=[x.layer];else if(this.planGridMode==="pair"&&!R.includes(x.layer))this.planShownLayers=R.length>=2?[R[0],x.layer]:[...R,x.layer]}let B=typeof t.revision==="number"?t.revision:void 0;this.render(),n("plan.update",{ops:[{op:"set",id:k,fields:x}],...B!==void 0?{base:B}:{}})};if(this.planCommitFields=ue,this.planSelectedId){let k="",x=null;for(let H of ee){let B=(H.items??[]).find((K)=>K.id===this.planSelectedId);if(B){k=H.layer,x=B;break}}if(x){let H=pt(k,t.copper_layers,ae),B=document.createElement("div");B.className="bp-plan-inspector",B.setAttribute("data-testid","mgmt-plan-inspector");let K=document.createElement("div");K.className="bp-plan-ins-row";let ie=document.createElement("span");ie.className="bp-plan-ins-sw",ie.style.background=x.kind==="corridor"?kt(x.name||x.id,x.color||""):Dt(x.name||x.id,x.color||"");let we=document.createElement("span");we.className="bp-mgmt-strong",we.textContent=x.name||x.id;let D=document.createElement("span");if(D.className="bp-dim",D.textContent=H,K.append(ie,we,D),x.edited||x.state==="edited"){let q=document.createElement("span");q.className="bp-plan-ins-pill warn",q.textContent=h("gpui.mgmt.plan.edited","Edited"),K.appendChild(q)}if(x.locked){let q=document.createElement("span");q.className="bp-plan-ins-pill",q.textContent=h("gpui.mgmt.plan.locked","Locked"),K.appendChild(q)}let ne=document.createElement("span");ne.className="bp-mgmt-flex1",K.appendChild(ne);let Ne=document.createElement("button");if(Ne.type="button",Ne.className="bp-mgmt-btn bp-plan-mini-btn",Ne.setAttribute("data-testid","mgmt-plan-lock"),Ne.textContent=x.locked?h("gpui.mgmt.plan.unlock","Unlock"):h("gpui.mgmt.plan.lock","Lock"),Ne.addEventListener("click",()=>ue(x.id,{locked:!x.locked})),K.appendChild(Ne),x.state==="proposed"||x.state==="edited"){let q=document.createElement("button");q.type="button",q.className="primary bp-mgmt-btn bp-plan-mini-btn",q.textContent=h("android.hub.machines.approve","Approve"),q.addEventListener("click",()=>n("plan.approve",{layer:"",ids:[x.id],approve:!0}));let he=document.createElement("button");he.type="button",he.className="bp-mgmt-btn bp-plan-mini-btn",he.textContent=h("gpui.mgmt.plan.reject","Reject"),he.addEventListener("click",()=>n("plan.approve",{layer:"",ids:[x.id],approve:!1})),K.append(q,he)}let Ae=document.createElement("button");Ae.type="button",Ae.className="bp-mgmt-btn bp-plan-mini-btn",Ae.setAttribute("data-testid","mgmt-plan-note-toggle"),Ae.textContent=h("gpui.mgmt.plan.addnote","Add note"),Ae.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(Ae,Me),B.appendChild(K),!x.locked){let q=document.createElement("div");if(q.className="bp-plan-ins-row",x.kind==="corridor"){let oe=typeof x.width==="number"?x.width:1.5,Re=document.createElement("span");Re.className="bp-dim",Re.textContent=h("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 tt=Math.round(Math.max(0.15,oe-0.25)*100)/100;ue(x.id,{width:tt})});let He=document.createElement("span");He.className="bp-plan-ins-val",He.textContent=`${oe.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 tt=Math.round(Math.min(25,oe+0.25)*100)/100;ue(x.id,{width:tt})});let fe=document.createElement("span");fe.className="bp-plan-sep",q.append(Re,je,He,ge,fe)}let he=(t.copper_layers??[]).length>0?(t.copper_layers??[]).map((oe)=>oe.layer):ee.map((oe)=>oe.layer);if(he.length>0){let oe=document.createElement("span");oe.className="bp-dim",oe.textContent=h("gpui.mgmt.plan.layer.short","Layer"),q.appendChild(oe),q.appendChild(P(`${H} ${this.planMoveLayerOpen?"▴":"▾"}`,this.planMoveLayerOpen,"mgmt-plan-move-toggle",()=>{this.planMoveLayerOpen=!this.planMoveLayerOpen,this.render()}))}if(B.appendChild(q),this.planMoveLayerOpen&&he.length>0){let oe=document.createElement("div");oe.className="bp-plan-ins-row";for(let Re of he){let je=pt(Re,t.copper_layers,ae);oe.appendChild(P(je,Re===k,`mgmt-plan-move-${Re}`,()=>{if(this.planMoveLayerOpen=!1,Re!==k)ue(x.id,{layer:Re});else this.render()}))}B.appendChild(oe)}}if(this.planNoteOpen){let q=document.createElement("form");q.className="bp-plan-note-form";let he=document.createElement("input");he.type="text",he.className="bp-plan-note-input",he.setAttribute("data-testid","mgmt-plan-note-input"),he.placeholder=h("gpui.mgmt.plan.note.placeholder","Steering note for router…");let oe=document.createElement("button");oe.type="submit",oe.className="primary bp-mgmt-btn bp-plan-mini-btn",oe.setAttribute("data-testid","mgmt-plan-note-submit"),oe.textContent=h("gpui.mgmt.plan.addnote","Add note"),q.append(he,oe),q.addEventListener("submit",(Re)=>{Re.preventDefault();let je=he.value.trim();if(!je)return;he.value="",this.planNoteOpen=!1;let He=typeof t.revision==="number"?t.revision:void 0;this.render(),n("plan.update",{ops:[{op:"note",target:x.id,text:je}],...He!==void 0?{base:He}:{}})}),B.appendChild(q)}if(this.planViewMode!=="list"&&!x.locked){let q=document.createElement("div");q.className="bp-plan-hint",q.textContent=h("gpui.mgmt.plan.hint","Drag waypoints to steer · Click + on edge to insert · Right-click vertex to remove"),B.appendChild(q)}e.appendChild(B)}}let le=document.createElement("div");le.className="bp-mgmt-rows"+(this.planViewMode==="split"?" bp-plan-split-list":""),le.setAttribute("data-testid","mgmt-plan-rows");let Q=h("gpui.mgmt.plan.done","done"),me=Ki(this.planViewMode,ee,R);if(this.planViewMode==="split"&&me.length===0){let k=document.createElement("div");k.className="bp-dim",k.style.padding="6px 8px",k.style.fontSize="11px",k.textContent=h("gpui.mgmt.plan.noitems","No corridors or planes on this layer"),le.appendChild(k)}for(let k of me){let x=k.items??[],H=pt(k.layer,t.copper_layers,ae)||k.layer;if(this.planViewMode==="split"){if(me.length>1){let B=document.createElement("div");B.className="bp-plan-split-divider";let K=k.role==="power"||k.role==="plane",ie=document.createElement("span");ie.className="bp-plan-card-bar "+(K?"pwr":"sig");let we=document.createElement("span");we.className="bp-mgmt-strong",we.textContent=H;let D=document.createElement("span");D.className="bp-dim",D.textContent=`${k.done??0}/${x.length} ${Q}`,B.append(ie,we,D),le.appendChild(B)}}else{let B=document.createElement("div");B.className="bp-mgmt-group-head bp-plan-layer-head";let K=document.createElement("div");K.className="bp-mgmt-row-line";let ie=document.createElement("span");ie.className="bp-mgmt-strong",ie.textContent=H;let we=document.createElement("span");if(we.className="bp-dim bp-mgmt-flex1",we.textContent=`${k.role?`${k.role} · `:""}${k.done??0}/${x.length} ${Q}`,K.append(ie,we),k.status!=="approved"&&x.length>0){let D=document.createElement("button");D.type="button",D.className="bp-mgmt-btn",D.textContent=h("gpui.mgmt.plan.layer","Approve layer"),D.addEventListener("click",()=>n("plan.approve",{layer:k.layer,ids:[],approve:!0}));let ne=document.createElement("button");ne.type="button",ne.className="bp-mgmt-btn",ne.textContent=h("gpui.mgmt.plan.reject","Reject"),ne.addEventListener("click",()=>n("plan.approve",{layer:k.layer,ids:[],approve:!1})),K.append(D,ne)}if(B.appendChild(K),k.stackup){let D=document.createElement("div");D.className="bp-plan-layer-stackup",D.textContent=k.stackup,B.appendChild(D)}le.appendChild(B)}for(let B of x){if(this.planHideDone&&Di(B))continue;let K=this.planSelectedId===B.id,ie=document.createElement("div");ie.className="bp-mgmt-row bp-plan-row"+(K?" active":""),ie.setAttribute("data-testid",`mgmt-plan-row-${B.id}`);let we=document.createElement("div");we.className="bp-mgmt-row-line";let D=document.createElement("span");D.className=`bp-plan-swatch bp-plan-st-${B.state||"proposed"}`,D.style.setProperty("--swatch-color",B.color||"#8a8a8a");let ne=document.createElement("span");ne.className="bp-mgmt-flex1"+(B.state==="blocked"||B.state==="failed"?" bp-tone-bad":B.state==="edited"?" bp-tone-warn":B.state==="rejected"||B.state==="routed"||B.state==="verified"?" bp-dim":""),ne.textContent=`${B.name||B.id}${B.locked?" \uD83D\uDD12":""}`;let Ne=[];if(B.kind==="plane"){if(B.reference)Ne.push(h("gpui.mgmt.plan.reference","over {layer}",{layer:B.reference}))}else{let q=B.nets??0;Ne.push(q===1?h("web.plan.net.one","1 net"):h("web.plan.nets","{n} nets",{n:q}))}if(typeof B.width==="number"&&Number.isFinite(B.width))Ne.push(`${B.width.toFixed(2)}mm`);if(B.impedance)Ne.push(B.impedance);let Ae=Ne.join(" · "),Me=document.createElement("span");if(Me.className="bp-plan-mark "+(B.state==="blocked"||B.state==="failed"?"bp-tone-bad":B.state==="verified"||B.state==="routed"?"bp-tone-ok":B.state==="approved"?"bp-tone-accent":"bp-dim"),Me.textContent=Hi(B),we.append(D,ne,Me),B.state==="proposed"||B.state==="edited"){let q=document.createElement("button");q.type="button",q.className="bp-mgmt-btn",q.textContent="✓",q.title=h("gpui.mgmt.plan.layer","Approve layer"),q.addEventListener("click",(oe)=>{oe.stopPropagation(),n("plan.approve",{layer:"",ids:[B.id],approve:!0})});let he=document.createElement("button");he.type="button",he.className="bp-mgmt-btn",he.textContent="✗",he.title=h("gpui.mgmt.plan.reject","Reject"),he.addEventListener("click",(oe)=>{oe.stopPropagation(),n("plan.approve",{layer:"",ids:[B.id],approve:!1})}),we.append(q,he)}if(ie.appendChild(we),Ae){let q=document.createElement("div");q.className="bp-mgmt-row-sub bp-plan-detail bp-dim",q.textContent=Ae,ie.appendChild(q)}if(B.state==="routing"&&typeof B.total==="number"&&B.total>0){let q=document.createElement("div");q.className="bp-plan-microbar";let he=document.createElement("div");he.className="bp-plan-microbar-fill";let oe=Math.max(0,Math.min(100,Math.round((B.routed??0)/B.total*100)));he.style.width=`${oe}%`,q.appendChild(he),ie.appendChild(q)}if(B.problem_text){let q=document.createElement("div");q.className="bp-plan-problem",q.textContent=B.problem_text,ie.appendChild(q)}ie.addEventListener("click",()=>{this.planSelectedId=B.id,n("plan.focus",{id:B.id}),this.render()}),le.appendChild(ie)}}if(this.planViewMode!=="list"){if(!this.planCanvas)this.planCanvas=new An({onSelect:(B)=>{if(this.planSelectedId=B,!B)this.planNoteOpen=!1;this.render()},onFocusItem:(B)=>{n("plan.focus",{id:B})},onDragEnd:()=>{if(this.planRenderDeferred)this.planRenderDeferred=!1,this.render()},onCommitFields:(B,K)=>{(this.planCommitFields??ue)(B,K)},onApproveLayer:(B,K)=>{n("plan.approve",{layer:B,ids:[],approve:K})},onQuickApprove:(B,K)=>{n("plan.approve",{layer:"",ids:B,approve:K})}});let k=this.panelEl.parentElement?.classList.contains("bp-has-viewer")===!1,x=this.planExpanded||this.panelEl.clientWidth>=540||k;this.planCanvas.update({gridMode:this.planGridMode,syncZoom:this.planSyncZoom,shownLayers:R,selectedId:this.planSelectedId,board:re,bands:be,regions:Pe,layers:ae,copperLayers:t.copper_layers},x);let H=document.createElement("div");H.className="bp-plan-canvas-scroll",H.appendChild(this.planCanvas.root),e.appendChild(H)}if(this.planViewMode!=="canvas")e.appendChild(le);if((t.draw?.bands?.length??0)>0||(t.draw?.regions?.length??0)>0){let k=document.createElement("div");k.className="bp-plan-footer",k.textContent=h("gpui.mgmt.plan.drawn","The plan's corridors and planes are drawn on the board while this panel is open. Close it to hide them."),e.appendChild(k)}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,S=this.project;this.fabStatus="",this.cb.hub.rpc("fab.profile",{pro:S,action:w,...C}).catch((T)=>{if(A!==this.watchGen||S!==this.project)return;this.fabStatus=T instanceof Error?T.message:"Fab action failed",this.render()})},i=document.createElement("div");i.className="bp-mgmt-head";let s=document.createElement("span");s.className="bp-mgmt-strong",s.textContent=h("gpui.mgmt.fab.thefab","The fab");let 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=h("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,p=document.createElement("div");p.className="bp-mgmt-row";let l=document.createElement("div");l.className="bp-mgmt-row-line";let u=document.createElement("span"),d=(c?.counts?.error??0)>0;if(u.className="bp-mgmt-flex1 "+(d?"bp-tone-bad":"bp-dim"),u.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(u),c?.at!=null){let w=document.createElement("button");w.type="button",w.className="bp-mgmt-btn",w.textContent=h("gpui.mgmt.fab.findings","Findings"),w.addEventListener("click",()=>this.togglePanel("checks")),l.appendChild(w)}if(!c?.running){let w=document.createElement("button");w.type="button",w.className="bp-mgmt-btn",w.textContent=h("gpui.mgmt.fab.reviewbtn","Review"),w.addEventListener("click",()=>n("review")),l.appendChild(w)}if(c?.judge){let w=document.createElement("button");w.type="button",w.className="bp-mgmt-btn",w.textContent=h("gpui.mgmt.fab.judge","Datasheets"),w.addEventListener("click",()=>{if(c.judge)this.cb.onSendText(c.judge)}),l.appendChild(w)}p.appendChild(l),o.appendChild(p);let m=Gi(t.drc?.state??""),f=document.createElement("div");f.className="bp-mgmt-row";let b=document.createElement("div");b.className="bp-mgmt-row-line";let g=document.createElement("span");if(g.className="bp-mgmt-flex1 "+(m.button?"bp-tone-warn":"bp-dim"),g.textContent=m.text,b.appendChild(g),m.button){let w=document.createElement("button");w.type="button",w.className="bp-mgmt-btn",w.textContent=m.button,w.addEventListener("click",()=>n("drc")),b.appendChild(w)}f.appendChild(b),o.appendChild(f);for(let w of t.conflicts??[]){let 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 S=document.createElement("span");S.className="bp-mgmt-flex1 bp-tone-warn",S.textContent=`${w.label||w.key}: board ${w.project??"?"} mm, fab ${w.fab??"?"} mm`;let T=document.createElement("button");T.type="button",T.className="bp-mgmt-btn",T.textContent=h("gpui.mgmt.fab.apply","Apply"),T.addEventListener("click",()=>n("apply",{key:w.key})),A.append(S,T),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",S=document.createElement("span");if(S.className="bp-mgmt-flex1 "+(A?"bp-tone-warn":"bp-dim"),S.textContent=`${A?"Proposed: ":""}${t.stackup.chosen}${t.stackup.outer_50_mm?` (50Ω ${t.stackup.outer_50_mm} mm)`:""}`,C.appendChild(S),A){let T=t.stackup.chosen,I=document.createElement("button");I.type="button",I.className="bp-mgmt-btn",I.textContent=h("gpui.mgmt.fab.use","Use"),I.addEventListener("click",()=>n("stackup",{id:T})),C.appendChild(I)}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=h("gpui.mgmt.fab.changed","Changed since you last looked");let S=document.createElement("button");S.type="button",S.className="bp-mgmt-btn",S.textContent=h("gpui.mgmt.fab.seen","Seen"),S.addEventListener("click",()=>n("seen")),C.append(A,S),w.appendChild(C);for(let T of t.changed.slice(0,12)){let I=document.createElement("div");I.className="bp-mgmt-faint",I.textContent=T,w.appendChild(I)}o.appendChild(w)}let y=Array.isArray(t.limits)?t.limits:[];if(y.length>0){let w=document.createElement("div");w.className="bp-mgmt-group-head";let C=document.createElement("span");C.className="bp-mgmt-flex1",C.textContent=h("gpui.mgmt.fab.limit","Limit");let A=document.createElement("span");A.className="bp-mgmt-col",A.textContent=h("gpui.mgmt.fab.free","Base price");let S=document.createElement("span");S.className="bp-mgmt-col",S.textContent=h("gpui.mgmt.fab.extra","Costs more");let T=document.createElement("span");T.className="bp-mgmt-col bp-mgmt-col-read",T.textContent=h("gpui.mgmt.fab.readcol","Read"),w.append(C,A,S,T),o.appendChild(w);for(let P of y){let j=document.createElement("div");j.className="bp-mgmt-row";let G=document.createElement("div");G.className="bp-mgmt-row-line";let L=document.createElement("span");L.className="bp-mgmt-flex1"+(P.changed?" bp-tone-warn":P.inherited?" bp-dim":""),L.textContent=`${P.changed?"• ":""}${P.label??""}`;let Y=document.createElement("span");Y.className="bp-mgmt-col",Y.textContent=P.free?.text||"—";let re=document.createElement("span");re.className="bp-mgmt-col bp-dim",re.textContent=P.extra?.text||"—";let se=P.free&&typeof P.free==="object"?P.free:P.extra,be=se?.fetched??"",Pe=Boolean(be)&&se?.confidence!=="published",Ee=be?Pe?`${be}*`:be:"—",ee=se?.source??"",ae;if(ee.startsWith("https://")&&be){let R=document.createElement("a");R.className="bp-mgmt-col bp-mgmt-col-read bp-mgmt-read-link",R.href=ee,R.target="_blank",R.rel="noopener noreferrer",R.textContent=Ee,ae=R}else{let R=document.createElement("span");R.className="bp-mgmt-col bp-mgmt-col-read bp-mgmt-faint",R.textContent=Ee,ae=R}G.append(L,Y,re,ae),j.appendChild(G),o.appendChild(j)}let I=document.createElement("div");I.className="bp-mgmt-note bp-mgmt-faint",I.textContent=h("gpui.mgmt.fab.derived","* worked out from the fab's page. Dimmed: the rigid board's value. A date opens the source page."),o.appendChild(I)}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 Lr={trs:(e)=>e,t:(e,t)=>t},Nr=new Set(["/settle"]);function is(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 rs(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 as(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 os(e,t=Lr){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=Nr.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:p}=ss(o);s.push({label:o.title||"Untitled thread",place:o.project?r.get(o.project)??"":"",kind:"thread",urgency:c,want:p,dotClass:rs(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 ls(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 f of i)d.set(f.id,f.title||f.id);let m=new Set;for(let f of c)if(f.action.type==="thread")m.add(f.action.id);for(let f of n.threads){if(!f.id||m.has(f.id))continue;m.add(f.id);let{urgency:b,want:g}=ss(f);c.push({label:f.title||"Untitled thread",place:f.project?d.get(f.project)??"":"",kind:"thread",urgency:b,want:g,dotClass:rs(f),action:{type:"thread",id:f.id}})}}let p=[];for(let d=0;d0)p.push({score:g,index:d,item:m})}p.sort((d,m)=>{if(o){let g=(m.item.urgency??0)-(d.item.urgency??0);if(g!==0)return g}if(m.score!==d.score)return m.score-d.score;let f=d.item.kind==="thread"?0:1,b=m.item.kind==="thread"?0:1;if(f!==b)return f-b;return d.index-m.index});let l=new Set,u=[];for(let d of p){let m=`${d.item.label}\x00${d.item.place}\x00${d.item.kind}`;if(l.has(m))continue;if(l.add(m),u.push(d.item),u.length>=s)break}if(n?.messages&&n.messages.length>0&&u.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=os(t,{t:h,trs:pe}),i=this.query.trim()===this.searchHitsQuery?this.searchHits:null;if(this.listed=ls(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=h("gpui.nothing.matches","Nothing matches"),this.listEl.replaceChildren(a);return}let s=document.createDocumentFragment(),r=null;for(let a=0;a0)p.appendChild(document.createTextNode(o.label.slice(0,d)));let f=document.createElement("strong");if(f.className="bp-palette-mark",f.textContent=o.label.slice(d,m),p.appendChild(f),m{if(this.activeIdx!==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 Br=new Set(["resume","raise","retry","move","signin"]);function Bn(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 sn(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(Br.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 us(e){let t=e&&typeof e==="object"?e.open:void 0;if(typeof t!=="string")return null;let n=t.indexOf(":"),i=n<0?"":t.slice(n+1);if(!i)return null;if(t.startsWith("account:"))return{kind:"account",id:i};if(t.startsWith("thread:"))return{kind:"thread",id:i};return null}var Rn=[{id:"general",label:"General"},{id:"ai",label:"Agents and tools"},{id:"connect",label:"Connect"}],xt=[{id:"appearance",group:"general",title:"Appearance",subtitle:"Kept in this browser only. Never sent to the hub.",icon:"sun",keywords:["theme","dark","light","auto","color","language","locale","english","espanol","japanese"]},{id:"providers",group:"ai",title:"AI providers",subtitle:"Account sign-ins live in the desktop or mobile app.",icon:"cpu",keywords:["accounts","claude","codex","antigravity","grok","openai","anthropic","signin","login","model"]},{id:"devices",group:"connect",title:"Devices & browser",subtitle:"This browser session and paired devices on this hub.",icon:"link",keywords:["sign out","logout","session","cookie","revoke","paired","phone","browser","pair"]},{id:"home",group:"connect",title:"Home machine",subtitle:"Which machine hosts your always-on hub and bots.",icon:"globe",keywords:["host","boat","move","online","away","queued","linked"]}];function ms(e){if(e==="dark"||e==="light"||e==="auto")return e;return"auto"}function hs(e){if(e==="en"||e==="es"||e==="ja"||e==="auto")return e;return"auto"}function Ht(e,t){if(e==="dark"||e==="light")return e;return t==="light"?"light":"dark"}function bs(e){return e.trim().toLowerCase().split(/\s+/).filter(Boolean)}function In(e,t){if(t.length===0)return!0;let n=e.toLowerCase();return t.every((i)=>n.includes(i))}function gs(e,t){let n=bs(t);if(n.length===0)return[];return e.filter((i)=>{let s=[i.groupLabel,i.pageTitle,i.rowTitle,i.rowDetail,...i.keywords??[]].join(" ");return In(s,n)})}function jn(e,t,n){let i=bs(n);if(i.length===0)return e.map((a)=>({page:a,hits:[]}));let s=new Map(Rn.map((a)=>[a.id,a.label])),r=[];for(let a of e){let c=t.filter((l)=>l.pageId===a.id).filter((l)=>In([l.rowTitle,l.rowDetail,l.pageTitle,l.groupLabel,...l.keywords??[]].join(" "),i));if(In([s.get(a.group)??"",a.title,a.subtitle,...a.keywords].join(" "),i)||c.length>0){let l=[];for(let u of c){if(!l.includes(u.rowTitle))l.push(u.rowTitle);if(l.length>=2)break}r.push({page:a,hits:l})}}return r}function Ir(e){let n=document.createElementNS("http://www.w3.org/2000/svg","svg");n.setAttribute("viewBox","0 0 24 24"),n.setAttribute("width","15"),n.setAttribute("height","15"),n.setAttribute("fill","none"),n.setAttribute("stroke","currentColor"),n.setAttribute("stroke-width","1.75"),n.setAttribute("stroke-linecap","square"),n.setAttribute("stroke-linejoin","miter"),n.setAttribute("aria-hidden","true");let i=(s,r)=>{let a=document.createElementNS("http://www.w3.org/2000/svg",s);for(let[o,c]of Object.entries(r))a.setAttribute(o,c);n.appendChild(a)};switch(e){case"sun":i("circle",{cx:"12",cy:"12",r:"4"}),i("path",{d:"M12 2v2m0 16v2M4.93 4.93l1.41 1.41m11.32 11.32 1.41 1.41M2 12h2m16 0h2M4.93 19.07l1.41-1.41m11.32-11.32 1.41-1.41"});break;case"cpu":i("rect",{x:"5",y:"5",width:"14",height:"14"}),i("rect",{x:"9",y:"9",width:"6",height:"6"}),i("path",{d:"M9 2v3m6-3v3M9 19v3m6-3v3M2 9h3m-3 6h3M19 9h3m-3 6h3"});break;case"link":i("path",{d:"M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"}),i("path",{d:"M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"});break;case"globe":i("circle",{cx:"12",cy:"12",r:"10"}),i("path",{d:"M2 12h20M12 2a15.3 15.3 0 0 1 4 10 15.3 15.3 0 0 1-4 10 15.3 15.3 0 0 1-4-10 15.3 15.3 0 0 1 4-10z"});break}return n}function Rr(){let t=document.createElementNS("http://www.w3.org/2000/svg","svg");t.setAttribute("viewBox","0 0 24 24"),t.setAttribute("width","13"),t.setAttribute("height","13"),t.setAttribute("fill","none"),t.setAttribute("stroke","currentColor"),t.setAttribute("stroke-width","1.75"),t.setAttribute("aria-hidden","true");let n=document.createElementNS("http://www.w3.org/2000/svg","circle");n.setAttribute("cx","11"),n.setAttribute("cy","11"),n.setAttribute("r","7");let i=document.createElementNS("http://www.w3.org/2000/svg","path");return i.setAttribute("d","m20 20-3.5-3.5"),t.append(n,i),t}function rn(e,t){switch(e){case"general":return h("gpui.settings.group.general",t);case"ai":return h("gpui.settings.group.agents",t);case"connect":return h("native.pair.connect",t)}}function mt(e,t){switch(e){case"appearance":return h("settings.appearance",t);case"providers":return h("web.settings.providers",t);case"devices":return t;case"home":return h("home.machine",t)}}class Dn{backdrop;titleEl;badgeEl;closeBtn;navListEl;searchInput;searchClearBtn;paneEl;cb;openState=!1;activePage="appearance";forceProviders=!1;query="";searchBrowseAll=!1;devicesLoaded=!1;devicesLoading=!1;devicesRows=[];devicesError="";loadGen=0;constructor(e,t){this.cb=t,this.backdrop=document.createElement("div"),this.backdrop.className="bp-modal-backdrop bp-hidden",this.backdrop.setAttribute("data-testid","settings-modal");let n=document.createElement("div");n.className="bp-modal bp-settings-modal",n.setAttribute("role","dialog"),n.setAttribute("aria-modal","true"),n.setAttribute("aria-labelledby","bp-settings-title");let i=document.createElement("div");i.className="bp-modal-head";let s=document.createElement("div");s.className="bp-settings-head-title",this.titleEl=document.createElement("h2"),this.titleEl.id="bp-settings-title",this.titleEl.textContent=h("palette.settings","Settings"),this.badgeEl=document.createElement("span"),this.badgeEl.className="bp-settings-badge",this.badgeEl.textContent="Browser",s.append(this.titleEl,this.badgeEl),this.closeBtn=document.createElement("button"),this.closeBtn.type="button",this.closeBtn.className="icon",this.closeBtn.textContent="×",this.closeBtn.setAttribute("aria-label",h("common.close","Close")),this.closeBtn.addEventListener("click",()=>this.close()),i.append(s,this.closeBtn);let r=document.createElement("div");r.className="bp-settings-body";let a=document.createElement("aside");a.className="bp-settings-nav";let o=document.createElement("div");o.className="bp-settings-search";let c=document.createElement("span");c.className="bp-settings-search-icon",c.appendChild(Rr()),this.searchInput=document.createElement("input"),this.searchInput.type="text",this.searchInput.className="bp-settings-search-input",this.searchInput.placeholder="Search settings…",this.searchInput.setAttribute("aria-label","Search settings"),this.searchInput.setAttribute("data-testid","settings-search"),this.searchClearBtn=document.createElement("button"),this.searchClearBtn.type="button",this.searchClearBtn.className="bp-settings-search-clear bp-hidden",this.searchClearBtn.textContent="×",this.searchClearBtn.title="Clear search",this.searchClearBtn.setAttribute("aria-label","Clear search"),o.append(c,this.searchInput,this.searchClearBtn),this.navListEl=document.createElement("nav"),this.navListEl.className="bp-settings-nav-list",this.navListEl.setAttribute("aria-label","Settings sections"),a.append(o,this.navListEl),this.paneEl=document.createElement("div"),this.paneEl.className="bp-settings-pane",r.append(a,this.paneEl),n.append(i,r),this.backdrop.appendChild(n),this.backdrop.addEventListener("click",(p)=>{if(p.target===this.backdrop)this.close()}),this.searchInput.addEventListener("input",()=>{this.query=this.searchInput.value,this.searchBrowseAll=this.query.trim().length>0,this.syncSearchClear(),this.render()}),this.searchInput.addEventListener("keydown",(p)=>{if(p.key==="Enter"){let l=jn(xt,this.buildSearchItems(),this.query);if(l.length>0)p.preventDefault(),this.activePage=l[0].page.id,this.searchBrowseAll=!1,this.render()}else if(p.key==="Escape"&&this.query.trim().length>0)p.preventDefault(),p.stopPropagation(),this.clearSearch()}),this.searchClearBtn.addEventListener("click",()=>{this.clearSearch(),this.searchInput.focus()}),e.appendChild(this.backdrop)}isOpen(){return this.openState}handleEscape(){if(!this.openState)return;if(this.query.trim().length>0)this.clearSearch(),this.searchInput.focus();else this.close()}async open(e){if(this.openState=!0,e)this.activePage=e;this.backdrop.classList.remove("bp-hidden"),this.render(),this.loadDevices(),window.setTimeout(()=>{if(this.openState)this.searchInput.focus()},0)}async openToAccounts(){this.forceProviders=!0,this.query="",this.searchInput.value="",this.searchBrowseAll=!1,this.syncSearchClear(),await this.open("providers")}close(){this.openState=!1,this.forceProviders=!1,this.query="",this.searchInput.value="",this.searchBrowseAll=!1,this.syncSearchClear(),this.backdrop.classList.add("bp-hidden")}refreshLocale(){if(this.titleEl.textContent=h("palette.settings","Settings"),this.closeBtn.setAttribute("aria-label",h("common.close","Close")),this.openState)this.render()}async refresh(){if(!this.openState)return;this.render(),await this.loadDevices()}clearSearch(){this.query="",this.searchInput.value="",this.searchBrowseAll=!1,this.syncSearchClear(),this.render()}syncSearchClear(){this.searchClearBtn.classList.toggle("bp-hidden",this.query.length===0)}async loadDevices(){let e=++this.loadGen;if(this.devicesLoading=!this.devicesLoaded,this.devicesLoading&&this.openState)this.renderPane();try{let t=await this.cb.onLoadDevices();if(e!==this.loadGen)return;this.devicesRows=t,this.devicesError="",this.devicesLoaded=!0}catch(t){if(e!==this.loadGen)return;let n=t instanceof Error&&t.message?t.message:"Not available from a browser";this.devicesError=`${n} — manage paired devices in Backplane › Settings › Devices on desktop or a paired phone.`,this.devicesRows=[],this.devicesLoaded=!0}finally{if(e===this.loadGen){if(this.devicesLoading=!1,this.openState)this.render()}}}buildSearchItems(){let e=this.cb.onGetHome?.()??null,t=this.cb.onGetNoProvider?.()??null,n=rn("general","General"),i=rn("ai","Agents and tools"),s=rn("connect","Connect"),r=mt("appearance","Appearance"),a=mt("providers","AI providers"),o=mt("devices","Devices & browser"),c=mt("home","Home machine"),p=[{pageId:"appearance",pageTitle:r,groupLabel:n,rowTitle:h("settings.theme","Theme"),rowDetail:"Auto (follow hub), Dark, or Light in this browser.",keywords:["theme","dark","light","auto","appearance","colors"]},{pageId:"appearance",pageTitle:r,groupLabel:n,rowTitle:h("settings.lang","Language"),rowDetail:"Interface language for this browser.",keywords:["locale","english","espanol","japanese","language"]},{pageId:"providers",pageTitle:a,groupLabel:i,rowTitle:t?pe(t.head):"Provider connections",rowDetail:"Connect Claude, Codex, Antigravity, or other AI providers in Settings → Accounts.",keywords:["accounts","claude","codex","antigravity","grok","openai","signin"]},{pageId:"devices",pageTitle:o,groupLabel:s,rowTitle:"This browser",rowDetail:"Sign out and revoke this browser's session cookie.",keywords:["logout","sign out","session","cookie"]},{pageId:"devices",pageTitle:o,groupLabel:s,rowTitle:"Paired devices",rowDetail:this.devicesRows.map((l)=>`${l.title||l.head||""} ${l.detail||l.text||""}`).join(" ")||"Paired phones and browsers on this hub.",keywords:["phone","pair","revoke","browser"]},{pageId:"home",pageTitle:c,groupLabel:s,rowTitle:e?.name?`${e.name}`:c,rowDetail:"Which machine hosts your always-on hub and bots.",keywords:["boat","move","online","away","queued","machine"]}];for(let l of this.devicesRows){let u=l.title||l.head||"";if(u)p.push({pageId:"devices",pageTitle:o,groupLabel:s,rowTitle:u,rowDetail:l.detail||l.text||"",keywords:["paired","device"]})}return p}render(){this.renderNav(),this.renderPane()}renderNav(){let e=document.createDocumentFragment(),t=jn(xt,this.buildSearchItems(),this.query),n=this.cb.onGetNoProvider?.()??null,i=this.cb.onGetHome?.()??null;if(t.length===0){let r=document.createElement("div");r.className="bp-settings-nav-empty",r.setAttribute("data-testid","settings-nav-empty"),r.textContent="No matching settings",e.appendChild(r),this.navListEl.replaceChildren(e);return}let s="";for(let r of t){let a=r.page;if(a.group!==s){s=a.group;let d=Rn.find((m)=>m.id===a.group);if(d){let m=document.createElement("div");m.className="bp-settings-group",m.textContent=rn(d.id,d.label),e.appendChild(m)}}let o=document.createElement("button");o.type="button";let c=!this.searchBrowseAll&&a.id===this.activePage;o.className="bp-settings-nav-item"+(c?" active":""),o.setAttribute("data-testid",`settings-nav-${a.id}`);let p=document.createElement("div");p.className="bp-settings-nav-row";let l=document.createElement("span");l.className="bp-settings-nav-icon",l.appendChild(Ir(a.icon));let u=document.createElement("span");if(u.className="bp-settings-nav-label",u.textContent=mt(a.id,a.title),p.append(l,u),a.id==="providers"&&(n||this.forceProviders)){let d=document.createElement("span");d.className="bp-settings-nav-dot warn",d.title="Action needed",p.appendChild(d)}else if(a.id==="home"&&i){let d=document.createElement("span");d.className="bp-settings-nav-dot "+(i.moving?.state==="failed"?"bad":i.online?"ok":"warn"),p.appendChild(d)}if(o.appendChild(p),r.hits.length>0)for(let d of r.hits){let m=document.createElement("div");m.className="bp-settings-hit",m.textContent=d,o.appendChild(m)}o.addEventListener("click",()=>{this.activePage=a.id,this.searchBrowseAll=!1,this.render()}),e.appendChild(o)}this.navListEl.replaceChildren(e)}renderPane(){let e=document.createDocumentFragment(),t=this.query.trim();if(t&&this.searchBrowseAll){this.renderSearchResults(e,t),this.paneEl.replaceChildren(e);return}let n=xt.find((a)=>a.id===this.activePage)??xt[0],i=document.createElement("div");i.className="bp-settings-pane-head";let s=document.createElement("h3");s.textContent=mt(n.id,n.title);let r=document.createElement("div");switch(r.className="bp-settings-pane-sub",r.textContent=n.subtitle,i.append(s,r),e.appendChild(i),n.id){case"appearance":this.renderAppearancePage(e);break;case"providers":this.renderProvidersPage(e);break;case"devices":this.renderDevicesPage(e);break;case"home":this.renderHomePage(e);break}this.paneEl.replaceChildren(e)}renderSearchResults(e,t){let n=gs(this.buildSearchItems(),t),i=document.createElement("div");i.className="bp-settings-pane-head";let s=document.createElement("h3");s.textContent="Search results";let r=document.createElement("div");if(r.className="bp-settings-pane-sub",r.textContent=n.length===0?`No settings match "${t}".`:`${n.length} matching ${n.length===1?"setting":"settings"} for "${t}"`,i.append(s,r),e.appendChild(i),n.length===0){let o=document.createElement("div");o.className="bp-settings-empty",o.textContent="Try searching for theme, language, providers, sign out, devices, or home.",e.appendChild(o);return}let a=Array.from(new Set(n.map((o)=>o.pageId)));for(let o of a){let c=xt.find((m)=>m.id===o);if(!c)continue;let p=document.createElement("div");p.className="bp-settings-search-sec";let l=document.createElement("div");l.className="bp-settings-subhead",l.textContent=mt(c.id,c.title);let u=document.createElement("button");u.type="button",u.className="bp-settings-search-open",u.textContent="Open page ›",u.addEventListener("click",()=>{this.activePage=o,this.searchBrowseAll=!1,this.render()}),p.append(l,u),e.appendChild(p);let d=new Set(n.filter((m)=>m.pageId===o).map((m)=>m.rowTitle));if(o==="appearance")this.renderAppearancePage(e,d);else if(o==="providers")this.renderProvidersPage(e);else if(o==="devices")this.renderDevicesPage(e,d);else if(o==="home")this.renderHomePage(e)}}renderAppearancePage(e,t){let n=this.cb.onGetThemePref?.()??"auto",i=this.cb.onGetHubTheme?.()??"dark",s=Ht(n,i),r=this.cb.onGetLocalePref?.()??"auto",a=h("settings.theme","Theme"),o=h("settings.lang","Language");if(!t||t.has(a)){let c=h("settings.theme.dark","Dark"),p=h("settings.theme.light","Light"),l=n==="auto"?`Following hub theme (${i==="light"?p:c}). Stored in this browser only.`:`Using ${s==="light"?p:c} in this browser. Select Auto to follow the hub.`;e.appendChild(this.makeSegmentedRow(a,l,[{value:"auto",label:"Auto"},{value:"dark",label:c},{value:"light",label:p}],n,"settings-theme",(u)=>{this.cb.onSetThemePref?.(u),this.render()}))}if(!t||t.has(o))e.appendChild(this.makeSegmentedRow(o,"Interface language for this browser. Automatic follows the hub or browser language.",[{value:"auto",label:h("settings.lang.auto","Automatic")},{value:"en",label:h("settings.lang.en","English")},{value:"es",label:h("settings.lang.es","Español")},{value:"ja",label:h("settings.lang.ja","日本語")}],r,"settings-locale",(c)=>{this.cb.onSetLocalePref?.(c),this.render()}))}makeSegmentedRow(e,t,n,i,s,r){let a=document.createElement("div");a.className="bp-settings-row";let o=document.createElement("div");o.className="bp-settings-row-info";let c=document.createElement("div");c.className="bp-settings-row-title",c.textContent=e;let p=document.createElement("div");p.className="bp-settings-row-detail",p.textContent=t,o.append(c,p);let l=document.createElement("div");l.className="bp-chip-group",l.setAttribute("role","group"),l.setAttribute("aria-label",e);for(let u of n){let d=document.createElement("button");d.type="button";let m=u.value===i;d.className="bp-chip"+(m?" active":""),d.textContent=u.label,d.setAttribute("aria-pressed",m?"true":"false"),d.setAttribute("data-testid",`${s}-${u.value}`),d.addEventListener("click",()=>r(u.value)),l.appendChild(d)}return a.append(o,l),a}renderProvidersPage(e){let t=this.cb.onGetNoProvider?.()??null,n=document.createElement("section");if(n.className="bp-settings-section",n.setAttribute("data-testid","settings-providers"),t||this.forceProviders){let i=document.createElement("div");i.className="bp-settings-notice warn";let s=document.createElement("div");s.className="bp-settings-row-info";let r=document.createElement("div");r.className="bp-settings-row-title",r.textContent=t?pe(t.head):h("provider.notice.head","No AI provider connected");let a=document.createElement("div");a.className="bp-settings-row-detail",a.textContent=h("web.settings.providers.browser","Connect a provider in the Backplane desktop or mobile app under Settings → Accounts."),s.append(r,a);let o=document.createElement("div");o.className="bp-set-btns";let c=document.createElement("a");c.className="bp-link-btn primary",c.href=t?.url||"backplane://settings/accounts",c.setAttribute("data-testid","settings-open-accounts"),c.textContent=t?pe(t.button):h("provider.notice.button","Open Settings → Accounts"),o.appendChild(c),i.append(s,o),n.appendChild(i)}else{let i=document.createElement("div");i.className="bp-settings-row";let s=document.createElement("div");s.className="bp-settings-row-info";let r=document.createElement("div");r.className="bp-settings-row-title-wrap";let a=document.createElement("span");a.className="bp-settings-row-title",a.textContent="Provider connections";let o=document.createElement("span");o.className="bp-status-pill ok",o.textContent=h("gpui.acct.connected","Connected"),r.append(a,o);let c=document.createElement("div");c.className="bp-settings-row-detail",c.textContent="Provider sign-ins, fallback order, API keys, and usage limits are managed in the Backplane desktop or mobile app.",s.append(r,c);let p=document.createElement("div");p.className="bp-set-btns";let l=document.createElement("a");l.className="bp-link-btn",l.href="backplane://settings/accounts",l.setAttribute("data-testid","settings-open-accounts"),l.textContent=h("provider.notice.button","Open Settings → Accounts"),p.appendChild(l),i.append(s,p),n.appendChild(i)}e.appendChild(n)}renderDevicesPage(e,t){let n=!t||t.has("This browser"),i=!t||t.has("Paired devices")||this.devicesRows.some((a)=>t.has(a.title||a.head||""));if(n){let a=document.createElement("div");a.className="bp-settings-subhead",a.textContent="This browser",e.appendChild(a);let o=document.createElement("div");o.className="bp-settings-row";let c=document.createElement("div");c.className="bp-settings-row-info";let p=document.createElement("div");p.className="bp-settings-row-title",p.textContent="Browser session";let l=document.createElement("div");l.className="bp-settings-row-detail",l.textContent="Sign out and revoke this browser's session cookie.",c.append(p,l);let u=document.createElement("button");u.type="button",u.className="primary stop",u.textContent=h("agy.signout","Sign out"),u.setAttribute("data-testid","logout-btn"),u.addEventListener("click",()=>{u.disabled=!0,this.cb.onLogout().catch(()=>{l.setAttribute("role","alert"),l.className="bp-settings-row-detail bp-bad",l.textContent=h("web.logout.failed","Could not confirm sign-out. Try again."),u.disabled=!1})}),o.append(c,u),e.appendChild(o)}if(!i)return;let s=document.createElement("div");if(s.className="bp-settings-subhead",s.textContent="Paired devices",e.appendChild(s),this.devicesLoading){let a=document.createElement("div");a.className="bp-settings-empty",a.textContent="Loading paired devices…",e.appendChild(a);return}if(this.devicesError){let a=document.createElement("div");a.className="bp-settings-notice bad";let o=document.createElement("div");o.className="bp-settings-row-detail",o.textContent=this.devicesError,a.appendChild(o),e.appendChild(a);return}let r=!t||t.has("Paired devices")?this.devicesRows:this.devicesRows.filter((a)=>t.has(a.title||a.head||""));if(r.length===0){let a=document.createElement("div");a.className="bp-settings-empty",a.textContent="No paired devices listed.",e.appendChild(a)}else for(let a of r){let o=document.createElement("div");o.className="bp-settings-row";let c=document.createElement("div");c.className="bp-settings-row-info";let p=document.createElement("div");p.className="bp-settings-row-title-wrap";let l=document.createElement("span");l.className="bp-settings-row-title",l.textContent=a.title||a.head||"",p.appendChild(l);let u=a.detail||a.text||"";if(u){let d=document.createElement("span"),m=u.toLowerCase();d.className="bp-status-pill "+(m.includes("this browser")?"accent":"neutral"),d.textContent=u,p.appendChild(d)}if(c.appendChild(p),o.appendChild(c),a.buttons?.length){let d=document.createElement("div");d.className="bp-set-btns";for(let m of a.buttons){let f=document.createElement("button");if(f.type="button",m.primary)f.className="primary";if(m.danger)f.className="primary stop";f.textContent=m.label||h("common.remove","Remove"),f.addEventListener("click",()=>{f.disabled=!0,this.cb.onDevicesAct(m.action,m.value).finally(()=>{this.refresh()})}),d.appendChild(f)}o.appendChild(d)}e.appendChild(o)}if(!t){let a=document.createElement("div");a.className="bp-settings-footnote",a.textContent="Pair new browsers or phones, configure Tailscale HTTPS forwarding, or revoke access in desktop or mobile Settings → Devices.",e.appendChild(a)}}renderHomePage(e){let t=this.cb.onGetHome?.()??null,n=document.createElement("section");if(n.className="bp-settings-section",n.setAttribute("data-testid","settings-home"),!t){let d=document.createElement("div");d.className="bp-settings-empty",d.textContent="Single-hub mode — this hub is running locally without linked home machines.",n.appendChild(d),e.appendChild(n);return}let i=document.createElement("div");i.className="bp-settings-row";let s=document.createElement("div");s.className="bp-settings-row-info";let r=document.createElement("div");r.className="bp-settings-row-title-wrap";let a=document.createElement("span");a.className="bp-settings-row-title",a.textContent=t.name||(t.kind==="boat"?"Boat":"This machine"),r.appendChild(a);let o=document.createElement("span");o.className="bp-status-pill neutral",o.textContent=t.kind==="local"?"This machine":t.kind==="boat"?"Boat":"Linked machine",r.appendChild(o);let c=document.createElement("span"),p="Online",l="ok";if(t.moving?.state==="moving")p="Moving",l="accent";else if(t.moving?.state==="failed")p="Move failed",l="bad";else if(!t.online)p="Away",l="warn";c.className=`bp-status-pill ${l}`,c.textContent=p,r.appendChild(c);let u=document.createElement("div");if(u.className="bp-settings-row-detail",t.moving?.state==="moving")u.textContent=t.moving.step?h("home.moving.step","Moving home to {to}: {step}").replace("{to}",t.moving.to).replace("{step}",t.moving.step):h("home.moving","Moving home to {to}…").replace("{to}",t.moving.to);else if(t.moving?.state==="failed")u.textContent=t.moving.note?h("home.move.failed.note","Home move failed: {note}").replace("{note}",t.moving.note):h("home.move.failed","Home move failed");else if(!t.online)u.textContent=t.queuedCount>0?h("home.away.queued","Home ({name}) is away · {n} queued").replace("{name}",t.name||"home").replace("{n}",String(t.queuedCount)):h("home.away","Home ({name}) is away").replace("{name}",t.name||"home");else u.textContent="Your active home hub is online and serving threads and bots.";if(s.append(r,u),i.appendChild(s),t.canMoveHere&&this.cb.onMoveHomeHere){let d=document.createElement("button");d.type="button",d.className="primary",d.textContent=h("home.move.here","Make this machine the home"),d.setAttribute("data-testid","home-move-here-btn"),d.addEventListener("click",()=>{d.disabled=!0,this.cb.onMoveHomeHere?.().finally(()=>{this.refresh()})}),i.appendChild(d)}n.appendChild(i),e.appendChild(n)}}function xe(e,t,n){let i=document.createElement(e);if(t)i.className=t;if(n)i.textContent=n;return i}function Ft(e,t,n=!1){let i=xe("button",n?"primary":"bp-btn-ghost",e);return i.type="button",i.addEventListener("click",t),i}function Hn(e){return xe("pre","bp-context-code",e)}function jr(e){return xe("span",`bp-context-badge ${e==="Native"||e==="Enabled"?"active":e==="Untrusted"||e==="Invalid"?"warn":""}`,pe(e))}function an(e,t){let n=xe("div","bp-context-row");return n.append(xe("strong",void 0,e),jr(t)),n}class Fn{fetchContext;dialog=xe("dialog","bp-context");title=xe("h2");cwd=xe("div","bp-context-path");tabs=xe("div","bp-context-tabs");body=xe("div","bp-context-body");notice=xe("p","bp-context-notice");current;thread="";requestId=0;tab=0;busy=!1;constructor(e,t){this.fetchContext=t;let n=xe("div","bp-context-head"),i=xe("div");i.append(this.title,this.cwd),this.title.id="bp-context-title",this.dialog.setAttribute("aria-labelledby",this.title.id),this.notice.setAttribute("role","status"),n.append(i,Ft(h("common.refresh","Refresh"),()=>{this.load()}),Ft(h("common.close","Close"),()=>this.dialog.close())),this.dialog.append(n,this.tabs,this.notice,this.body),this.dialog.addEventListener("close",()=>{this.requestId++}),e.append(this.dialog)}open(e){if(this.thread=e,this.tab=0,this.current=void 0,this.busy=!1,this.title.textContent=h("thread.context.title","Context & Prompt"),this.cwd.textContent="",!this.dialog.open)this.dialog.showModal();this.render(),this.load()}async load(e){if(this.busy)return;let t=++this.requestId;this.busy=!0,this.notice.textContent=h("thread.context.reading","Reading thread context…"),this.render();try{let n=await this.fetchContext(this.thread,e);if(t!==this.requestId)return;this.current=n,this.cwd.textContent=n.cwd,this.notice.textContent=""}catch(n){if(t===this.requestId)this.notice.textContent=String(n)}finally{if(t===this.requestId)this.busy=!1,this.render()}}render(){let e=[h("thread.context.instructions","Instructions"),h("thread.context.system","System Prompt"),h("thread.context.skills","Skills"),h("thread.context.mcp","Project MCPs")];this.tabs.replaceChildren(...e.map((n,i)=>{let s=Ft(n,()=>{this.tab=i,this.render(),this.body.scrollTop=0,this.tabs.children[i].focus()});return s.setAttribute("aria-pressed",String(i===this.tab)),s})),this.body.replaceChildren();let t=this.current;if(!t)return;switch(this.tab){case 0:this.instructions(t.instructions);break;case 1:this.prompt(t);break;case 2:this.skills(t.skills);break;case 3:this.mcps(t.mcp);break}}instructions(e){if(!e.length)this.body.append(xe("p","bp-dim",h("thread.context.none.instructions","No project instructions found.")));for(let t of e){let n=xe("details","bp-context-card"),i=xe("summary");if(i.append(an(t.path,t.status),xe("small","bp-dim",h("thread.context.size","{bytes} B · ≈{tokens} tokens",{bytes:t.bytes,tokens:t.estimated_tokens}))),n.append(i,Hn(t.preview)),t.note)n.append(xe("small","bp-dim",t.note));this.body.append(n)}}prompt(e){let t=xe("div","bp-context-row"),n=Ft(h("thread.context.copy","Copy prompt"),()=>{navigator.clipboard.writeText(e.prompt).then(()=>{this.notice.textContent=h("thread.context.copied","Prompt copied.")}).catch((i)=>{this.notice.textContent=String(i)})});t.append(xe("p","bp-dim",h("thread.context.native.note","Backplane’s launch prompt. Native files are loaded by the provider.")),n),this.body.append(t);for(let[i,s]of[[h("thread.context.base","Backplane"),e.sections.base],[h("thread.context.injected.label","Injected project instructions"),e.sections.instructions],[h("thread.context.index","Available skills index"),e.sections.skills]])if(s)this.body.append(xe("h3",void 0,i),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(xe("h3",void 0,pe(t)));for(let i of n){let s=xe("article","bp-context-card");s.append(an(i.name,i.status),xe("p",void 0,i.description),xe("small","bp-context-path",[i.source,i.provider,i.model].filter(Boolean).join(" · ")),xe("small","bp-context-path",i.path)),this.body.append(s)}}}mcps(e){if(!e.length)this.body.append(xe("p","bp-dim",h("thread.context.none.mcp","No project MCP configurations found.")));for(let t of e){let n=xe("article","bp-context-card");n.append(an(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(an(s.name,s.status),Hn(r)),s.cwd)n.append(xe("small","bp-context-path",s.cwd))}if(t.error)n.append(xe("p","bp-warn",t.error));let i=t.state==="Untrusted"?"trust":t.state==="Enabled"?"disable":t.state==="Disabled"?"enable":"";if(i){let s=i==="trust"?h("thread.context.trust","Trust and enable"):i==="disable"?h("thread.context.disable","Disable"):h("thread.context.enable","Enable"),r=Ft(s,()=>{this.load({action:i,path:t.path,sha256:t.sha256})},i==="trust");r.disabled=this.busy;let a=xe("div","bp-context-actions");a.append(r),n.append(a)}this.body.append(n)}}}function Dr(e,t){if(e.settled)return!1;if(e.state==="done"||e.state==="stopped")return!1;if(!t)return!0;let n=e.working??0,i=Boolean(e.monitoring),s=Boolean(Bn(e.need))||e.word==="needs";return(n>0||i)&&e.state!=="paused"||s}function Hr(e){if(e.wake)return{icon:"◷",label:"Snoozed",tone:"dim"};let t=(e.label??"").trim(),n=(e.tone??"").trim();if(t){let s=t.toLowerCase();return{icon:s==="approve"||s==="sign in"?"!":s==="input"?"?":s==="failed"||s==="stopped"?"×":s==="working"||s==="running"?"▸":s==="waiting"?"◌":s==="done"?"✓":"•",label:t,tone:n==="bad"?s==="failed"||s==="stopped"?"bad-out":"bad":n==="run"?"run":n==="wait"?"wait":n==="ok"?"ok":"dim"}}let i=e.word||"";if(i==="needs"){if(e.want==="approval")return{icon:"!",label:"Approve",tone:"bad"};if(e.want==="sign-in")return{icon:"!",label:"Sign in",tone:"bad"};return{icon:"?",label:"Input",tone:"bad"}}if(i==="failed"||e.status==="failed"||e.state==="fail")return{icon:"×",label:"Failed",tone:"bad-out"};if(i==="cut"||i==="interrupted")return{icon:"×",label:"Stopped",tone:"bad-out"};if(i==="running"||e.status==="active"||e.status==="working"||e.state==="run")return{icon:"▸",label:"Working",tone:"run"};if(i==="monitoring"||i==="limit"||e.status==="waiting")return{icon:"◌",label:"Waiting",tone:"wait"};if(i==="done"||e.status==="finished")return{icon:"✓",label:"Done",tone:"ok"};return null}var fs="http://www.w3.org/2000/svg";function ht(e,t=14,n=""){let i=document.createElementNS(fs,"svg");if(i.setAttribute("viewBox","0 0 24 24"),i.setAttribute("width",String(t)),i.setAttribute("height",String(t)),i.setAttribute("fill","none"),i.setAttribute("stroke","currentColor"),i.setAttribute("stroke-width","1.75"),i.setAttribute("stroke-linecap","square"),i.setAttribute("stroke-linejoin","miter"),i.setAttribute("aria-hidden","true"),n)i.classList.add(...n.split(" "));for(let s of e){let r=document.createElementNS(fs,"path");r.setAttribute("d",s),i.appendChild(r)}return i}function vs(){return ht(["M3 6h6l2 2h10v11H3z"],14,"bp-folder-icon")}function ys(e=14,t="bp-folder-icon bp-hw-icon"){return ht(["M3 3h18v18H3z","M9 3v6h6","M9 21v-6","M15 9a2 2 0 1 0 0-4 2 2 0 0 0 0 4z","M9 15a2 2 0 1 0 0-4 2 2 0 0 0 0 4z"],e,t)}function Fr(e=13){return ht(["M6 6h12v12H6z","M9 2v4","M15 2v4","M9 18v4","M15 18v4","M2 9h4","M2 15h4","M18 9h4","M18 15h4"],e)}function $r(e=15){return ht(["M4 10V4l4 3h8l4-3v6l-2 9H6z","M9 13h1","M14 13h1","M11 16h2"],e,"bp-cat-glyph")}function Gr(e=11){return ht(["M4 12l5 5 11-11"],e)}function Or(e=11){return ht(["M12 22a10 10 0 1 0 0-20 10 10 0 0 0 0 20z","M12 6v6l4 2"],e)}function Vr(e=11){return ht(["M12 17v5","M8 4h8l-1 5 3 3v2H6v-2l3-3z"],e,"bp-pin-icon")}function ws(e){if(!e)return"";let t=e<10000000000?e*1000:e,n=Math.max(0,Math.floor((Date.now()-t)/1000));if(n<60)return"now";if(n<3600)return`${Math.floor(n/60)}m`;if(n<86400)return`${Math.floor(n/3600)}h`;return`${Math.floor(n/86400)}d`}function Ur(e){let t=e.replace(/^@/,"").trim();if(!t)return"?";let n=t.split(/[\s_-]+/).filter(Boolean);if(n.length>=2)return(n[0][0]+n[1][0]).toUpperCase();return t.slice(0,2).toUpperCase()}function $n(e){if(e==="wait"||e==="error")return"bp-mood-wait";if(e==="work"||e==="talk")return"bp-mood-work";return"bp-mood-idle"}function et(e){let t=e.lastIndexOf("|");return t>=0?e.slice(t+1):e}class Gn{el;hostLabel;homeBanner;crewEl;filterInput;listEl;connEl;filterText="";allFilter="all";snoozeMenuRowId="";collapsedProjects=new Set;addShown=!1;sections=null;projects=[];threads=[];bots=[];rooms=[];selectedThreadId="";cb;needErr=new Map;needBusy=new Set;constructor(e,t){this.el=e,this.cb=t;let n=document.createElement("div");n.className="bp-side-host";let i=document.createElement("div");i.className="bp-side-host-left",this.hostLabel=document.createElement("span"),this.hostLabel.textContent="This computer";let s=document.createElement("span");s.className="bp-dim",s.textContent="›",i.append(this.hostLabel,s);let r=document.createElement("button");r.type="button",r.className="icon bp-side-collapse",r.textContent="‹",r.title="Collapse sidebar",r.setAttribute("aria-label","Collapse sidebar"),r.setAttribute("data-testid","sidebar-collapse"),r.addEventListener("click",()=>this.cb.onCollapseSidebar?.()),n.append(i,r);let a=document.createElement("div");a.className="bp-side-head",this.filterInput=document.createElement("input"),this.filterInput.type="search",this.filterInput.className="bp-input bp-side-search";let o=h("sidebar.search.projects","Search projects, threads…");this.filterInput.placeholder=o,this.filterInput.setAttribute("aria-label",o),this.filterInput.setAttribute("data-testid","sidebar-filter"),this.filterInput.addEventListener("input",()=>{this.filterText=this.filterInput.value.trim().toLowerCase(),this.render()});let c=document.createElement("button");c.type="button",c.className="icon bp-side-add",c.textContent="+",c.title=h("thread.new","New thread"),c.setAttribute("aria-label",h("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.crewEl=document.createElement("div"),this.crewEl.className="bp-crew-band bp-hidden",this.crewEl.setAttribute("data-testid","sidebar-crew"),this.listEl=document.createElement("div"),this.listEl.className="bp-side-list",this.listEl.setAttribute("data-testid","sidebar-list");let p=document.createElement("div");p.className="bp-side-footer",this.connEl=document.createElement("span"),this.connEl.className="bp-conn-status",this.connEl.textContent="Connecting…",this.connEl.setAttribute("data-testid","conn-status"),p.appendChild(this.connEl),this.el.append(n,a,this.homeBanner,this.crewEl,this.listEl,p)}setHome(e){if(!e){this.homeBanner.classList.add("bp-hidden"),this.homeBanner.textContent="";return}let t="",n=!1;if(e.moving?.state==="moving")t=e.moving.step?h("home.moving.step","Moving home to {to}: {step}").replace("{to}",e.moving.to).replace("{step}",e.moving.step):h("home.moving","Moving home to {to}…").replace("{to}",e.moving.to);else if(e.moving?.state==="failed")t=e.moving.note?h("home.move.failed.note","Home move failed: {note}").replace("{note}",e.moving.note):h("home.move.failed","Home move failed"),n=!0;else if(!e.online){let i=e.name||"home",s="";if(e.awaySince&&e.awaySince>0){let r=new Date(e.awaySince);s=`${String(r.getHours()).padStart(2,"0")}:${String(r.getMinutes()).padStart(2,"0")}`}if(s&&e.queuedCount>0)t=h("home.away.since.queued","Home ({name}) is away since {time} · {n} queued").replace("{name}",i).replace("{time}",s).replace("{n}",String(e.queuedCount));else if(s)t=h("home.away.since","Home ({name}) is away since {time}").replace("{name}",i).replace("{time}",s);else if(e.queuedCount>0)t=h("home.away.queued","Home ({name}) is away · {n} queued").replace("{name}",i).replace("{n}",String(e.queuedCount));else t=h("home.away","Home ({name}) is away").replace("{name}",i)}if(!t)this.homeBanner.classList.add("bp-hidden"),this.homeBanner.textContent="";else this.homeBanner.textContent=t,this.homeBanner.className=n?"bp-side-home bp-bad":"bp-side-home bp-dim",this.homeBanner.classList.remove("bp-hidden")}setHostName(e){this.hostLabel.textContent=e||"This computer"}setConnStatus(e,t){this.connEl.textContent=e,this.connEl.className=`bp-conn-status ${t}`.trim()}setData(e,t,n,i){this.projects=e,this.threads=t,this.bots=n,this.rooms=i,this.render()}setSections(e,t,n){this.sections=e,this.bots=t,this.rooms=n,this.render()}setSelected(e){this.selectedThreadId=e,this.render()}focusFilter(){this.filterInput.focus()}firstProjectId(){if(this.sections){for(let e of this.sections)if(e.kind==="projects"&&e.rows.length>0){let t=e.rows[0];if(t.id&&!t.off)return t.id}}return this.projects[0]?.id??""}refreshLocale(){let e=h("sidebar.search.projects","Search projects, threads…");this.filterInput.placeholder=e,this.filterInput.setAttribute("aria-label",e),this.render()}renderCrewBand(e){let t=this.bots.find((c)=>c.uber),n=this.bots.filter((c)=>!c.uber&&(!e||c.name.toLowerCase().includes(e))),i=this.rooms.filter((c)=>!e||c.name.toLowerCase().includes(e)),s=Boolean(t&&(!e||t.name.toLowerCase().includes(e))),r=n.length>0||Boolean(this.cb.onNewBot)&&!e,a=i.length>0||Boolean(this.cb.onNewRoom)&&!e;if(!s&&!r&&!a){this.crewEl.classList.add("bp-hidden"),this.crewEl.replaceChildren();return}let o=document.createDocumentFragment();if(s&&t){let c=document.createElement("button");c.type="button",c.className="bp-crew-uber"+(t.thread===this.selectedThreadId?" active":""),c.setAttribute("data-testid",`crew-uber-${t.id}`);let p=document.createElement("span");if(p.className=`bp-crew-uber-avatar ${$n(t.mood)}`,t.color)p.style.color=t.color;p.appendChild($r(14));let l=document.createElement("span");l.className="bp-crew-uber-meta";let u=document.createElement("span");if(u.className="bp-crew-uber-name",u.textContent=t.name,l.appendChild(u),t.note){let d=document.createElement("span");d.className=`bp-crew-uber-note ${$n(t.mood)}`,d.textContent=t.note,l.appendChild(d)}if(c.append(p,l),t.mood==="wait"||t.mood==="error"){let d=document.createElement("span");d.className="bp-status-pill bp-pill-bad",d.textContent="? Input",c.appendChild(d)}c.addEventListener("click",()=>this.cb.onSelectBot(t)),o.appendChild(c)}if(r){let c=document.createElement("div");c.className="bp-crew-bots",c.setAttribute("data-testid","crew-bots");let p=document.createElement("span");p.className="bp-crew-lbl",p.textContent=h("tour.title.bots","Bots").toUpperCase(),c.appendChild(p);let l=document.createElement("div");l.className="bp-crew-bot-tiles";for(let u of n){let d=document.createElement("button");if(d.type="button",d.className=`bp-crew-bot-tile ${$n(u.mood)}`+(u.thread===this.selectedThreadId?" active":""),d.title=u.note?`@${u.name} — ${u.note}`:`@${u.name}`,d.setAttribute("aria-label",`@${u.name}`),d.setAttribute("data-testid",`crew-bot-${u.id}`),u.color)d.style.setProperty("--bot-c",u.color);let m=document.createElement("span");if(m.className="bp-crew-bot-init",m.textContent=Ur(u.name),d.appendChild(m),u.mood==="wait"||u.mood==="error"){let f=document.createElement("span");f.className="bp-crew-bot-wait",d.appendChild(f)}d.addEventListener("click",()=>this.cb.onSelectBot(u)),l.appendChild(d)}if(this.cb.onNewBot&&!e){let u=document.createElement("button");u.type="button",u.className="bp-crew-bot-tile bp-crew-add",u.textContent="+",u.title=h("bots.new","New bot"),u.setAttribute("aria-label",h("bots.new","New bot")),u.setAttribute("data-testid","crew-new-bot"),u.addEventListener("click",()=>this.cb.onNewBot?.()),l.appendChild(u)}c.appendChild(l),o.appendChild(c)}if(a){let c=document.createElement("div");c.className="bp-crew-rooms",c.setAttribute("data-testid","crew-rooms");for(let p of i){let l=document.createElement("button");l.type="button",l.className="bp-crew-room-chip",l.setAttribute("data-testid",`crew-room-${p.id}`);let u=document.createElement("span");u.className="bp-dim",u.textContent="#";let d=document.createElement("span");if(d.textContent=p.name,l.append(u,d),p.members!==void 0&&p.members>0){let m=document.createElement("span");m.className="bp-crew-room-cnt",m.textContent=String(p.members),l.appendChild(m)}l.title=p.members?`#${p.name} (${p.members})`:`#${p.name}`,l.addEventListener("click",()=>this.cb.onSelectRoom?.(p)),c.appendChild(l)}if(this.cb.onNewRoom&&!e){let p=document.createElement("button");p.type="button",p.className="bp-crew-room-chip bp-crew-add",p.textContent="+",p.title=h("rooms.new","New room"),p.setAttribute("aria-label",h("rooms.new","New room")),p.setAttribute("data-testid","crew-new-room"),p.addEventListener("click",()=>this.cb.onNewRoom?.()),c.appendChild(p)}o.appendChild(c)}this.crewEl.classList.remove("bp-hidden"),this.crewEl.replaceChildren(o)}projectsHead(e){let t=document.createElement("div");if(t.className="bp-side-section-head",!this.cb.onAddProject||this.addShown)return t.textContent=e,t;this.addShown=!0,t.classList.add("bp-side-section-row");let n=document.createElement("span");n.textContent=e;let i=document.createElement("button");i.type="button",i.className="bp-side-sec-plus bp-side-sec-btn",i.textContent="+";let s=h("sidebar.add.project","Add project");return i.title=s,i.setAttribute("aria-label",s),i.setAttribute("data-testid","sidebar-add-project"),i.addEventListener("click",(r)=>{r.stopPropagation(),this.cb.onAddProject?.()}),t.append(n,i),t}renderStatusPill(e,t){let n=document.createElement("span");if(n.className=`bp-status-pill bp-pill-${e.tone}`,n.textContent=`${e.icon} ${e.label}`,t)n.title=t;return n}renderRowActions(e){if(e.off)return null;let t=Array.isArray(e.snooze)&&e.snooze.length>0&&Boolean(this.cb.onSnoozeRow),n=Boolean(e.wake)&&Boolean(this.cb.onSnoozeRow),i=e.kind==="swarm",s=Boolean(e.settle)&&(!i||Boolean(this.cb.onSettleSwarm));if(!t&&!n&&!s)return null;let r=document.createElement("span");if(r.className="bp-row-acts",n&&e.wake){let a=document.createElement("button");a.type="button",a.className="bp-row-act-btn bp-wake-btn",a.textContent=h("menu.wake","Wake"),a.title=h("menu.wake","Wake snoozed thread"),a.setAttribute("data-testid",`wake-row-${e.id}`),a.addEventListener("click",(o)=>{o.stopPropagation(),this.cb.onSnoozeRow?.(e.wake)}),r.appendChild(a)}if(t&&e.snooze){let a=document.createElement("button");a.type="button",a.className="bp-row-act-btn bp-snooze-btn",a.title=h("menu.snooze","Snooze thread"),a.setAttribute("aria-label",h("menu.snooze","Snooze thread")),a.setAttribute("data-testid",`snooze-row-${e.id}`),a.appendChild(Or(11)),a.addEventListener("click",(o)=>{o.stopPropagation(),this.snoozeMenuRowId=this.snoozeMenuRowId===e.id?"":e.id,this.render()}),r.appendChild(a)}if(s&&e.settle){let a=document.createElement("button");a.type="button",a.className="bp-row-act-btn bp-settle-btn",a.title=h("menu.settle","Settle"),a.setAttribute("aria-label",h("menu.settle","Settle")),a.setAttribute("data-testid",`settle-row-${e.id}`),a.appendChild(Gr(11)),a.addEventListener("click",(o)=>{if(o.stopPropagation(),i)this.cb.onSettleSwarm?.(et(e.settle));else this.cb.onThreadAct(et(e.settle),"settle")}),r.appendChild(a)}return r}renderSectionThreadRow(e,t,n=!1){let i=document.createElement("div");i.className="bp-thread-row"+(n?" bp-inbox-row":"")+(e.id===this.selectedThreadId||et(e.id)===this.selectedThreadId?" active":"")+(e.off?" bp-dim":""),i.setAttribute("data-thread-id",e.id),i.setAttribute("data-testid",`thread-row-${e.id}`);let s=Hr(e),r=this.renderRowActions(e);if(n){let l=document.createElement("div");l.className="bp-inbox-main";let u=document.createElement("div");u.className="bp-inbox-top";let d=document.createElement("div");if(d.className="bp-thread-title",d.textContent=e.title||"Untitled thread",u.appendChild(d),r)u.appendChild(r);let m=document.createElement("div");if(m.className="bp-inbox-meta",s)m.appendChild(this.renderStatusPill(s,e.say));if(e.project){let f=document.createElement("span");f.className="bp-inbox-proj",f.textContent=e.project,m.appendChild(f)}if(e.ago){let f=document.createElement("span");if(f.className="bp-thread-age",f.textContent=e.ago,e.pinned)f.title=h("tools.pinned","Pinned");m.appendChild(f)}l.append(u,m),i.appendChild(l)}else{if(t){let u=document.createElement("span");u.className="bp-tree-branch",u.setAttribute("aria-hidden","true"),i.appendChild(u)}if(s)i.appendChild(this.renderStatusPill(s,e.say));let l=document.createElement("div");if(l.className="bp-thread-title",l.textContent=e.title||"Untitled thread",i.appendChild(l),r)i.appendChild(r);if(e.ago){let u=document.createElement("span");if(u.className="bp-thread-age",u.textContent=e.ago,e.pinned)u.title=h("tools.pinned","Pinned");i.appendChild(u)}}let a=e.nav||e.id;if(!e.off&&a&&!a.startsWith("@room:"))i.addEventListener("click",()=>this.cb.onSelectThread(et(a)));let o=this.snoozeMenuRowId===e.id&&Array.isArray(e.snooze)&&e.snooze.length>0,c=e.kind==="swarm"?Bn(e.need):null;if(!c&&!o)return i;let p=document.createElement("div");if(p.className="bp-need-wrap",p.appendChild(i),o&&e.snooze){let l=document.createElement("div");l.className="bp-snooze-bar"+(t?" nested":""),l.setAttribute("data-testid",`snooze-bar-${e.id}`);let u=document.createElement("span");u.className="bp-dim",u.textContent="Snooze:",l.appendChild(u);for(let d of e.snooze){let m=document.createElement("button");m.type="button",m.className="bp-snooze-opt",m.textContent=d.label,m.addEventListener("click",(f)=>{f.stopPropagation(),this.snoozeMenuRowId="",this.cb.onSnoozeRow?.(d.value),this.render()}),l.appendChild(m)}p.appendChild(l)}if(c){let l=document.createElement("div");l.className="bp-need"+(t?" nested":"")+(e.off?" bp-dim":""),l.setAttribute("data-testid",`need-${e.id}`);let u=document.createElement("span");u.className="bp-need-line",u.textContent=c.line,u.title=c.line,l.appendChild(u);for(let m of c.actions){if(!sn(m,Boolean(this.cb.hasRoomView)))continue;let f=document.createElement("button");f.type="button",f.className="bp-need-btn",f.textContent=m.label,f.setAttribute("data-testid",`need-${m.act}-${e.id}`),f.disabled=Boolean(e.off)||this.needBusy.has(e.id)||!this.cb.onNeedAct,f.addEventListener("click",(b)=>{b.stopPropagation();let g=this.cb.onNeedAct;if(!g)return;this.needErr.delete(e.id),this.needBusy.add(e.id),this.render(),g(m).catch((y)=>{this.needErr.set(e.id,y instanceof Error?y.message:String(y))}).finally(()=>{this.needBusy.delete(e.id),this.render()})}),l.appendChild(f)}p.appendChild(l);let d=this.needErr.get(e.id);if(d){let m=document.createElement("div");m.className="bp-need-err"+(t?" nested":""),m.textContent=d,p.appendChild(m)}}return p}renderHubSections(e,t){let n=this.sections??[],i=new Set;for(let a of n)if(a.kind==="threads")for(let o of a.rows)i.add(o.id),i.add(et(o.id));else if(a.kind==="projects")for(let o of a.rows)for(let c of o.threads??[])i.add(c.id),i.add(et(c.id));let s=this.selectedThreadId?this.threads.find((a)=>a.id===this.selectedThreadId)??null:null,r=!1;for(let a of n)if(a.kind==="projects"&&(a.rows.length>0||(a.count??0)>0))r=!0;for(let a of n){if(a.kind==="bub")continue;if(a.kind==="threads"){let o=Boolean(a.fold&&a.toggle),c=a.rows.filter((l)=>{if(!t)return!0;return`${l.title} ${l.project??""}`.toLowerCase().includes(t)});if(!o&&c.length===0)continue;if(o&&t&&c.length===0)continue;if(o&&!t&&(a.count??c.length)===0)continue;let p=document.createElement("section");if(p.className=`bp-side-section bp-side-inbox bp-sec-${a.id}`,p.setAttribute("data-section-id",a.id),o){let l=document.createElement("button");l.type="button",l.className="bp-side-section-head bp-side-section-toggle";let u=t?c.length:a.count??c.length,d=a.open||Boolean(t)?"▾":"▸";if(l.textContent=`${d} ${a.title.toUpperCase()} (${u})`,a.hint)l.title=a.hint;l.setAttribute("data-testid",`section-toggle-${a.id}`),l.addEventListener("click",()=>{if(a.toggle)this.cb.onToggleSection?.(a.toggle)}),p.appendChild(l)}else{let l=document.createElement("div");l.className="bp-side-section-head"+(a.id==="needs"?" bp-head-needs":a.id==="running"?" bp-head-running":""),l.textContent=`${a.title.toUpperCase()} ${c.length}`,p.appendChild(l)}if(!o||Boolean(a.open)||Boolean(t))for(let l of c)p.appendChild(this.renderSectionThreadRow(l,!1,!0));e.appendChild(p);continue}if(a.kind==="projects"){let o=a.rows,c=o.filter((d)=>{if(!t)return!0;if((d.title||d.id).toLowerCase().includes(t))return!0;if((d.threads??[]).some((m)=>m.title.toLowerCase().includes(t)))return!0;if((d.swarms??[]).some((m)=>m.title.toLowerCase().includes(t)))return!0;return!1}),p=Boolean(a.fold&&a.toggle);if(t&&c.length===0)continue;if(!p&&a.id!=="active"&&c.length===0)continue;let l=document.createElement("section");if(l.className=`bp-side-section bp-sec-${a.id}`,l.setAttribute("data-section-id",a.id),p){let d=document.createElement("button");d.type="button",d.className="bp-side-section-head bp-side-section-toggle";let m=t?c.length:a.count??c.length,f=a.open||Boolean(t)?"▾":"▸";if(d.textContent=`${f} ${a.title.toUpperCase()} (${m})`,a.hint)d.title=a.hint;d.setAttribute("data-testid",`section-toggle-${a.id}`),d.addEventListener("click",()=>{if(a.toggle)this.cb.onToggleSection?.(a.toggle)}),l.appendChild(d)}else l.appendChild(this.projectsHead(a.title.toUpperCase()));if(!p||Boolean(a.open)||Boolean(t)){if(a.id==="all"&&!t){let d=o.some((f)=>f.hasBoard||f.hasSchematic),m=o.some((f)=>!f.hasBoard&&!f.hasSchematic);if(d&&m){let f=document.createElement("div");f.className="bp-proj-filter",f.setAttribute("data-testid","all-projects-filter");let b=[{id:"all",label:"All"},{id:"hw",label:"Boards"},{id:"sw",label:"Code"}];for(let g of b){let y=document.createElement("button");y.type="button",y.className="bp-proj-filter-btn"+(this.allFilter===g.id?" active":""),y.textContent=g.label,y.addEventListener("click",()=>{this.allFilter=g.id,this.render()}),f.appendChild(y)}if(l.appendChild(f),this.allFilter==="hw")c=c.filter((g)=>g.hasBoard||g.hasSchematic);else if(this.allFilter==="sw")c=c.filter((g)=>!g.hasBoard&&!g.hasSchematic)}}if(a.id==="active"&&!r&&!t){let d=document.createElement("div");d.className="bp-side-empty",d.textContent="No projects yet.",l.appendChild(d)}for(let d of c){let m=document.createElement("div");if(m.className="bp-proj-group"+(d.off||a.id==="quiet"?" bp-dim":""),m.setAttribute("data-project-id",d.id),d.nav||d.key)m.setAttribute("data-project-key",d.nav||d.key||"");let f=document.createElement("div");f.className="bp-proj-head";let b=document.createElement("button");b.type="button",b.className="bp-proj-toggle";let y=Boolean(d.hasBoard||d.hasSchematic)?ys(14):vs();if(d.css)y.style.color=d.css;let w=document.createElement("span");if(w.className="bp-proj-name",w.textContent=d.title||d.id,b.append(y,w),d.fold==="project-fold"&&d.nav)b.addEventListener("click",()=>this.cb.onToggleProjectFold?.(d.nav));let C=document.createElement("div");if(C.className="bp-proj-meta",(d.needsCount??0)>0){let P=document.createElement("span");P.className="bp-proj-badge-need",P.textContent=String(d.needsCount),P.title=`${d.needsCount} needing you`,C.appendChild(P)}if((d.running??0)>0){let P=document.createElement("span");P.className="bp-proj-badge-run",P.textContent=String(d.running),P.title=`${d.running} running`,C.appendChild(P)}if(d.pinned&&a.id!=="pinned")C.appendChild(Vr(11));let A=document.createElement("div");if(A.className="bp-proj-acts",!d.off&&this.cb.onQuickOpenViewer){if(d.hasBoard){let P=document.createElement("button");P.type="button",P.className="bp-proj-quick",P.title=h("viewer.board","Open Board"),P.setAttribute("aria-label",`Open Board (${d.title})`),P.setAttribute("data-testid",`quick-board-${d.id}`),P.appendChild(ys(13,"")),P.addEventListener("click",(j)=>{j.stopPropagation(),this.cb.onQuickOpenViewer?.(et(d.id),"board")}),A.appendChild(P)}if(d.hasSchematic){let P=document.createElement("button");P.type="button",P.className="bp-proj-quick",P.title=h("viewer.schematic","Open Schematic"),P.setAttribute("aria-label",`Open Schematic (${d.title})`),P.setAttribute("data-testid",`quick-sch-${d.id}`),P.appendChild(Fr(13)),P.addEventListener("click",(j)=>{j.stopPropagation(),this.cb.onQuickOpenViewer?.(et(d.id),"schematic")}),A.appendChild(P)}}let S=document.createElement("button");if(S.type="button",S.className="icon bp-proj-add",S.title=h("thread.new","New thread"),S.textContent="+",S.setAttribute("data-testid",`new-thread-${d.id}`),d.off)S.disabled=!0;S.addEventListener("click",(P)=>{P.stopPropagation(),this.cb.onNewThread(et(d.id))}),A.appendChild(S),f.append(b,C,A),m.appendChild(f);let T=Boolean(t)&&(d.title||d.id).toLowerCase().includes(t),I=Boolean(d.folded&&!t);for(let P of d.swarms??[]){if(!Dr(P,I))continue;if(t&&!T&&!P.title.toLowerCase().includes(t))continue;m.appendChild(this.renderSectionThreadRow(P,!0))}if(!I){for(let P of d.threads??[]){if(t&&!T&&!P.title.toLowerCase().includes(t))continue;m.appendChild(this.renderSectionThreadRow(P,!0))}if(s&&s.project===et(d.id)&&!i.has(s.id)&&(!t||T||s.title.toLowerCase().includes(t)))m.appendChild(this.renderSectionThreadRow({id:s.id,title:s.title,status:s.status,state:s.state,ago:ws(s.updatedAt),pinned:s.pinned,nav:s.id},!0))}l.appendChild(m)}}e.appendChild(l)}}}render(){this.addShown=!1;let e=this.filterText;this.renderCrewBand(e);let t=document.createDocumentFragment();if(this.sections!==null)this.renderHubSections(t,e);else{let n=new Map;for(let i of this.threads){if(i.archived||i.swarm)continue;if(e){if(!`${i.title} ${i.preview??""}`.toLowerCase().includes(e))continue}let s=n.get(i.project)??[];s.push(i),n.set(i.project,s)}if(t.appendChild(this.projectsHead("RECENT")),this.projects.length===0&&this.threads.length===0){let i=document.createElement("div");i.className="bp-side-empty",i.textContent="No projects yet.",t.appendChild(i)}for(let i of this.projects){let s=n.get(i.id)??[];if(e&&s.length===0&&!i.title.toLowerCase().includes(e))continue;let r=document.createElement("section");r.className="bp-proj-group",r.setAttribute("data-project-id",i.id);let a=document.createElement("div");a.className="bp-proj-head";let o=document.createElement("button");o.type="button",o.className="bp-proj-toggle";let c=this.collapsedProjects.has(i.id)&&!e,p=vs();if(i.css)p.style.color=i.css;let l=document.createElement("span");l.className="bp-proj-name",l.textContent=i.title||i.id,o.append(p,l),o.addEventListener("click",()=>{if(this.collapsedProjects.has(i.id))this.collapsedProjects.delete(i.id);else this.collapsedProjects.add(i.id);this.render()});let u=document.createElement("button");if(u.type="button",u.className="icon bp-proj-add",u.title=h("thread.new","New thread"),u.textContent="+",u.setAttribute("data-testid",`new-thread-${i.id}`),u.addEventListener("click",(d)=>{d.stopPropagation(),this.cb.onNewThread(i.id)}),a.append(o,u),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:ws(d.updatedAt),pinned:d.pinned,nav:d.id},!0));t.appendChild(r)}}this.listEl.replaceChildren(t)}}function Wr(e){try{return new URL(e,window.location.origin).searchParams.get("s")||""}catch{return""}}function $t(e){if(!e)return;for(let t of e.getTracks())try{t.stop()}catch{}}function _r(e,t){if(t===16000){let r=new Int16Array(e.length);for(let a=0;a0?c/p:0));s[r]=l<0?l*32768:l*32767}return s}class On{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){$t(n);return}if(this.stream=n,await this.stopDrain,t!==this.sessionGen||this.cb.getThreadId()!==e){if($t(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($t(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?Wr(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($t(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=_r(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;$t(this.stream),this.stream=null}}var Es=[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],ks=[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],Cs=[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],xs=[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],zr=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];function Gt(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 qr=(()=>{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),Gt(e,288)})(),Kr=(()=>{let e=new Uint8Array(32);return e.fill(5),Gt(e,32)})();class Vn{win=new Uint8Array(32768);winPos=0;feed(e,t=16777216){let n=0,i=0,s=0,r=(u)=>{while(s=e.length)throw Error("truncated deflate frame");i|=e[n++]<>>=u,s-=u,d},a=(u)=>{let d=0,m=0,f=0;for(let b=1;b<=u.maxBits;b++){d|=r(1);let g=u.counts[b];if(d-g{let d=c+u;if(d>t)throw Error("inflated frame exceeds limit");if(d<=o.length)return;let m=o.length;while(m{p(1),o[c++]=u,this.win[this.winPos]=u,this.winPos=this.winPos+1&32767};while(n0){if(n>=e.length&&s<3)break;let u=r(1),d=r(2);if(d===0){if(i=0,s=0,n+4>e.length)throw Error("truncated stored block");let m=e[n]|e[n+1]<<8,f=e[n+2]|e[n+3]<<8;if(n+=4,(m^65535)!==f)throw Error("invalid stored block length");if(n+m>e.length)throw Error("truncated stored payload");p(m);for(let b=0;b=e.length)break}else if(d===1||d===2){let m=qr,f=Kr;if(d===2){let b=r(5)+257,g=r(5)+1,y=r(4)+4,w=new Uint8Array(19);for(let I=0;IA)throw Error("code length overflow");for(let G=0;GA)throw Error("code length overflow");T+=P}else if(I===18){let P=r(7)+11;if(T+P>A)throw Error("code length overflow");T+=P}else throw Error("invalid code length symbol")}m=Gt(S,b),f=Gt(S.subarray(b),g)}while(!0){let b=a(m);if(b<256)l(b);else if(b===256)break;else{let g=b-257;if(g>=Es.length)throw Error("invalid length symbol");let y=Es[g]+(ks[g]?r(ks[g]):0),w=a(f);if(w>=Cs.length)throw Error("invalid distance symbol");let C=Cs[w]+(xs[w]?r(xs[w]):0);p(y);let A=this.winPos-C&32767;for(let S=0;S{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",p=typeof r.errorCode==="string"?r.errorCode:void 0,l=typeof r.machine==="string"?r.machine:void 0,u=typeof r.thread==="string"?r.thread:void 0;a.reject(new Ot(c,{code:p,machine:l,thread:u}))}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 Jr=new TextDecoder;function Ps(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 Ss(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,p=i(o&31);if(p===null)return null;switch(c){case 0:return p;case 1:return-1-p;case 2:{if(t+p>e.length)return null;let l=e.subarray(t,t+p);return t+=p,l}case 3:{if(t+p>e.length)return null;let l=Jr.decode(e.subarray(t,t+p));return t+=p,l}case 4:{if(p>e.length)return null;let l=Array(p);for(let u=0;u=this.b.length)return this.ok=!1,0;let n=this.b[this.i++],i=7*t;if(i>=28&&(n&240)!==0)return this.ok=!1,0;if(e=(e|(n&127)<>>0,n<128)return e}return this.ok=!1,0}nextI32(){let e=this.nextU32();return e>>>1^-(e&1)}}function Ls(e){let t=0xcbf29ce484222325n,n=0x100000001b3n,i=0xffffffffffffffffn;for(let s=0;stypeof e[b]==="number"?e[b]:g,n=t("l",0),i=t("c",0),s=t("a",255)/255,r=t("m",1),a=t("w",0),o=a/2,c=r===0&&a!==0,p=e.d instanceof Uint8Array?e.d:new Uint8Array(0),l=new As(p),u=[],d=[],m=0,f=0;while(l.more()){let b=l.nextU32(),g=u.length,y=1/0,w=1/0,C=-1/0,A=-1/0;if(r===2)m=m+l.nextI32()|0,f=f+l.nextI32()|0,u.push(m,f),y=C=m,w=A=f;else{let T=Math.min(l.nextU32(),1048576);for(let I=0;IC)C=m;if(fA)A=f}}let S=(u.length-g)/2;if(S>0){let T=r===2||S===1?2:r===0?0:1,I=r===0?0:o;d.push({info:b,x0:y-I,y0:w-I,x1:C+I,y1:A+I,at:g,n:S,kind:T})}}return{layer:n,color:i,alpha:s,mode:r,r:o,own:c,pts:new Float32Array(u),pieces:d}}function Ns(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 p=n.keys().next().value;if(p!==void 0)n.delete(p);else break}}}}return{key:typeof e.key==="string"?e.key:"",fam:typeof e.fam==="string"?e.fam:"",base:typeof e.base==="string"?e.base:"",box:i(e.box),edge:i(e.edge),thick:typeof e.thick==="number"?e.thick:1600,note:typeof e.note==="string"?e.note:"",warn:typeof e.warn==="number"?e.warn!==0:!1,chunks:r}}function Ms(e,t,n,i=!0){if(n.width<=0||n.height<=0||n.naturalWidth<=0||n.naturalHeight<=0)return null;let s=Math.min(n.width/n.naturalWidth,n.height/n.naturalHeight),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,p=(e-o)/r,l=(t-c)/a;if(p<0||p>1||l<0||l>1)return null;return{x:Math.max(0,Math.min(1000,Math.round(p*1000))),y:Math.max(0,Math.min(1000,Math.round(l*1000)))}}var Ts=[["Enter","Enter"],["Tab","Tab"],["Bksp","Backspace"],["Esc","Escape"],["↑","ArrowUp"],["↓","ArrowDown"],["←","ArrowLeft"],["→","ArrowRight"]];function Bs(e){let t=e.trim();if(!t)return"";if(/^[a-zA-Z][a-zA-Z0-9+.-]*:/.test(t))return t;return`https://${t}`}class Wn{tail=Promise.resolve();enqueue(e){let t=this.tail.then(e,e);return this.tail=t.catch(()=>{}),t}}function Is(e,t,n){let i=!0,s=!1,r=!1,a="",o=!1,c=!1,p=-1,l=null,u=new Wn,d=document.createElement("div");d.className="bp-pane bp-browser-pane",d.setAttribute("data-testid","pane-browser");let m=document.createElement("div");m.className="bp-pane-bar bp-browser-nav";function f(Q,me,k){let x=document.createElement("button");if(x.type="button",x.className="bp-v-btn",x.textContent=Q,x.setAttribute("data-testid",me),k)x.title=k;return x}let b=f("←","browser-back","Back"),g=f("→","browser-forward","Forward"),y=f("↻","browser-reload","Reload"),w=document.createElement("form");w.className="bp-browser-url-form";let 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=f("Go","browser-go","Navigate");A.type="submit",w.append(C,A);let S=f("Take over","browser-takeover");S.classList.add("is-primary"),m.append(b,g,y,w,S);let T=document.createElement("div");T.className="bp-browser-drive-bar",T.hidden=!0;let I=document.createElement("div");I.className="bp-browser-keys-row";let P=document.createElement("input");P.type="text",P.className="bp-browser-input",P.placeholder="Type text or press Enter/Tab/Arrows…",P.autocomplete="off",P.spellcheck=!1,P.setAttribute("data-testid","browser-keys");let j=f("Send","browser-type-send");I.append(P,j);let G=document.createElement("div");G.className="bp-browser-quick-keys";for(let[Q,me]of Ts){let k=f(Q,`browser-key-${me}`);k.addEventListener("click",()=>ee("press",{key:me})),G.append(k)}T.append(I,G);let L=document.createElement("div");L.className="bp-browser-err",L.setAttribute("data-testid","browser-error"),L.hidden=!0;let Y=document.createElement("div");Y.className="bp-browser-stage",Y.setAttribute("data-testid","browser-stage");let re=document.createElement("img");re.className="bp-browser-img",re.alt="Hub browser screen",re.draggable=!1,re.hidden=!0,re.setAttribute("data-testid","browser-frame");let se=document.createElement("div");se.className="bp-pane-empty",se.setAttribute("data-testid","browser-empty"),se.textContent="Loading browser screen…",Y.append(re,se);let be=document.createElement("div");be.className="bp-browser-hint",be.textContent="You have the page: click to tap, scroll to wheel, type in the key box. Hand it back when done.",be.hidden=!0,d.append(m,T,L,Y,be),e.replaceChildren(d);function Pe(Q){L.textContent=Q,L.hidden=!Q}function Ee(){T.hidden=!s,be.hidden=!s,S.textContent=s?"Hand back":"Take over",S.setAttribute("data-testid",s?"browser-handback":"browser-takeover"),S.classList.toggle("is-on",s),re.classList.toggle("is-driving",s)}function ee(Q,me={},k){u.enqueue(async()=>{if(!i)return;Pe("");try{if(await t.hub.rpc("browser",{thread:n,op:Q,...me}),!i)return;k?.(),ue()}catch(x){if(!i)return;Pe(x instanceof Error?x.message:String(x))}})}function ae(Q){ee("toolbar",{command:Q},()=>{s=!0,Ee()})}b.addEventListener("click",()=>ae("back")),g.addEventListener("click",()=>ae("forward")),y.addEventListener("click",()=>ae("reload")),w.addEventListener("submit",(Q)=>{Q.preventDefault();let me=Bs(C.value);if(!me)return;if(C.value=me,!s)ee("takeover",{},()=>{s=!0,Ee()});ee("navigate",{url:me},()=>{s=!0,Ee()})}),S.addEventListener("click",()=>{if(s)ee("handback",{},()=>{s=!1,Ee()});else ee("takeover",{},()=>{s=!0,Ee(),P.focus()})});function R(){let Q=P.value;if(!Q)return;P.value="",ee("type",{text:Q})}j.addEventListener("click",R),P.addEventListener("keydown",(Q)=>{if(!s)return;if(Q.key==="Enter"){if(Q.preventDefault(),P.value)R();ee("press",{key:"Enter"});return}if(Q.key==="Tab"||Q.key==="Escape"||Q.key==="ArrowUp"||Q.key==="ArrowDown"||Q.key==="ArrowLeft"||Q.key==="ArrowRight"||Q.key==="Backspace"&&P.value==="")Q.preventDefault(),ee("press",{key:Q.key})}),re.addEventListener("click",(Q)=>{if(!s||!r)return;let me=re.getBoundingClientRect(),k=Ms(Q.clientX,Q.clientY,{left:me.left,top:me.top,width:me.width,height:me.height,naturalWidth:re.naturalWidth,naturalHeight:re.naturalHeight});if(!k)return;ee("click",k)}),re.addEventListener("wheel",(Q)=>{if(!s||!r)return;Q.preventDefault();let me=Math.round(Q.deltaX),k=Math.round(Q.deltaY);if(me===0&&k===0)return;ee("scroll",{dx:me,dy:k})},{passive:!1});async function ue(){if(!i)return;if(o){c=!0;return}o=!0;try{do{c=!1,l=new AbortController;let Q=await fetch(`/bots/${encodeURIComponent(n)}/screen.jpg`,{credentials:"same-origin",cache:"no-store",signal:l.signal});if(!i)return;if(Q.ok){let me=await Q.blob();if(!i)return;let k=URL.createObjectURL(me),x=a;if(a=k,re.src=k,re.hidden=!1,se.hidden=!0,r=!0,x)URL.revokeObjectURL(x)}else if(!r)re.hidden=!0,se.hidden=!1,se.textContent="No browser page yet. An agent opens one when it needs the web."}while(i&&c)}catch{if(!i)return;if(!r)re.hidden=!0,se.hidden=!1,se.textContent="No browser page yet. An agent opens one when it needs the web."}finally{l=null,o=!1}}let le=t.hub.onFrame((Q)=>{if(!i)return;if(Q.t==="shot"&&Q.bot===n){if(typeof Q.n==="number"){if(Q.n===p)return;p=Q.n}ue()}});return ue(),{destroy(){if(i=!1,le(),l?.abort(),a)URL.revokeObjectURL(a),a=""}}}function V(e,t,n){let i=document.createElement(e);if(t)i.className=t;if(n!==void 0)i.textContent=n;return i}function on(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 js(e){let t=e.lastIndexOf(".");return t>=0?e.slice(t+1).toLowerCase():""}function Yr(e){return["png","jpg","jpeg","gif","webp","svg","bmp","ico"].includes(e)}function Rs(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 Zr(e){let t=js(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 Ds(e,t,n,i){let s=!0,r="",a="",o=V("div","bp-pane bp-files-pane");o.setAttribute("data-testid","pane-files");let c=V("div","bp-pane-bar"),p=V("div","bp-files-crumbs"),l=V("button","bp-v-btn","Refresh");l.type="button",l.addEventListener("click",()=>void g(r)),c.append(p,l);let u=V("div","bp-files-split"),d=V("div","bp-files-list");d.setAttribute("data-testid","files-list");let m=V("div","bp-files-preview");m.setAttribute("data-testid","files-preview"),m.append(V("div","bp-pane-empty","Select a file to preview")),u.append(d,m),o.append(c,u),e.replaceChildren(o);function f(){p.replaceChildren();let y=V("button","bp-crumb-btn","project");if(y.type="button",y.addEventListener("click",()=>void g("")),p.append(y),!r)return;let w=r.split("/").filter(Boolean),C="";for(let A of w){C=C?`${C}/${A}`:A;let S=C;p.append(V("span","bp-vh-sep","/"));let T=V("button","bp-crumb-btn",A);T.type="button",T.addEventListener("click",()=>void g(S)),p.append(T)}}async function b(y,w,C){a=y,m.replaceChildren();let A=V("div","bp-files-prev-head");A.append(V("span","bp-files-prev-name",y));let S=V("div","bp-files-prev-acts"),T=Zr(w);if(T){let G=V("button","bp-v-btn is-primary",`Open in ${T}`);G.type="button",G.setAttribute("data-testid","files-open-viewer"),G.addEventListener("click",()=>i(T,y)),S.append(G)}let I=`/files/get?thread=${encodeURIComponent(n)}&path=${encodeURIComponent(y)}`,P=V("a","bp-v-btn","Download");P.href=I,P.download=w,S.append(P),A.append(S),m.append(A);let j=js(w);if(Yr(j)){let G=V("div","bp-files-img-wrap"),L=document.createElement("img");L.className="bp-files-img",L.alt=w,L.src=I,G.append(L),m.append(G);return}if(C>524288&&!Rs(j)){m.append(V("div","bp-pane-empty",`Binary file (${on(C)}). Use Download to save.`));return}if(Rs(j)||C<=65536){let G=V("div","bp-pane-empty","Loading…");m.append(G);try{let L=await fetch(I,{credentials:"same-origin"});if(!s||a!==y)return;if(!L.ok){G.textContent=`Could not load file (${L.status})`;return}if((L.headers.get("content-type")||"").startsWith("image/")){G.remove();let le=document.createElement("img");le.className="bp-files-img",le.alt=w,le.src=I,m.append(le);return}let re=262144,se=[],be=0,Pe=!1;if(L.body){let le=L.body.getReader();try{while(!0){let{done:Q,value:me}=await le.read();if(Q||!me)break;if(be+me.byteLength>re){let k=re-be;if(k>0)se.push(me.subarray(0,k)),be+=k;Pe=!0,await le.cancel();break}se.push(me),be+=me.byteLength}}finally{le.releaseLock()}}if(!s||a!==y)return;let Ee=new Uint8Array(be),ee=0;for(let le of se)Ee.set(le,ee),ee+=le.byteLength;let ae=!1;for(let le=0;leA.dir===S.dir?A.name.localeCompare(S.name):A.dir?-1:1),d.replaceChildren(),y){let A=V("button","bp-file-row is-dir");A.type="button",A.append(V("span","bp-file-icon","↰"),V("span","bp-file-name",".."));let S=y.includes("/")?y.slice(0,y.lastIndexOf("/")):"";A.addEventListener("click",()=>void g(S)),d.append(A)}if(C.length===0){d.append(V("div","bp-pane-empty","Empty folder"));return}for(let A of C){let S=y?`${y}/${A.name}`:A.name,T=V("button","bp-file-row"+(A.dir?" is-dir":"")+(S===a?" is-sel":""));T.type="button",T.setAttribute("data-testid",`file-row-${A.name}`),T.append(V("span","bp-file-icon",A.dir?"▸":"·"),V("span","bp-file-name",A.name),V("span","bp-file-size",A.dir?"":on(A.size))),T.addEventListener("click",()=>{if(A.dir)g(S);else d.querySelectorAll(".bp-file-row.is-sel").forEach((I)=>I.classList.remove("is-sel")),T.classList.add("is-sel"),b(S,A.name,A.size)}),d.append(T)}}catch(w){if(!s)return;d.replaceChildren(V("div","bp-pane-empty",w instanceof Error?w.message:String(w)))}}return g(""),{destroy(){s=!1}}}function Hs(e,t,n){let i=!0,s=V("div","bp-pane bp-diff-pane");s.setAttribute("data-testid","pane-diff");let r=V("div","bp-pane-bar"),a=V("span","bp-diff-summary","Loading diff…"),o=V("button","bp-v-btn","Refresh");o.type="button",o.addEventListener("click",()=>void p()),r.append(a,o);let c=V("div","bp-diff-body");c.setAttribute("data-testid","diff-body"),s.append(r,c),e.replaceChildren(s);async function p(){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(V("div","bp-pane-empty","This project is not a git repository."));return}let u=typeof l?.diff==="string"?l.diff:"";if(!u.trim()){a.textContent="Clean working tree",c.append(V("div","bp-pane-empty","No uncommitted changes."));return}let d=u.split(` -`),m=0,f=0,b=0,g=document.createDocumentFragment(),y=V("div","bp-diff-file");for(let w of d){if(w.startsWith("diff --git ")){if(y.childNodes.length>0)g.append(y);y=V("div","bp-diff-file"),m++;let C=w.match(/ b\/(.+)$/);y.append(V("div","bp-diff-file-head",C?C[1]:w));continue}if(w.startsWith("index ")||w.startsWith("--- ")||w.startsWith("+++ "))y.append(V("div","bp-diff-line is-meta",w));else if(w.startsWith("@@"))y.append(V("div","bp-diff-line is-hunk",w));else if(w.startsWith("+"))f++,y.append(V("div","bp-diff-line is-add",w));else if(w.startsWith("-"))b++,y.append(V("div","bp-diff-line is-del",w));else y.append(V("div","bp-diff-line",w))}if(y.childNodes.length>0)g.append(y);a.textContent=`${m||1} file${m===1?"":"s"} · +${f} -${b}`,c.append(g)}catch(l){if(!i)return;a.textContent="Diff unavailable",c.append(V("div","bp-pane-empty",l instanceof Error?l.message:String(l)))}}return p(),{destroy(){i=!1}}}function Qr(e,t){let n=t.rel||"",i=t.manifest||{},s=(p)=>`/files/get?thread=${encodeURIComponent(e)}&path=${encodeURIComponent(`${n}/${p}`)}`,r=(p)=>typeof p==="string"&&p!==""&&!p.startsWith("/")&&!p.split(/[\\/]/).includes(".."),a=(Array.isArray(i.drawings)?i.drawings:[]).filter((p)=>r(p?.file)),o=new Set(a.map((p)=>p.file)),c=a.map((p)=>({title:p.title||p.kind||p.file,file:p.file,url:s(p.file),drawing:!0}));for(let p of Array.isArray(i.files)?i.files:[])if(r(p)&&!o.has(p))c.push({title:p,file:p,url:s(p),drawing:!1});return c}function Fs(e,t,n){let i=!0,s="checks",r=V("div","bp-pane bp-review-pane");r.setAttribute("data-testid","pane-review");let a=V("div","bp-pane-bar"),o=V("div","bp-review-tabs"),c=V("button","bp-v-btn is-on","Checks"),p=V("button","bp-v-btn","BOM"),l=V("button","bp-v-btn","Comments"),u=V("button","bp-v-btn","Release");u.setAttribute("data-testid","review-tab-release"),c.type=p.type=l.type=u.type="button",o.append(c,p,l,u);let d=V("button","bp-v-btn","Refresh");d.type="button",d.addEventListener("click",()=>void y()),a.append(o,d);let m=V("div","bp-review-body");m.setAttribute("data-testid","review-body"),r.append(a,m),e.replaceChildren(r);function f(w){s=w,c.classList.toggle("is-on",s==="checks"),p.classList.toggle("is-on",s==="bom"),l.classList.toggle("is-on",s==="comments"),u.classList.toggle("is-on",s==="release"),y()}c.addEventListener("click",()=>f("checks")),p.addEventListener("click",()=>f("bom")),l.addEventListener("click",()=>f("comments")),u.addEventListener("click",()=>f("release"));function b(w){let C=V("div","bp-review-md bp-review-release");C.setAttribute("data-testid","review-release");let A=w.manifest||{};C.append(V("h2","bp-review-h",w.tag||"Release")),C.append(V("p","bp-review-p",[A.commit?`Commit ${A.commit.slice(0,12)}`:"",A.date||""].filter(Boolean).join(" · ")));let S=Qr(n,w),T=(P,j)=>{if(j.length===0)return;C.append(V("h3","bp-review-h",P));let G=V("table","bp-review-table");for(let L of j){let Y=document.createElement("tr"),re=V("td",void 0,L.title);re.title=L.file;let se=document.createElement("td"),be=V("a","bp-v-btn","Download");be.href=L.url,be.download=L.file.split("/").pop()||L.file,se.append(be),Y.append(re,se),G.append(Y)}C.append(G)};T("Drawings",S.filter((P)=>P.drawing));let I=Array.isArray(A.openFabNotes)?A.openFabNotes:[];if(I.length>0)C.append(V("div","bp-review-gate",`Open fabrication notes, not in the board (agree them with the fabricator): ${I.join(", ")}.`));if(T("Files",S.filter((P)=>!P.drawing)),w.rel){let P=V("a","bp-v-btn","Download all (.zip)");P.href=`/files/zip?thread=${encodeURIComponent(n)}&path=${encodeURIComponent(w.rel)}`,C.append(P)}return C}function g(w){let C=V("div","bp-review-md"),A=w.split(` -`),S=0;while(S{j.preventDefault();let G=I.value.trim();if(!G)return;P.disabled=!0,t.hub.rpc("review.comment",{thread:n,text:G}).then(()=>{I.value="",P.disabled=!1,y()},()=>{P.disabled=!1})}),m.append(T),S.length===0){m.append(V("div","bp-pane-empty","No review comments yet."));return}for(let j of S){let G=V("div","bp-review-comment"+(j.resolved?" is-resolved":"")),L=[j.by||"review",j.file,j.layer,j.item].filter(Boolean).join(" · ");G.append(V("div","bp-review-comment-meta",L),V("div","bp-review-comment-text",j.text)),m.append(G)}return}let w=await t.hub.rpc("review.page",{thread:n,page:s});if(!i)return;let C=w?.report||{};if(m.replaceChildren(),C.line||C.gate){let A=V("div","bp-review-gate",[C.gate,C.line].filter(Boolean).join(" · "));m.append(A)}if(C.err)m.append(V("div","bp-review-err",C.err));if(Array.isArray(C.tasks)&&C.tasks.length>0){let A=V("div","bp-review-tasks");C.tasks.forEach((S,T)=>{let I=V("label","bp-review-task"),P=document.createElement("input");P.type="checkbox",P.checked=!!(S.done??S.checked);let j=typeof S.index==="number"?S.index:T;P.addEventListener("change",()=>{t.hub.rpc("review.tick",{thread:n,index:j}).then(()=>void y(),()=>{})}),I.append(P,V("span",void 0,S.text||S.label||`Item ${T+1}`)),A.append(I)}),m.append(A)}if(s==="release"&&C.release&&C.release.manifest)m.append(b(C.release));else if(C.md&&C.md.trim())m.append(g(C.md));else if(!C.err&&(!C.tasks||C.tasks.length===0))m.append(V("div","bp-pane-empty",s==="release"?"No release yet. A release tags this design and makes its fabrication outputs and drawings in .backplane/releases.":`No ${s==="bom"?"BOM":"design checks"} report available.`))}catch(w){if(!i)return;m.replaceChildren(V("div","bp-pane-empty",w instanceof Error?w.message:String(w)))}}return y(),{destroy(){i=!1}}}function $s(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 _n{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),p=Math.max(o.height,200);this.cx=(t+i)*0.5,this.cy=(n+s)*0.5,this.scale=Math.min(c/r,p/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,p=n*0.5,l=this.scale,u=this.cx,d=this.cy,m=u-c/l,f=u+c/l,b=d-p/l,g=d+p/l,{off:y,dim:w,lift:C}=this.masks,A=[],S=[];for(let I=0;I>>P&1)===1)continue;if(P===C)S.push(I);else A.push(I)}let T=A.concat(S);a.lineCap="round",a.lineJoin="round";for(let I=0;I>>j.layer&1)===1,L=j.alpha*(G?0.25:1);if(L<=0.01)continue;this.drawChunk(a,j,L,m,b,f,g,u,d,l,c,p)}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 I=this.lightTheme?"rgba(27,29,33,0.77)":"rgba(217,221,228,0.77)";for(let P=0;Pr||g.y1a)continue;if(g.n<3)continue;let y=(d[g.at]-o)*p+l,w=(d[g.at+1]-c)*p+u;e.moveTo(y,w);for(let C=1;C0)e.fill()}else if(t.mode===2){let f=Math.max(0.75,t.r*p);e.fillStyle=m,e.beginPath();let b=0;for(let g=0;gr||y.y1a)continue;let w=(d[y.at]-o)*p+l,C=(d[y.at+1]-c)*p+u;e.moveTo(w+f,C),e.arc(w,C,f,0,Math.PI*2),b++}if(b>0)e.fill()}else{e.strokeStyle=m,e.lineWidth=Math.max(1,t.r*2*p),e.beginPath();let f=0;for(let b=0;br||g.y1a)continue;let y=(d[g.at]-o)*p+l,w=(d[g.at+1]-c)*p+u;if(g.n===1)e.moveTo(y,w),e.lineTo(y+0.01,w);else{e.moveTo(y,w);for(let C=1;C0)e.stroke()}}drawLitPieces(e,t,n,i,s,r,a,o,c,p,l,u,d){let m=t.pts,f=$s(t.color,t.alpha);for(let b=0;ba||g.y1o)continue;let y=(m[g.at]-c)*l+u,w=(m[g.at+1]-p)*l+d;if(g.kind===2){let C=Math.max(1.5,t.r*l);e.fillStyle=f,e.beginPath(),e.arc(y,w,C,0,Math.PI*2),e.fill(),e.strokeStyle=i,e.lineWidth=1.5,e.stroke()}else if(g.kind===0&&g.n>=3){e.fillStyle=f,e.beginPath(),e.moveTo(y,w);for(let C=1;C=0;l--){let u=n.chunks[l];if(u.layer<32&&(p>>>u.layer&1)===1)continue;for(let d=0;dm.x1+a||rm.y1+a)continue;let f=(m.x1-m.x0+1)*(m.y1-m.y0+1);if(f{if(this.canvas.setPointerCapture(e.pointerId),this.pointers.set(e.pointerId,{x:e.clientX,y:e.clientY}),this.pointers.size===1)this.dragStart={x:e.clientX,y:e.clientY,cx:this.cx,cy:this.cy,moved:!1},this.pinchStart=null;else if(this.pointers.size===2){let[t,n]=Array.from(this.pointers.values());this.pinchStart={dist:Math.hypot(n.x-t.x,n.y-t.y)||1,midX:(t.x+n.x)*0.5,midY:(t.y+n.y)*0.5,scale:this.scale,cx:this.cx,cy:this.cy},this.dragStart=null}};onPointerMove=(e)=>{if(!this.pointers.has(e.pointerId))return;if(this.pointers.set(e.pointerId,{x:e.clientX,y:e.clientY}),this.pointers.size===2&&this.pinchStart){let[t,n]=Array.from(this.pointers.values()),i=Math.hypot(n.x-t.x,n.y-t.y)||1,s=(t.x+n.x)*0.5,r=(t.y+n.y)*0.5,a=i/this.pinchStart.dist,o=Math.max(0.0000001,Math.min(2,this.pinchStart.scale*a)),c=this.canvas.getBoundingClientRect(),p=this.pinchStart.midX-c.left-c.width*0.5,l=this.pinchStart.midY-c.top-c.height*0.5,u=s-c.left-c.width*0.5,d=r-c.top-c.height*0.5;this.scale=o,this.cx=this.pinchStart.cx+p/this.pinchStart.scale-u/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 Gs=[{id:"fit",label:"Fit"},{id:"iso",label:"Iso"},{id:"top",label:"Top"},{id:"bottom",label:"Bottom"},{id:"front",label:"Front"},{id:"right",label:"Right"},{id:"back",label:"Back"},{id:"left",label:"Left"}];function Os(e){switch(e){case"top":return{yaw:0,pitch:Math.PI*0.499};case"bottom":return{yaw:0,pitch:-Math.PI*0.499};case"front":return{yaw:0,pitch:0};case"right":return{yaw:Math.PI*0.5,pitch:0};case"back":return{yaw:Math.PI,pitch:0};case"left":return{yaw:-Math.PI*0.5,pitch:0};case"iso":case"fit":default:return{yaw:0.6,pitch:0.7}}}function zn(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 qn{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 ea=`#version 300 es +`),h=document.createElement("div");h.className="bp-code-block";let d=document.createElement("div");d.className="bp-code-head";let u=document.createElement("span");u.className="bp-code-lang",u.textContent=c||"code";let f=document.createElement("button");f.type="button",f.className="bp-btn-ghost bp-code-copy";let b=m("common.copy","Copy");f.textContent=b,f.addEventListener("click",()=>{navigator.clipboard?.writeText(l).then(()=>{f.textContent="✓",window.setTimeout(()=>{f.textContent=b},1200)}).catch(()=>{})}),d.append(u,f);let v=document.createElement("pre"),y=document.createElement("code");y.textContent=l,v.appendChild(y),h.append(d,v),t.appendChild(h);continue}if(!s.trim()){i++;continue}let r=/^(#{1,4})\s+(.+)$/.exec(s);if(r){let c=document.createElement(`h${Math.min(4,r[1].length+1)}`);c.className="bp-md-h",Ht(c,r[2]),t.appendChild(c),i++;continue}if(s.startsWith("> ")){let c=document.createElement("blockquote");c.className="bp-md-quote";let p=[];while(i "))p.push(n[i].slice(2)),i++;Ht(c,p.join(` +`)),t.appendChild(c);continue}if(/^\s*[-*]\s+/.test(s)){let c=document.createElement("ul");c.className="bp-md-list";while(i ")&&!/^\s*[-*]\s+/.test(n[i])&&!/^\s*\d+\.\s+/.test(n[i]))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"));Ht(o,a[c])}t.appendChild(o)}return t}var Ir=new Set(["(","[",'"',"'","`"]);function Rr(e){return/[\p{L}\p{N}\-_\/+\[]/u.test(e)}function jr(e){return/[\p{L}\p{N}\-_\/]/u.test(e)}function Hr(e){return/[\p{L}\p{N}]/u.test(e)}function Ni(e,t){if(!e)return[];let n=(t??[]).filter((r)=>r.kind==="model"&&r.word&&r.label);if(n.length===0)return[{kind:"text",text:e}];let i=[],s=0;while(sa)r=l,a=h,o=c;break}p=l+1}}if(o===null)break;if(r>s)i.push({kind:"text",text:e.slice(s,r)});i.push({kind:"model",word:o.word,label:o.label}),s=a}if(s3600000)return"";let t=Math.max(1,Math.round(e/1000));if(t<60)return`${t}s`;let n=Math.floor(t/60),i=t%60;return i>0?`${n}m ${i}s`:`${n}m`}function $r(e,t){let n=document.createDocumentFragment(),i=Ni(e,t),s=m("native.thread.model","Model").toLowerCase();for(let r of i){if(r.kind==="text"){n.appendChild(document.createTextNode(r.text));continue}let a=document.createElement("span");a.className="bp-ref-chip bp-ref-model",a.title=r.word,a.setAttribute("data-ref-word",r.word);let o=document.createElement("span");o.className="bp-ref-sigil",o.textContent="&";let c=document.createElement("span");c.className="bp-ref-label",c.textContent=r.label;let p=document.createElement("span");p.className="bp-ref-kind",p.textContent=s,a.append(o,c,p),n.appendChild(a)}return n}function Or(e){e.addEventListener("copy",(t)=>{let n=typeof window<"u"?window.getSelection():null;if(!n||n.rangeCount===0||n.isCollapsed)return;let i=n.getRangeAt(0);if(!e.contains(i.commonAncestorContainer))return;let s=i.commonAncestorContainer,o=(s.nodeType===Node.ELEMENT_NODE?s:s.parentElement)?.closest(".bp-ref-chip[data-ref-word]")?.getAttribute("data-ref-word"),c;if(o)c=o;else{let p=i.cloneContents(),l=p.querySelectorAll(".bp-ref-chip[data-ref-word]");if(l.length===0)return;for(let d of l){let u=d.getAttribute("data-ref-word")||d.textContent||"";d.replaceWith(document.createTextNode(u))}let h=p.querySelectorAll(".bp-entry");for(let d=1;d{if(!this.loadingOlder&&this.hasMore)this.loadingOlder=!0,this.cb.onLoadOlder()}),this.scrollEl.addEventListener("scroll",()=>{if(this.pinnedToBottom=this.isNearBottom(),this.hasMore&&!this.loadingOlder&&this.scrollEl.scrollTop<48)this.loadingOlder=!0,this.cb.onLoadOlder()}),typeof ResizeObserver<"u"){let n=0;new ResizeObserver(()=>{let s=this.scrollEl.clientHeight;if(n>0&&s!==n&&this.pinnedToBottom)this.scrollToBottom();n=s}).observe(this.scrollEl)}this.listEl=document.createElement("div"),this.listEl.className="bp-timeline-list",Or(this.scrollEl),this.scrollEl.append(this.olderBtn,this.listEl),e.append(this.bannerEl,this.scrollEl)}setLoading(e){this.thread=e,this.entries=[],this.hasMore=!1,this.loadingOlder=!1,this.review=null,this.unanswered=null,this.btwNote=null,this.liveNodes.clear(),this.planExpanded.clear(),this.planRevisingId="",this.planReviseDrafts.clear(),this.renderBanners(),this.olderBtn.classList.add("bp-hidden");let t=document.createElement("div");t.className="bp-empty-state",t.textContent=m("web.chat.loading","Loading messages…"),this.listEl.replaceChildren(t)}setError(e,t,n){this.thread=e,this.entries=[],this.hasMore=!1,this.loadingOlder=!1,this.review=null,this.unanswered=null,this.btwNote=null,this.liveNodes.clear(),this.planExpanded.clear(),this.planRevisingId="",this.planReviseDrafts.clear(),this.renderBanners(),this.olderBtn.classList.add("bp-hidden");let i=document.createElement("div");i.className="bp-empty-state";let s=document.createElement("div");s.className="bp-bad",s.textContent=t;let r=document.createElement("button");r.type="button",r.textContent=m("tools.retry","Retry"),r.addEventListener("click",n),i.append(s,r),this.listEl.replaceChildren(i)}getEntries(){return this.entries.slice()}refreshLocale(){let e=this.scrollEl.scrollTop;if(this.olderBtn.textContent=m("android.load.earlier","Load earlier"),this.renderBanners(),this.thread&&this.entries.length>0)this.renderEntries(!1);this.scrollEl.scrollTop=e}setThread(e,t,n,i,s){if((this.thread?.id??"")!==(e?.id??""))this.planExpanded.clear(),this.planRevisingId="",this.planReviseDrafts.clear();this.thread=e,this.entries=t.filter((r)=>!Cn(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)=>!Cn(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(Cn(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(Dt(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||m("web.chat.review.mode","Review mode"),t.appendChild(n),this.review.button){let i=document.createElement("button");i.type="button",i.textContent=this.review.button,i.addEventListener("click",()=>this.cb.onToggleReview(!(this.review?.on??!0))),t.appendChild(i)}e.appendChild(t)}if(this.unanswered&&(this.unanswered.head||this.unanswered.text)){let t=document.createElement("div");t.className="bp-banner bp-unanswered",t.setAttribute("data-testid","unanswered-notice");let n=document.createElement("div");if(n.className="bp-unanswered-body",this.unanswered.head){let i=document.createElement("strong");i.textContent=this.unanswered.head,n.appendChild(i)}if(this.unanswered.text){let i=document.createElement("span");i.textContent=this.unanswered.text,n.appendChild(i)}if(t.appendChild(n),this.unanswered.buttons?.length){let i=document.createElement("div");i.className="bp-banner-actions";for(let s of this.unanswered.buttons){let r=document.createElement("button");if(r.type="button",s.primary)r.className="primary";r.textContent=s.label,r.addEventListener("click",()=>this.cb.onUnansweredAction(s.action,s.value)),i.appendChild(r)}t.appendChild(i)}e.appendChild(t)}if(this.btwNote){let t=document.createElement("div");t.className="bp-banner bp-btw-banner";let n=document.createElement("div"),i=document.createElement("div");i.className="bp-dim",i.textContent=`/btw ${this.btwNote.q}`;let s=document.createElement("div");s.appendChild(Dt(this.btwNote.a)),n.append(i,s);let r=document.createElement("button");r.type="button",r.className="icon",r.textContent="×",r.addEventListener("click",()=>{this.btwNote=null,this.renderBanners()}),t.append(n,r),e.appendChild(t)}this.bannerEl.replaceChildren(e)}makeEntryActions(e,t,n){let i=document.createElement("div");i.className="bp-entry-foot"+(t?" user":"");let s=document.createElement("button");s.type="button",s.className="bp-entry-act";let r=m("common.copy","Copy"),a=document.createElement("span");a.textContent=r,s.append(Ft(["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=m("reply.action","Reply"),o.append(Ft(["M9 17l-5-5 5-5","M20 18v-2a4 4 0 0 0-4-4H4"]),c),o.addEventListener("click",()=>this.cb.onReplyEntry(e));let p=!e.live&&!e.id.startsWith("local-")&&!e.id.startsWith("live:"),l=document.createElement("span");l.className="bp-entry-time";let h=Dr(e.at);if(t)l.textContent=h,i.append(s,...p?[o]:[],l);else{let d=n&&e.at?Fr(xn(e.at)-xn(n)):"",u=h?d?m("web.chat.finished.dur","Finished {time} · {dur}",{time:h,dur:d}):m("web.chat.finished","Finished {time}",{time:h}):"";l.textContent=e.live?m("web.chat.streaming","Streaming…"):u,i.append(l,s,...p?[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=m("web.chat.choose","Choose a project thread on the left to begin."),i.appendChild(r),this.listEl.replaceChildren(i);return}if(this.entries.length===0){let r=document.createElement("div");r.className="bp-empty-state",r.textContent=m("web.chat.empty","No messages yet. Type below to start a turn."),i.appendChild(r),this.listEl.replaceChildren(i);return}let s=0;for(let r of this.entries){if(r.kind==="user"&&r.at)s=r.at;let 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 h=document.createElement("span");if(h.className="bp-tool-name",h.textContent=r.tool.name,l.appendChild(h),r.tool.summary){let d=document.createElement("span");d.className="bp-tool-summary",d.textContent=r.tool.summary,l.appendChild(d)}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 h=document.createElement("div");h.className="bp-ask-card",h.setAttribute("data-testid",`ask-${l.id}`);let d=document.createElement("div");if(d.className="bp-ask-q",d.textContent=l.question,h.appendChild(d),l.state==="open"){let u=document.createElement("div");if(u.className="bp-ask-opts",l.options&&l.options.length>0)for(let f of l.options){let b=document.createElement("button");b.type="button",b.textContent=f.label,b.addEventListener("click",()=>this.cb.onAnswerAsk(l.id,f.id)),u.appendChild(b)}else{let f=document.createElement("input");f.type="text",f.className="bp-input",f.placeholder=m("web.chat.answer.placeholder","Type answer…");let b=document.createElement("button");b.type="button",b.className="primary",b.textContent=m("web.chat.answer.btn","Answer"),b.addEventListener("click",()=>{if(f.value.trim())this.cb.onAnswerAsk(l.id,f.value.trim())}),u.append(f,b)}h.appendChild(u)}else{let u=document.createElement("div");u.className="bp-ask-answered",u.textContent=m("web.chat.answered","Answered: {answer}",{answer:l.answered??""}),h.appendChild(u)}a.appendChild(h),i.appendChild(a);continue}let o=Boolean(r.text&&r.text.trim().length>0),c=Boolean(r.images&&r.images.length>0),p=Boolean(r.attachments&&r.attachments.length>0);if(!o&&!c&&!p&&!r.live)continue;if(r.replyTo?.quote){let l=document.createElement("div");l.className="bp-reply-quote",l.textContent=m("gpui.b.in.reply.to","↩ In reply to: {quote}",{quote:r.replyTo.quote});let h=r.replyTo.id;l.setAttribute("role","button"),l.tabIndex=0,l.setAttribute("data-testid","entry-reply-quote");let d=()=>{if(this.cb.onGoToEntry)this.cb.onGoToEntry(h);else this.goTo(h)};l.addEventListener("click",d),l.addEventListener("keydown",(u)=>{if(u.key==="Enter"||u.key===" ")u.preventDefault(),d()}),a.appendChild(l)}if(o||r.live){let l=document.createElement("div");if(l.className="bp-entry-body",r.kind==="user")l.appendChild($r(r.text||"",r.refs));else l.appendChild(Dt(r.text||""));if(r.live)this.liveNodes.set(r.id,l);a.appendChild(l)}if(p&&r.attachments){let l=document.createElement("div");l.className="bp-entry-images";for(let h of r.attachments)if(h.previewUrl){let d=document.createElement("img");d.className="bp-reply-img",d.src=h.previewUrl,d.alt=h.name||"attachment",l.appendChild(d)}else if(h.path||h.name){let d=document.createElement("span");d.className="bp-tool-pill",d.textContent=h.name||h.path||"image",l.appendChild(d)}if(l.childElementCount>0)a.appendChild(l)}if(r.images&&r.images.length>0){let l=document.createElement("div");l.className="bp-entry-images";for(let h of r.images){let d=document.createElement("img");d.className="bp-reply-img",d.alt=h;let u=`${r.id}|${h}`,f=this.imageCache.get(u);if(f)d.src=f;else this.cb.onLoadImage(r.id,h).then((b)=>{if(!b)return;let v=b.url??(b.mime&&b.data?`data:${b.mime};base64,${b.data}`:"");if(!v)return;this.imageCache.set(u,v),d.src=v});l.appendChild(d)}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=Ft(["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"?m("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=m("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 h=m("common.copy","Copy"),d=document.createElement("span");d.textContent=h,l.append(Ft(["M9 9h11v11H9z","M5 15H4a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1h10a1 1 0 0 1 1 1v1"]),d),l.addEventListener("click",()=>{navigator.clipboard?.writeText(e.question).then(()=>{l.classList.add("copied"),d.textContent=m("web.clone.copied","Copied"),window.setTimeout(()=>{l.classList.remove("copied"),d.textContent=h},1200)}).catch(()=>{})}),s.appendChild(l)}let c=document.createElement("button");c.type="button",c.className="bp-plan-head-btn",c.setAttribute("data-testid","plan-expand"),c.textContent=t?m("gpui.c.term.collapse","Collapse"):m("gpui.c.term.expand","Expand"),c.addEventListener("click",()=>{if(this.planExpanded.has(e.id))this.planExpanded.delete(e.id);else this.planExpanded.add(e.id);let l=this.scrollEl.scrollTop;this.renderEntries(!1),this.scrollEl.scrollTop=l}),s.appendChild(c),i.appendChild(s);let p=document.createElement("div");if(p.className="bp-plan-body"+(t?" is-expanded":""),p.setAttribute("data-testid","plan-body"),p.appendChild(Dt(e.question||"")),i.appendChild(p),e.state==="open"){let l=document.createElement("div");l.className="bp-plan-actions";let h=e.options?.find((b)=>b.id==="implement"||b.id.endsWith("|implement")),d=document.createElement("button");if(d.type="button",d.className="primary",d.setAttribute("data-testid","plan-implement"),d.textContent=h?.label&&h.label!=="Implement"?pe(h.label):m("approval.implement","Implement"),d.addEventListener("click",()=>{this.planRevisingId="",this.planReviseDrafts.delete(e.id),this.cb.onAnswerAsk(e.id,h?.id??"implement")}),l.appendChild(d),e.revise!==!1){let b=document.createElement("button");b.type="button",b.className="bp-plan-revise-btn"+(n?" active":""),b.setAttribute("data-testid","plan-revise"),b.append(Ft(["M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7","M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"]),document.createTextNode(m("gpui.ask.plan.revise","Revise"))),b.addEventListener("click",()=>{let v=this.planRevisingId!==e.id;this.planRevisingId=v?e.id:"";let y=this.scrollEl.scrollTop;if(this.renderEntries(!1),this.scrollEl.scrollTop=y,v)this.listEl.querySelector(`[data-testid="ask-${CSS.escape(e.id)}"] .bp-plan-revise-input`)?.focus()}),l.appendChild(b)}let u=e.options?.find((b)=>b.id==="dismiss"||b.id.endsWith("|dismiss")),f=document.createElement("button");if(f.type="button",f.className="bp-plan-dismiss-btn",f.setAttribute("data-testid","plan-dismiss"),f.textContent=u?.label&&u.label!=="Dismiss"?pe(u.label):m("approval.dismiss","Dismiss"),f.addEventListener("click",()=>{this.planRevisingId="",this.planReviseDrafts.delete(e.id),this.cb.onAnswerAsk(e.id,u?.id??"dismiss")}),l.appendChild(f),i.appendChild(l),n){let b=document.createElement("div");b.className="bp-plan-revise",b.setAttribute("data-testid","plan-revise-drawer");let v=document.createElement("textarea");v.rows=2,v.className="bp-input bp-plan-revise-input",v.placeholder=m("gpui.ask.plan.reviseph","What should change in the plan?"),v.value=this.planReviseDrafts.get(e.id)??"";let y=document.createElement("button");y.type="button",y.className="bp-plan-revise-send",y.setAttribute("data-testid","plan-revise-send"),y.textContent=m("gpui.ask.plan.sendrev","Send revision"),y.disabled=v.value.trim().length===0;let w=()=>{let N=v.value.trim();if(!N)return;this.planRevisingId="",this.planReviseDrafts.delete(e.id),this.cb.onAnswerAsk(e.id,`revise:${N}`)},C=()=>{this.closePlanRevise()};b.addEventListener("keydown",(N)=>{if(N.key==="Escape")N.preventDefault(),N.stopPropagation(),C()}),v.addEventListener("input",()=>{this.planReviseDrafts.set(e.id,v.value),y.disabled=v.value.trim().length===0}),v.addEventListener("keydown",(N)=>{if(N.key==="Enter"&&!N.shiftKey)N.preventDefault(),w()}),y.addEventListener("click",w);let L=document.createElement("button");L.type="button",L.className="bp-btn-ghost",L.textContent=m("common.cancel","Cancel"),L.addEventListener("click",C),b.append(v,y,L),i.appendChild(b)}}else{let l=document.createElement("div");l.className="bp-ask-answered",l.textContent=m("web.chat.answered","Answered: {answer}",{answer:e.answered??""}),i.appendChild(l)}return i}}var Gr={claude:"Claude Code",codex:"Codex CLI",grok:"Grok CLI",muse:"Muse Code",antigravity:"Google Antigravity",opencode:"OpenCode",pi:"Pi",omp:"Oh My Pi"};var Ti=/[\x00-\x1f\x7f]/,Vr=/\s/;function wt(e){return e.trim().replace(/^@+/,"").toLowerCase()}function ht(e,t){if(Ti.test(e)||Ti.test(t))return"";let n=wt(e),i=t.trim();if(!n||!i||n.includes("/")||Vr.test(n))return"";if(n.length+1+i.length>200)return"";return`${n}/${i}`}function Bi(e){let t=e.indexOf("/");if(t<=0)return null;let n=e.slice(0,t),i=e.slice(t+1);if(!ht(n,i))return null;return{provider:wt(n),model:i.trim()}}function lt(e){if(!Array.isArray(e))return[];let t=[],n=new Set;for(let i of e){if(typeof i!=="string")continue;let s=Bi(i);if(!s)continue;let r=`${s.provider}/${s.model}`;if(!n.has(r)){if(n.add(r),t.push(r),t.length>=64)break}}return t}function Sn(e,t,n,i){let s=ht(t,n),r=lt(e);if(!s)return{keys:r,starred:!1};let a=r.indexOf(s),o=i!==void 0?i:a<0;if(o&&a<0){if(r.length>=64)return{keys:r,starred:!1};r.push(s)}else if(!o&&a>=0)r.splice(a,1);return{keys:r,starred:o}}function tt(e){return e&&typeof e==="object"&&!Array.isArray(e)?e:null}function yt(e){return Array.isArray(e)?e:[]}function Le(e){return typeof e==="string"?e:""}function Ur(e){return Gr[e]??e}function Ii(e,t,n,i){let s=new Map;for(let a of e)s.set(a.provider,a);let r=[];for(let a of lt(t)){let o=Bi(a);if(!o)continue;let c=s.get(o.provider),p=Boolean(c&&c.models.some((u)=>u.value!=="")),l=c?.models.find((u)=>u.value===o.model),h=l?l.ok&&(c?.ok??!0):c?.ok??!0,d=l?.why||c?.why||"";if(h&&p&&!l)h=!1,d="not available on this machine";r.push({key:a,provider:o.provider,model:o.model,label:l?.label||o.model,note:l?.note||"",on:o.provider===n&&o.model===i,ok:h,why:d})}return r}function Ri(e,t=[]){let n=tt(e),i=tt(n?.picker)??n??{},s=yt(i.sections).map(tt).filter((x)=>Boolean(x)),r=(x)=>s.find((Y)=>Le(Y.action)===x),a=r("provider"),o=r("model"),c=r("effort"),p=yt(a?.choices).map(tt).filter((x)=>Boolean(x)),l=yt(o?.choices).map(tt).filter((x)=>Boolean(x)),h=yt(c?.choices).map(tt).filter((x)=>Boolean(x)),d=Le(i.chip),u=Le(p.find((x)=>x.on===!0)?.value)||d.split("/")[0]?.trim()||"claude",f=wt(u)||"claude",b=Le(l.find((x)=>x.on===!0)?.value),v=Le(h.find((x)=>x.on===!0)?.value),y=h.map((x)=>({value:Le(x.value),label:Le(x.label)||"auto",on:x.on===!0})),w=tt(i.agents),C=[],L=new Set,N=(x)=>{let Y=wt(x);if(Y&&!L.has(Y))L.add(Y),C.push(Y)};for(let x of p)N(Le(x.value)||Le(x.label));if(w)for(let x of Object.keys(w))N(x);N(f);let A=C.map((x)=>{let Y=p.find((ee)=>wt(Le(ee.value)||Le(ee.label))===x),se=tt(w?.[x]),ne=se?se.ok!==!1:Y?Y.ok!==!1:!0,he=Le(se?.why)||Le(Y?.why),Se=yt(se?.models).map(tt).filter((ee)=>Boolean(ee)),ke;if(Se.length>0)ke=Se.map((ee)=>{let re=Le(ee.value),R=Le(ee.label)||(re===""?"default":re),ue=Le(ee.note);return{value:re,label:R,note:ue,on:x===f&&re===b,ok:ee.ok!==!1&&ne,why:Le(ee.why)||he}});else if(x===f&&l.length>0)ke=l.map((ee)=>{let re=Le(ee.value),R=Le(ee.label);return{value:re,label:re===""?"default":re,note:R&&R!==re?R:"",on:ee.on===!0,ok:ee.ok!==!1&&ne,why:Le(ee.why)||he}});else if(ne)ke=[{value:"",label:"default",note:"",on:x===f&&b==="",ok:!0,why:""}];else ke=[];if(x===f&&b&&!ke.some((ee)=>ee.value===b)){let ee=l.find((R)=>Le(R.value)===b),re=Le(ee?.label);ke.push({value:b,label:b,note:re&&re!==b?re:"",on:!0,ok:!0,why:""})}return{provider:x,label:Ur(x),ok:ne,why:he,models:ke}}),B=Array.isArray(i.favoriteKeys),M=yt(i.favorites).map(tt).filter((x)=>Boolean(x)),j=B?lt(i.favoriteKeys):M.length>0?lt(M.map((x)=>Le(x.key)||ht(Le(x.provider),Le(x.model)))):lt(t),O=M.length>0?M.map((x)=>{let Y=wt(Le(x.provider)),se=Le(x.model).trim(),ne=ht(Y,se);if(!ne)return null;return{key:ne,provider:Y,model:se,label:Le(x.label)||se,note:Le(x.note),on:x.on===!0||Y===f&&se===b,ok:x.ok!==!1,why:Le(x.why)}}).filter((x)=>Boolean(x)):Ii(A,j,f,b);return{chip:d,provider:f,model:b,effort:v,efforts:y,providers:A,favoriteKeys:j,favorites:O}}function $t(e,t){let n=lt(t);return{...e,favoriteKeys:n,favorites:Ii(e.providers,n,e.provider,e.model)}}function ji(e,t){let n=t.trim().toLowerCase().split(/\s+/).filter(Boolean),i=(o)=>{if(n.length===0)return!0;let c=o.toLowerCase();return n.every((p)=>c.includes(p))},s=new Set(e.favoriteKeys),r=e.favorites.filter((o)=>i(`${o.provider} ${o.model} ${o.label} ${o.note}`)),a=[];for(let o of e.providers){let c=o.models.filter((p)=>i(`${o.provider} ${o.label} ${p.value} ${p.label} ${p.note}`)).map((p)=>{let l=p.value?ht(o.provider,p.value):"";return{...p,provider:o.provider,starrable:p.value!=="",starred:Boolean(l&&s.has(l))}});if(c.length>0||n.length===0&&!o.ok&&o.why)a.push({provider:o.provider,label:o.label,ok:o.ok,why:o.why,models:c})}return{favorites:r,groups:a,efforts:e.efforts}}var Hi={claude:{viewBox:"0 0 24 24",d:"m4.7144 15.9555 4.7174-2.6471.079-.2307-.079-.1275h-.2307l-.7893-.0486-2.6956-.0729-2.3375-.0971-2.2646-.1214-.5707-.1215-.5343-.7042.0546-.3522.4797-.3218.686.0608 1.5179.1032 2.2767.1578 1.6514.0972 2.4468.255h.3886l.0546-.1579-.1336-.0971-.1032-.0972L6.973 9.8356l-2.55-1.6879-1.3356-.9714-.7225-.4918-.3643-.4614-.1578-1.0078.6557-.7225.8803.0607.2246.0607.8925.686 1.9064 1.4754 2.4893 1.8336.3643.3035.1457-.1032.0182-.0728-.164-.2733-1.3539-2.4467-1.445-2.4893-.6435-1.032-.17-.6194c-.0607-.255-.1032-.4674-.1032-.7285L6.287.1335 6.6997 0l.9957.1336.419.3642.6192 1.4147 1.0018 2.2282 1.5543 3.0296.4553.8985.2429.8318.091.255h.1579v-.1457l.1275-1.706.2368-2.0947.2307-2.6957.0789-.7589.3764-.9107.7468-.4918.5828.2793.4797.686-.0668.4433-.2853 1.8517-.5586 2.9021-.3643 1.9429h.2125l.2429-.2429.9835-1.3053 1.6514-2.0643.7286-.8196.85-.9046.5464-.4311h1.0321l.759 1.1293-.34 1.1657-1.0625 1.3478-.8804 1.1414-1.2628 1.7-.7893 1.36.0729.1093.1882-.0183 2.8535-.607 1.5421-.2794 1.8396-.3157.8318.3886.091.3946-.3278.8075-1.967.4857-2.3072.4614-3.4364.8136-.0425.0304.0486.0607 1.5482.1457.6618.0364h1.621l3.0175.2247.7892.522.4736.6376-.079.4857-1.2142.6193-1.6393-.3886-3.825-.9107-1.3113-.3279h-.1822v.1093l1.0929 1.0686 2.0035 1.8092 2.5075 2.3314.1275.5768-.3218.4554-.34-.0486-2.2039-1.6575-.85-.7468-1.9246-1.621h-.1275v.17l.4432.6496 2.3436 3.5214.1214 1.0807-.17.3521-.6071.2125-.6679-.1214-1.3721-1.9246L14.38 17.959l-1.1414-1.9428-.1397.079-.674 7.2552-.3156.3703-.7286.2793-.6071-.4614-.3218-.7468.3218-1.4753.3886-1.9246.3157-1.53.2853-1.9004.17-.6314-.0121-.0425-.1397.0182-1.4328 1.9672-2.1796 2.9446-1.7243 1.8456-.4128.164-.7164-.3704.0667-.6618.4008-.5889 2.386-3.0357 1.4389-1.882.929-1.0868-.0062-.1579h-.0546l-6.3385 4.1164-1.1293.1457-.4857-.4554.0608-.7467.2307-.2429 1.9064-1.3114Z"},codex:{viewBox:"0 0 256 260",d:"M239.184 106.203a64.716 64.716 0 0 0-5.576-53.103C219.452 28.459 191 15.784 163.213 21.74A65.586 65.586 0 0 0 52.096 45.22a64.716 64.716 0 0 0-43.23 31.36c-14.31 24.602-11.061 55.634 8.033 76.74a64.665 64.665 0 0 0 5.525 53.102c14.174 24.65 42.644 37.324 70.446 31.36a64.72 64.72 0 0 0 48.754 21.744c28.481.025 53.714-18.361 62.414-45.481a64.767 64.767 0 0 0 43.229-31.36c14.137-24.558 10.875-55.423-8.083-76.483Zm-97.56 136.338a48.397 48.397 0 0 1-31.105-11.255l1.535-.87l51.67-29.825a8.595 8.595 0 0 0 4.247-7.367v-72.85l21.845 12.636c.218.111.37.32.409.563v60.367c-.056 26.818-21.783 48.545-48.601 48.601Zm-104.466-44.61a48.345 48.345 0 0 1-5.781-32.589l1.534.921l51.722 29.826a8.339 8.339 0 0 0 8.441 0l63.181-36.425v25.221a.87.87 0 0 1-.358.665l-52.335 30.184c-23.257 13.398-52.97 5.431-66.404-17.803ZM23.549 85.38a48.499 48.499 0 0 1 25.58-21.333v61.39a8.288 8.288 0 0 0 4.195 7.316l62.874 36.272l-21.845 12.636a.819.819 0 0 1-.767 0L41.353 151.53c-23.211-13.454-31.171-43.144-17.804-66.405v.256Zm179.466 41.695l-63.08-36.63L161.73 77.86a.819.819 0 0 1 .768 0l52.233 30.184a48.6 48.6 0 0 1-7.316 87.635v-61.391a8.544 8.544 0 0 0-4.4-7.213Zm21.742-32.69l-1.535-.922l-51.619-30.081a8.39 8.39 0 0 0-8.492 0L99.98 99.808V74.587a.716.716 0 0 1 .307-.665l52.233-30.133a48.652 48.652 0 0 1 72.236 50.391v.205ZM88.061 139.097l-21.845-12.585a.87.87 0 0 1-.41-.614V65.685a48.652 48.652 0 0 1 79.757-37.346l-1.535.87l-51.67 29.825a8.595 8.595 0 0 0-4.246 7.367l-.051 72.697Zm11.868-25.58L128.067 97.3l28.188 16.218v32.434l-28.086 16.218l-28.188-16.218l-.052-32.434Z"},grok:{viewBox:"0 0 24 24",d:"M9.497 15.122 L16.811 9.491 C17.169 9.215 17.682 9.323 17.852 9.751 C18.752 12.013 18.35 14.73 16.561 16.596 C14.772 18.462 12.283 18.871 10.007 17.939 L7.522 19.139 C11.087 21.68 15.416 21.052 18.121 18.229 C20.267 15.991 20.931 12.941 20.31 10.19 L20.315 10.196 C19.414 6.155 20.537 4.54 22.837 1.237 C22.891 1.159 22.946 1.08 23 1 L19.974 4.156 L19.974 4.146 L9.495 15.124 M7.987 16.49 C5.429 13.941 5.87 9.996 8.053 7.721 C9.667 6.037 12.313 5.35 14.622 6.361 L17.102 5.166 C16.655 4.829 16.082 4.467 15.425 4.213 C12.455 2.938 8.9 3.573 6.485 6.088 C4.163 8.51 3.433 12.234 4.687 15.411 C5.624 17.786 4.088 19.466 2.541 21.162 C1.993 21.763 1.443 22.364 1 23 L7.985 16.492"},muse:{viewBox:"0 0 24 24",d:"M10.73.032c-1.333 0-2.032 1.016-2.032 2.285 0 2.223 2.127 4.953 4.318 4.953 1.301 0 2-.953 2-2.254 0-2.254-2.095-4.984-4.286-4.984m8.413 2.984c-1.968 0-3.397 2.73-3.397 4.825 0 1.556.794 3.016 2.254 3.016 2 0 3.365-2.762 3.365-4.794 0-1.523-.762-3.047-2.222-3.047M4.857 4.159c-1.968 0-3.778 1.016-3.778 2.54 0 1.65 2.16 2.793 4.254 2.793 1.873 0 3.778-.92 3.778-2.508 0-1.682-2.159-2.825-4.254-2.825m-.222 6.476C2.413 10.635 0 13.175 0 15.397c0 1.301.825 2.159 2.095 2.159 2.19 0 4.603-2.508 4.603-4.794 0-1.27-.761-2.127-2.063-2.127m16.667.698c-2.223 0-5.016 1.62-5.016 3.651 0 1.238 1.047 2.19 2.698 2.19 2.159 0 5.016-1.587 5.016-3.682 0-1.302-1.08-2.159-2.698-2.159M7.619 16c-1.524 0-2.38 1.746-2.38 3.429 0 2.063 1.269 4.54 3.047 4.54 1.524 0 2.38-1.81 2.38-3.461C10.667 18.57 9.46 16 7.62 16m6.571 1.016c-1.333 0-2.476.667-2.476 2.032 0 2.095 2.667 4.063 4.92 4.063 1.366 0 2.54-.73 2.54-2.063 0-2.032-2.698-4.032-4.984-4.032"},antigravity:{viewBox:"0 0 24 24",d:"M20.197 20.618 C21.318 21.459 23 20.898 21.459 19.357 C16.834 14.873 17.815 2.541 12.07 2.541 C6.325 2.541 7.306 14.873 2.682 19.357 C1 21.038 2.822 21.459 3.943 20.618 C8.287 17.675 8.006 12.49 12.07 12.49 C16.134 12.49 15.853 17.675 20.197 20.618 Z"},opencode:{viewBox:"0 0 24 24",d:"M22 24H2V0h20zM17 4.8H7v14.4h10z"},pi:{viewBox:"0 0 24 24",d:"M0 0v24h6v-6h6v-6H6V6h6v6h6V0Zm18 12v12h6V12Z"},omp:{viewBox:"0 0 24 24",d:"M1.44 3.86 L22.56 3.86 C23 3.86 23 3.86 23 4.3 L23 6.06 C23 6.5 23 6.5 22.56 6.5 L1.44 6.5 C1 6.5 1 6.5 1 6.06 L1 4.3 C1 3.86 1 3.86 1.44 3.86 Z M4.74 6.5 L6.5 6.5 C6.94 6.5 6.94 6.5 6.94 6.94 L6.94 19.7 C6.94 20.14 6.94 20.14 6.5 20.14 L4.74 20.14 C4.3 20.14 4.3 20.14 4.3 19.7 L4.3 6.94 C4.3 6.5 4.3 6.5 4.74 6.5 Z M15.74 6.5 L17.5 6.5 C17.94 6.5 17.94 6.5 17.94 6.94 L17.94 13.32 C17.94 13.76 17.94 13.76 17.5 13.76 L15.74 13.76 C15.3 13.76 15.3 13.76 15.3 13.32 L15.3 6.94 C15.3 6.5 15.3 6.5 15.74 6.5 Z M15.08 14.64 L18.16 14.64 C18.82 14.64 18.82 14.64 18.82 15.3 L18.82 17.5 C18.82 18.16 18.82 18.16 18.16 18.16 L15.08 18.16 C14.42 18.16 14.42 18.16 14.42 17.5 L14.42 15.3 C14.42 14.64 14.42 14.64 15.08 14.64 Z"}};var Et="http://www.w3.org/2000/svg",Di=4,Fi=new Set(["image/png","image/jpeg","image/webp","image/gif"]);function tn(e){let t=document.createElementNS(Et,"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(Et,"path");i.setAttribute("d",n),t.appendChild(i)}return t}function Ln(){return tn(["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 $i(){return tn(["M6 4l14 8-14 8z"])}function Oi(e){let t=document.createElementNS(Et,"svg");t.setAttribute("viewBox","0 0 24 24"),t.setAttribute("width","13"),t.setAttribute("height","13"),t.setAttribute("fill",e?"currentColor":"none"),t.setAttribute("stroke","currentColor"),t.setAttribute("stroke-width","1.8"),t.setAttribute("stroke-linejoin","round"),t.setAttribute("aria-hidden","true");let n=document.createElementNS(Et,"path");return n.setAttribute("d","M12 2.5l2.9 6 6.6.9-4.8 4.6 1.2 6.5L12 17.4l-5.9 3.1 1.2-6.5-4.8-4.6 6.6-.9z"),t.appendChild(n),t}function Gi(e){let t=(e||"").toLowerCase();if(t.includes("claude")||t.includes("anthropic"))return{mark:"claude",glyph:"A",color:"#d97757",title:"Claude"};if(t.includes("codex")||t.includes("openai"))return{mark:"codex",glyph:"O",color:"#10a37f",title:"Codex"};if(t.includes("gemini")||t.includes("antigravity")||t==="agy")return{mark:"antigravity",glyph:"G",color:"#4285f4",title:"Antigravity"};if(t.includes("grok"))return{mark:"grok",glyph:"X",color:"#6b7280",title:"Grok"};if(t.includes("muse"))return{mark:"muse",glyph:"M",color:"#8b5cf6",title:"Muse"};if(t.includes("opencode"))return{mark:"opencode",glyph:"C",color:"#2563eb",title:"OpenCode"};if(t.includes("omp")||t.includes("oh-my-pi"))return{mark:"omp",glyph:"Ω",color:"#c026d3",title:"Oh My Pi"};if(t==="pi"||t.startsWith("pi/")||t.startsWith("@pi"))return{mark:"pi",glyph:"π",color:"#db2777",title:"Pi"};return{glyph:"●",color:"var(--accent)",title:e||"Model"}}function Vi(e){let t=Hi[e];if(!t||!t.d)return null;let n=document.createElementNS(Et,"svg");n.setAttribute("viewBox",t.viewBox||"0 0 24 24"),n.setAttribute("width","14"),n.setAttribute("height","14"),n.setAttribute("fill","currentColor"),n.setAttribute("aria-hidden","true");let i=document.createElementNS(Et,"path");return i.setAttribute("d",t.d),n.appendChild(i),n}class An{popupEl;attachStripEl;planBarEl;fileInput;textarea;memoryEl;memoryFill;memoryText;modelBtn;providerMarkEl;modelTextEl;ctxEl;modelPickerEl;modelSearchInput;modelPickerBodyEl;modelPickerEffortsEl;modelPickerOpen=!1;modelPickerLoading=!1;modelPickerSnap=null;modelPickerQuery="";modelPickerFocusIdx=-1;onDocMouseDown;planChipBtn;planChipIconHost;planChipLbl;attachBtn;voiceBtn;sendBtn;stopBtn;errorEl;replyEl;cb;commands=[];popupMode="none";filteredSlash=[];mentionItems=[];popupIdx=0;enabled=!1;attachments=[];planMode=null;constructor(e,t){this.cb=t;let n=document.createElement("div");n.className="bp-composer",n.setAttribute("data-testid","composer");let i=document.createElement("div");i.className="bp-composer-inner",this.popupEl=document.createElement("div"),this.popupEl.className="bp-composer-popup bp-hidden",this.popupEl.setAttribute("data-testid","slash-menu"),this.errorEl=document.createElement("div"),this.errorEl.className="bp-composer-err bp-hidden",this.replyEl=document.createElement("div"),this.replyEl.className="bp-reply-strip bp-hidden",this.replyEl.setAttribute("data-testid","composer-reply"),this.attachStripEl=document.createElement("div"),this.attachStripEl.className="bp-attach-strip bp-hidden",this.attachStripEl.setAttribute("data-testid","composer-attachments"),this.planBarEl=document.createElement("div"),this.planBarEl.className="bp-plan-bar bp-hidden",this.planBarEl.setAttribute("data-testid","composer-plan-bar"),this.fileInput=document.createElement("input"),this.fileInput.type="file",this.fileInput.accept="image/png,image/jpeg,image/webp,image/gif",this.fileInput.multiple=!0,this.fileInput.className="bp-hidden",this.fileInput.setAttribute("data-testid","composer-file-input"),this.fileInput.addEventListener("change",()=>{if(this.fileInput.files)this.addFiles(Array.from(this.fileInput.files));this.fileInput.value=""}),this.textarea=document.createElement("textarea"),this.textarea.className="bp-composer-input",this.textarea.rows=2,this.textarea.placeholder=m("composer.placeholder","Ask anything: @bot, >thread, %project, #room, $skill, /btw"),this.textarea.setAttribute("data-testid","composer-input");let s=document.createElement("div");s.className="bp-composer-bar";let r=document.createElement("button");r.type="button",r.className="bp-composer-model",r.setAttribute("data-testid","composer-model-chip"),r.setAttribute("aria-haspopup","dialog"),r.setAttribute("aria-expanded","false"),r.title=m("composer.model.tip","Choose the model and effort"),this.modelBtn=r,this.providerMarkEl=document.createElement("span"),this.providerMarkEl.className="bp-provider-mark",this.providerMarkEl.textContent="●",this.modelTextEl=document.createElement("span"),this.modelTextEl.className="bp-model-text",this.modelTextEl.textContent="default",this.ctxEl=document.createElement("span"),this.ctxEl.className="bp-ctx-pct bp-hidden",this.ctxEl.setAttribute("data-testid","composer-ctx");let a=document.createElement("span");a.className="bp-model-caret",a.textContent="▾",r.append(this.providerMarkEl,this.modelTextEl,this.ctxEl,a),r.addEventListener("click",()=>{this.toggleModelPicker()}),this.modelPickerEl=document.createElement("div"),this.modelPickerEl.className="bp-model-picker bp-hidden",this.modelPickerEl.setAttribute("data-testid","model-picker"),this.modelPickerEl.setAttribute("role","dialog");let o=document.createElement("div");o.className="bp-mp-search-wrap",this.modelSearchInput=document.createElement("input"),this.modelSearchInput.type="search",this.modelSearchInput.className="bp-mp-search",this.modelSearchInput.placeholder=m("gpui.search.models","Search models"),this.modelSearchInput.setAttribute("data-testid","model-picker-search"),this.modelSearchInput.addEventListener("input",()=>{this.modelPickerQuery=this.modelSearchInput.value,this.modelPickerFocusIdx=-1,this.renderModelPicker()}),this.modelSearchInput.addEventListener("keydown",(l)=>{if(l.key==="Escape"){l.preventDefault(),l.stopPropagation(),this.closeModelPicker(),this.textarea.focus();return}if(l.key==="ArrowDown"||l.key==="ArrowUp"){let h=this.modelPickerFocusableButtons();if(h.length===0)return;l.preventDefault();let d=l.key==="ArrowDown"?1:-1;this.modelPickerFocusIdx=this.modelPickerFocusIdx<0?d>0?0:h.length-1:(this.modelPickerFocusIdx+d+h.length)%h.length,this.updateModelPickerKbdFocus(h);return}if(l.key==="Enter"){let h=this.modelPickerFocusableButtons(),d=this.modelPickerFocusIdx>=0&&this.modelPickerFocusIdxthis.cb.onCyclePlanMode?.()),this.memoryEl=document.createElement("div"),this.memoryEl.className="bp-composer-memory bp-hidden",this.memoryEl.setAttribute("data-testid","composer-memory");let c=document.createElement("div");c.className="bp-memory-meter",this.memoryFill=document.createElement("div"),this.memoryFill.className="bp-memory-fill",c.appendChild(this.memoryFill),this.memoryText=document.createElement("span"),this.memoryEl.append(c,this.memoryText);let p=document.createElement("div");p.className="bp-composer-btns",this.attachBtn=document.createElement("button"),this.attachBtn.type="button",this.attachBtn.className="icon bp-composer-tool",this.attachBtn.title=m("web.composer.attach","Attach image"),this.attachBtn.setAttribute("aria-label",m("web.composer.attach","Attach image")),this.attachBtn.setAttribute("data-testid","composer-attach"),this.attachBtn.appendChild(tn(["M21.44 11.05l-9.19 9.19a6 6 0 0 1-8.49-8.49l9.19-9.19a4 4 0 0 1 5.66 5.66l-9.2 9.19a2 2 0 0 1-2.83-2.83l8.49-8.48"])),this.attachBtn.addEventListener("click",()=>this.fileInput.click()),this.voiceBtn=document.createElement("button"),this.voiceBtn.type="button",this.voiceBtn.className="icon bp-composer-tool",this.voiceBtn.title=m("web.composer.voice","Voice dictation"),this.voiceBtn.setAttribute("aria-label",m("web.composer.voice","Voice dictation")),this.voiceBtn.setAttribute("data-testid","composer-voice"),this.voiceBtn.appendChild(tn(["M12 1a3 3 0 0 0-3 3v8a3 3 0 0 0 6 0V4a3 3 0 0 0-3-3z","M19 10v2a7 7 0 0 1-14 0v-2","M12 19v4","M8 23h8"])),this.voiceBtn.addEventListener("click",()=>this.cb.onToggleVoice?.()),this.stopBtn=document.createElement("button"),this.stopBtn.type="button",this.stopBtn.className="primary stop bp-hidden",this.stopBtn.textContent=m("composer.stop","Stop"),this.stopBtn.setAttribute("data-testid","composer-stop"),this.stopBtn.addEventListener("click",()=>this.cb.onInterrupt()),this.sendBtn=document.createElement("button"),this.sendBtn.type="button",this.sendBtn.className="primary bp-send-btn",this.sendBtn.textContent=m("composer.send","Send"),this.sendBtn.setAttribute("data-testid","composer-send"),this.sendBtn.addEventListener("click",()=>this.submit()),p.append(this.attachBtn,this.voiceBtn,this.stopBtn,this.sendBtn),s.append(r,this.planChipBtn,this.memoryEl,p),i.append(this.modelPickerEl,this.popupEl,this.errorEl,this.replyEl,this.attachStripEl,this.planBarEl,this.fileInput,this.textarea,s),n.appendChild(i),e.appendChild(n),this.onDocMouseDown=(l)=>{if(!this.modelPickerEl.isConnected){document.removeEventListener("mousedown",this.onDocMouseDown);return}if(!this.modelPickerOpen)return;let h=l.target;if(h&&(this.modelPickerEl.contains(h)||this.modelBtn.contains(h)))return;this.closeModelPicker()},document.addEventListener("mousedown",this.onDocMouseDown),this.textarea.addEventListener("paste",(l)=>{let h=l.clipboardData?.items;if(!h)return;let d=[];for(let u=0;u0)l.preventDefault(),this.addFiles(d)}),this.textarea.addEventListener("input",()=>{this.autoGrow(),this.clearError(),this.updatePopups()}),this.textarea.addEventListener("keydown",(l)=>{if(this.popupMode!=="none"){let h=this.popupMode==="slash"?this.filteredSlash.length:this.mentionItems.length;if(l.key==="ArrowDown"){l.preventDefault(),this.popupIdx=(this.popupIdx+1)%Math.max(1,h),this.renderPopup();return}if(l.key==="ArrowUp"){l.preventDefault(),this.popupIdx=(this.popupIdx-1+Math.max(1,h))%Math.max(1,h),this.renderPopup();return}if(l.key==="Tab"||l.key==="Enter"&&!l.shiftKey&&this.shouldCompleteOnEnter()){l.preventDefault(),this.applyPopupChoice(this.popupIdx);return}if(l.key==="Escape"){l.preventDefault(),this.closePopup();return}}if(l.key==="Tab"&&l.shiftKey&&this.planMode!==null){l.preventDefault(),this.cb.onCyclePlanMode?.();return}if(l.key==="Enter"&&!l.shiftKey)l.preventDefault(),this.submit()})}setCommands(e){this.commands=e.map((t)=>({...t,word:t.word.replace(/^\//,"")}))}setModelChip(e,t,n){let i=Gi(t),s=i.mark?Vi(i.mark):null;if(s)this.providerMarkEl.replaceChildren(s);else this.providerMarkEl.textContent=i.glyph;if(this.providerMarkEl.style.color=i.color,this.providerMarkEl.title=i.title,this.modelTextEl.textContent=e||"default",typeof n==="number"&&Number.isFinite(n)&&n>=0)this.ctxEl.textContent=`ctx ${Math.round(n)}%`,this.ctxEl.classList.remove("bp-hidden");else this.ctxEl.textContent="",this.ctxEl.classList.add("bp-hidden")}setFeatures(e,t){this.attachBtn.classList.toggle("bp-hidden",!e),this.voiceBtn.classList.toggle("bp-hidden",!t)}setVoiceRecording(e){this.voiceBtn.classList.toggle("recording",e),this.voiceBtn.setAttribute("aria-pressed",e?"true":"false")}setVoiceLevel(e){this.voiceBtn.setAttribute("data-level",String(e))}getDraft(){return this.textarea.value}getCaret(){return this.textarea.selectionStart??this.textarea.value.length}setMemory(e){if(this.memoryEl.classList.toggle("bp-hidden",!e),!e)return;let t=e.total??0,n=t>0?Math.min(1,(e.done??0)/t):1;this.memoryFill.style.width=`${Math.round(n*100)}%`,this.memoryFill.dataset.state=e.state??"",this.memoryText.textContent=e.line??"",this.memoryEl.title=[e.status,e.lines,e.viewLine].filter(Boolean).join(` +`)}setPlanMode(e){if(this.planMode=e,this.textarea.classList.remove("is-plan","is-plan-exec"),this.sendBtn.classList.remove("is-plan","is-plan-exec"),this.planChipBtn.classList.remove("is-plan","is-exec"),this.planBarEl.classList.remove("is-exec"),!e){this.planChipBtn.classList.add("bp-hidden"),this.planChipBtn.setAttribute("aria-pressed","false"),this.planBarEl.classList.add("bp-hidden"),this.planBarEl.replaceChildren(),this.sendBtn.textContent=m("composer.send","Send");return}let t=e.phase,n=t!=="off",i=t==="armed"||t==="planning"||t==="pending",s=t==="executing";this.planChipBtn.classList.remove("bp-hidden"),this.planChipBtn.classList.toggle("is-plan",i),this.planChipBtn.classList.toggle("is-exec",s),this.planChipBtn.setAttribute("aria-pressed",n?"true":"false");let r=`${m("gpui.planmode.tip","Plan before acting (1 turn, always, or off)")} · Shift+Tab`;if(this.planChipBtn.title=r,this.planChipBtn.setAttribute("aria-label",r),this.planChipIconHost.replaceChildren(s?$i():Ln()),this.planChipLbl.textContent=s?m("gpui.planmode.chip.building","Building"):t==="pending"?m("gpui.mgmt.fab.reviewbtn","Review"):i&&e.once?m("gpui.planmode.chip.once","Plan · 1t"):m("gpui.mgmt.plan.tab","Plan"),this.textarea.classList.toggle("is-plan",i),this.textarea.classList.toggle("is-plan-exec",s),this.sendBtn.classList.toggle("is-plan",i),this.sendBtn.classList.toggle("is-plan-exec",s),this.sendBtn.textContent=i?m("gpui.mgmt.plan.tab","Plan"):m("composer.send","Send"),!n){this.planBarEl.classList.add("bp-hidden"),this.planBarEl.replaceChildren();return}this.planBarEl.classList.remove("bp-hidden"),this.planBarEl.classList.toggle("is-exec",s);let a=document.createElement("span");a.className="bp-plan-bar-ic",a.appendChild(s?$i():Ln());let o=document.createElement("span");o.className="bp-plan-bar-text",o.textContent=t==="armed"&&e.once?m("gpui.planmode.bar.once","Plan mode (1 turn) — explores and proposes a plan before editing"):t==="armed"?m("gpui.planmode.bar.always","Plan mode — explores and proposes a plan before editing"):t==="planning"?m("gpui.planmode.bar.planning","Planning — drafting a plan before edits"):t==="pending"?m("gpui.planmode.bar.pending","Proposed plan awaits review below"):m("gpui.planmode.bar.executing","Building the approved plan");let c=[a,o];if(t==="armed"||t==="planning"){let p=document.createElement("div");p.className="bp-plan-scopes";let l=(h,d,u,f)=>{let b=document.createElement("button");return b.type="button",b.className="bp-plan-scope-btn"+(d?" active":""),b.textContent=h,b.disabled=!this.enabled,b.setAttribute("data-testid",f),b.addEventListener("click",()=>this.cb.onSetPlanMode?.(u)),b};p.append(l(m("gpui.planmode.scope.once","1 turn"),e.once,"once","plan-scope-once"),l(m("gpui.planmode.scope.always","Always"),!e.once,"always","plan-scope-always"),l(m("gpui.bots.recall.off","Off"),!1,"off","plan-scope-off")),c.push(p)}this.planBarEl.replaceChildren(...c)}setState(e,t){if(this.enabled=e,this.textarea.disabled=!e,this.sendBtn.disabled=!e,this.attachBtn.disabled=!e,this.voiceBtn.disabled=!e,this.modelBtn.disabled=!e,!e)this.closeModelPicker();this.planChipBtn.disabled=!e,this.planBarEl.querySelectorAll(".bp-plan-scope-btn").forEach((n)=>{n.disabled=!e}),this.stopBtn.classList.toggle("bp-hidden",!t)}destroy(){document.removeEventListener("mousedown",this.onDocMouseDown)}isModelPickerOpen(){return this.modelPickerOpen}closeModelPicker(){if(!this.modelPickerOpen)return;this.modelPickerOpen=!1,this.modelPickerFocusIdx=-1,this.modelPickerEl.classList.add("bp-hidden"),this.modelBtn.classList.remove("is-open"),this.modelBtn.setAttribute("aria-expanded","false")}modelPickerFocusableButtons(){return Array.from(this.modelPickerBodyEl.querySelectorAll(".bp-mp-row-main:not(:disabled)"))}updateModelPickerKbdFocus(e){e.forEach((t,n)=>{let i=n===this.modelPickerFocusIdx;if(t.classList.toggle("is-kbd",i),i)t.scrollIntoView({block:"nearest"})})}updateFavoriteModels(e){if(!this.modelPickerSnap)return;if(this.modelPickerSnap=$t(this.modelPickerSnap,e),this.modelPickerOpen)this.renderModelPicker()}async toggleModelPicker(){if(!this.enabled)return;if(this.modelPickerOpen){this.closeModelPicker();return}this.closePopup(),this.modelPickerOpen=!0,this.modelPickerQuery="",this.modelPickerFocusIdx=-1,this.modelSearchInput.value="",this.modelPickerEl.classList.remove("bp-hidden"),this.modelBtn.classList.add("is-open"),this.modelBtn.setAttribute("aria-expanded","true"),this.modelPickerLoading=!0,this.renderModelPicker(),this.modelSearchInput.focus(),await this.reloadModelPicker()}async reloadModelPicker(){if(!this.cb.onLoadModelPicker){this.modelPickerLoading=!1,this.renderModelPicker();return}try{let e=await this.cb.onLoadModelPicker();if(!this.modelPickerOpen)return;this.modelPickerSnap=Ri(e,this.cb.getFavoriteModels?.()??[])}catch{}finally{if(this.modelPickerLoading=!1,this.modelPickerOpen)this.renderModelPicker()}}async toggleFavoriteInPicker(e,t){if(!this.modelPickerSnap)return;let n=this.modelPickerSnap,i=ht(e,t);if(!i)return;let s=n.favoriteKeys.includes(i),r=Sn(n.favoriteKeys,e,t);if(r.keys.length===n.favoriteKeys.length&&r.starred===s)return;if(this.modelPickerSnap=$t(n,r.keys),this.renderModelPicker(),!this.cb.onToggleFavorite)return;try{let a=await this.cb.onToggleFavorite(e,t,r.starred);if(Array.isArray(a)&&this.modelPickerSnap){if(this.modelPickerSnap=$t(this.modelPickerSnap,lt(a)),this.modelPickerOpen)this.renderModelPicker()}}catch(a){if(this.modelPickerSnap){let o=this.cb.getFavoriteModels?.(),c=Array.isArray(o)?lt(o):Sn(this.modelPickerSnap.favoriteKeys,e,t,!r.starred).keys;if(this.modelPickerSnap=$t(this.modelPickerSnap,c),this.modelPickerOpen)this.renderModelPicker()}this.showError(a instanceof Error&&a.message?a.message:"Could not update favorite model")}}renderProviderGlyph(e){let t=Gi(e),n=document.createElement("span");n.className="bp-mp-mark",n.style.color=t.color,n.title=t.title;let i=t.mark?Vi(t.mark):null;if(i)n.appendChild(i);else n.textContent=t.glyph;return n}makeStarButton(e,t,n,i="model-star"){let s=document.createElement("button");s.type="button",s.className="bp-mp-star"+(n?" is-starred":"");let r=n?m("gpui.picker.favorite.remove","Remove from favorites"):m("gpui.picker.favorite.add","Add to favorites");return s.title=r,s.setAttribute("aria-label",r),s.setAttribute("aria-pressed",n?"true":"false"),s.setAttribute("data-testid",`${i}-${e}-${t}`),s.appendChild(Oi(n)),s.addEventListener("click",(a)=>{a.preventDefault(),a.stopPropagation(),this.toggleFavoriteInPicker(e,t)}),s}renderModelPicker(){if(!this.modelPickerOpen)return;if(this.modelPickerFocusIdx=-1,!this.modelPickerSnap){let i=document.createElement("div");i.className="bp-mp-empty",i.textContent=this.modelPickerLoading?"…":m("gpui.no.models","No models"),this.modelPickerBodyEl.replaceChildren(i),this.modelPickerEffortsEl.classList.add("bp-hidden"),this.modelPickerEffortsEl.replaceChildren();return}let e=ji(this.modelPickerSnap,this.modelPickerQuery),t=document.createDocumentFragment();if(e.favorites.length>0){let i=document.createElement("div");i.className="bp-mp-section bp-mp-favorites",i.setAttribute("data-testid","model-picker-favorites");let s=document.createElement("div");s.className="bp-mp-head";let r=document.createElement("span");r.className="bp-mp-head-star",r.appendChild(Oi(!0));let a=document.createElement("span");a.textContent=m("gpui.picker.favorites","Favorites"),s.append(r,a),i.appendChild(s);for(let o of e.favorites){let c=document.createElement("div");c.className="bp-mp-row"+(o.on?" is-active":"")+(!o.ok?" is-disabled":""),c.setAttribute("data-testid",`model-fav-row-${o.provider}-${o.model}`);let p=document.createElement("button");if(p.type="button",p.className="bp-mp-row-main",p.disabled=!o.ok,!o.ok&&o.why)p.title=o.why;let l=document.createElement("span");l.className="bp-mp-check",l.textContent=o.on?"✓":"";let h=document.createElement("span");h.className="bp-mp-name",h.textContent=o.label;let d=document.createElement("span");d.className="bp-mp-note",d.textContent=!o.ok&&o.why?pe(o.why):o.note&&o.note!==o.label?pe(o.note):o.provider,p.append(l,this.renderProviderGlyph(o.provider),h,d),p.addEventListener("click",()=>{if(!o.ok)return;this.closeModelPicker(),this.textarea.focus(),this.cb.onSelectModel?.(o.provider,o.model)}),c.append(p,this.makeStarButton(o.provider,o.model,!0,"model-fav-star")),i.appendChild(c)}t.appendChild(i)}let n=document.createElement("div");if(n.className="bp-mp-groups",n.setAttribute("data-testid","model-picker-groups"),e.groups.length===0){let i=document.createElement("div");i.className="bp-mp-empty",i.textContent=this.modelPickerQuery.trim()?m("gpui.nothing.matches","Nothing matches"):m("gpui.no.models","No models"),n.appendChild(i)}else for(let i of e.groups){let s=document.createElement("div");s.className="bp-mp-group";let r=document.createElement("div");r.className="bp-mp-group-head";let a=document.createElement("span");if(a.className="bp-mp-group-title",a.textContent=i.label,r.append(this.renderProviderGlyph(i.provider),a),!i.ok&&i.why){let o=document.createElement("span");o.className="bp-mp-group-why",o.textContent=pe(i.why),r.appendChild(o)}s.appendChild(r);for(let o of i.models){let c=document.createElement("div");c.className="bp-mp-row"+(o.on?" is-active":"")+(!o.ok?" is-disabled":""),c.setAttribute("data-testid",`model-row-${i.provider}-${o.value||"default"}`);let p=document.createElement("button");if(p.type="button",p.className="bp-mp-row-main",p.disabled=!o.ok,!o.ok&&o.why)p.title=o.why;let l=document.createElement("span");l.className="bp-mp-check",l.textContent=o.on?"✓":"";let h=document.createElement("span");h.className="bp-mp-name",h.textContent=o.label;let d=document.createElement("span");if(d.className="bp-mp-note",d.textContent=o.note&&o.note!==o.label?pe(o.note):"",p.append(l,h,d),p.addEventListener("click",()=>{if(!o.ok)return;this.closeModelPicker(),this.textarea.focus(),this.cb.onSelectModel?.(i.provider,o.value)}),c.appendChild(p),o.starrable)c.appendChild(this.makeStarButton(i.provider,o.value,o.starred));s.appendChild(c)}n.appendChild(s)}if(t.appendChild(n),this.modelPickerBodyEl.replaceChildren(t),e.efforts.length>0){let i=document.createDocumentFragment(),s=document.createElement("span");s.className="bp-mp-efforts-lbl",s.textContent=m("model.col.effort","Effort"),i.appendChild(s);for(let r of e.efforts){let a=document.createElement("button");a.type="button",a.className="bp-mp-effort"+(r.on?" active":""),a.textContent=r.label,a.addEventListener("click",()=>{Promise.resolve(this.cb.onSelectEffort?.(r.value)).then(()=>{if(this.modelPickerOpen)this.reloadModelPicker()})}),i.appendChild(a)}this.modelPickerEffortsEl.replaceChildren(i),this.modelPickerEffortsEl.classList.remove("bp-hidden")}else this.modelPickerEffortsEl.classList.add("bp-hidden"),this.modelPickerEffortsEl.replaceChildren()}setDraft(e){this.textarea.value=e,this.autoGrow(),this.textarea.focus()}setReply(e,t,n){if(!e){this.replyEl.replaceChildren(),this.replyEl.classList.add("bp-hidden");return}let i=document.createElement("button");i.type="button",i.className="bp-reply-strip-body",i.setAttribute("data-testid","composer-reply-go");let s=document.createElement("span");s.className="bp-reply-strip-who",s.textContent=e.who;let r=document.createElement("span");if(r.className="bp-reply-strip-line",r.textContent=m("gpui.b.replying.to","↩ Replying to: {line}",{line:e.line}),i.append(s,r),t)i.addEventListener("click",t);let a=document.createElement("button");a.type="button",a.className="icon bp-reply-strip-drop",a.textContent="×";let o=m("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(){if(this.textarea.placeholder=m("composer.placeholder","Ask anything: @bot, >thread, %project, #room, $skill, /btw"),this.attachBtn.title=m("web.composer.attach","Attach image"),this.attachBtn.setAttribute("aria-label",m("web.composer.attach","Attach image")),this.voiceBtn.title=m("web.composer.voice","Voice dictation"),this.voiceBtn.setAttribute("aria-label",m("web.composer.voice","Voice dictation")),this.modelBtn.title=m("composer.model.tip","Choose the model and effort"),this.modelSearchInput.placeholder=m("gpui.search.models","Search models"),this.sendBtn.textContent=m("composer.send","Send"),this.stopBtn.textContent=m("composer.stop","Stop"),this.setPlanMode(this.planMode),this.modelPickerOpen)this.renderModelPicker()}autoGrow(){this.textarea.style.height="auto",this.textarea.style.height=`${Math.min(180,Math.max(54,this.textarea.scrollHeight))}px`}shouldCompleteOnEnter(){if(this.popupMode==="mention")return!0;if(this.popupMode==="slash"){let e=this.textarea.value;return e.startsWith("/")&&!e.includes(" ")}return!1}updatePopups(){let e=this.textarea.value;if(e.startsWith("/")&&!e.includes(" ")&&!e.includes(` +`)){let n=e.slice(1).toLowerCase();if(this.filteredSlash=this.commands.filter((i)=>i.word.toLowerCase().startsWith(n)),this.filteredSlash.length>0){this.popupMode="slash",this.popupIdx=Math.min(this.popupIdx,this.filteredSlash.length-1),this.renderPopup();return}}let t=/(?:^|\s)([@>%#])([a-zA-Z0-9._-]{1,32})$/.exec(e.slice(0,this.textarea.selectionStart));if(t){let n=t[1],i=t[2];this.cb.onQueryMentions(i,n).then((s)=>{if(s.length>0)this.mentionItems=s,this.popupMode="mention",this.popupIdx=0,this.renderPopup();else if(this.popupMode==="mention")this.closePopup()});return}this.closePopup()}closePopup(){this.popupMode="none",this.popupEl.classList.add("bp-hidden"),this.popupEl.replaceChildren()}renderPopup(){let e=document.createDocumentFragment();if(this.popupMode==="slash")this.filteredSlash.forEach((t,n)=>{let i=document.createElement("button");i.type="button",i.className="bp-popup-row"+(n===this.popupIdx?" active":""),i.setAttribute("data-testid",`slash-item-${t.word}`);let s=document.createElement("span");s.className="bp-popup-name",s.textContent=`/${t.word}`;let r=document.createElement("span");r.className="bp-popup-desc",r.textContent=t.desc||t.label,i.append(s,r),i.addEventListener("mousedown",(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(!Fi.has(t.type)){this.showError(m("web.composer.unsupported","Unsupported image type: {type}",{type:t.type||t.name}));continue}if(this.attachments.length>=Di){this.showError(m("web.composer.maximages","At most {max} images per message.",{max:Di}));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=m("common.remove","Remove"),r.addEventListener("click",()=>{this.attachments.splice(n,1),this.renderAttachments()}),i.append(s,r),e.appendChild(i)}),this.attachStripEl.replaceChildren(e),this.attachStripEl.classList.remove("bp-hidden")}submit(){if(!this.enabled)return;let e=this.textarea.value.trim();if(!e&&this.attachments.length===0)return;if(this.closePopup(),this.clearError(),e.startsWith("/")&&this.attachments.length===0){let n=e.slice(1).split(/\s+/)[0]?.toLowerCase()??"";if(this.commands.some((i)=>i.word.toLowerCase()===n)){this.textarea.value="",this.autoGrow(),this.cb.onRunCommand(e);return}}let t=this.attachments.map(({name:n,mime:i,data:s})=>({name:n,mime:i,data:s}));this.attachments=[],this.renderAttachments(),this.textarea.value="",this.autoGrow(),this.cb.onSend(e,t)}}async function Ui(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 Wr=new Set(["bom","checks","life","plan","fab"]);function nn(e){if(!e||!Array.isArray(e.panels))return[];return e.panels.filter((t)=>t&&typeof t.id==="string"&&Wr.has(t.id))}function Ji(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 sn(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 kt(e){if(!Number.isFinite(e)||e<0)return"?";if(e<1000)return String(Math.round(e));if(e<1e6){let n=e/1000;return n<10?`${n.toFixed(1).replace(/\.0$/,"")}k`:`${Math.round(n)}k`}let t=e/1e6;return t<10?`${t.toFixed(1).replace(/\.0$/,"")}M`:`${Math.round(t)}M`}function Ct(e){if(!Number.isFinite(e))return"";if(e>=1)return`$${e.toFixed(2)}`;let t=e.toFixed(4).replace(/0+$/,"");return(t.split(".")[1]??"").length<2?`$${e.toFixed(2)}`:`$${t}`}var _r=new Set(["0201","0402","0603","0805","1206","1210","1812","2010","2512"]),zr=new Set(["QFN","DFN","SOT","SOIC","SOP","SSOP","TSSOP","MSOP","QFP","LQFP","TQFP","BGA","WLCSP","SOD","TO","SON","LGA"]);function Yi(e){if(!e)return"";let t=e.indexOf(":"),i=(t>=0?e.slice(t+1):e).split("_");for(let a of i)if(_r.has(a))return a;let s=i[0]??"",r=s.replace(/[^a-zA-Z].*$/,"").toUpperCase();if(zr.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 Xi(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 ${kt(Math.max(n,0))}`,tone:"bad"};if(t==="low")return{text:`low ${kt(n)}`,tone:"warn"};return{text:kt(n),tone:"ok"}}function Qi(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 Zi(e,t){if(!t)return e;return e.filter((n)=>n.source===t)}function Mn(e){if(e==="active")return{label:"Active",tone:"ok"};if(e==="nrnd")return{label:"NRND",tone:"warn"};if(e==="eol")return{label:"EOL",tone:"bad"};return{label:"Unknown",tone:"faint"}}function rn(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 es(e){return e.state==="routed"||e.state==="verified"}function ts(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 ns(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 is(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 ss(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 rs(e){return e==="extra"?"costs-more limits":"base-price limits"}function Tn(e,t){return e.watchGen===t.watchGen&&e.editGen===t.editGen&&e.project!==""&&e.project===t.project&&e.editId!==""&&e.editId===t.editId}function as(e){return{project:e.project,refs:e.refs.slice(),field:e.field,value:e.was}}function Bn(e,t){return e.watchGen===t.watchGen&&e.project!==""&&e.project===t.project&&e.threadId!==""&&e.threadId===t.threadId&&e.threadGen===t.threadGen}var Wi=["#f59e0b","#38bdf8","#c084fc","#2dd4bf","#ef4444","#a3e635","#f97316","#ec4899"],_i=["#14b8a6","#f59e0b","#c084fc","#22c55e","#38bdf8","#ef4444","#e879f9","#84cc16"];function os(e){let t=2166136261;for(let n=0;n>>0;return t}function Ot(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 Wi[os(i)%Wi.length]}function xt(e,t=""){let n=t.trim().toLowerCase();if(n&&n!=="#8a8a8a")return t;return _i[os(e)%_i.length]}function ls(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 qe(e,t,n,i,s){return[i*0.5+(t-e.cx)*e.scale,s*0.5+(n-e.cy)*e.scale]}function an(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 cs(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 ds(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)),[p,l]=an(e,n,i,s,r);return{...e,cx:p-(n-s*0.5)/c,cy:l-(i-r*0.5)/c,scale:c,touched:!0}}function ps(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 In(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 qr(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 p=Math.max(0,Math.min(1,((e-n)*a+(t-i)*o)/c)),l=n+p*a,h=i+p*o;return(e-l)*(e-l)+(t-h)*(t-h)}function zi(e,t,n){if(n.length<3)return!1;let i=!1;for(let s=0,r=n.length-1;st!==p>t&&e<(c-a)*(t-o)/(p-o+0.000000000001)+a)i=!i}return i}function Rn(e,t){return Math.max(5,Math.min(32,e*t))}function on(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 u=d.path??[];for(let f=0;f=3)for(let f=0;f=0;d--){let u=t[d];if(u.layer!==n)continue;let f=u.outline??[];if(!zi(l,h,f))continue;if(!(u.holes??[]).some((v)=>zi(l,h,v)))return{kind:"region",id:u.id}}return null}function Pt(e){let t=null,n=null,i=[];for(let r of e){if(!r.layer)continue;i.push(r.layer);let a=r.items??[],o=a.filter((p)=>p.kind==="corridor").length,c=a.filter((p)=>p.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 qi(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 ut(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 hs(e,t,n){if(e==="split"&&n.length>0)return t.filter((i)=>n.includes(i.layer));return t}function Nn(e,t){return!(e[2]<=t[0]||e[0]>=t[2]||e[3]<=t[1]||e[1]>=t[3])}function Ki(e,t,n){if(n.length<3)return!1;let i=!1;for(let s=0,r=n.length-1;st!==p>t&&e<(c-a)*(t-o)/(p-o+0.000000000001)+a)i=!i}return i}function us(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 p of e)n=Math.min(n,p[0]),i=Math.min(i,p[1]),s=Math.max(s,p[0]),r=Math.max(r,p[1]),a+=p[0],o+=p[1];let c=[[(n+s)*0.5,(i+r)*0.5],[a/e.length,o/e.length]];for(let p of[0.5,0.25,0.75,0.125,0.875])for(let l of[0.5,0.25,0.75,0.125,0.875])c.push([n+(s-n)*l,i+(r-i)*p]);for(let p of c)if(Ki(p[0],p[1],e)&&!t.some((l)=>Ki(p[0],p[1],l)))return p;return null}function ms(e,t,n,i,s,r){let a=[];for(let l of e){let h=l.nets??0,d=l.path??[];if(h<=0||d.length<2)continue;let u=0;for(let f=1;f{let d=l.sel||l.hov?1:0,u=h.sel||h.hov?1:0;if(u!==d)return u-d;if(h.nets!==l.nets)return h.nets-l.nets;return l.b.id.localeCompare(h.b.id)});let o=[],c=[],p=(l,h,d,u,f)=>[l-d*0.5-f,h-u*0.5-f,l+d*0.5+f,h+u*0.5+f];for(let l of a){let h=l.b.name||"",d=String(l.nets),u=h?`${h} · ${l.nets}`:d,f=(l.sel||l.hov||l.pxLen>=95)&&h?[u,d]:[d],b=null,v=(w,C)=>Math.max(C*0.5+3,Math.min(Math.max(C*0.5+3,n-C*0.5-3),w)),y=(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 f){let C=Math.max(16,w.length*5.9+10),L=15;for(let N of[0.5,0.35,0.65,0.22,0.78]){let A=qi(l.pts,N);if(!A)continue;let[B,M]=qe(t,A[0],A[1],n,i),j=v(B,C),O=y(M,15),x=p(j,O,C,15,2);if(!o.some((Y)=>Nn(x,Y))){b={id:l.b.id,text:w,cx:j,cy:O,pw:C,ph:15,col:l.col,sel:l.sel};break e}}}if(!b){let w=qi(l.pts,0.5);if(w){let[C,L]=qe(t,w[0],w[1],n,i),N=Math.max(16,d.length*6.5+8),A=15,B=v(C,N);for(let M of[-18,18]){let j=y(L+M,15);if(!o.some((O)=>Nn(p(B,j,N,15,2),O))){b={id:l.b.id,text:d,cx:B,cy:j,pw:N,ph:15,col:l.col,sel:l.sel};break}}}}if(b)o.push(p(b.cx,b.cy,b.pw,b.ph,2)),c.push(b)}return c}function bs(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[h,d]=qe(t,l.b[0],l.b[1],n,i),[u,f]=qe(t,l.b[2],l.b[3],n,i),b=Math.abs(u-h),v=Math.abs(f-d);if(b<13||v<9)continue;let y=(h+u)*0.5,w=(d+f)*0.5;if(y<8||y>n-8||w<8||w>i-8)continue;o.push({text:l.r,cx:y,cy:w,bw:l.r.length*5.8+4,bh:11,score:b*v+(a.has(l.r)?1e4:0)})}o.sort((l,h)=>h.score-l.score);let c=[...r],p=[];for(let l of o){let h=[l.cx-l.bw*0.5,l.cy-l.bh*0.5,l.cx+l.bw*0.5,l.cy+l.bh*0.5];if(!c.some((u)=>Nn(h,u)))c.push(h),p.push({text:l.text,cx:l.cx,cy:l.cy})}return p}function gs(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 ln(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 fs(e,t,n,i,s,r,a,o){return e===t&&n===i&&s===r&&(o===void 0||a>=o)}var vs="#111917",Kr="#16201d",Jr="rgba(212, 224, 219, 0.92)",Yr="rgba(61, 80, 73, 0.72)",Xr="rgba(82, 107, 97, 0.85)";var ys="#f59e0b",Qr="#eef5f2",ws="#ef4444";function mt(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 Zr(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 ea(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 ta(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 jn{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=ln(e.layers,e.copperLayers);if(t.length===0)return[];if(e.gridMode==="all")return t;if(e.gridMode==="single"){let s=e.shownLayers.find((a)=>t.some((o)=>o.layer===a))??Pt(t)[0]??t[0]?.layer,r=t.find((a)=>a.layer===s);return r?[r]:[]}let n=e.shownLayers.length>0&&e.shownLayers.every((s)=>t.some((r)=>r.layer===s))?e.shownLayers.slice(0,2):Pt(t),i=[];for(let s of n){let r=t.find((a)=>a.layer===s);if(r)i.push(r)}return i.length>0?i:t.slice(0,2)}update(e,t){this.state=e;let n=this.visibleLayers(e);this.root.classList.toggle("two-cols",t&&n.length>1);let i=n.map((s)=>s.layer).join("|");if(i!==this.renderedLayerKey){this.renderedLayerKey=i;for(let s of this.cards.values())s.ro.disconnect();this.cards.clear(),this.root.replaceChildren();for(let s of n){let r=this.buildCard(s);this.cards.set(s.layer,r),this.root.appendChild(r.el)}}else for(let s of n){let r=this.cards.get(s.layer);if(r)this.syncCardHeaderAndLegend(r,s)}this.scheduleDraw()}effectiveBbox(e){let t=e.bbox;if(!t||t.length!==4||Math.abs(t[2]-t[0])<0.5||Math.abs(t[3]-t[1])<0.5)return[0,0,100,70];return t}getCam(e,t,n){let i=this.state,s=i?.syncZoom?this.sharedCam:this.layerCams.get(e)??null;if(s&&s.touched)return s;return ls(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=m("gpui.mgmt.plan.layer","Approve layer"),c.addEventListener("click",(w)=>{w.stopPropagation(),this.cb.onApproveLayer(e.layer,!0)});let p=document.createElement("button");p.type="button",p.className="bp-mgmt-btn bp-plan-mini-btn",p.textContent="✗",p.title=m("gpui.mgmt.plan.rejectlayer","Reject layer"),p.addEventListener("click",(w)=>{w.stopPropagation(),this.cb.onApproveLayer(e.layer,!1)}),i.append(s,a,o,c,p);let l=document.createElement("div");l.className="bp-plan-card-sub",n.append(i,l);let h=document.createElement("div");h.className="bp-plan-card-canvas-wrap";let d=document.createElement("canvas");d.className="bp-plan-card-canvas",d.setAttribute("data-testid",`mgmt-plan-canvas-${e.layer}`);let u=document.createElement("div");u.className="bp-plan-hover-hud bp-hidden",h.append(d,u);let f=document.createElement("div");f.className="bp-plan-legend bp-hidden",t.append(n,h,f);let b=d.getContext("2d"),v=new ResizeObserver(()=>this.scheduleDraw());v.observe(h),this.attachPointerListeners(d,e.layer);let y={layer:e.layer,el:t,canvas:d,ctx:b,legendEl:f,okBtn:c,noBtn:p,statusEl:o,titleEl:a,subtitleEl:l,hoverHudEl:u,ro:v};return this.syncCardHeaderAndLegend(y,e),y}syncCardHeaderAndLegend(e,t){e.titleEl.textContent=ut(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=ta(t);e.statusEl.className=`bp-plan-card-status tone-${s.tone==="warn"?"dim":s.tone}`,e.statusEl.textContent=i.length>0?m(s.key,s.label):"",e.statusEl.classList.toggle("bp-hidden",i.length===0);let r=i.some((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 p=document.createElement("button");p.type="button";let l=this.state?.selectedId===c.id;p.className="bp-plan-legend-chip"+(l?" active":"");let h=document.createElement("span");h.className="bp-plan-legend-sw",h.style.background=Ot(c.net||c.id,c.color||"");let d=document.createElement("span");d.textContent=c.net||c.id,p.append(h,d),p.addEventListener("click",()=>{this.cb.onSelect(c.id),this.cb.onFocusItem(c.id)}),o.appendChild(p)}e.legendEl.replaceChildren(o)}}attachPointerListeners(e,t){e.addEventListener("contextmenu",(i)=>i.preventDefault()),e.addEventListener("dblclick",()=>this.fitAll()),e.addEventListener("pointerdown",(i)=>{let s=this.state;if(!s)return;this.root.focus({preventScroll:!0});let r=e.getBoundingClientRect(),a=i.clientX-r.left,o=i.clientY-r.top,c=Math.max(1,r.width),p=Math.max(1,r.height),l=this.getCam(t,c,p),h=on(s.bands,s.regions,t,s.selectedId,l,c,p,a,o);if(i.button===2){if(h?.kind==="vertex"){let d=this.getItemPts(h.id,h.isPlane),u=In(d,h.idx,h.isPlane);if(u)this.selectedVertex=null,this.cb.onCommitFields(h.id,{[h.isPlane?"outline":"path"]:u})}return}if(i.button!==0)return;if(e.setPointerCapture(i.pointerId),this.downPos={x:i.clientX,y:i.clientY},h?.kind==="vertex"){let d=this.getItemPts(h.id,h.isPlane),u=d.map((f)=>[f[0],f[1]]);this.selectedVertex={id:h.id,idx:h.idx},this.drag={layer:t,kind:"vertex",id:h.id,isPlane:h.isPlane,idx:h.idx,pts:d.map((f)=>[f[0],f[1]]),origPts:u,moved:!1},this.scheduleDraw()}else if(h?.kind==="midpoint"){let d=this.getItemPts(h.id,h.isPlane),u=d.map((v)=>[v[0],v[1]]),f=ps(d,h.segIdx,h.pos,h.isPlane),b=h.isPlane&&h.segIdx+1>=d.length?f.length-1:Math.min(h.segIdx+1,f.length-1);this.selectedVertex={id:h.id,idx:b},this.patchLocalItem(h.id,h.isPlane,f),this.drag={layer:t,kind:"vertex",id:h.id,isPlane:h.isPlane,idx:b,pts:f,origPts:u,moved:!0},this.scheduleDraw()}else this.selectedVertex=null,this.drag={layer:t,kind:"pan",lastX: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),p=Math.max(1,r.height);if(this.drag&&this.drag.layer===t){if(this.drag.kind==="pan"){let L=this.getCam(t,c,p);this.setCam(t,cs(L,a-this.drag.lastX,o-this.drag.lastY)),this.drag.lastX=a,this.drag.lastY=o,this.scheduleDraw();return}if(this.downPos&&Math.hypot(i.clientX-this.downPos.x,i.clientY-this.downPos.y)<1.5&&!this.drag.moved)return;let b=this.getCam(t,c,p),[v,y]=an(b,a,o,c,p),w=[Math.round(v*1000)/1000,Math.round(y*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,p),h=on(s.bands,s.regions,t,s.selectedId,l,c,p,a,o),d=this.hover?.hit?"id"in this.hover.hit?this.hover.hit.id:"":"",u=this.hover?.hit.kind??"",f=h?h.id:"";if(this.hover=h?{layer:t,hit:h}:null,e.style.cursor=h?"pointer":"crosshair",d!==f||(h?.kind??"")!==u)this.syncHoverHud(t),this.scheduleDraw()}),e.addEventListener("pointerleave",()=>{if(this.hover?.layer===t)this.hover=null,this.syncHoverHud(t),this.scheduleDraw()});let n=()=>{let i=this.drag;if(!i||i.layer!==t)return;if(this.drag=null,this.downPos=null,i.kind==="vertex"&&i.moved){let s=i.origPts.map((r)=>[r[0],r[1]]);this.patchLocalItem(i.id,i.isPlane,s)}this.cb.onDragEnd?.(),this.scheduleDraw()};e.addEventListener("pointercancel",n),e.addEventListener("lostpointercapture",n),e.addEventListener("pointerup",(i)=>{let s=this.state,r=this.drag,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,p=i.clientY-o.top,l=Math.max(1,o.width),h=Math.max(1,o.height),d=this.getCam(t,l,h),u=on(s.bands,s.regions,t,s.selectedId,d,l,h,c,p);if(u&&(u.kind==="band"||u.kind==="region")){this.cb.onSelect(u.id),this.cb.onFocusItem(u.id);return}if(!u&&s.selectedId){this.cb.onSelect("");return}}this.cb.onDragEnd?.()}),e.addEventListener("wheel",(i)=>{i.preventDefault();let s=e.getBoundingClientRect(),r=i.clientX-s.left,a=i.clientY-s.top,o=Math.max(1,s.width),c=Math.max(1,s.height),p=this.getCam(t,o,c),l=Math.max(0.65,Math.min(1.55,1-i.deltaY*0.002));this.setCam(t,ds(p,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=In(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=(b,v)=>qe(r,b,v,n,i);e.fillStyle=vs,e.fillRect(0,0,n,i);let o=(s.board.outline??[]).filter((b)=>b.length>=3);if(e.fillStyle=Kr,o.length>0){e.beginPath();for(let b of o){for(let v=0;vb.layer===t),p=this.hover?.layer===t?this.hover.hit:null;for(let b of c){let v=b.outline??[];if(v.length<3)continue;let y=s.selectedId===b.id,w=p?.id===b.id,C=ea(b.state||"proposed",y,w),L=Ot(b.net||b.id,b.color||"");e.beginPath();for(let A=0;AM)M=x;if(Y>j)j=Y}if(Math.abs(M-A)>=38&&Math.abs(j-B)>=18){let O=us(v,b.holes??[]);if(O){let[x,Y]=a(O[0],O[1]);e.fillStyle=mt(L,y?0.91:0.67),e.font="bold 10px ui-monospace, 'SFMono-Regular', Menlo, monospace",e.textAlign="center",e.textBaseline="middle",e.fillText(N,x,Y)}}}}if(e.strokeStyle=Jr,e.lineWidth=1.25,e.lineCap="round",e.lineJoin="round",o.length>0){e.beginPath();for(let b of o){for(let v=0;vb.layer===t),d=ms(h,r,n,i,s.selectedId,p?.id??""),u=d.map((b)=>[b.cx-b.pw*0.5-1,b.cy-b.ph*0.5-1,b.cx+b.pw*0.5+1,b.cy+b.ph*0.5+1]),f=[];for(let b of h){for(let v of b.from??[])f.push(v);for(let v of b.to??[])f.push(v)}e.fillStyle="rgba(143, 163, 155, 0.72)",e.font="9.5px ui-monospace, 'SFMono-Regular', Menlo, monospace",e.textAlign="center",e.textBaseline="middle";for(let b of bs(l,r,n,i,f,u))e.fillText(b.text,b.cx,b.cy);for(let b of h){let v=b.guides??[];if(v.length===0)continue;let y=s.selectedId===b.id||p?.id===b.id,w=xt(b.name||b.id,b.color||"");e.strokeStyle=mt(w,y?0.38:0.17),e.lineWidth=y?1:0.7,e.beginPath();for(let C of v){let[L,N]=a(C[0],C[1]),[A,B]=a(C[2],C[3]);e.moveTo(L,N),e.lineTo(A,B)}e.stroke()}for(let b of h){let v=b.path??[];if(v.length<2)continue;let y=s.selectedId===b.id,w=p?.id===b.id,C=Zr(b.state||"proposed",y,w),L=xt(b.name||b.id,b.color||""),N=Rn(b.width??1.5,r.scale),A=()=>{e.beginPath();for(let B=0;B{let w=y?v.length:Math.max(0,v.length-1);for(let C=0;Cn.id===e))return;if(this.openPanel!==e)this.togglePanel(e)}getTabs(){return nn(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=nn(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 p=document.createElement("span");p.textContent=pe(a.label),o.appendChild(p);let l=this.getPanelData(a.id),h=Ji(l);if(h){let d=document.createElement("span");d.className=`bp-mgmt-badge bp-tone-${h.tone}`,d.textContent=h.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=m("gpui.mgmt.close","Close the panel"),a.setAttribute("aria-label",m("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 p=document.createElement("span");p.className="bp-dim",p.textContent=(t.priced??0)<(t.lookups??0)?`≥ ${Ct(t.cost)}/board`:`${Ct(t.cost)}/board`,i.appendChild(p)}if(t.paused){let p=document.createElement("span");p.className="bp-mgmt-faint",p.textContent="Stock check paused",i.appendChild(p)}if(e.appendChild(i),t.stock_note){let p=document.createElement("div");p.className="bp-mgmt-note bp-mgmt-faint",p.textContent=pe(t.stock_note),e.appendChild(p)}let o=this.bomEditingId?n.find((p)=>p.id===this.bomEditingId)??null:null;if(o)e.appendChild(this.renderBomEditor(o));else{let p=document.createElement("div");p.className="bp-mgmt-filter-row";let l=document.createElement("input");l.type="text",l.className="bp-mgmt-filter",l.placeholder="Filter BOM (ref, value, footprint, MPN, dnp)…",l.value=this.bomFilter,l.setAttribute("data-testid","mgmt-bom-filter"),l.addEventListener("input",()=>{this.bomFilter=l.value,this.renderBomRows(c,n)}),p.appendChild(l),e.appendChild(p)}let c=document.createElement("div");return c.className="bp-mgmt-rows",c.setAttribute("data-testid","mgmt-bom-rows"),this.renderBomRows(c,n),e.appendChild(c),e}renderBomRows(e,t){let n=Qi(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 p=document.createElement("span");if(p.className="bp-mgmt-strong bp-mgmt-flex1",p.textContent=sn(a,24),c.appendChild(p),r.dnp){let b=document.createElement("span");b.className="bp-mgmt-pill",b.textContent=m("gpui.mgmt.bom.dnp","DNP"),c.appendChild(b)}else{let b=Xi(r.stock);if(b){let v=document.createElement("span");v.className=`bp-tone-${b.tone}`,v.textContent=b.text,c.appendChild(v)}}let l=document.createElement("button");l.type="button",l.className="bp-mgmt-btn",l.textContent="Edit",l.addEventListener("click",(b)=>{b.stopPropagation(),this.bomEditGen++,this.bomEditingId=r.id,this.bomEditDraft=r.mpn??"",this.bomEditStatus="",this.bomLastUndo=null,this.render()}),c.appendChild(l);let h=document.createElement("div");h.className="bp-mgmt-row-sub";let d=[`${r.qty??a.length}×`,r.value??"",Yi(r.footprint??"")].filter(Boolean).join(" · "),u=document.createElement("span");u.className="bp-dim",u.textContent=d;let f=document.createElement("span");if(f.className="bp-mgmt-flex1",r.mpn)f.textContent=r.mpn;else if(i&&!r.dnp)f.className+=" bp-tone-warn",f.textContent=m("gpui.mgmt.bom.nompn","no MPN");if(h.append(u,f),!r.dnp&&typeof r.stock?.price==="number"){let b=document.createElement("span");b.className="bp-dim",b.textContent=Ct(r.stock.price),h.appendChild(b)}if(!r.dnp&&r.stock?.class){let b=document.createElement("span");b.className="bp-mgmt-faint",b.textContent=pe(r.stock.class),h.appendChild(b)}o.append(c,h),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=sn(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,u=!1)=>{let f=o();this.bomEditStatus="Writing…",this.render();try{let b=await this.cb.hub.rpc("mgmt.bom.edit",d);if(!Tn(f,o()))return;this.bomLastUndo=!u&&(b.changed??0)>0?{project:d.project,editId:f.editId,refs:d.refs.slice(),field:d.field,was:typeof b.was==="string"?b.was:d.field==="mpn"?e.mpn??"":e.dnp?"yes":"no"}:null,this.bomEditStatus=u?"Restored":(b.changed??0)===0?"No change":b.via==="kicad"?"Updated in KiCad":"Saved to schematic"}catch(b){if(!Tn(f,o()))return;this.bomEditStatus=b instanceof Error?b.message:"Could not save edit"}this.render()},p=document.createElement("div");p.className="bp-mgmt-btn-row";let l=document.createElement("button");l.type="button",l.className="primary bp-mgmt-btn",l.textContent="Save MPN",l.addEventListener("click",()=>{c({project:this.project,refs:n.slice(),field:"mpn",value:this.bomEditDraft.trim()})});let h=document.createElement("button");if(h.type="button",h.className="bp-mgmt-btn",h.textContent=e.dnp?"Clear DNP":"Mark DNP",h.addEventListener("click",()=>{c({project:this.project,refs:n.slice(),field:"dnp",value:e.dnp?"no":"yes"})}),p.append(l,h),this.bomLastUndo&&this.bomLastUndo.project===this.project&&this.bomLastUndo.editId===this.bomEditingId){let d=this.bomLastUndo,u=document.createElement("button");u.type="button",u.className="bp-mgmt-btn",u.textContent="Undo",u.addEventListener("click",()=>{c(as(d),!0)}),p.appendChild(u)}if(t.append(i,a,p),this.bomEditStatus){let d=document.createElement("div");d.className="bp-mgmt-faint",d.textContent=this.bomEditStatus,t.appendChild(d)}return t}renderChecks(){let e=document.createElement("div");e.className="bp-mgmt-body";let t=this.getPanelData("checks");if(!t)return e.appendChild(this.makeEmpty("Reading checks…")),e;let n=Array.isArray(t.groups)?t.groups:[],i=Array.from(new Set(n.map((d)=>d.source).filter(Boolean))),s=(d)=>t.sources?.[d]?.label||d.toUpperCase(),r=(d)=>t.sources?.[d]?.judged===!0,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=m("gpui.mgmt.checks.all","All"),o.addEventListener("click",()=>{this.checksSource="",this.render()}),a.appendChild(o);for(let d of i){let u=document.createElement("button");u.type="button",u.className="bp-mgmt-btn"+(this.checksSource===d?" active":""),u.textContent=s(d)+(r(d)?" · judged":""),u.addEventListener("click",()=>{this.checksSource=this.checksSource===d?"":d,this.render()}),a.appendChild(u)}let c=document.createElement("span");c.className="bp-mgmt-flex1";let p=document.createElement("button");if(p.type="button",p.className="bp-mgmt-btn",p.textContent=m("gpui.mgmt.checks.run","Run"),p.addEventListener("click",()=>{let d=this.watchGen,u=this.project;this.checksStatus="Running checks…",this.render(),this.cb.hub.rpc("kicad.checks.run",{project:u}).then(()=>{if(d!==this.watchGen||u!==this.project)return;this.checksStatus="",this.render()}).catch((f)=>{if(d!==this.watchGen||u!==this.project)return;this.checksStatus=f instanceof Error?f.message:"Could not run checks",this.render()})}),a.append(c,p),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 h=Zi(n,this.checksSource);if(h.length===0)l.appendChild(this.makeEmpty("No check findings."));else for(let d of h){let u=d.severity==="error"?"bad":d.severity==="warning"?"warn":"faint",f=document.createElement("div");f.className="bp-mgmt-group-head";let b=document.createElement("span");b.className=`bp-mgmt-dot bp-tone-bg-${u}`;let v=document.createElement("span");v.className="bp-mgmt-flex1",v.textContent=`${s(d.source)} · ${d.rule}`;let y=document.createElement("span");y.className=`bp-tone-${u}`,y.textContent=String(d.n),f.append(b,v,y),l.appendChild(f);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=pe(w.title??""),C.appendChild(L),w.names||this.checksSelectedId===w.id){let N=document.createElement("div");N.className="bp-mgmt-row-sub";let A=document.createElement("span");if(A.className="bp-dim bp-mgmt-flex1",A.textContent=w.names??"",N.appendChild(A),this.checksSelectedId===w.id){let B=document.createElement("button");B.type="button",B.className="bp-mgmt-btn accent",B.textContent=m("gpui.mgmt.checks.fix","Fix with agent"),B.addEventListener("click",(M)=>{M.stopPropagation();let j={watchGen:this.watchGen,project:this.project,threadId:this.cb.getThreadId(),threadGen:this.cb.getThreadGen()};this.cb.hub.rpc("kicad.checks.fix",{project:j.project,id:w.id}).then((O)=>{let x={watchGen:this.watchGen,project:this.project,threadId:this.cb.getThreadId(),threadGen:this.cb.getThreadGen()};if(!Bn(j,x))return;if(O.text)this.cb.onSendText(O.text),this.checksStatus="Sent to agent",this.render()}).catch((O)=>{let x={watchGen:this.watchGen,project:this.project,threadId:this.cb.getThreadId(),threadGen:this.cb.getThreadGen()};if(!Bn(j,x))return;this.checksStatus=O instanceof Error?O.message:"Could not send finding",this.render()})}),N.appendChild(B)}C.appendChild(N)}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 p=i[c]??0,l=Mn(c),h=document.createElement("span");h.className=p>0?`bp-tone-${l.tone}`:"bp-mgmt-faint",h.textContent=`${l.label} ${p}`,n.appendChild(h)}if((i.unknown??0)>0){let c=document.createElement("span");c.className="bp-mgmt-faint",c.textContent=`${i.unknown} unknown`,n.appendChild(c)}if(t.since){let c=document.createElement("span");c.className="bp-mgmt-flex1";let p=document.createElement("span");p.className="bp-mgmt-faint",p.textContent=`since ${rn(t.since)} (${t.samples??0})`,n.append(c,p)}e.appendChild(n);let s=document.createElement("div");s.className="bp-mgmt-rows",s.setAttribute("data-testid","mgmt-life-rows");let r=t.bom?.cost??[],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],p=a[a.length-1],l=document.createElement("div");l.className="bp-mgmt-note bp-dim",l.textContent=`Parts/board: ${Ct(c[1])} · ${Math.round(p?.[1]??0)}/${o} lines in stock (${rn(c[0])})`,s.appendChild(l)}for(let c of t.parts??[]){let p=this.lifeSelectedKey===c.key,l=Mn(c.lifecycle??"unknown"),h=document.createElement("div");h.className="bp-mgmt-row"+(p?" active":"");let d=document.createElement("div");d.className="bp-mgmt-row-line";let u=document.createElement("span");u.className="bp-mgmt-strong",u.textContent=sn(c.refs??[],14);let f=document.createElement("span");f.className="bp-mgmt-flex1 bp-dim",f.textContent=c.mpn||c.key;let b=document.createElement("span");if(b.className=`bp-tone-${l.tone}`,b.textContent=l.label,d.append(u,f,b),typeof c.stock==="number"){let v=document.createElement("span");v.className="bp-dim",v.textContent=kt(c.stock),d.appendChild(v)}if(h.appendChild(d),p){let v=document.createElement("div");if(v.className="bp-mgmt-row-sub bp-mgmt-faint",this.lifePartLoading)v.textContent=m("gpui.mgmt.life.reading","Reading its history…");else if(this.lifePartSamples&&this.lifePartSamples.length>0){let y=this.lifePartSamples[this.lifePartSamples.length-1];v.textContent=`${this.lifePartSamples.length} samples · latest ${y.at?rn(y.at):""}`+(typeof y.stock==="number"?` · stock ${kt(y.stock)}`:"")+(typeof y.price==="number"?` · ${Ct(y.price)}`:"")}else v.textContent=m("gpui.mgmt.life.nopart","No reading of this part yet.");h.appendChild(v)}h.addEventListener("click",()=>{if(this.lifeSelectedKey===c.key){this.lifeSelectedKey="",this.lifePartSamples=null,this.render();return}this.lifeSelectedKey=c.key,this.lifePartSamples=null,this.lifePartLoading=!0,this.render(),this.cb.hub.rpc("mgmt.life.part",{project:this.project,key:c.key}).then((v)=>{if(this.lifeSelectedKey!==c.key)return;this.lifePartLoading=!1,this.lifePartSamples=Array.isArray(v.samples)?v.samples:[],this.render()}).catch(()=>{if(this.lifeSelectedKey!==c.key)return;this.lifePartLoading=!1,this.lifePartSamples=[],this.render()})}),s.appendChild(h)}return e.appendChild(s),e}renderPlan(){let e=document.createElement("div");e.className="bp-mgmt-body";let t=this.getPanelData("plan");if(!t)return e.appendChild(this.makeEmpty(m("gpui.mgmt.plan.reading","Reading the routing plan…"))),e;let n=(k,P)=>{let F=this.watchGen,I=this.project;this.planStatus="",this.cb.hub.rpc(k,{pro:I,...P}).catch((J)=>{if(F!==this.watchGen||I!==this.project)return;this.planOptimistic.clear(),this.planStatus=J instanceof Error?J.message:m("gpui.mgmt.plan.refused","KiCad refused"),this.render()})};if(t.revision!==this.planOptimisticRev)this.planOptimisticRev=t.revision,this.planOptimistic.clear();let i=`${this.project}:${t.revision??0}`;if(t.board_trimmed&&this.planHydrateAskedKey!==i&&this.project){this.planHydrateAskedKey=i;let k=this.watchGen,P=++this.planHydrateGen,F=this.project,I=t.revision??0;this.cb.hub.rpc("plan.get",{pro:F,board:!0}).then((J)=>{let ie=gs(J);if(!ie)return;let Ee=typeof ie.revision==="number"?ie.revision:I;if(!fs(k,this.watchGen,P,this.planHydrateGen,F,this.project,Ee,this.planHydratedRev))return;this.planHydratedRev=Ee,this.planHydratedKey=`${F}:${Ee}`,this.planHydratedBoard=ie.board??null,this.planHydratedDraw=ie.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=m("gpui.mgmt.plan.before","Plan before routing"),o.title=s?m("gpui.mgmt.plan.onwords","Before routing a board with 4 or more copper layers or more than 60 nets, the agent proposes corridors and plane regions here. It routes only what you approve."):m("gpui.mgmt.plan.offwords","Agents route as you ask. Turn it on to have them propose a routing plan first and route only what you approve here."),a.appendChild(o);let c=t.awaiting??0,p=t.blocked??0,l=t.done??0,h=t.total??0,d=t.revision??0,u=t.empty?[]:is(t),f=u.reduce((k,P)=>k+P.count,0);if(!t.empty){let k=ns(t),P=document.createElement("span");if(P.className=`bp-plan-status-badge tone-${k.tone}`,P.textContent=m(k.key,k.label),a.appendChild(P),d>0){let I=document.createElement("span");I.className="bp-dim",I.textContent=`v${d}`,a.appendChild(I)}let F=document.createElement("span");if(F.className="bp-plan-header-counts bp-mgmt-flex1 "+(c>0?"bp-tone-warn":p>0?"bp-tone-bad":"bp-dim"),F.textContent=h>0?`${l}/${h} ${m("gpui.mgmt.plan.done","done")}`:c>0?m("web.plan.awaiting","{n} awaiting approval",{n:c}):m("gpui.mgmt.plan.nothing","Nothing awaits your approval"),a.appendChild(F),!t.live){let I=document.createElement("span");I.className="bp-mgmt-pill",I.textContent=m("gpui.mgmt.plan.saved","saved plan"),a.appendChild(I)}}else{let k=document.createElement("span");k.className="bp-mgmt-flex1",a.appendChild(k)}let b=document.createElement("button");b.type="button",b.className="bp-mgmt-btn bp-plan-chip-btn"+(s?" active":""),b.setAttribute("data-testid","mgmt-plan-on"),b.setAttribute("aria-pressed",s?"true":"false"),b.textContent=m("gpui.bots.recall.on","On"),b.addEventListener("click",()=>n("plan.enable",{on:!0}));let v=document.createElement("button");if(v.type="button",v.className="bp-mgmt-btn bp-plan-chip-btn"+(!s?" active":""),v.setAttribute("data-testid","mgmt-plan-off"),v.setAttribute("aria-pressed",!s?"true":"false"),v.textContent=m("gpui.bots.recall.off","Off"),v.addEventListener("click",()=>n("plan.enable",{on:!1})),a.append(b,v),r.appendChild(a),f>0){let k=document.createElement("div");k.className="bp-plan-segbar";for(let P of u){if(P.count<=0)continue;let F=document.createElement("div");F.className=`bp-plan-seg bp-tone-bg-${P.tone}`,F.style.flexGrow=String(P.count),k.appendChild(F)}r.appendChild(k)}e.appendChild(r);for(let k of t.elsewhere??[]){let P=document.createElement("div");P.className="bp-plan-elsewhere";let F=document.createElement("span");F.className="bp-tone-warn bp-mgmt-flex1",F.textContent=m("gpui.mgmt.plan.elsewhere","A routing plan for {board} awaits your approval",{board:k.name||k.rel||""}),P.appendChild(F),e.appendChild(P)}if(t.empty){let k=document.createElement("div");k.className="bp-mgmt-note";let P=document.createElement("div");P.className="bp-dim",P.textContent=m("gpui.mgmt.plan.noboard","No routing plan for this board.");let F=document.createElement("div");return F.className="bp-mgmt-faint",F.textContent=m("gpui.mgmt.plan.emptysub","Layers, corridors, and planes appear here once a plan is proposed."),k.append(P,F),e.appendChild(k),e}let y=t.stackup_summary??"",w=Array.isArray(t.impedances)?t.impedances:[],C=Boolean(y)||w.length>0,L=document.createElement("div");if(L.className="bp-mgmt-head",c>0){let k=document.createElement("button");k.type="button",k.className="primary bp-mgmt-btn",k.setAttribute("data-testid","mgmt-plan-approve-all"),k.textContent=m("gpui.mgmt.plan.all","Approve all"),k.addEventListener("click",()=>n("plan.approve",{layer:"",ids:[],approve:!0})),L.appendChild(k)}if(t.routing){let k=document.createElement("button");k.type="button",k.className="bp-mgmt-btn",k.setAttribute("data-testid","mgmt-plan-stop"),k.textContent=m("gpui.mgmt.plan.stop","Stop routing"),k.addEventListener("click",()=>n("plan.stop",{})),L.appendChild(k)}if(t.live&&l>0){let k=document.createElement("button");k.type="button",k.className="bp-mgmt-btn",k.setAttribute("data-testid","mgmt-plan-verify"),k.textContent=m("gpui.mgmt.plan.verify","Verify"),k.addEventListener("click",()=>n("plan.verify",{})),L.appendChild(k)}let N=document.createElement("span");if(N.className="bp-mgmt-flex1",L.appendChild(N),C){let k=document.createElement("button");k.type="button",k.className="bp-mgmt-btn bp-plan-chip-btn"+(this.planStackupOpen?" active":""),k.setAttribute("data-testid","mgmt-plan-stackup-toggle"),k.setAttribute("aria-expanded",this.planStackupOpen?"true":"false"),k.textContent=`${m("gpui.mgmt.plan.stackup.short","Stackup")} ${this.planStackupOpen?"▾":"▸"}`,k.addEventListener("click",()=>{this.planStackupOpen=!this.planStackupOpen,this.render()}),L.appendChild(k)}let A=document.createElement("button");A.type="button",A.className="bp-mgmt-btn",A.setAttribute("data-testid","mgmt-plan-hide"),A.textContent=this.planHideDone?m("gpui.mgmt.plan.show","Show done"):m("gpui.mgmt.plan.hide","Hide done"),A.addEventListener("click",()=>{this.planHideDone=!this.planHideDone,this.render()}),L.appendChild(A),e.appendChild(L);let B=Array.isArray(t.asks)?t.asks:[];if(B.length>0){let k=B.map((ie)=>ie.what||"").filter(Boolean).join(", "),P=B[0]?.note||"",F=document.createElement("div");F.className="bp-plan-elsewhere";let I=document.createElement("div");I.className="bp-plan-ask-col";let J=document.createElement("div");if(J.className="bp-tone-warn",J.textContent=k?m("gpui.mgmt.plan.requested","Approval requested: {what}",{what:k}):m("gpui.mgmt.plan.reqplain","Approval requested"),I.appendChild(J),P){let ie=document.createElement("div");ie.className="bp-dim",ie.textContent=P,I.appendChild(ie)}F.appendChild(I),e.appendChild(F)}if(this.planStatus){let k=document.createElement("div");k.className="bp-mgmt-note bp-plan-err bp-tone-bad";let P=document.createElement("span");P.className="bp-mgmt-flex1",P.textContent=this.planStatus==="KiCad refused"?m("gpui.mgmt.plan.refused","KiCad refused"):pe(this.planStatus);let F=document.createElement("button");F.type="button",F.className="icon",F.textContent="×",F.title=m("common.close","Close"),F.addEventListener("click",()=>{this.planStatus="",this.render()}),k.append(P,F),e.appendChild(k)}if(t.keys_note){let k=document.createElement("div");k.className="bp-mgmt-note bp-dim";let P="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.";k.textContent=t.keys_note===P?m("gpui.mgmt.plan.keysnote",P):pe(t.keys_note),e.appendChild(k)}if(C&&this.planStackupOpen){let k=document.createElement("div");if(k.className="bp-plan-stackup-body",k.setAttribute("data-testid","mgmt-plan-stackup-body"),y){let P=document.createElement("div");P.className="bp-dim",P.textContent=y,k.appendChild(P)}for(let P of w){let F=document.createElement("div");F.className="bp-mgmt-faint",F.textContent=`· ${P}`,k.appendChild(F)}e.appendChild(k)}let M=(k,P,F,I)=>{let J=document.createElement("button");return J.type="button",J.className="bp-mgmt-btn bp-plan-chip-btn"+(P?" active":""),J.setAttribute("data-testid",F),J.setAttribute("aria-pressed",P?"true":"false"),J.textContent=k,J.addEventListener("click",I),J},j=document.createElement("div");if(j.className="bp-plan-viewbar",j.append(M(m("gpui.mgmt.plan.view.canvas","Canvas"),this.planViewMode==="canvas","mgmt-plan-view-canvas",()=>{this.planViewMode="canvas",this.render()}),M(m("gpui.mgmt.plan.view.split","Split"),this.planViewMode==="split","mgmt-plan-view-split",()=>{this.planViewMode="split",this.render()}),M(m("gpui.mgmt.plan.view.list","List"),this.planViewMode==="list","mgmt-plan-view-list",()=>{this.planViewMode="list",this.render()})),this.planViewMode!=="list"){let k=document.createElement("span");k.className="bp-plan-sep";let P=document.createElement("span");P.className="bp-plan-sep";let F=document.createElement("button");F.type="button",F.className="bp-mgmt-btn bp-plan-mini-btn",F.setAttribute("data-testid","mgmt-plan-fit"),F.textContent=m("gpui.mgmt.plan.fit","Fit"),F.addEventListener("click",()=>this.planCanvas?.fitAll()),j.append(k,M(m("gpui.mgmt.plan.grid.pair","Side by side"),this.planGridMode==="pair","mgmt-plan-grid-pair",()=>{this.planGridMode="pair",this.render()}),M(m("gpui.mgmt.plan.grid.all","All layers"),this.planGridMode==="all","mgmt-plan-grid-all",()=>{this.planGridMode="all",this.render()}),M(m("gpui.mgmt.plan.grid.single","Single"),this.planGridMode==="single","mgmt-plan-grid-single",()=>{this.planGridMode="single",this.render()}),P,M(m("gpui.mgmt.plan.sync","Link zoom"),this.planSyncZoom,"mgmt-plan-sync",()=>{this.planSyncZoom=!this.planSyncZoom,this.render()}),F)}let O=document.createElement("span");O.className="bp-mgmt-flex1";let x=document.createElement("button");x.type="button",x.className="bp-mgmt-btn bp-plan-mini-btn",x.setAttribute("data-testid","mgmt-plan-expand"),x.textContent=this.planExpanded?m("gpui.mgmt.plan.compact","Compact"):m("gpui.mgmt.plan.expand","Expand"),x.addEventListener("click",()=>{this.planExpanded=!this.planExpanded,this.render()}),j.append(O,x),e.appendChild(j);let Y=Boolean(this.planHydratedBoard)&&this.planHydratedKey.startsWith(`${this.project}:`)&&(this.planHydratedKey===i||this.planHydratedRev!==void 0&&this.planHydratedRev>=(t.revision??0)),se=Y&&this.planHydratedBoard?this.planHydratedBoard:t.board??{bbox:[0,0,100,70],outline:[],parts:[]},ne=Y&&this.planHydratedDraw?this.planHydratedDraw:t.draw??{bands:[],regions:[]},he=(ne.bands??[]).map((k)=>{let P=this.planOptimistic.get(k.id);if(!P)return{...k};return{...k,...P,edited:!0,state:k.state==="proposed"?"edited":k.state}}),Se=(ne.regions??[]).map((k)=>{let P=this.planOptimistic.get(k.id);if(!P)return{...k};return{...k,...P,edited:!0,state:k.state==="proposed"?"edited":k.state}}),ke=[],ee=(t.layers??[]).map((k)=>{let P=[];for(let F of k.items??[]){let I=this.planOptimistic.get(F.id);if(!I){P.push(F);continue}let J={...F,width:typeof I.width==="number"?I.width:F.width,locked:typeof I.locked==="boolean"?I.locked:F.locked,edited:!0,state:F.state==="proposed"?"edited":F.state};if(typeof I.layer==="string"&&I.layer!==k.layer)ke.push({target:I.layer,item:J});else P.push(J)}return{...k,items:P}});for(let k of ke){let P=ee.find((F)=>F.layer===k.target);if(P)P.items=[...P.items??[],k.item]}let re=ln(ee,t.copper_layers),R=this.planGridMode==="all"?re.map((k)=>k.layer):this.planGridMode==="single"?[this.planShownLayers.find((k)=>re.some((P)=>P.layer===k))??Pt(re)[0]??re[0]?.layer??""].filter(Boolean):this.planShownLayers.length>0&&this.planShownLayers.every((k)=>re.some((P)=>P.layer===k))?this.planShownLayers.slice(0,2):Pt(re);if(this.planViewMode!=="list"&&this.planGridMode!=="all"&&re.length>1){let k=document.createElement("div");k.className="bp-plan-layerbar";for(let P of re){let F=R.includes(P.layer),I=(P.items??[]).length,J=ut(P.layer,t.copper_layers,re)||P.title||P.layer,ie=I>0?`${J} · ${I}`:J,Ee=M(ie,F,`mgmt-plan-layerpill-${P.layer}`,()=>{if(this.planGridMode==="single")this.planShownLayers=[P.layer];else if(this.planGridMode==="pair"){if(!R.includes(P.layer))this.planShownLayers=R.length>=2?[R[0],P.layer]:[...R,P.layer]}else this.planGridMode="single",this.planShownLayers=[P.layer];this.render()});if(I===0&&!F)Ee.classList.add("empty-layer");k.appendChild(Ee)}e.appendChild(k)}let ue=(k,P)=>{let F=this.planOptimistic.get(k)??{};if(this.planOptimistic.set(k,{...F,...P}),typeof P.layer==="string"){if(this.planGridMode==="single")this.planShownLayers=[P.layer];else if(this.planGridMode==="pair"&&!R.includes(P.layer))this.planShownLayers=R.length>=2?[R[0],P.layer]:[...R,P.layer]}let I=typeof t.revision==="number"?t.revision:void 0;this.render(),n("plan.update",{ops:[{op:"set",id:k,fields:P}],...I!==void 0?{base:I}:{}})};if(this.planCommitFields=ue,this.planSelectedId){let k="",P=null;for(let F of ee){let I=(F.items??[]).find((J)=>J.id===this.planSelectedId);if(I){k=F.layer,P=I;break}}if(P){let F=ut(k,t.copper_layers,re),I=document.createElement("div");I.className="bp-plan-inspector",I.setAttribute("data-testid","mgmt-plan-inspector");let J=document.createElement("div");J.className="bp-plan-ins-row";let ie=document.createElement("span");ie.className="bp-plan-ins-sw",ie.style.background=P.kind==="corridor"?xt(P.name||P.id,P.color||""):Ot(P.name||P.id,P.color||"");let Ee=document.createElement("span");Ee.className="bp-mgmt-strong",Ee.textContent=P.name||P.id;let D=document.createElement("span");if(D.className="bp-dim",D.textContent=F,J.append(ie,Ee,D),P.edited||P.state==="edited"){let q=document.createElement("span");q.className="bp-plan-ins-pill warn",q.textContent=m("gpui.mgmt.plan.edited","Edited"),J.appendChild(q)}if(P.locked){let q=document.createElement("span");q.className="bp-plan-ins-pill",q.textContent=m("gpui.mgmt.plan.locked","Locked"),J.appendChild(q)}let te=document.createElement("span");te.className="bp-mgmt-flex1",J.appendChild(te);let Me=document.createElement("button");if(Me.type="button",Me.className="bp-mgmt-btn bp-plan-mini-btn",Me.setAttribute("data-testid","mgmt-plan-lock"),Me.textContent=P.locked?m("gpui.mgmt.plan.unlock","Unlock"):m("gpui.mgmt.plan.lock","Lock"),Me.addEventListener("click",()=>ue(P.id,{locked:!P.locked})),J.appendChild(Me),P.state==="proposed"||P.state==="edited"){let q=document.createElement("button");q.type="button",q.className="primary bp-mgmt-btn bp-plan-mini-btn",q.textContent=m("android.hub.machines.approve","Approve"),q.addEventListener("click",()=>n("plan.approve",{layer:"",ids:[P.id],approve:!0}));let fe=document.createElement("button");fe.type="button",fe.className="bp-mgmt-btn bp-plan-mini-btn",fe.textContent=m("gpui.mgmt.plan.reject","Reject"),fe.addEventListener("click",()=>n("plan.approve",{layer:"",ids:[P.id],approve:!1})),J.append(q,fe)}let Ae=document.createElement("button");Ae.type="button",Ae.className="bp-mgmt-btn bp-plan-mini-btn",Ae.setAttribute("data-testid","mgmt-plan-note-toggle"),Ae.textContent=m("gpui.mgmt.plan.addnote","Add note"),Ae.addEventListener("click",()=>{this.planNoteOpen=!this.planNoteOpen,this.render()});let Te=document.createElement("button");if(Te.type="button",Te.className="icon",Te.textContent="×",Te.addEventListener("click",()=>{this.planSelectedId="",this.planNoteOpen=!1,this.planMoveLayerOpen=!1,this.render()}),J.append(Ae,Te),I.appendChild(J),!P.locked){let q=document.createElement("div");if(q.className="bp-plan-ins-row",P.kind==="corridor"){let oe=typeof P.width==="number"?P.width:1.5,He=document.createElement("span");He.className="bp-dim",He.textContent=m("gpui.mgmt.plan.width","Width");let De=document.createElement("button");De.type="button",De.className="bp-mgmt-btn bp-plan-mini-btn",De.setAttribute("data-testid","mgmt-plan-w-down"),De.textContent="-",De.addEventListener("click",()=>{let _e=Math.round(Math.max(0.15,oe-0.25)*100)/100;ue(P.id,{width:_e})});let Fe=document.createElement("span");Fe.className="bp-plan-ins-val",Fe.textContent=`${oe.toFixed(2)}mm`;let Be=document.createElement("button");Be.type="button",Be.className="bp-mgmt-btn bp-plan-mini-btn",Be.setAttribute("data-testid","mgmt-plan-w-up"),Be.textContent="+",Be.addEventListener("click",()=>{let _e=Math.round(Math.min(25,oe+0.25)*100)/100;ue(P.id,{width:_e})});let Ge=document.createElement("span");Ge.className="bp-plan-sep",q.append(He,De,Fe,Be,Ge)}let fe=(t.copper_layers??[]).length>0?(t.copper_layers??[]).map((oe)=>oe.layer):ee.map((oe)=>oe.layer);if(fe.length>0){let oe=document.createElement("span");oe.className="bp-dim",oe.textContent=m("gpui.mgmt.plan.layer.short","Layer"),q.appendChild(oe),q.appendChild(M(`${F} ${this.planMoveLayerOpen?"▴":"▾"}`,this.planMoveLayerOpen,"mgmt-plan-move-toggle",()=>{this.planMoveLayerOpen=!this.planMoveLayerOpen,this.render()}))}if(I.appendChild(q),this.planMoveLayerOpen&&fe.length>0){let oe=document.createElement("div");oe.className="bp-plan-ins-row";for(let He of fe){let De=ut(He,t.copper_layers,re);oe.appendChild(M(De,He===k,`mgmt-plan-move-${He}`,()=>{if(this.planMoveLayerOpen=!1,He!==k)ue(P.id,{layer:He});else this.render()}))}I.appendChild(oe)}}if(this.planNoteOpen){let q=document.createElement("form");q.className="bp-plan-note-form";let fe=document.createElement("input");fe.type="text",fe.className="bp-plan-note-input",fe.setAttribute("data-testid","mgmt-plan-note-input"),fe.placeholder=m("gpui.mgmt.plan.note.placeholder","Steering note for router…");let oe=document.createElement("button");oe.type="submit",oe.className="primary bp-mgmt-btn bp-plan-mini-btn",oe.setAttribute("data-testid","mgmt-plan-note-submit"),oe.textContent=m("gpui.mgmt.plan.addnote","Add note"),q.append(fe,oe),q.addEventListener("submit",(He)=>{He.preventDefault();let De=fe.value.trim();if(!De)return;fe.value="",this.planNoteOpen=!1;let Fe=typeof t.revision==="number"?t.revision:void 0;this.render(),n("plan.update",{ops:[{op:"note",target:P.id,text:De}],...Fe!==void 0?{base:Fe}:{}})}),I.appendChild(q)}if(this.planViewMode!=="list"&&!P.locked){let q=document.createElement("div");q.className="bp-plan-hint",q.textContent=m("gpui.mgmt.plan.hint","Drag waypoints to steer · Click + on edge to insert · Right-click vertex to remove"),I.appendChild(q)}e.appendChild(I)}}let le=document.createElement("div");le.className="bp-mgmt-rows"+(this.planViewMode==="split"?" bp-plan-split-list":""),le.setAttribute("data-testid","mgmt-plan-rows");let Q=m("gpui.mgmt.plan.done","done"),ge=hs(this.planViewMode,ee,R);if(this.planViewMode==="split"&&ge.length===0){let k=document.createElement("div");k.className="bp-dim",k.style.padding="6px 8px",k.style.fontSize="11px",k.textContent=m("gpui.mgmt.plan.noitems","No corridors or planes on this layer"),le.appendChild(k)}for(let k of ge){let P=k.items??[],F=ut(k.layer,t.copper_layers,re)||k.layer;if(this.planViewMode==="split"){if(ge.length>1){let I=document.createElement("div");I.className="bp-plan-split-divider";let J=k.role==="power"||k.role==="plane",ie=document.createElement("span");ie.className="bp-plan-card-bar "+(J?"pwr":"sig");let Ee=document.createElement("span");Ee.className="bp-mgmt-strong",Ee.textContent=F;let D=document.createElement("span");D.className="bp-dim",D.textContent=`${k.done??0}/${P.length} ${Q}`,I.append(ie,Ee,D),le.appendChild(I)}}else{let I=document.createElement("div");I.className="bp-mgmt-group-head bp-plan-layer-head";let J=document.createElement("div");J.className="bp-mgmt-row-line";let ie=document.createElement("span");ie.className="bp-mgmt-strong",ie.textContent=F;let Ee=document.createElement("span");if(Ee.className="bp-dim bp-mgmt-flex1",Ee.textContent=`${k.role?`${k.role} · `:""}${k.done??0}/${P.length} ${Q}`,J.append(ie,Ee),k.status!=="approved"&&P.length>0){let D=document.createElement("button");D.type="button",D.className="bp-mgmt-btn",D.textContent=m("gpui.mgmt.plan.layer","Approve layer"),D.addEventListener("click",()=>n("plan.approve",{layer:k.layer,ids:[],approve:!0}));let te=document.createElement("button");te.type="button",te.className="bp-mgmt-btn",te.textContent=m("gpui.mgmt.plan.reject","Reject"),te.addEventListener("click",()=>n("plan.approve",{layer:k.layer,ids:[],approve:!1})),J.append(D,te)}if(I.appendChild(J),k.stackup){let D=document.createElement("div");D.className="bp-plan-layer-stackup",D.textContent=k.stackup,I.appendChild(D)}le.appendChild(I)}for(let I of P){if(this.planHideDone&&es(I))continue;let J=this.planSelectedId===I.id,ie=document.createElement("div");ie.className="bp-mgmt-row bp-plan-row"+(J?" active":""),ie.setAttribute("data-testid",`mgmt-plan-row-${I.id}`);let Ee=document.createElement("div");Ee.className="bp-mgmt-row-line";let D=document.createElement("span");D.className=`bp-plan-swatch bp-plan-st-${I.state||"proposed"}`,D.style.setProperty("--swatch-color",I.color||"#8a8a8a");let te=document.createElement("span");te.className="bp-mgmt-flex1"+(I.state==="blocked"||I.state==="failed"?" bp-tone-bad":I.state==="edited"?" bp-tone-warn":I.state==="rejected"||I.state==="routed"||I.state==="verified"?" bp-dim":""),te.textContent=`${I.name||I.id}${I.locked?" \uD83D\uDD12":""}`;let Me=[];if(I.kind==="plane"){if(I.reference)Me.push(m("gpui.mgmt.plan.reference","over {layer}",{layer:I.reference}))}else{let q=I.nets??0;Me.push(q===1?m("web.plan.net.one","1 net"):m("web.plan.nets","{n} nets",{n:q}))}if(typeof I.width==="number"&&Number.isFinite(I.width))Me.push(`${I.width.toFixed(2)}mm`);if(I.impedance)Me.push(I.impedance);let Ae=Me.join(" · "),Te=document.createElement("span");if(Te.className="bp-plan-mark "+(I.state==="blocked"||I.state==="failed"?"bp-tone-bad":I.state==="verified"||I.state==="routed"?"bp-tone-ok":I.state==="approved"?"bp-tone-accent":"bp-dim"),Te.textContent=ts(I),Ee.append(D,te,Te),I.state==="proposed"||I.state==="edited"){let q=document.createElement("button");q.type="button",q.className="bp-mgmt-btn",q.textContent="✓",q.title=m("gpui.mgmt.plan.layer","Approve layer"),q.addEventListener("click",(oe)=>{oe.stopPropagation(),n("plan.approve",{layer:"",ids:[I.id],approve:!0})});let fe=document.createElement("button");fe.type="button",fe.className="bp-mgmt-btn",fe.textContent="✗",fe.title=m("gpui.mgmt.plan.reject","Reject"),fe.addEventListener("click",(oe)=>{oe.stopPropagation(),n("plan.approve",{layer:"",ids:[I.id],approve:!1})}),Ee.append(q,fe)}if(ie.appendChild(Ee),Ae){let q=document.createElement("div");q.className="bp-mgmt-row-sub bp-plan-detail bp-dim",q.textContent=Ae,ie.appendChild(q)}if(I.state==="routing"&&typeof I.total==="number"&&I.total>0){let q=document.createElement("div");q.className="bp-plan-microbar";let fe=document.createElement("div");fe.className="bp-plan-microbar-fill";let oe=Math.max(0,Math.min(100,Math.round((I.routed??0)/I.total*100)));fe.style.width=`${oe}%`,q.appendChild(fe),ie.appendChild(q)}if(I.problem_text){let q=document.createElement("div");q.className="bp-plan-problem",q.textContent=I.problem_text,ie.appendChild(q)}ie.addEventListener("click",()=>{this.planSelectedId=I.id,n("plan.focus",{id:I.id}),this.render()}),le.appendChild(ie)}}if(this.planViewMode!=="list"){if(!this.planCanvas)this.planCanvas=new jn({onSelect:(I)=>{if(this.planSelectedId=I,!I)this.planNoteOpen=!1;this.render()},onFocusItem:(I)=>{n("plan.focus",{id:I})},onDragEnd:()=>{if(this.planRenderDeferred)this.planRenderDeferred=!1,this.render()},onCommitFields:(I,J)=>{(this.planCommitFields??ue)(I,J)},onApproveLayer:(I,J)=>{n("plan.approve",{layer:I,ids:[],approve:J})},onQuickApprove:(I,J)=>{n("plan.approve",{layer:"",ids:I,approve:J})}});let k=this.panelEl.parentElement?.classList.contains("bp-has-viewer")===!1,P=this.planExpanded||this.panelEl.clientWidth>=540||k;this.planCanvas.update({gridMode:this.planGridMode,syncZoom:this.planSyncZoom,shownLayers:R,selectedId:this.planSelectedId,board:se,bands:he,regions:Se,layers:re,copperLayers:t.copper_layers},P);let F=document.createElement("div");F.className="bp-plan-canvas-scroll",F.appendChild(this.planCanvas.root),e.appendChild(F)}if(this.planViewMode!=="canvas")e.appendChild(le);if((t.draw?.bands?.length??0)>0||(t.draw?.regions?.length??0)>0){let k=document.createElement("div");k.className="bp-plan-footer",k.textContent=m("gpui.mgmt.plan.drawn","The plan's corridors and planes are drawn on the board while this panel is open. Close it to hide them."),e.appendChild(k)}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,N=this.project;this.fabStatus="",this.cb.hub.rpc("fab.profile",{pro:N,action:w,...C}).catch((A)=>{if(L!==this.watchGen||N!==this.project)return;this.fabStatus=A instanceof Error?A.message:"Fab action failed",this.render()})},i=document.createElement("div");i.className="bp-mgmt-head";let s=document.createElement("span");s.className="bp-mgmt-strong",s.textContent=m("gpui.mgmt.fab.thefab","The fab");let r=document.createElement("span");r.className="bp-dim bp-mgmt-flex1",r.textContent=`rev ${t.rev??0}${t.updated?` · ${t.updated}`:""}${t.board?` · ${t.board}`:""} · ${rs(t.tier??"")}`;let a=document.createElement("button");if(a.type="button",a.className="bp-mgmt-btn",a.textContent=m("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,p=document.createElement("div");p.className="bp-mgmt-row";let l=document.createElement("div");l.className="bp-mgmt-row-line";let h=document.createElement("span"),d=(c?.counts?.error??0)>0;if(h.className="bp-mgmt-flex1 "+(d?"bp-tone-bad":"bp-dim"),h.textContent=c?.running?"Reviewing the design…":c?.at==null?"No design review yet":`${c.counts?.error??0} must-fix · ${c.counts?.warning??0} should-fix · ${c.counts?.info??0} notes${c.scope?` (${c.scope})`:""}`,l.appendChild(h),c?.at!=null){let w=document.createElement("button");w.type="button",w.className="bp-mgmt-btn",w.textContent=m("gpui.mgmt.fab.findings","Findings"),w.addEventListener("click",()=>this.togglePanel("checks")),l.appendChild(w)}if(!c?.running){let w=document.createElement("button");w.type="button",w.className="bp-mgmt-btn",w.textContent=m("gpui.mgmt.fab.reviewbtn","Review"),w.addEventListener("click",()=>n("review")),l.appendChild(w)}if(c?.judge){let w=document.createElement("button");w.type="button",w.className="bp-mgmt-btn",w.textContent=m("gpui.mgmt.fab.judge","Datasheets"),w.addEventListener("click",()=>{if(c.judge)this.cb.onSendText(c.judge)}),l.appendChild(w)}p.appendChild(l),o.appendChild(p);let u=ss(t.drc?.state??""),f=document.createElement("div");f.className="bp-mgmt-row";let b=document.createElement("div");b.className="bp-mgmt-row-line";let v=document.createElement("span");if(v.className="bp-mgmt-flex1 "+(u.button?"bp-tone-warn":"bp-dim"),v.textContent=u.text,b.appendChild(v),u.button){let w=document.createElement("button");w.type="button",w.className="bp-mgmt-btn",w.textContent=u.button,w.addEventListener("click",()=>n("drc")),b.appendChild(w)}f.appendChild(b),o.appendChild(f);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 N=document.createElement("span");N.className="bp-mgmt-flex1 bp-tone-warn",N.textContent=`${w.label||w.key}: board ${w.project??"?"} mm, fab ${w.fab??"?"} mm`;let A=document.createElement("button");A.type="button",A.className="bp-mgmt-btn",A.textContent=m("gpui.mgmt.fab.apply","Apply"),A.addEventListener("click",()=>n("apply",{key:w.key})),L.append(N,A),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",N=document.createElement("span");if(N.className="bp-mgmt-flex1 "+(L?"bp-tone-warn":"bp-dim"),N.textContent=`${L?"Proposed: ":""}${t.stackup.chosen}${t.stackup.outer_50_mm?` (50Ω ${t.stackup.outer_50_mm} mm)`:""}`,C.appendChild(N),L){let A=t.stackup.chosen,B=document.createElement("button");B.type="button",B.className="bp-mgmt-btn",B.textContent=m("gpui.mgmt.fab.use","Use"),B.addEventListener("click",()=>n("stackup",{id:A})),C.appendChild(B)}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=m("gpui.mgmt.fab.changed","Changed since you last looked");let N=document.createElement("button");N.type="button",N.className="bp-mgmt-btn",N.textContent=m("gpui.mgmt.fab.seen","Seen"),N.addEventListener("click",()=>n("seen")),C.append(L,N),w.appendChild(C);for(let A of t.changed.slice(0,12)){let B=document.createElement("div");B.className="bp-mgmt-faint",B.textContent=A,w.appendChild(B)}o.appendChild(w)}let y=Array.isArray(t.limits)?t.limits:[];if(y.length>0){let w=document.createElement("div");w.className="bp-mgmt-group-head";let C=document.createElement("span");C.className="bp-mgmt-flex1",C.textContent=m("gpui.mgmt.fab.limit","Limit");let L=document.createElement("span");L.className="bp-mgmt-col",L.textContent=m("gpui.mgmt.fab.free","Base price");let N=document.createElement("span");N.className="bp-mgmt-col",N.textContent=m("gpui.mgmt.fab.extra","Costs more");let A=document.createElement("span");A.className="bp-mgmt-col bp-mgmt-col-read",A.textContent=m("gpui.mgmt.fab.readcol","Read"),w.append(C,L,N,A),o.appendChild(w);for(let M of y){let j=document.createElement("div");j.className="bp-mgmt-row";let O=document.createElement("div");O.className="bp-mgmt-row-line";let x=document.createElement("span");x.className="bp-mgmt-flex1"+(M.changed?" bp-tone-warn":M.inherited?" bp-dim":""),x.textContent=`${M.changed?"• ":""}${M.label??""}`;let Y=document.createElement("span");Y.className="bp-mgmt-col",Y.textContent=M.free?.text||"—";let se=document.createElement("span");se.className="bp-mgmt-col bp-dim",se.textContent=M.extra?.text||"—";let ne=M.free&&typeof M.free==="object"?M.free:M.extra,he=ne?.fetched??"",Se=Boolean(he)&&ne?.confidence!=="published",ke=he?Se?`${he}*`:he:"—",ee=ne?.source??"",re;if(ee.startsWith("https://")&&he){let R=document.createElement("a");R.className="bp-mgmt-col bp-mgmt-col-read bp-mgmt-read-link",R.href=ee,R.target="_blank",R.rel="noopener noreferrer",R.textContent=ke,re=R}else{let R=document.createElement("span");R.className="bp-mgmt-col bp-mgmt-col-read bp-mgmt-faint",R.textContent=ke,re=R}O.append(x,Y,se,re),j.appendChild(O),o.appendChild(j)}let B=document.createElement("div");B.className="bp-mgmt-note bp-mgmt-faint",B.textContent=m("gpui.mgmt.fab.derived","* worked out from the fab's page. Dimmed: the rigid board's value. A date opens the source page."),o.appendChild(B)}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 na={trs:(e)=>e,t:(e,t)=>t},ia=new Set(["/settle"]);function Es(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 Cs(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 xs(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 Ps(e,t=na){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=ia.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:p}=ks(o);s.push({label:o.title||"Untitled thread",place:o.project?r.get(o.project)??"":"",kind:"thread",urgency:c,want:p,dotClass:Cs(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 Ss(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 f of i)d.set(f.id,f.title||f.id);let u=new Set;for(let f of c)if(f.action.type==="thread")u.add(f.action.id);for(let f of n.threads){if(!f.id||u.has(f.id))continue;u.add(f.id);let{urgency:b,want:v}=ks(f);c.push({label:f.title||"Untitled thread",place:f.project?d.get(f.project)??"":"",kind:"thread",urgency:b,want:v,dotClass:Cs(f),action:{type:"thread",id:f.id}})}}let p=[];for(let d=0;d0)p.push({score:v,index:d,item:u})}p.sort((d,u)=>{if(o){let v=(u.item.urgency??0)-(d.item.urgency??0);if(v!==0)return v}if(u.score!==d.score)return u.score-d.score;let f=d.item.kind==="thread"?0:1,b=u.item.kind==="thread"?0:1;if(f!==b)return f-b;return d.index-u.index});let l=new Set,h=[];for(let d of p){let u=`${d.item.label}\x00${d.item.place}\x00${d.item.kind}`;if(l.has(u))continue;if(l.add(u),h.push(d.item),h.length>=s)break}if(n?.messages&&n.messages.length>0&&h.length{if(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=Ps(t,{t:m,trs:pe}),i=this.query.trim()===this.searchHitsQuery?this.searchHits:null;if(this.listed=Ss(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=m("gpui.nothing.matches","Nothing matches"),this.listEl.replaceChildren(a);return}let s=document.createDocumentFragment(),r=null;for(let a=0;a0)p.appendChild(document.createTextNode(o.label.slice(0,d)));let f=document.createElement("strong");if(f.className="bp-palette-mark",f.textContent=o.label.slice(d,u),p.appendChild(f),u{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;t0?Math.floor(t.leadDays):0,i=[];for(let s of cn(t.warnings)){let r=nt(s).trim();if(r&&!i.includes(r))i.push(r)}return{project:nt(t.project),root:nt(t.root),intent:nt(t.intent),parts:cn(t.parts).map((s)=>Fn(s)).map((s)=>({name:nt(s.name),kind:nt(s.kind),path:nt(s.path)})).filter((s)=>s.name||s.path),boards:cn(t.boards).map(nt).filter(Boolean),mech:cn(t.mech).map((s)=>Fn(s)).map((s)=>({path:nt(s.path),name:nt(s.name),size:typeof s.size==="number"&&s.size>0?s.size:0})).filter((s)=>s.name||s.path),leadDays:n,warnings:i}}function $n(e){let t=[];for(let n of e.split(` +`)){let i=n.trimEnd();if(!i.trim())continue;if(t.length>=60)break;let s=i.trimStart();if(s.startsWith("#"))t.push({kind:"h",text:s.replace(/^#+/,"").trim()});else if(s.startsWith("- ")||s.startsWith("* "))t.push({kind:"li",text:s.slice(2).trim()});else t.push({kind:"p",text:s})}return t}function As(e){return!$n(e).some((t)=>t.kind!=="h"&&t.text.length>0)}function Ns(e){if(!Number.isFinite(e)||e<=0)return"";if(e<1024)return`${Math.floor(e)} B`;if(e<1048576)return`${(e/1024).toFixed(e<10240?1:0)} KB`;return`${(e/1048576).toFixed(1)} MB`}function On(e){let t=e.lastIndexOf("|");return t>=0?e.slice(t+1):e}function be(e,t,n){let i=document.createElement(e);if(t)i.className=t;if(n!==void 0)i.textContent=n;return i}class Gn{root;titleEl;rootEl;newBtn;newLbl;threadsEl;bodyEl;cb;projectId="";data=null;threads=null;error="";constructor(e,t){this.cb=t,this.root=be("section","bp-project-home bp-hidden"),this.root.setAttribute("data-testid","project-home");let n=be("div","bp-home-inner"),i=be("header","bp-home-head");this.titleEl=be("h1","bp-home-title"),this.titleEl.setAttribute("data-testid","project-home-title"),this.rootEl=be("div","bp-home-root"),i.append(this.titleEl,this.rootEl);let s=be("div","bp-home-bar");this.newBtn=be("button","primary bp-home-new"),this.newBtn.type="button",this.newBtn.setAttribute("data-testid","project-home-new-thread");let r=be("span","bp-home-new-plus","+");r.setAttribute("aria-hidden","true"),this.newLbl=be("span","",m("thread.new","New thread")),this.newBtn.append(r,this.newLbl),this.newBtn.addEventListener("click",()=>{if(this.projectId)this.cb.onNewThread(this.projectId)}),s.appendChild(this.newBtn),this.threadsEl=be("div","bp-home-threads"),this.bodyEl=be("div","bp-home-body"),n.append(i,s,this.threadsEl,this.bodyEl),this.root.appendChild(n),e.appendChild(this.root)}isOpen(){return this.projectId!==""}show(e){if(this.projectId!==e.id)this.data=null,this.threads=null,this.root.scrollTop=0;this.error="",this.projectId=e.id,this.titleEl.textContent=e.title||e.id,this.root.classList.remove("bp-hidden"),this.render()}hide(){this.projectId="",this.root.classList.add("bp-hidden")}setTitle(e){if(e)this.titleEl.textContent=e}setData(e){this.data=e,this.error="",this.render()}setThreads(e){this.threads=e,this.render()}setError(e){this.error=e,this.render()}refreshLocale(){if(this.newLbl.textContent=m("thread.new","New thread"),this.isOpen())this.render()}section(e){return be("h2","bp-home-section",e)}render(){this.rootEl.textContent=this.data?.root??"",this.rootEl.classList.toggle("bp-hidden",!this.data?.root),this.renderThreads(),this.renderBody()}renderThreads(){let e=document.createDocumentFragment(),t=this.threads;if(t){if(e.appendChild(this.section(m("gpui.projects.threads","THREADS ({n})",{n:t.length}))),t.length===0)e.appendChild(be("div","bp-home-empty",m("gpui.no.threads.yet","No threads yet.")));for(let n of t){let i=be("button","bp-home-row bp-home-thread"+(n.settled?" bp-dim":""));i.type="button",i.setAttribute("data-testid",`project-home-thread-${n.id}`);let s=be("span",`bp-dot ${n.dot}`);if(n.status)s.title=n.status;let r=be("span","bp-home-row-main",n.title||"Untitled thread"),a=be("span","bp-home-row-faint",n.age);i.append(s,r,a),i.addEventListener("click",()=>this.cb.onOpenThread(n.id)),e.appendChild(i)}}this.threadsEl.replaceChildren(e)}renderBody(){let e=document.createDocumentFragment(),t=this.data;if(this.error){let s=be("div","bp-home-error");s.setAttribute("data-testid","project-home-error"),s.appendChild(be("span","",this.error));let r=be("button","bp-btn-ghost",m("tools.retry","Retry"));r.type="button";let a=this.projectId;r.addEventListener("click",()=>this.cb.onRetry(a)),s.appendChild(r),e.appendChild(s)}if(!t){if(!this.error)e.appendChild(be("div","bp-home-empty",m("web.home.loading","Loading project…")));this.bodyEl.replaceChildren(e);return}e.appendChild(this.section(m("gpui.goal.notes","GOAL & NOTES")));let n=be("div","bp-home-intent");if(n.setAttribute("data-testid","project-home-intent"),As(t.intent))e.appendChild(be("div","bp-home-empty",m("gpui.no.goal.yet.ask.an","No goal yet. Ask an agent to write what this project is for, or edit .backplane/intent.md.")));else{for(let s of $n(t.intent))if(s.kind==="h")n.appendChild(be("div","bp-home-intent-h",s.text));else if(s.kind==="li"){let r=be("div","bp-home-intent-li"),a=be("span","bp-home-bullet","•");a.setAttribute("aria-hidden","true"),r.append(a,be("span","",s.text)),n.appendChild(r)}else n.appendChild(be("div","",s.text));e.appendChild(n)}let i=this.threads?.[0]?.id??"";if(t.mech.length>0)e.appendChild(this.section(m("gpui.projects.mech","MECHANICAL ({n})",{n:t.mech.length}))),t.mech.forEach((s,r)=>{let a=r===0&&t.mech.length>1,o=this.fileRow(i,"mech",`project-home-mech-${r}`);if(o.title=s.path,o.appendChild(be("span","bp-home-row-main",s.name||s.path)),a)o.appendChild(be("span","bp-home-row-accent",m("gpui.assembly","Assembly")));o.appendChild(be("span","bp-home-row-faint",Ns(s.size))),e.appendChild(o)});if(t.parts.length>0){e.appendChild(this.section(m("gpui.projects.to.order","TO ORDER ({n})",{n:t.parts.length})));let s=be("div","bp-home-order");if(s.setAttribute("data-testid","project-home-order"),t.parts.forEach((r,a)=>{let o=be("div","bp-home-row");o.setAttribute("data-testid",`project-home-part-${a}`),o.append(be("span","bp-home-row-main",r.name||r.path),be("span","bp-home-row-dim",r.kind),be("span","bp-home-row-faint",r.path)),s.appendChild(o)}),t.leadDays>0){let r=be("div","bp-home-order-note",t.leadDays===1?m("web.home.lead.one","Lead time: 1 day"):m("web.home.lead","Lead time: {n} days",{n:t.leadDays}));r.setAttribute("data-testid","project-home-lead"),s.appendChild(r)}for(let r of t.warnings){let a=be("div","bp-home-order-note warn",r);a.setAttribute("data-testid","project-home-warning"),s.appendChild(a)}e.appendChild(s)}if(t.boards.length>0)e.appendChild(this.section(m("gpui.projects.boards","BOARDS ({n})",{n:t.boards.length}))),t.boards.forEach((s,r)=>{let a=this.fileRow(i,"board",`project-home-board-${r}`);a.appendChild(be("span","bp-home-row-main",s)),e.appendChild(a)});this.bodyEl.replaceChildren(e)}fileRow(e,t,n){if(!e){let s=be("div","bp-home-row");return s.setAttribute("data-testid",n),s}let i=be("button","bp-home-row bp-home-open");return i.type="button",i.setAttribute("data-testid",n),i.addEventListener("click",()=>this.cb.onOpenViewer(e,t)),i}}function Vn(e){let t=null;if(typeof e==="string"){let i=e.trim();if(!i)return null;try{let s=JSON.parse(i);if(s&&typeof s==="object"&&!Array.isArray(s))t=s}catch{return null}}else if(e&&typeof e==="object"&&!Array.isArray(e))t=e;if(!t)return null;let n=typeof t.head==="string"?t.head.trim():"";if(!n)return null;return{reason:typeof t.reason==="string"?t.reason:"",head:n,text:typeof t.text==="string"?t.text:"",button:typeof t.button==="string"&&t.button.trim()?t.button:"Open Settings → Accounts",url:typeof t.url==="string"&&t.url.trim()?t.url:"backplane://settings/accounts"}}function sa(e){return e.startsWith("No AI provider connected yet.")}function Ms(e,t){if(t==="no_provider")return!0;if(t)return!1;return sa(e)}function it(e){return typeof e==="string"?e:""}function Un(e){return typeof e==="number"&&Number.isFinite(e)?e:0}function Ts(e){let t=e&&typeof e==="object"?e:{},n=[];for(let i of Array.isArray(t.notes)?t.notes:[]){if(!i||typeof i!=="object")continue;let s=i,r=it(s.id);if(!r)continue;n.push({id:r,said:Un(s.said),gesture:it(s.gesture),words:it(s.words),model:it(s.model),conf:typeof s.conf==="number"&&Number.isFinite(s.conf)?s.conf:null,unsure:it(s.unsure),state:it(s.state),error:it(s.error),thread:it(s.thread),play:it(s.play),heard:Un(s.heard)})}return{total:Math.max(Un(t.total),n.length),notes:n,busy:it(t.busy)}}function Bs(e){let t=/\/ring\/audio\/(n[0-9a-f]{16})(?:\.m4a)?\?k=([0-9a-fA-F]+)$/.exec(e);return t?`/ring/audio/${t[1]}?k=${t[2]}`:""}function Is(e){if(!e.model)return{key:"web.ring.not.heard",fallback:"Not heard"};if(e.model==="ring")return{key:"web.ring.app.words",fallback:"The Pebble app's words"};if(e.conf!==null)return{key:"web.ring.heard.by.sure",fallback:"Heard by {model}, {conf}% sure",vars:{model:e.model,conf:Math.round(e.conf)}};return{key:"web.ring.heard.by",fallback:"Heard by {model}",vars:{model:e.model}}}function Rs(e,t){if(t)return{key:"web.ring.state.busy",fallback:"being heard now"};switch(e){case"sent":return{key:"web.ring.state.sent",fallback:"given to Pebble"};case"new":return{key:"web.ring.state.new",fallback:"waiting to be heard"};case"heard":return{key:"web.ring.state.heard",fallback:"waiting to go to Pebble"};case"failed":return{key:"web.ring.state.failed",fallback:"not given to Pebble"};default:return{key:"",fallback:e}}}function js(e,t,n){if(e<=0)return{key:"ring.no.recordings.yet",fallback:"No recordings yet."};if(n.trim())return{key:"web.ring.found",fallback:"{found} of {total} have “{q}”.",vars:{found:t,total:e,q:n.trim()}};return e===1?{key:"web.ring.count.one",fallback:"1 recording"}:{key:"web.ring.count",fallback:"{n} recordings",vars:{n:e}}}var Hs="http://www.w3.org/2000/svg",Ds={terminal:["M4 17l6-6-6-6","M12 19h8"],search:["M11 19a8 8 0 1 0 0-16 8 8 0 0 0 0 16z","M21 21l-4.3-4.3"],"circuit-board":["M3 3h18v18H3z","M9 3v6h6","M9 21v-6","M15 9a2 2 0 1 0 0-4 2 2 0 0 0 0 4z","M9 15a2 2 0 1 0 0-4 2 2 0 0 0 0 4z"],cpu:["M6 6h12v12H6z","M9 2v4","M15 2v4","M9 18v4","M15 18v4","M2 9h4","M2 15h4","M18 9h4","M18 15h4"],box:["M21 16V8l-9-5-9 5v8l9 5 9-5z","M3.3 7L12 12l8.7-5","M12 22V12"],gauge:["M12 14l4-4","M3.3 19a10 10 0 1 1 17.4 0"],"file-stack":["M16 2H6v12h10V2z","M20 6v12H10","M4 18h10v4H4z"],"layout-panel-left":["M3 3h18v18H3z","M10 3v18"],layers:["M12 2L2 7l10 5 10-5-10-5z","M2 12l10 5 10-5","M2 17l10 5 10-5"],wrench:["M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.77-3.77a6 6 0 0 1-7.94 7.94l-6.91 6.91a2.12 2.12 0 0 1-3-3l6.91-6.91a6 6 0 0 1 7.94-7.94l-3.76 3.76z"],folder:["M3 6h6l2 2h10v11H3z"],diff:["M12 5v10","M7 10h10","M7 19h10"],"circle-check":["M12 22a10 10 0 1 0 0-20 10 10 0 0 0 0 20z","M9 12l2 2 4-4"],globe:["M12 22a10 10 0 1 0 0-20 10 10 0 0 0 0 20z","M2 12h20","M12 2a15 15 0 0 1 0 20 15 15 0 0 1 0-20z"]};function ra(e){let t=document.createElementNS(Hs,"svg");t.setAttribute("viewBox","0 0 24 24"),t.setAttribute("width","18"),t.setAttribute("height","18"),t.setAttribute("fill","none"),t.setAttribute("stroke","currentColor"),t.setAttribute("stroke-width","1.75"),t.setAttribute("stroke-linecap","square"),t.setAttribute("stroke-linejoin","miter"),t.setAttribute("aria-hidden","true");let n=Ds[e]??Ds.folder;for(let i of n){let s=document.createElementNS(Hs,"path");s.setAttribute("d",i),t.appendChild(s)}return t}class Wn{el;items=[];activeId="";onPress;pagesRo=null;constructor(e,t){this.el=e,this.onPress=t,this.render()}setItems(e){this.items=e.slice(),this.render()}setActive(e){this.activeId=e,this.render()}renderButton(e){let t=e.state==="disabled",n=!t&&(e.state==="on"||this.activeId!==""&&e.id===this.activeId),i=pe(e.label),s=e.why?pe(e.why):"",r=document.createElement("button");if(r.type="button",r.className="bp-rail-btn"+(n?" active":"")+(t?" disabled":""),r.disabled=t,r.setAttribute("aria-pressed",n?"true":"false"),t){if(r.title=s||i,s)r.setAttribute("data-why",s)}else r.title=e.key?`${i} (${e.key.toUpperCase()})`:i;r.setAttribute("data-rail-id",e.id),r.setAttribute("data-testid",`rail-${e.id}`),r.appendChild(ra(e.icon));let a=document.createElement("span");if(a.className="bp-rail-lbl",a.textContent=i,r.appendChild(a),!t)r.addEventListener("click",()=>this.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 aa=new Set(["resume","raise","retry","move","signin"]);function _n(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 dn(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(aa.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 Fs(e){let t=e&&typeof e==="object"?e.open:void 0;if(typeof t!=="string")return null;let n=t.indexOf(":"),i=n<0?"":t.slice(n+1);if(!i)return null;if(t.startsWith("account:"))return{kind:"account",id:i};if(t.startsWith("thread:"))return{kind:"thread",id:i};return null}var qn=[{id:"general",label:"General"},{id:"ai",label:"Agents and tools"},{id:"connect",label:"Connect"}],St=[{id:"appearance",group:"general",title:"Appearance",subtitle:"Kept in this browser only. Never sent to the hub.",icon:"sun",keywords:["theme","dark","light","auto","color","language","locale","english","espanol","japanese"]},{id:"providers",group:"ai",title:"AI providers",subtitle:"Account sign-ins live in the desktop or mobile app.",icon:"cpu",keywords:["accounts","claude","codex","antigravity","grok","openai","anthropic","signin","login","model"]},{id:"ring",group:"ai",title:"Ring",subtitle:"Voice notes from your Pebble ring. Its webhook is set up in the desktop or mobile app.",icon:"mic",keywords:["pebble","index","voice","note","notes","recording","recordings","play","hear","transcribe","search"]},{id:"devices",group:"connect",title:"Devices & browser",subtitle:"This browser session and paired devices on this hub.",icon:"link",keywords:["sign out","logout","session","cookie","revoke","paired","phone","browser","pair"]},{id:"home",group:"connect",title:"Home machine",subtitle:"Which machine hosts your always-on hub and bots.",icon:"globe",keywords:["host","boat","move","online","away","queued","linked"]}];function $s(e){if(e==="dark"||e==="light"||e==="auto")return e;return"auto"}function Os(e){if(e==="en"||e==="es"||e==="ja"||e==="auto")return e;return"auto"}function Gt(e,t){if(e==="dark"||e==="light")return e;return t==="light"?"light":"dark"}function Gs(e){return e.trim().toLowerCase().split(/\s+/).filter(Boolean)}function zn(e,t){if(t.length===0)return!0;let n=e.toLowerCase();return t.every((i)=>n.includes(i))}function Vs(e,t){let n=Gs(t);if(n.length===0)return[];return e.filter((i)=>{let s=[i.groupLabel,i.pageTitle,i.rowTitle,i.rowDetail,...i.keywords??[]].join(" ");return zn(s,n)})}function Kn(e,t,n){let i=Gs(n);if(i.length===0)return e.map((a)=>({page:a,hits:[]}));let s=new Map(qn.map((a)=>[a.id,a.label])),r=[];for(let a of e){let c=t.filter((l)=>l.pageId===a.id).filter((l)=>zn([l.rowTitle,l.rowDetail,l.pageTitle,l.groupLabel,...l.keywords??[]].join(" "),i));if(zn([s.get(a.group)??"",a.title,a.subtitle,...a.keywords].join(" "),i)||c.length>0){let l=[];for(let h of c){if(!l.includes(h.rowTitle))l.push(h.rowTitle);if(l.length>=2)break}r.push({page:a,hits:l})}}return r}function Jn(e){return e.key?m(e.key,e.fallback,e.vars):e.fallback}function oa(e){let n=document.createElementNS("http://www.w3.org/2000/svg","svg");n.setAttribute("viewBox","0 0 24 24"),n.setAttribute("width","15"),n.setAttribute("height","15"),n.setAttribute("fill","none"),n.setAttribute("stroke","currentColor"),n.setAttribute("stroke-width","1.75"),n.setAttribute("stroke-linecap","square"),n.setAttribute("stroke-linejoin","miter"),n.setAttribute("aria-hidden","true");let i=(s,r)=>{let a=document.createElementNS("http://www.w3.org/2000/svg",s);for(let[o,c]of Object.entries(r))a.setAttribute(o,c);n.appendChild(a)};switch(e){case"sun":i("circle",{cx:"12",cy:"12",r:"4"}),i("path",{d:"M12 2v2m0 16v2M4.93 4.93l1.41 1.41m11.32 11.32 1.41 1.41M2 12h2m16 0h2M4.93 19.07l1.41-1.41m11.32-11.32 1.41-1.41"});break;case"cpu":i("rect",{x:"5",y:"5",width:"14",height:"14"}),i("rect",{x:"9",y:"9",width:"6",height:"6"}),i("path",{d:"M9 2v3m6-3v3M9 19v3m6-3v3M2 9h3m-3 6h3M19 9h3m-3 6h3"});break;case"link":i("path",{d:"M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"}),i("path",{d:"M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"});break;case"mic":i("rect",{x:"9",y:"2",width:"6",height:"12"}),i("path",{d:"M5 11a7 7 0 0 0 14 0M12 18v4M8 22h8"});break;case"globe":i("circle",{cx:"12",cy:"12",r:"10"}),i("path",{d:"M2 12h20M12 2a15.3 15.3 0 0 1 4 10 15.3 15.3 0 0 1-4 10 15.3 15.3 0 0 1-4-10 15.3 15.3 0 0 1 4-10z"});break}return n}function la(){let t=document.createElementNS("http://www.w3.org/2000/svg","svg");t.setAttribute("viewBox","0 0 24 24"),t.setAttribute("width","13"),t.setAttribute("height","13"),t.setAttribute("fill","none"),t.setAttribute("stroke","currentColor"),t.setAttribute("stroke-width","1.75"),t.setAttribute("aria-hidden","true");let n=document.createElementNS("http://www.w3.org/2000/svg","circle");n.setAttribute("cx","11"),n.setAttribute("cy","11"),n.setAttribute("r","7");let i=document.createElementNS("http://www.w3.org/2000/svg","path");return i.setAttribute("d","m20 20-3.5-3.5"),t.append(n,i),t}function pn(e,t){switch(e){case"general":return m("gpui.settings.group.general",t);case"ai":return m("gpui.settings.group.agents",t);case"connect":return m("native.pair.connect",t)}}function pt(e,t){switch(e){case"appearance":return m("settings.appearance",t);case"providers":return m("web.settings.providers",t);case"ring":return m("ring.ring",t);case"devices":return t;case"home":return m("home.machine",t)}}class Yn{backdrop;titleEl;badgeEl;closeBtn;navListEl;searchInput;searchClearBtn;paneEl;cb;openState=!1;activePage="appearance";forceProviders=!1;query="";searchBrowseAll=!1;devicesLoaded=!1;devicesLoading=!1;devicesRows=[];devicesError="";loadGen=0;ringLoaded=!1;ringLoading=!1;ringList={total:0,notes:[],busy:""};ringCountEl=null;ringErrorEl=null;ringRows=new Map;ringShownQuery="";ringError="";ringQuery="";ringDraft="";ringGen=0;ringBusy=new Set;ringPolls=0;ringTimers=[];constructor(e,t){this.cb=t,this.backdrop=document.createElement("div"),this.backdrop.className="bp-modal-backdrop bp-hidden",this.backdrop.setAttribute("data-testid","settings-modal");let n=document.createElement("div");n.className="bp-modal bp-settings-modal",n.setAttribute("role","dialog"),n.setAttribute("aria-modal","true"),n.setAttribute("aria-labelledby","bp-settings-title");let i=document.createElement("div");i.className="bp-modal-head";let s=document.createElement("div");s.className="bp-settings-head-title",this.titleEl=document.createElement("h2"),this.titleEl.id="bp-settings-title",this.titleEl.textContent=m("palette.settings","Settings"),this.badgeEl=document.createElement("span"),this.badgeEl.className="bp-settings-badge",this.badgeEl.textContent="Browser",s.append(this.titleEl,this.badgeEl),this.closeBtn=document.createElement("button"),this.closeBtn.type="button",this.closeBtn.className="icon",this.closeBtn.textContent="×",this.closeBtn.setAttribute("aria-label",m("common.close","Close")),this.closeBtn.addEventListener("click",()=>this.close()),i.append(s,this.closeBtn);let r=document.createElement("div");r.className="bp-settings-body";let a=document.createElement("aside");a.className="bp-settings-nav";let o=document.createElement("div");o.className="bp-settings-search";let c=document.createElement("span");c.className="bp-settings-search-icon",c.appendChild(la()),this.searchInput=document.createElement("input"),this.searchInput.type="text",this.searchInput.className="bp-settings-search-input",this.searchInput.placeholder="Search settings…",this.searchInput.setAttribute("aria-label","Search settings"),this.searchInput.setAttribute("data-testid","settings-search"),this.searchClearBtn=document.createElement("button"),this.searchClearBtn.type="button",this.searchClearBtn.className="bp-settings-search-clear bp-hidden",this.searchClearBtn.textContent="×",this.searchClearBtn.title="Clear search",this.searchClearBtn.setAttribute("aria-label","Clear search"),o.append(c,this.searchInput,this.searchClearBtn),this.navListEl=document.createElement("nav"),this.navListEl.className="bp-settings-nav-list",this.navListEl.setAttribute("aria-label","Settings sections"),a.append(o,this.navListEl),this.paneEl=document.createElement("div"),this.paneEl.className="bp-settings-pane",r.append(a,this.paneEl),n.append(i,r),this.backdrop.appendChild(n),this.backdrop.addEventListener("click",(p)=>{if(p.target===this.backdrop)this.close()}),this.searchInput.addEventListener("input",()=>{this.query=this.searchInput.value,this.searchBrowseAll=this.query.trim().length>0,this.syncSearchClear(),this.render()}),this.searchInput.addEventListener("keydown",(p)=>{if(p.key==="Enter"){let l=Kn(St,this.buildSearchItems(),this.query);if(l.length>0)p.preventDefault(),this.activePage=l[0].page.id,this.searchBrowseAll=!1,this.render()}else if(p.key==="Escape"&&this.query.trim().length>0)p.preventDefault(),p.stopPropagation(),this.clearSearch()}),this.searchClearBtn.addEventListener("click",()=>{this.clearSearch(),this.searchInput.focus()}),e.appendChild(this.backdrop)}isOpen(){return this.openState}handleEscape(){if(!this.openState)return;if(this.query.trim().length>0)this.clearSearch(),this.searchInput.focus();else this.close()}async open(e){if(this.openState=!0,e)this.activePage=e;if(this.backdrop.classList.remove("bp-hidden"),this.render(),this.loadDevices(),this.activePage==="ring")this.loadRing();window.setTimeout(()=>{if(this.openState)this.searchInput.focus()},0)}async openToAccounts(){this.forceProviders=!0,this.query="",this.searchInput.value="",this.searchBrowseAll=!1,this.syncSearchClear(),await this.open("providers")}close(){this.openState=!1,this.forceProviders=!1,this.query="",this.searchInput.value="",this.searchBrowseAll=!1,this.syncSearchClear(),this.backdrop.classList.add("bp-hidden");for(let e of this.ringTimers)window.clearTimeout(e);if(this.ringTimers=[],this.ringBusy.clear(),this.ringPolls=0,this.activePage==="ring")this.paneEl.replaceChildren()}refreshLocale(){if(this.titleEl.textContent=m("palette.settings","Settings"),this.closeBtn.setAttribute("aria-label",m("common.close","Close")),this.openState)this.render()}async refresh(){if(!this.openState)return;this.render(),await this.loadDevices()}clearSearch(){this.query="",this.searchInput.value="",this.searchBrowseAll=!1,this.syncSearchClear(),this.render()}syncSearchClear(){this.searchClearBtn.classList.toggle("bp-hidden",this.query.length===0)}async loadDevices(){let e=++this.loadGen;if(this.devicesLoading=!this.devicesLoaded,this.devicesLoading&&this.openState)this.renderPane();try{let t=await this.cb.onLoadDevices();if(e!==this.loadGen)return;this.devicesRows=t,this.devicesError="",this.devicesLoaded=!0}catch(t){if(e!==this.loadGen)return;let n=t instanceof Error&&t.message?t.message:"Not available from a browser";this.devicesError=`${n} — manage paired devices in Backplane › Settings › Devices on desktop or a paired phone.`,this.devicesRows=[],this.devicesLoaded=!0}finally{if(e===this.loadGen){if(this.devicesLoading=!1,this.openState)this.render()}}}async loadRing(){if(!this.cb.onRingList||!(this.cb.hasRing?.()??!1))return;let e=++this.ringGen;if(this.ringLoading=!this.ringLoaded,this.ringLoading)this.showRing();try{let t=await this.cb.onRingList(this.ringQuery);if(e!==this.ringGen)return;if(this.ringList=t,this.ringError="",!t.busy)this.ringBusy.clear();if(t.busy&&this.openState&&this.ringPolls<40)this.ringPolls++,this.ringLater(3000);else if(!t.busy)this.ringPolls=0}catch(t){if(e!==this.ringGen)return;this.ringError=t instanceof Error&&t.message?t.message:m("web.ring.error","Could not load recordings.")}finally{if(e===this.ringGen)this.ringLoaded=!0,this.ringLoading=!1,this.showRing()}}ringLater(e){let t=window.setTimeout(()=>{if(this.ringTimers=this.ringTimers.filter((n)=>n!==t),this.openState)this.loadRing()},e);this.ringTimers.push(t)}ringIsBusy(e){return this.ringBusy.has(e)||this.ringList.busy===e}showRing(){if(!this.openState||this.activePage!=="ring"||this.query.trim()&&this.searchBrowseAll)return;let e=this.ringList.notes.map((i)=>i.id),t=Array.from(this.ringRows.keys());if(!(this.ringCountEl?.isConnected===!0&&this.ringShownQuery===this.ringQuery&&e.length===t.length&&e.every((i,s)=>i===t[s]))){this.renderPane();return}if(this.ringCountEl)this.ringCountEl.textContent=this.ringCountLine();if(this.ringErrorEl)this.ringErrorEl.textContent=this.ringError,this.ringErrorEl.classList.toggle("bp-hidden",!this.ringError);for(let i of this.ringList.notes)this.fillRingNote(i)}ringCountLine(){return this.ringLoading?m("web.ring.loading","Loading recordings…"):Jn(js(this.ringList.total,this.ringList.notes.length,this.ringQuery))}fillRingNote(e){let t=this.ringRows.get(e.id);if(!t)return;let n=this.ringIsBusy(e.id);t.state.className="bp-status-pill "+(n?"accent":e.state==="sent"?"ok":e.state==="failed"?"bad":"warn"),t.state.textContent=Jn(Rs(e.state,n)),t.words.className="bp-ring-words"+(e.words?"":" bp-dim"),t.words.textContent=e.words||m("web.ring.no.words","(no words)"),t.meta.textContent=[Jn(Is(e)),e.unsure,e.error].filter(Boolean).join(" · ");for(let i of t.hear)i.disabled=n}async hearRing(e,t){if(!this.cb.onRingHear||this.ringIsBusy(e))return;this.ringBusy.add(e),this.ringError="",this.showRing();try{await this.cb.onRingHear(e,t),this.ringPolls=0,this.ringLater(1500)}catch(n){this.ringBusy.delete(e),this.ringError=n instanceof Error&&n.message?n.message:m("web.ring.error","Could not load recordings."),this.showRing()}}buildSearchItems(){let e=this.cb.onGetHome?.()??null,t=this.cb.onGetNoProvider?.()??null,n=pn("general","General"),i=pn("ai","Agents and tools"),s=pn("connect","Connect"),r=pt("appearance","Appearance"),a=pt("providers","AI providers"),o=pt("devices","Devices & browser"),c=pt("home","Home machine"),p=[{pageId:"appearance",pageTitle:r,groupLabel:n,rowTitle:m("settings.theme","Theme"),rowDetail:"Auto (follow hub), Dark, or Light in this browser.",keywords:["theme","dark","light","auto","appearance","colors"]},{pageId:"appearance",pageTitle:r,groupLabel:n,rowTitle:m("settings.lang","Language"),rowDetail:"Interface language for this browser.",keywords:["locale","english","espanol","japanese","language"]},{pageId:"providers",pageTitle:a,groupLabel:i,rowTitle:t?pe(t.head):"Provider connections",rowDetail:"Connect Claude, Codex, Antigravity, or other AI providers in Settings → Accounts.",keywords:["accounts","claude","codex","antigravity","grok","openai","signin"]},{pageId:"ring",pageTitle:pt("ring","Ring"),groupLabel:i,rowTitle:m("ring.recordings","Recordings"),rowDetail:"Read, search, play and hear again the voice notes from your Pebble ring.",keywords:["pebble","voice","note","recording","play","hear","transcribe"]},{pageId:"devices",pageTitle:o,groupLabel:s,rowTitle:"This browser",rowDetail:"Sign out and revoke this browser's session cookie.",keywords:["logout","sign out","session","cookie"]},{pageId:"devices",pageTitle:o,groupLabel:s,rowTitle:"Paired devices",rowDetail:this.devicesRows.map((l)=>`${l.title||l.head||""} ${l.detail||l.text||""}`).join(" ")||"Paired phones and browsers on this hub.",keywords:["phone","pair","revoke","browser"]},{pageId:"home",pageTitle:c,groupLabel:s,rowTitle:e?.name?`${e.name}`:c,rowDetail:"Which machine hosts your always-on hub and bots.",keywords:["boat","move","online","away","queued","machine"]}];for(let l of this.devicesRows){let h=l.title||l.head||"";if(h)p.push({pageId:"devices",pageTitle:o,groupLabel:s,rowTitle:h,rowDetail:l.detail||l.text||"",keywords:["paired","device"]})}return p}render(){this.renderNav(),this.renderPane()}renderNav(){let e=document.createDocumentFragment(),t=Kn(St,this.buildSearchItems(),this.query),n=this.cb.onGetNoProvider?.()??null,i=this.cb.onGetHome?.()??null;if(t.length===0){let r=document.createElement("div");r.className="bp-settings-nav-empty",r.setAttribute("data-testid","settings-nav-empty"),r.textContent="No matching settings",e.appendChild(r),this.navListEl.replaceChildren(e);return}let s="";for(let r of t){let a=r.page;if(a.group!==s){s=a.group;let d=qn.find((u)=>u.id===a.group);if(d){let u=document.createElement("div");u.className="bp-settings-group",u.textContent=pn(d.id,d.label),e.appendChild(u)}}let o=document.createElement("button");o.type="button";let c=!this.searchBrowseAll&&a.id===this.activePage;o.className="bp-settings-nav-item"+(c?" active":""),o.setAttribute("data-testid",`settings-nav-${a.id}`);let p=document.createElement("div");p.className="bp-settings-nav-row";let l=document.createElement("span");l.className="bp-settings-nav-icon",l.appendChild(oa(a.icon));let h=document.createElement("span");if(h.className="bp-settings-nav-label",h.textContent=pt(a.id,a.title),p.append(l,h),a.id==="providers"&&(n||this.forceProviders)){let d=document.createElement("span");d.className="bp-settings-nav-dot warn",d.title="Action needed",p.appendChild(d)}else if(a.id==="home"&&i){let d=document.createElement("span");d.className="bp-settings-nav-dot "+(i.moving?.state==="failed"?"bad":i.online?"ok":"warn"),p.appendChild(d)}if(o.appendChild(p),r.hits.length>0)for(let d of r.hits){let u=document.createElement("div");u.className="bp-settings-hit",u.textContent=d,o.appendChild(u)}o.addEventListener("click",()=>{if(this.activePage=a.id,this.searchBrowseAll=!1,this.render(),a.id==="ring")this.loadRing()}),e.appendChild(o)}this.navListEl.replaceChildren(e)}renderPane(){let e=document.createDocumentFragment(),t=this.query.trim();if(t&&this.searchBrowseAll){this.renderSearchResults(e,t),this.paneEl.replaceChildren(e);return}let n=St.find((a)=>a.id===this.activePage)??St[0],i=document.createElement("div");i.className="bp-settings-pane-head";let s=document.createElement("h3");s.textContent=pt(n.id,n.title);let r=document.createElement("div");switch(r.className="bp-settings-pane-sub",r.textContent=n.subtitle,i.append(s,r),e.appendChild(i),n.id){case"appearance":this.renderAppearancePage(e);break;case"providers":this.renderProvidersPage(e);break;case"ring":this.renderRingPage(e);break;case"devices":this.renderDevicesPage(e);break;case"home":this.renderHomePage(e);break}this.paneEl.replaceChildren(e)}renderSearchResults(e,t){let n=Vs(this.buildSearchItems(),t),i=document.createElement("div");i.className="bp-settings-pane-head";let s=document.createElement("h3");s.textContent="Search results";let r=document.createElement("div");if(r.className="bp-settings-pane-sub",r.textContent=n.length===0?`No settings match "${t}".`:`${n.length} matching ${n.length===1?"setting":"settings"} for "${t}"`,i.append(s,r),e.appendChild(i),n.length===0){let o=document.createElement("div");o.className="bp-settings-empty",o.textContent="Try searching for theme, language, providers, sign out, devices, or home.",e.appendChild(o);return}let a=Array.from(new Set(n.map((o)=>o.pageId)));for(let o of a){let c=St.find((u)=>u.id===o);if(!c)continue;let p=document.createElement("div");p.className="bp-settings-search-sec";let l=document.createElement("div");l.className="bp-settings-subhead",l.textContent=pt(c.id,c.title);let h=document.createElement("button");h.type="button",h.className="bp-settings-search-open",h.textContent="Open page ›",h.addEventListener("click",()=>{if(this.activePage=o,this.searchBrowseAll=!1,this.render(),o==="ring")this.loadRing()}),p.append(l,h),e.appendChild(p);let d=new Set(n.filter((u)=>u.pageId===o).map((u)=>u.rowTitle));if(o==="appearance")this.renderAppearancePage(e,d);else if(o==="providers")this.renderProvidersPage(e);else if(o==="ring"){let u=document.createElement("div");u.className="bp-settings-empty",u.textContent="Read, search, play and hear again the voice notes from your Pebble ring.",e.appendChild(u)}else if(o==="devices")this.renderDevicesPage(e,d);else if(o==="home")this.renderHomePage(e)}}renderAppearancePage(e,t){let n=this.cb.onGetThemePref?.()??"auto",i=this.cb.onGetHubTheme?.()??"dark",s=Gt(n,i),r=this.cb.onGetLocalePref?.()??"auto",a=m("settings.theme","Theme"),o=m("settings.lang","Language");if(!t||t.has(a)){let c=m("settings.theme.dark","Dark"),p=m("settings.theme.light","Light"),l=n==="auto"?`Following hub theme (${i==="light"?p:c}). Stored in this browser only.`:`Using ${s==="light"?p:c} in this browser. Select Auto to follow the hub.`;e.appendChild(this.makeSegmentedRow(a,l,[{value:"auto",label:"Auto"},{value:"dark",label:c},{value:"light",label:p}],n,"settings-theme",(h)=>{this.cb.onSetThemePref?.(h),this.render()}))}if(!t||t.has(o))e.appendChild(this.makeSegmentedRow(o,"Interface language for this browser. Automatic follows the hub or browser language.",[{value:"auto",label:m("settings.lang.auto","Automatic")},{value:"en",label:m("settings.lang.en","English")},{value:"es",label:m("settings.lang.es","Español")},{value:"ja",label:m("settings.lang.ja","日本語")}],r,"settings-locale",(c)=>{this.cb.onSetLocalePref?.(c),this.render()}))}makeSegmentedRow(e,t,n,i,s,r){let a=document.createElement("div");a.className="bp-settings-row";let o=document.createElement("div");o.className="bp-settings-row-info";let c=document.createElement("div");c.className="bp-settings-row-title",c.textContent=e;let p=document.createElement("div");p.className="bp-settings-row-detail",p.textContent=t,o.append(c,p);let l=document.createElement("div");l.className="bp-chip-group",l.setAttribute("role","group"),l.setAttribute("aria-label",e);for(let h of n){let d=document.createElement("button");d.type="button";let u=h.value===i;d.className="bp-chip"+(u?" active":""),d.textContent=h.label,d.setAttribute("aria-pressed",u?"true":"false"),d.setAttribute("data-testid",`${s}-${h.value}`),d.addEventListener("click",()=>r(h.value)),l.appendChild(d)}return a.append(o,l),a}renderProvidersPage(e){let t=this.cb.onGetNoProvider?.()??null,n=document.createElement("section");if(n.className="bp-settings-section",n.setAttribute("data-testid","settings-providers"),t||this.forceProviders){let i=document.createElement("div");i.className="bp-settings-notice warn";let s=document.createElement("div");s.className="bp-settings-row-info";let r=document.createElement("div");r.className="bp-settings-row-title",r.textContent=t?pe(t.head):m("provider.notice.head","No AI provider connected");let a=document.createElement("div");a.className="bp-settings-row-detail",a.textContent=m("web.settings.providers.browser","Connect a provider in the Backplane desktop or mobile app under Settings → Accounts."),s.append(r,a);let o=document.createElement("div");o.className="bp-set-btns";let c=document.createElement("a");c.className="bp-link-btn primary",c.href=t?.url||"backplane://settings/accounts",c.setAttribute("data-testid","settings-open-accounts"),c.textContent=t?pe(t.button):m("provider.notice.button","Open Settings → Accounts"),o.appendChild(c),i.append(s,o),n.appendChild(i)}else{let i=document.createElement("div");i.className="bp-settings-row";let s=document.createElement("div");s.className="bp-settings-row-info";let r=document.createElement("div");r.className="bp-settings-row-title-wrap";let a=document.createElement("span");a.className="bp-settings-row-title",a.textContent="Provider connections";let o=document.createElement("span");o.className="bp-status-pill ok",o.textContent=m("gpui.acct.connected","Connected"),r.append(a,o);let c=document.createElement("div");c.className="bp-settings-row-detail",c.textContent="Provider sign-ins, fallback order, API keys, and usage limits are managed in the Backplane desktop or mobile app.",s.append(r,c);let p=document.createElement("div");p.className="bp-set-btns";let l=document.createElement("a");l.className="bp-link-btn",l.href="backplane://settings/accounts",l.setAttribute("data-testid","settings-open-accounts"),l.textContent=m("provider.notice.button","Open Settings → Accounts"),p.appendChild(l),i.append(s,p),n.appendChild(i)}e.appendChild(n)}renderDevicesPage(e,t){let n=!t||t.has("This browser"),i=!t||t.has("Paired devices")||this.devicesRows.some((a)=>t.has(a.title||a.head||""));if(n){let a=document.createElement("div");a.className="bp-settings-subhead",a.textContent="This browser",e.appendChild(a);let o=document.createElement("div");o.className="bp-settings-row";let c=document.createElement("div");c.className="bp-settings-row-info";let p=document.createElement("div");p.className="bp-settings-row-title",p.textContent="Browser session";let l=document.createElement("div");l.className="bp-settings-row-detail",l.textContent="Sign out and revoke this browser's session cookie.",c.append(p,l);let h=document.createElement("button");h.type="button",h.className="primary stop",h.textContent=m("agy.signout","Sign out"),h.setAttribute("data-testid","logout-btn"),h.addEventListener("click",()=>{h.disabled=!0,this.cb.onLogout().catch(()=>{l.setAttribute("role","alert"),l.className="bp-settings-row-detail bp-bad",l.textContent=m("web.logout.failed","Could not confirm sign-out. Try again."),h.disabled=!1})}),o.append(c,h),e.appendChild(o)}if(!i)return;let s=document.createElement("div");if(s.className="bp-settings-subhead",s.textContent="Paired devices",e.appendChild(s),this.devicesLoading){let a=document.createElement("div");a.className="bp-settings-empty",a.textContent="Loading paired devices…",e.appendChild(a);return}if(this.devicesError){let a=document.createElement("div");a.className="bp-settings-notice bad";let o=document.createElement("div");o.className="bp-settings-row-detail",o.textContent=this.devicesError,a.appendChild(o),e.appendChild(a);return}let r=!t||t.has("Paired devices")?this.devicesRows:this.devicesRows.filter((a)=>t.has(a.title||a.head||""));if(r.length===0){let a=document.createElement("div");a.className="bp-settings-empty",a.textContent="No paired devices listed.",e.appendChild(a)}else for(let a of r){let o=document.createElement("div");o.className="bp-settings-row";let c=document.createElement("div");c.className="bp-settings-row-info";let p=document.createElement("div");p.className="bp-settings-row-title-wrap";let l=document.createElement("span");l.className="bp-settings-row-title",l.textContent=a.title||a.head||"",p.appendChild(l);let h=a.detail||a.text||"";if(h){let d=document.createElement("span"),u=h.toLowerCase();d.className="bp-status-pill "+(u.includes("this browser")?"accent":"neutral"),d.textContent=h,p.appendChild(d)}if(c.appendChild(p),o.appendChild(c),a.buttons?.length){let d=document.createElement("div");d.className="bp-set-btns";for(let u of a.buttons){let f=document.createElement("button");if(f.type="button",u.primary)f.className="primary";if(u.danger)f.className="primary stop";f.textContent=u.label||m("common.remove","Remove"),f.addEventListener("click",()=>{f.disabled=!0,this.cb.onDevicesAct(u.action,u.value).finally(()=>{this.refresh()})}),d.appendChild(f)}o.appendChild(d)}e.appendChild(o)}if(!t){let a=document.createElement("div");a.className="bp-settings-footnote",a.textContent="Pair new browsers or phones, configure Tailscale HTTPS forwarding, or revoke access in desktop or mobile Settings → Devices.",e.appendChild(a)}}renderRingPage(e){let t=document.createElement("section");if(t.className="bp-settings-section",t.setAttribute("data-testid","settings-ring"),!this.cb.onRingList||!(this.cb.hasRing?.()??!1)){let o=document.createElement("div");o.className="bp-settings-empty",o.textContent=m("web.ring.unavailable","This hub does not show ring notes to a browser yet. Update it, or open Settings › Ring in the desktop app."),t.appendChild(o),e.appendChild(t);return}let n=document.createElement("form");n.className="bp-ring-search";let i=document.createElement("input");i.type="search",i.className="bp-ring-search-input",i.placeholder=m("ring.search.what.you.said","Search what you said"),i.setAttribute("aria-label",m("ring.search.what.you.said","Search what you said")),i.setAttribute("data-testid","ring-search"),i.value=this.ringDraft,i.addEventListener("input",()=>{this.ringDraft=i.value});let s=document.createElement("button");if(s.type="submit",s.className="primary",s.textContent=m("common.search","Search"),n.append(i,s),this.ringQuery){let o=document.createElement("button");o.type="button",o.className="bp-btn-ghost",o.textContent=m("ring.show.all","Show all"),o.addEventListener("click",()=>{this.ringDraft="",this.ringQuery="",this.loadRing()}),n.appendChild(o)}n.addEventListener("submit",(o)=>{o.preventDefault(),this.ringQuery=this.ringDraft.trim(),this.loadRing()}),t.appendChild(n);let r=document.createElement("div");r.className="bp-settings-notice bad"+(this.ringError?"":" bp-hidden"),r.setAttribute("data-testid","ring-error"),r.textContent=this.ringError,t.appendChild(r),this.ringErrorEl=r;let a=document.createElement("div");a.className="bp-ring-count",a.setAttribute("data-testid","ring-count"),a.textContent=this.ringCountLine(),t.appendChild(a),this.ringCountEl=a,this.ringRows.clear(),this.ringShownQuery=this.ringQuery;for(let o of this.ringList.notes)t.appendChild(this.renderRingNote(o));e.appendChild(t)}renderRingNote(e){let t=document.createElement("div");t.className="bp-ring-note"+(e.state==="failed"?" bad":""),t.setAttribute("data-testid",`ring-note-${e.id}`);let n=document.createElement("div");n.className="bp-ring-note-head";let i=document.createElement("span");i.className="bp-settings-row-title";let s=e.said>0?new Date(e.said*1000).toLocaleString(Ai(),{dateStyle:"medium",timeStyle:"short"}):"";i.textContent=[s,e.gesture].filter(Boolean).join(" · ");let r=document.createElement("span");n.append(i,r);let a=document.createElement("div"),o=document.createElement("div");o.className="bp-settings-row-detail";let c=[],p=document.createElement("div");p.className="bp-ring-acts";let l=Bs(e.play);if(l){let h=document.createElement("audio");h.className="bp-ring-audio",h.controls=!0,h.preload="none",h.src=l,h.setAttribute("data-testid",`ring-audio-${e.id}`),p.appendChild(h);for(let[d,u]of[["local",m("ring.hear.again.local","Hear again (local)")],["openai",m("ring.hear.again.openai","Hear again (OpenAI)")]]){let f=document.createElement("button");f.type="button",f.className="bp-btn-ghost",f.textContent=u,f.setAttribute("data-testid",`ring-hear-${d}-${e.id}`),c.push(f),f.addEventListener("click",()=>{this.hearRing(e.id,d)}),p.appendChild(f)}}if(e.thread&&this.cb.onOpenThread){let h=document.createElement("button");h.type="button",h.className="bp-btn-ghost",h.textContent=m("ring.what.happened","What happened"),h.addEventListener("click",()=>{this.close(),this.cb.onOpenThread?.(e.thread)}),p.appendChild(h)}if(t.append(n,a,o),p.childElementCount>0)t.appendChild(p);return this.ringRows.set(e.id,{state:r,words:a,meta:o,hear:c}),this.fillRingNote(e),t}renderHomePage(e){let t=this.cb.onGetHome?.()??null,n=document.createElement("section");if(n.className="bp-settings-section",n.setAttribute("data-testid","settings-home"),!t){let d=document.createElement("div");d.className="bp-settings-empty",d.textContent="Single-hub mode — this hub is running locally without linked home machines.",n.appendChild(d),e.appendChild(n);return}let i=document.createElement("div");i.className="bp-settings-row";let s=document.createElement("div");s.className="bp-settings-row-info";let r=document.createElement("div");r.className="bp-settings-row-title-wrap";let a=document.createElement("span");a.className="bp-settings-row-title",a.textContent=t.name||(t.kind==="boat"?"Boat":"This machine"),r.appendChild(a);let o=document.createElement("span");o.className="bp-status-pill neutral",o.textContent=t.kind==="local"?"This machine":t.kind==="boat"?"Boat":"Linked machine",r.appendChild(o);let c=document.createElement("span"),p="Online",l="ok";if(t.moving?.state==="moving")p="Moving",l="accent";else if(t.moving?.state==="failed")p="Move failed",l="bad";else if(!t.online)p="Away",l="warn";c.className=`bp-status-pill ${l}`,c.textContent=p,r.appendChild(c);let h=document.createElement("div");if(h.className="bp-settings-row-detail",t.moving?.state==="moving")h.textContent=t.moving.step?m("home.moving.step","Moving home to {to}: {step}").replace("{to}",t.moving.to).replace("{step}",t.moving.step):m("home.moving","Moving home to {to}…").replace("{to}",t.moving.to);else if(t.moving?.state==="failed")h.textContent=t.moving.note?m("home.move.failed.note","Home move failed: {note}").replace("{note}",t.moving.note):m("home.move.failed","Home move failed");else if(!t.online)h.textContent=t.queuedCount>0?m("home.away.queued","Home ({name}) is away · {n} queued").replace("{name}",t.name||"home").replace("{n}",String(t.queuedCount)):m("home.away","Home ({name}) is away").replace("{name}",t.name||"home");else h.textContent="Your active home hub is online and serving threads and bots.";if(s.append(r,h),i.appendChild(s),t.canMoveHere&&this.cb.onMoveHomeHere){let d=document.createElement("button");d.type="button",d.className="primary",d.textContent=m("home.move.here","Make this machine the home"),d.setAttribute("data-testid","home-move-here-btn"),d.addEventListener("click",()=>{d.disabled=!0,this.cb.onMoveHomeHere?.().finally(()=>{this.refresh()})}),i.appendChild(d)}n.appendChild(i),e.appendChild(n)}}function Pe(e,t,n){let i=document.createElement(e);if(t)i.className=t;if(n)i.textContent=n;return i}function Vt(e,t,n=!1){let i=Pe("button",n?"primary":"bp-btn-ghost",e);return i.type="button",i.addEventListener("click",t),i}function Xn(e){return Pe("pre","bp-context-code",e)}function ca(e){return Pe("span",`bp-context-badge ${e==="Native"||e==="Enabled"?"active":e==="Untrusted"||e==="Invalid"?"warn":""}`,pe(e))}function hn(e,t){let n=Pe("div","bp-context-row");return n.append(Pe("strong",void 0,e),ca(t)),n}class Qn{fetchContext;dialog=Pe("dialog","bp-context");title=Pe("h2");cwd=Pe("div","bp-context-path");tabs=Pe("div","bp-context-tabs");body=Pe("div","bp-context-body");notice=Pe("p","bp-context-notice");current;thread="";requestId=0;tab=0;busy=!1;constructor(e,t){this.fetchContext=t;let n=Pe("div","bp-context-head"),i=Pe("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,Vt(m("common.refresh","Refresh"),()=>{this.load()}),Vt(m("common.close","Close"),()=>this.dialog.close())),this.dialog.append(n,this.tabs,this.notice,this.body),this.dialog.addEventListener("close",()=>{this.requestId++}),e.append(this.dialog)}open(e){if(this.thread=e,this.tab=0,this.current=void 0,this.busy=!1,this.title.textContent=m("thread.context.title","Context & Prompt"),this.cwd.textContent="",!this.dialog.open)this.dialog.showModal();this.render(),this.load()}async load(e){if(this.busy)return;let t=++this.requestId;this.busy=!0,this.notice.textContent=m("thread.context.reading","Reading thread context…"),this.render();try{let n=await this.fetchContext(this.thread,e);if(t!==this.requestId)return;this.current=n,this.cwd.textContent=n.cwd,this.notice.textContent=""}catch(n){if(t===this.requestId)this.notice.textContent=String(n)}finally{if(t===this.requestId)this.busy=!1,this.render()}}render(){let e=[m("thread.context.instructions","Instructions"),m("thread.context.system","System Prompt"),m("thread.context.skills","Skills"),m("thread.context.mcp","Project MCPs")];this.tabs.replaceChildren(...e.map((n,i)=>{let s=Vt(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(Pe("p","bp-dim",m("thread.context.none.instructions","No project instructions found.")));for(let t of e){let n=Pe("details","bp-context-card"),i=Pe("summary");if(i.append(hn(t.path,t.status),Pe("small","bp-dim",m("thread.context.size","{bytes} B · ≈{tokens} tokens",{bytes:t.bytes,tokens:t.estimated_tokens}))),n.append(i,Xn(t.preview)),t.note)n.append(Pe("small","bp-dim",t.note));this.body.append(n)}}prompt(e){let t=Pe("div","bp-context-row"),n=Vt(m("thread.context.copy","Copy prompt"),()=>{navigator.clipboard.writeText(e.prompt).then(()=>{this.notice.textContent=m("thread.context.copied","Prompt copied.")}).catch((i)=>{this.notice.textContent=String(i)})});t.append(Pe("p","bp-dim",m("thread.context.native.note","Backplane’s launch prompt. Native files are loaded by the provider.")),n),this.body.append(t);for(let[i,s]of[[m("thread.context.base","Backplane"),e.sections.base],[m("thread.context.injected.label","Injected project instructions"),e.sections.instructions],[m("thread.context.index","Available skills index"),e.sections.skills]])if(s)this.body.append(Pe("h3",void 0,i),Xn(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(Pe("h3",void 0,pe(t)));for(let i of n){let s=Pe("article","bp-context-card");s.append(hn(i.name,i.status),Pe("p",void 0,i.description),Pe("small","bp-context-path",[i.source,i.provider,i.model].filter(Boolean).join(" · ")),Pe("small","bp-context-path",i.path)),this.body.append(s)}}}mcps(e){if(!e.length)this.body.append(Pe("p","bp-dim",m("thread.context.none.mcp","No project MCP configurations found.")));for(let t of e){let n=Pe("article","bp-context-card");n.append(hn(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(hn(s.name,s.status),Xn(r)),s.cwd)n.append(Pe("small","bp-context-path",s.cwd))}if(t.error)n.append(Pe("p","bp-warn",t.error));let i=t.state==="Untrusted"?"trust":t.state==="Enabled"?"disable":t.state==="Disabled"?"enable":"";if(i){let s=i==="trust"?m("thread.context.trust","Trust and enable"):i==="disable"?m("thread.context.disable","Disable"):m("thread.context.enable","Enable"),r=Vt(s,()=>{this.load({action:i,path:t.path,sha256:t.sha256})},i==="trust");r.disabled=this.busy;let a=Pe("div","bp-context-actions");a.append(r),n.append(a)}this.body.append(n)}}}function da(e,t){if(e.settled)return!1;if(e.state==="done"||e.state==="stopped")return!1;if(!t)return!0;let n=e.working??0,i=Boolean(e.monitoring),s=Boolean(_n(e.need))||e.word==="needs";return(n>0||i)&&e.state!=="paused"||s}function pa(e){if(e.wake)return{icon:"◷",label:"Snoozed",tone:"dim"};let t=(e.label??"").trim(),n=(e.tone??"").trim();if(t){let s=t.toLowerCase();return{icon:s==="approve"||s==="sign in"?"!":s==="input"?"?":s==="failed"||s==="stopped"?"×":s==="working"||s==="running"?"▸":s==="waiting"?"◌":s==="done"?"✓":"•",label:t,tone:n==="bad"?s==="failed"||s==="stopped"?"bad-out":"bad":n==="run"?"run":n==="wait"?"wait":n==="ok"?"ok":"dim"}}let i=e.word||"";if(i==="needs"){if(e.want==="approval")return{icon:"!",label:"Approve",tone:"bad"};if(e.want==="sign-in")return{icon:"!",label:"Sign in",tone:"bad"};return{icon:"?",label:"Input",tone:"bad"}}if(i==="failed"||e.status==="failed"||e.state==="fail")return{icon:"×",label:"Failed",tone:"bad-out"};if(i==="cut"||i==="interrupted")return{icon:"×",label:"Stopped",tone:"bad-out"};if(i==="running"||e.status==="active"||e.status==="working"||e.state==="run")return{icon:"▸",label:"Working",tone:"run"};if(i==="monitoring"||i==="limit"||e.status==="waiting")return{icon:"◌",label:"Waiting",tone:"wait"};if(i==="done"||e.status==="finished")return{icon:"✓",label:"Done",tone:"ok"};return null}var Us="http://www.w3.org/2000/svg";function bt(e,t=14,n=""){let i=document.createElementNS(Us,"svg");if(i.setAttribute("viewBox","0 0 24 24"),i.setAttribute("width",String(t)),i.setAttribute("height",String(t)),i.setAttribute("fill","none"),i.setAttribute("stroke","currentColor"),i.setAttribute("stroke-width","1.75"),i.setAttribute("stroke-linecap","square"),i.setAttribute("stroke-linejoin","miter"),i.setAttribute("aria-hidden","true"),n)i.classList.add(...n.split(" "));for(let s of e){let r=document.createElementNS(Us,"path");r.setAttribute("d",s),i.appendChild(r)}return i}function Ws(){return bt(["M3 6h6l2 2h10v11H3z"],14,"bp-folder-icon")}function _s(e=14,t="bp-folder-icon bp-hw-icon"){return bt(["M3 3h18v18H3z","M9 3v6h6","M9 21v-6","M15 9a2 2 0 1 0 0-4 2 2 0 0 0 0 4z","M9 15a2 2 0 1 0 0-4 2 2 0 0 0 0 4z"],e,t)}function ha(e=13){return bt(["M6 6h12v12H6z","M9 2v4","M15 2v4","M9 18v4","M15 18v4","M2 9h4","M2 15h4","M18 9h4","M18 15h4"],e)}function ua(e=15){return bt(["M4 10V4l4 3h8l4-3v6l-2 9H6z","M9 13h1","M14 13h1","M11 16h2"],e,"bp-cat-glyph")}function ma(e=11){return bt(["M4 12l5 5 11-11"],e)}function ba(e=11){return bt(["M12 22a10 10 0 1 0 0-20 10 10 0 0 0 0 20z","M12 6v6l4 2"],e)}function ga(e=11){return bt(["M12 17v5","M8 4h8l-1 5 3 3v2H6v-2l3-3z"],e,"bp-pin-icon")}function zs(e){if(!e)return"";let t=e<10000000000?e*1000:e,n=Math.max(0,Math.floor((Date.now()-t)/1000));if(n<60)return"now";if(n<3600)return`${Math.floor(n/60)}m`;if(n<86400)return`${Math.floor(n/3600)}h`;return`${Math.floor(n/86400)}d`}function fa(e){let t=e.replace(/^@/,"").trim();if(!t)return"?";let n=t.split(/[\s_-]+/).filter(Boolean);if(n.length>=2)return(n[0][0]+n[1][0]).toUpperCase();return t.slice(0,2).toUpperCase()}function Zn(e){if(e==="wait"||e==="error")return"bp-mood-wait";if(e==="work"||e==="talk")return"bp-mood-work";return"bp-mood-idle"}function Qe(e){let t=e.lastIndexOf("|");return t>=0?e.slice(t+1):e}class ei{el;hostLabel;homeBanner;crewEl;filterInput;listEl;connEl;filterText="";allFilter="all";snoozeMenuRowId="";collapsedProjects=new Set;addShown=!1;sections=null;projects=[];selectedProjectId="";threads=[];bots=[];rooms=[];selectedThreadId="";cb;needErr=new Map;needBusy=new Set;constructor(e,t){this.el=e,this.cb=t;let n=document.createElement("div");n.className="bp-side-host";let i=document.createElement("div");i.className="bp-side-host-left",this.hostLabel=document.createElement("span"),this.hostLabel.textContent="This computer";let s=document.createElement("span");s.className="bp-dim",s.textContent="›",i.append(this.hostLabel,s);let r=document.createElement("button");r.type="button",r.className="icon bp-side-collapse",r.textContent="‹",r.title="Collapse sidebar",r.setAttribute("aria-label","Collapse sidebar"),r.setAttribute("data-testid","sidebar-collapse"),r.addEventListener("click",()=>this.cb.onCollapseSidebar?.()),n.append(i,r);let 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=m("sidebar.search.projects","Search projects, threads…");this.filterInput.placeholder=o,this.filterInput.setAttribute("aria-label",o),this.filterInput.setAttribute("data-testid","sidebar-filter"),this.filterInput.addEventListener("input",()=>{this.filterText=this.filterInput.value.trim().toLowerCase(),this.render()});let c=document.createElement("button");c.type="button",c.className="icon bp-side-add",c.textContent="+",c.title=m("thread.new","New thread"),c.setAttribute("aria-label",m("thread.new","New thread")),c.setAttribute("data-testid","sidebar-new-thread"),c.addEventListener("click",()=>{let 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.crewEl=document.createElement("div"),this.crewEl.className="bp-crew-band bp-hidden",this.crewEl.setAttribute("data-testid","sidebar-crew"),this.listEl=document.createElement("div"),this.listEl.className="bp-side-list",this.listEl.setAttribute("data-testid","sidebar-list");let p=document.createElement("div");p.className="bp-side-footer",this.connEl=document.createElement("span"),this.connEl.className="bp-conn-status",this.connEl.textContent="Connecting…",this.connEl.setAttribute("data-testid","conn-status"),p.appendChild(this.connEl),this.el.append(n,a,this.homeBanner,this.crewEl,this.listEl,p)}setHome(e){if(!e){this.homeBanner.classList.add("bp-hidden"),this.homeBanner.textContent="";return}let t="",n=!1;if(e.moving?.state==="moving")t=e.moving.step?m("home.moving.step","Moving home to {to}: {step}").replace("{to}",e.moving.to).replace("{step}",e.moving.step):m("home.moving","Moving home to {to}…").replace("{to}",e.moving.to);else if(e.moving?.state==="failed")t=e.moving.note?m("home.move.failed.note","Home move failed: {note}").replace("{note}",e.moving.note):m("home.move.failed","Home move failed"),n=!0;else if(!e.online){let i=e.name||"home",s="";if(e.awaySince&&e.awaySince>0){let r=new Date(e.awaySince);s=`${String(r.getHours()).padStart(2,"0")}:${String(r.getMinutes()).padStart(2,"0")}`}if(s&&e.queuedCount>0)t=m("home.away.since.queued","Home ({name}) is away since {time} · {n} queued").replace("{name}",i).replace("{time}",s).replace("{n}",String(e.queuedCount));else if(s)t=m("home.away.since","Home ({name}) is away since {time}").replace("{name}",i).replace("{time}",s);else if(e.queuedCount>0)t=m("home.away.queued","Home ({name}) is away · {n} queued").replace("{name}",i).replace("{n}",String(e.queuedCount));else t=m("home.away","Home ({name}) is away").replace("{name}",i)}if(!t)this.homeBanner.classList.add("bp-hidden"),this.homeBanner.textContent="";else this.homeBanner.textContent=t,this.homeBanner.className=n?"bp-side-home bp-bad":"bp-side-home bp-dim",this.homeBanner.classList.remove("bp-hidden")}setHostName(e){this.hostLabel.textContent=e||"This computer"}setConnStatus(e,t){this.connEl.textContent=e,this.connEl.className=`bp-conn-status ${t}`.trim()}setData(e,t,n,i){this.projects=e,this.threads=t,this.bots=n,this.rooms=i,this.render()}setSections(e,t,n){this.sections=e,this.bots=t,this.rooms=n,this.render()}setSelected(e){this.selectedThreadId=e,this.render()}setSelectedProject(e){if(this.selectedProjectId===e)return;this.selectedProjectId=e,this.render()}makeFoldChevron(e,t){let n=document.createElement("button");n.type="button",n.className="bp-proj-chev"+(e?" folded":""),n.textContent=e?"▸":"▾";let i=e?m("web.home.unfold","Show threads"):m("web.home.fold","Hide threads");return n.title=i,n.setAttribute("aria-label",i),n.setAttribute("aria-expanded",e?"false":"true"),n.setAttribute("data-testid",`project-fold-${t}`),n}focusFilter(){this.filterInput.focus()}firstProjectId(){if(this.sections){for(let e of this.sections)if(e.kind==="projects"&&e.rows.length>0){let t=e.rows[0];if(t.id&&!t.off)return t.id}}return this.projects[0]?.id??""}refreshLocale(){let e=m("sidebar.search.projects","Search projects, threads…");this.filterInput.placeholder=e,this.filterInput.setAttribute("aria-label",e),this.render()}renderCrewBand(e){let t=this.bots.find((c)=>c.uber),n=this.bots.filter((c)=>!c.uber&&(!e||c.name.toLowerCase().includes(e))),i=this.rooms.filter((c)=>!e||c.name.toLowerCase().includes(e)),s=Boolean(t&&(!e||t.name.toLowerCase().includes(e))),r=n.length>0||Boolean(this.cb.onNewBot)&&!e,a=i.length>0||Boolean(this.cb.onNewRoom)&&!e;if(!s&&!r&&!a){this.crewEl.classList.add("bp-hidden"),this.crewEl.replaceChildren();return}let o=document.createDocumentFragment();if(s&&t){let c=document.createElement("button");c.type="button",c.className="bp-crew-uber"+(t.thread===this.selectedThreadId?" active":""),c.setAttribute("data-testid",`crew-uber-${t.id}`);let p=document.createElement("span");if(p.className=`bp-crew-uber-avatar ${Zn(t.mood)}`,t.color)p.style.color=t.color;p.appendChild(ua(14));let l=document.createElement("span");l.className="bp-crew-uber-meta";let h=document.createElement("span");if(h.className="bp-crew-uber-name",h.textContent=t.name,l.appendChild(h),t.note){let d=document.createElement("span");d.className=`bp-crew-uber-note ${Zn(t.mood)}`,d.textContent=t.note,l.appendChild(d)}if(c.append(p,l),t.mood==="wait"||t.mood==="error"){let d=document.createElement("span");d.className="bp-status-pill bp-pill-bad",d.textContent="? Input",c.appendChild(d)}c.addEventListener("click",()=>this.cb.onSelectBot(t)),o.appendChild(c)}if(r){let c=document.createElement("div");c.className="bp-crew-bots",c.setAttribute("data-testid","crew-bots");let p=document.createElement("span");p.className="bp-crew-lbl",p.textContent=m("tour.title.bots","Bots").toUpperCase(),c.appendChild(p);let l=document.createElement("div");l.className="bp-crew-bot-tiles";for(let h of n){let d=document.createElement("button");if(d.type="button",d.className=`bp-crew-bot-tile ${Zn(h.mood)}`+(h.thread===this.selectedThreadId?" active":""),d.title=h.note?`@${h.name} — ${h.note}`:`@${h.name}`,d.setAttribute("aria-label",`@${h.name}`),d.setAttribute("data-testid",`crew-bot-${h.id}`),h.color)d.style.setProperty("--bot-c",h.color);let u=document.createElement("span");if(u.className="bp-crew-bot-init",u.textContent=fa(h.name),d.appendChild(u),h.mood==="wait"||h.mood==="error"){let f=document.createElement("span");f.className="bp-crew-bot-wait",d.appendChild(f)}d.addEventListener("click",()=>this.cb.onSelectBot(h)),l.appendChild(d)}if(this.cb.onNewBot&&!e){let h=document.createElement("button");h.type="button",h.className="bp-crew-bot-tile bp-crew-add",h.textContent="+",h.title=m("bots.new","New bot"),h.setAttribute("aria-label",m("bots.new","New bot")),h.setAttribute("data-testid","crew-new-bot"),h.addEventListener("click",()=>this.cb.onNewBot?.()),l.appendChild(h)}c.appendChild(l),o.appendChild(c)}if(a){let c=document.createElement("div");c.className="bp-crew-rooms",c.setAttribute("data-testid","crew-rooms");for(let p of i){let l=document.createElement("button");l.type="button",l.className="bp-crew-room-chip",l.setAttribute("data-testid",`crew-room-${p.id}`);let h=document.createElement("span");h.className="bp-dim",h.textContent="#";let d=document.createElement("span");if(d.textContent=p.name,l.append(h,d),p.members!==void 0&&p.members>0){let u=document.createElement("span");u.className="bp-crew-room-cnt",u.textContent=String(p.members),l.appendChild(u)}l.title=p.members?`#${p.name} (${p.members})`:`#${p.name}`,l.addEventListener("click",()=>this.cb.onSelectRoom?.(p)),c.appendChild(l)}if(this.cb.onNewRoom&&!e){let p=document.createElement("button");p.type="button",p.className="bp-crew-room-chip bp-crew-add",p.textContent="+",p.title=m("rooms.new","New room"),p.setAttribute("aria-label",m("rooms.new","New room")),p.setAttribute("data-testid","crew-new-room"),p.addEventListener("click",()=>this.cb.onNewRoom?.()),c.appendChild(p)}o.appendChild(c)}this.crewEl.classList.remove("bp-hidden"),this.crewEl.replaceChildren(o)}projectsHead(e){let t=document.createElement("div");if(t.className="bp-side-section-head",!this.cb.onAddProject||this.addShown)return t.textContent=e,t;this.addShown=!0,t.classList.add("bp-side-section-row");let n=document.createElement("span");n.textContent=e;let i=document.createElement("button");i.type="button",i.className="bp-side-sec-plus bp-side-sec-btn",i.textContent="+";let s=m("sidebar.add.project","Add project");return i.title=s,i.setAttribute("aria-label",s),i.setAttribute("data-testid","sidebar-add-project"),i.addEventListener("click",(r)=>{r.stopPropagation(),this.cb.onAddProject?.()}),t.append(n,i),t}renderStatusPill(e,t){let n=document.createElement("span");if(n.className=`bp-status-pill bp-pill-${e.tone}`,n.textContent=`${e.icon} ${e.label}`,t)n.title=t;return n}renderRowActions(e){if(e.off)return null;let t=Array.isArray(e.snooze)&&e.snooze.length>0&&Boolean(this.cb.onSnoozeRow),n=Boolean(e.wake)&&Boolean(this.cb.onSnoozeRow),i=e.kind==="swarm",s=Boolean(e.settle)&&(!i||Boolean(this.cb.onSettleSwarm));if(!t&&!n&&!s)return null;let r=document.createElement("span");if(r.className="bp-row-acts",n&&e.wake){let a=document.createElement("button");a.type="button",a.className="bp-row-act-btn bp-wake-btn",a.textContent=m("menu.wake","Wake"),a.title=m("menu.wake","Wake snoozed thread"),a.setAttribute("data-testid",`wake-row-${e.id}`),a.addEventListener("click",(o)=>{o.stopPropagation(),this.cb.onSnoozeRow?.(e.wake)}),r.appendChild(a)}if(t&&e.snooze){let a=document.createElement("button");a.type="button",a.className="bp-row-act-btn bp-snooze-btn",a.title=m("menu.snooze","Snooze thread"),a.setAttribute("aria-label",m("menu.snooze","Snooze thread")),a.setAttribute("data-testid",`snooze-row-${e.id}`),a.appendChild(ba(11)),a.addEventListener("click",(o)=>{o.stopPropagation(),this.snoozeMenuRowId=this.snoozeMenuRowId===e.id?"":e.id,this.render()}),r.appendChild(a)}if(s&&e.settle){let a=document.createElement("button");a.type="button",a.className="bp-row-act-btn bp-settle-btn",a.title=m("menu.settle","Settle"),a.setAttribute("aria-label",m("menu.settle","Settle")),a.setAttribute("data-testid",`settle-row-${e.id}`),a.appendChild(ma(11)),a.addEventListener("click",(o)=>{if(o.stopPropagation(),i)this.cb.onSettleSwarm?.(Qe(e.settle));else this.cb.onThreadAct(Qe(e.settle),"settle")}),r.appendChild(a)}return r}renderSectionThreadRow(e,t,n=!1){let i=document.createElement("div");i.className="bp-thread-row"+(n?" bp-inbox-row":"")+(!this.selectedProjectId&&(e.id===this.selectedThreadId||Qe(e.id)===this.selectedThreadId)?" active":"")+(e.off?" bp-dim":""),i.setAttribute("data-thread-id",e.id),i.setAttribute("data-testid",`thread-row-${e.id}`);let s=pa(e),r=this.renderRowActions(e);if(n){let l=document.createElement("div");l.className="bp-inbox-main";let h=document.createElement("div");h.className="bp-inbox-top";let d=document.createElement("div");if(d.className="bp-thread-title",d.textContent=e.title||"Untitled thread",h.appendChild(d),r)h.appendChild(r);let u=document.createElement("div");if(u.className="bp-inbox-meta",s)u.appendChild(this.renderStatusPill(s,e.say));if(e.project){let f=document.createElement("span");f.className="bp-inbox-proj",f.textContent=e.project,u.appendChild(f)}if(e.ago){let f=document.createElement("span");if(f.className="bp-thread-age",f.textContent=e.ago,e.pinned)f.title=m("tools.pinned","Pinned");u.appendChild(f)}l.append(h,u),i.appendChild(l)}else{if(t){let h=document.createElement("span");h.className="bp-tree-branch",h.setAttribute("aria-hidden","true"),i.appendChild(h)}if(s)i.appendChild(this.renderStatusPill(s,e.say));let l=document.createElement("div");if(l.className="bp-thread-title",l.textContent=e.title||"Untitled thread",i.appendChild(l),r)i.appendChild(r);if(e.ago){let h=document.createElement("span");if(h.className="bp-thread-age",h.textContent=e.ago,e.pinned)h.title=m("tools.pinned","Pinned");i.appendChild(h)}}let a=e.nav||e.id;if(!e.off&&a&&!a.startsWith("@room:"))i.addEventListener("click",()=>this.cb.onSelectThread(Qe(a)));let o=this.snoozeMenuRowId===e.id&&Array.isArray(e.snooze)&&e.snooze.length>0,c=e.kind==="swarm"?_n(e.need):null;if(!c&&!o)return i;let p=document.createElement("div");if(p.className="bp-need-wrap",p.appendChild(i),o&&e.snooze){let l=document.createElement("div");l.className="bp-snooze-bar"+(t?" nested":""),l.setAttribute("data-testid",`snooze-bar-${e.id}`);let h=document.createElement("span");h.className="bp-dim",h.textContent="Snooze:",l.appendChild(h);for(let d of e.snooze){let u=document.createElement("button");u.type="button",u.className="bp-snooze-opt",u.textContent=d.label,u.addEventListener("click",(f)=>{f.stopPropagation(),this.snoozeMenuRowId="",this.cb.onSnoozeRow?.(d.value),this.render()}),l.appendChild(u)}p.appendChild(l)}if(c){let l=document.createElement("div");l.className="bp-need"+(t?" nested":"")+(e.off?" bp-dim":""),l.setAttribute("data-testid",`need-${e.id}`);let h=document.createElement("span");h.className="bp-need-line",h.textContent=c.line,h.title=c.line,l.appendChild(h);for(let u of c.actions){if(!dn(u,Boolean(this.cb.hasRoomView)))continue;let f=document.createElement("button");f.type="button",f.className="bp-need-btn",f.textContent=u.label,f.setAttribute("data-testid",`need-${u.act}-${e.id}`),f.disabled=Boolean(e.off)||this.needBusy.has(e.id)||!this.cb.onNeedAct,f.addEventListener("click",(b)=>{b.stopPropagation();let v=this.cb.onNeedAct;if(!v)return;this.needErr.delete(e.id),this.needBusy.add(e.id),this.render(),v(u).catch((y)=>{this.needErr.set(e.id,y instanceof Error?y.message:String(y))}).finally(()=>{this.needBusy.delete(e.id),this.render()})}),l.appendChild(f)}p.appendChild(l);let d=this.needErr.get(e.id);if(d){let u=document.createElement("div");u.className="bp-need-err"+(t?" nested":""),u.textContent=d,p.appendChild(u)}}return p}renderHubSections(e,t){let n=this.sections??[],i=new Set;for(let a of n)if(a.kind==="threads")for(let o of a.rows)i.add(o.id),i.add(Qe(o.id));else if(a.kind==="projects")for(let o of a.rows)for(let c of o.threads??[])i.add(c.id),i.add(Qe(c.id));let s=this.selectedThreadId?this.threads.find((a)=>a.id===this.selectedThreadId)??null:null,r=!1;for(let a of n)if(a.kind==="projects"&&(a.rows.length>0||(a.count??0)>0))r=!0;for(let a of n){if(a.kind==="bub")continue;if(a.kind==="threads"){let o=Boolean(a.fold&&a.toggle),c=a.rows.filter((l)=>{if(!t)return!0;return`${l.title} ${l.project??""}`.toLowerCase().includes(t)});if(!o&&c.length===0)continue;if(o&&t&&c.length===0)continue;if(o&&!t&&(a.count??c.length)===0)continue;let p=document.createElement("section");if(p.className=`bp-side-section bp-side-inbox bp-sec-${a.id}`,p.setAttribute("data-section-id",a.id),o){let l=document.createElement("button");l.type="button",l.className="bp-side-section-head bp-side-section-toggle";let h=t?c.length:a.count??c.length,d=a.open||Boolean(t)?"▾":"▸";if(l.textContent=`${d} ${a.title.toUpperCase()} (${h})`,a.hint)l.title=a.hint;l.setAttribute("data-testid",`section-toggle-${a.id}`),l.addEventListener("click",()=>{if(a.toggle)this.cb.onToggleSection?.(a.toggle)}),p.appendChild(l)}else{let l=document.createElement("div");l.className="bp-side-section-head"+(a.id==="needs"?" bp-head-needs":a.id==="running"?" bp-head-running":""),l.textContent=`${a.title.toUpperCase()} ${c.length}`,p.appendChild(l)}if(!o||Boolean(a.open)||Boolean(t))for(let l of c)p.appendChild(this.renderSectionThreadRow(l,!1,!0));e.appendChild(p);continue}if(a.kind==="projects"){let o=a.rows,c=o.filter((d)=>{if(!t)return!0;if((d.title||d.id).toLowerCase().includes(t))return!0;if((d.threads??[]).some((u)=>u.title.toLowerCase().includes(t)))return!0;if((d.swarms??[]).some((u)=>u.title.toLowerCase().includes(t)))return!0;return!1}),p=Boolean(a.fold&&a.toggle);if(t&&c.length===0)continue;if(!p&&a.id!=="active"&&c.length===0)continue;let l=document.createElement("section");if(l.className=`bp-side-section bp-sec-${a.id}`,l.setAttribute("data-section-id",a.id),p){let d=document.createElement("button");d.type="button",d.className="bp-side-section-head bp-side-section-toggle";let u=t?c.length:a.count??c.length,f=a.open||Boolean(t)?"▾":"▸";if(d.textContent=`${f} ${a.title.toUpperCase()} (${u})`,a.hint)d.title=a.hint;d.setAttribute("data-testid",`section-toggle-${a.id}`),d.addEventListener("click",()=>{if(a.toggle)this.cb.onToggleSection?.(a.toggle)}),l.appendChild(d)}else l.appendChild(this.projectsHead(a.title.toUpperCase()));if(!p||Boolean(a.open)||Boolean(t)){if(a.id==="all"&&!t){let d=o.some((f)=>f.hasBoard||f.hasSchematic),u=o.some((f)=>!f.hasBoard&&!f.hasSchematic);if(d&&u){let f=document.createElement("div");f.className="bp-proj-filter",f.setAttribute("data-testid","all-projects-filter");let b=[{id:"all",label:"All"},{id:"hw",label:"Boards"},{id:"sw",label:"Code"}];for(let v of b){let y=document.createElement("button");y.type="button",y.className="bp-proj-filter-btn"+(this.allFilter===v.id?" active":""),y.textContent=v.label,y.addEventListener("click",()=>{this.allFilter=v.id,this.render()}),f.appendChild(y)}if(l.appendChild(f),this.allFilter==="hw")c=c.filter((v)=>v.hasBoard||v.hasSchematic);else if(this.allFilter==="sw")c=c.filter((v)=>!v.hasBoard&&!v.hasSchematic)}}if(a.id==="active"&&!r&&!t){let d=document.createElement("div");d.className="bp-side-empty",d.textContent="No projects yet.",l.appendChild(d)}for(let d of c){let u=document.createElement("div");if(u.className="bp-proj-group"+(d.off||a.id==="quiet"?" bp-dim":""),u.setAttribute("data-project-id",d.id),d.nav||d.key)u.setAttribute("data-project-key",d.nav||d.key||"");let f=document.createElement("div");f.className="bp-proj-head";let b=document.createElement("button");b.type="button",b.className="bp-proj-toggle";let y=Boolean(d.hasBoard||d.hasSchematic)?_s(14):Ws();if(d.css)y.style.color=d.css;let w=document.createElement("span");w.className="bp-proj-name",w.textContent=d.title||d.id,b.append(y,w);let C=d.fold==="project-fold"&&Boolean(d.nav),L=()=>{if(C)this.cb.onToggleProjectFold?.(d.nav)};if(!d.off&&this.cb.canOpenProject?.())b.title=m("web.home.open","Open project home");if(b.setAttribute("data-testid",`project-open-${d.id}`),this.selectedProjectId&&Qe(d.id)===this.selectedProjectId)f.classList.add("active");b.addEventListener("click",()=>{if(d.off||!this.cb.onOpenProject?.(d.id))L()});let N=this.makeFoldChevron(Boolean(d.folded),d.id);if(C)N.addEventListener("click",(x)=>{x.stopPropagation(),L()});else N.disabled=!0;f.appendChild(N);let A=document.createElement("div");if(A.className="bp-proj-meta",(d.needsCount??0)>0){let x=document.createElement("span");x.className="bp-proj-badge-need",x.textContent=String(d.needsCount),x.title=`${d.needsCount} needing you`,A.appendChild(x)}if((d.running??0)>0){let x=document.createElement("span");x.className="bp-proj-badge-run",x.textContent=String(d.running),x.title=`${d.running} running`,A.appendChild(x)}if(d.pinned&&a.id!=="pinned")A.appendChild(ga(11));let B=document.createElement("div");if(B.className="bp-proj-acts",!d.off&&this.cb.onQuickOpenViewer){if(d.hasBoard){let x=document.createElement("button");x.type="button",x.className="bp-proj-quick",x.title=m("viewer.board","Open Board"),x.setAttribute("aria-label",`Open Board (${d.title})`),x.setAttribute("data-testid",`quick-board-${d.id}`),x.appendChild(_s(13,"")),x.addEventListener("click",(Y)=>{Y.stopPropagation(),this.cb.onQuickOpenViewer?.(Qe(d.id),"board")}),B.appendChild(x)}if(d.hasSchematic){let x=document.createElement("button");x.type="button",x.className="bp-proj-quick",x.title=m("viewer.schematic","Open Schematic"),x.setAttribute("aria-label",`Open Schematic (${d.title})`),x.setAttribute("data-testid",`quick-sch-${d.id}`),x.appendChild(ha(13)),x.addEventListener("click",(Y)=>{Y.stopPropagation(),this.cb.onQuickOpenViewer?.(Qe(d.id),"schematic")}),B.appendChild(x)}}let M=document.createElement("button");if(M.type="button",M.className="icon bp-proj-add",M.title=m("thread.new","New thread"),M.textContent="+",M.setAttribute("data-testid",`new-thread-${d.id}`),d.off)M.disabled=!0;M.addEventListener("click",(x)=>{x.stopPropagation(),this.cb.onNewThread(Qe(d.id))}),B.appendChild(M),f.append(b,A,B),u.appendChild(f);let j=Boolean(t)&&(d.title||d.id).toLowerCase().includes(t),O=Boolean(d.folded&&!t);for(let x of d.swarms??[]){if(!da(x,O))continue;if(t&&!j&&!x.title.toLowerCase().includes(t))continue;u.appendChild(this.renderSectionThreadRow(x,!0))}if(!O){for(let x of d.threads??[]){if(t&&!j&&!x.title.toLowerCase().includes(t))continue;u.appendChild(this.renderSectionThreadRow(x,!0))}if(s&&s.project===Qe(d.id)&&!i.has(s.id)&&(!t||j||s.title.toLowerCase().includes(t)))u.appendChild(this.renderSectionThreadRow({id:s.id,title:s.title,status:s.status,state:s.state,ago:zs(s.updatedAt),pinned:s.pinned,nav:s.id},!0))}l.appendChild(u)}}e.appendChild(l)}}}render(){this.addShown=!1;let e=this.filterText;this.renderCrewBand(e);let t=document.createDocumentFragment();if(this.sections!==null)this.renderHubSections(t,e);else{let n=new Map;for(let i of this.threads){if(i.archived||i.swarm)continue;if(e){if(!`${i.title} ${i.preview??""}`.toLowerCase().includes(e))continue}let s=n.get(i.project)??[];s.push(i),n.set(i.project,s)}if(t.appendChild(this.projectsHead("RECENT")),this.projects.length===0&&this.threads.length===0){let i=document.createElement("div");i.className="bp-side-empty",i.textContent="No projects yet.",t.appendChild(i)}for(let i of this.projects){let s=n.get(i.id)??[];if(e&&s.length===0&&!i.title.toLowerCase().includes(e))continue;let r=document.createElement("section");r.className="bp-proj-group",r.setAttribute("data-project-id",i.id);let a=document.createElement("div");a.className="bp-proj-head";let o=document.createElement("button");o.type="button",o.className="bp-proj-toggle";let c=this.collapsedProjects.has(i.id)&&!e,p=Ws();if(i.css)p.style.color=i.css;let l=document.createElement("span");l.className="bp-proj-name",l.textContent=i.title||i.id,o.append(p,l);let h=()=>{if(this.collapsedProjects.has(i.id))this.collapsedProjects.delete(i.id);else this.collapsedProjects.add(i.id);this.render()};if(this.cb.canOpenProject?.())o.title=m("web.home.open","Open project home");if(o.setAttribute("data-testid",`project-open-${i.id}`),this.selectedProjectId&&i.id===this.selectedProjectId)a.classList.add("active");o.addEventListener("click",()=>{if(!this.cb.onOpenProject?.(i.id))h()});let d=this.makeFoldChevron(c,i.id);d.addEventListener("click",(f)=>{f.stopPropagation(),h()}),a.appendChild(d);let u=document.createElement("button");if(u.type="button",u.className="icon bp-proj-add",u.title=m("thread.new","New thread"),u.textContent="+",u.setAttribute("data-testid",`new-thread-${i.id}`),u.addEventListener("click",(f)=>{f.stopPropagation(),this.cb.onNewThread(i.id)}),a.append(o,u),r.appendChild(a),!c)for(let f of s)r.appendChild(this.renderSectionThreadRow({id:f.id,title:f.title,status:f.status,state:f.state,ago:zs(f.updatedAt),pinned:f.pinned,nav:f.id},!0));t.appendChild(r)}}this.listEl.replaceChildren(t)}}function va(e){try{return new URL(e,window.location.origin).searchParams.get("s")||""}catch{return""}}function Ut(e){if(!e)return;for(let t of e.getTracks())try{t.stop()}catch{}}function ya(e,t){if(t===16000){let r=new Int16Array(e.length);for(let a=0;a0?c/p:0));s[r]=l<0?l*32768:l*32767}return s}class ti{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){Ut(n);return}if(this.stream=n,await this.stopDrain,t!==this.sessionGen||this.cb.getThreadId()!==e){if(Ut(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(Ut(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?va(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(Ut(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=ya(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;Ut(this.stream),this.stream=null}}var qs=[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],Ks=[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],Js=[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],Ys=[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],wa=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];function Wt(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 Ea=(()=>{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),Wt(e,288)})(),ka=(()=>{let e=new Uint8Array(32);return e.fill(5),Wt(e,32)})();class ni{win=new Uint8Array(32768);winPos=0;feed(e,t=16777216){let n=0,i=0,s=0,r=(h)=>{while(s=e.length)throw Error("truncated deflate frame");i|=e[n++]<>>=h,s-=h,d},a=(h)=>{let d=0,u=0,f=0;for(let b=1;b<=h.maxBits;b++){d|=r(1);let v=h.counts[b];if(d-v{let d=c+h;if(d>t)throw Error("inflated frame exceeds limit");if(d<=o.length)return;let u=o.length;while(u{p(1),o[c++]=h,this.win[this.winPos]=h,this.winPos=this.winPos+1&32767};while(n0){if(n>=e.length&&s<3)break;let h=r(1),d=r(2);if(d===0){if(i=0,s=0,n+4>e.length)throw Error("truncated stored block");let u=e[n]|e[n+1]<<8,f=e[n+2]|e[n+3]<<8;if(n+=4,(u^65535)!==f)throw Error("invalid stored block length");if(n+u>e.length)throw Error("truncated stored payload");p(u);for(let b=0;b=e.length)break}else if(d===1||d===2){let u=Ea,f=ka;if(d===2){let b=r(5)+257,v=r(5)+1,y=r(4)+4,w=new Uint8Array(19);for(let B=0;BL)throw Error("code length overflow");for(let O=0;OL)throw Error("code length overflow");A+=M}else if(B===18){let M=r(7)+11;if(A+M>L)throw Error("code length overflow");A+=M}else throw Error("invalid code length symbol")}u=Wt(N,b),f=Wt(N.subarray(b),v)}while(!0){let b=a(u);if(b<256)l(b);else if(b===256)break;else{let v=b-257;if(v>=qs.length)throw Error("invalid length symbol");let y=qs[v]+(Ks[v]?r(Ks[v]):0),w=a(f);if(w>=Js.length)throw Error("invalid distance symbol");let C=Js[w]+(Ys[w]?r(Ys[w]):0);p(y);let L=this.winPos-C&32767;for(let N=0;N{this.stateListeners.delete(e)}}onFrame(e){return this.frameListeners.add(e),()=>{this.frameListeners.delete(e)}}onBinary(e){return this.binaryListeners.add(e),()=>{this.binaryListeners.delete(e)}}rpc(e,t={},n=20000){return new Promise((i,s)=>{if(!this.ws||this.ws.readyState!==WebSocket.OPEN){s(Error("Not connected to hub"));return}let r=this.nextId++,a=window.setTimeout(()=>{this.pending.delete(r),s(Error(`RPC timeout: ${e}`))},n);this.pending.set(r,{resolve:i,reject:s,timer:a}),this.ws.send(JSON.stringify({id:r,m:e,p:t}))})}setState(e){this.state=e;for(let t of this.stateListeners)t(e,this.hello)}rejectAllPending(e){for(let[,t]of this.pending)window.clearTimeout(t.timer),t.reject(Error(e));this.pending.clear()}openSocket(){if(this.closed)return;this.inflater=null;let t=`${window.location.protocol==="https:"?"wss:":"ws:"}//${window.location.host}/ws?data=1&enc=json&z=deflate`,n=new WebSocket(t);n.binaryType="arraybuffer",this.ws=n;let i=(s)=>{let r;try{r=JSON.parse(s)}catch{return}if(r.t==="hub.restarting")this.restarting={reason:String(r.reason??""),build:String(r.build??""),text:String(r.text??""),at:Date.now()};if(r.t==="hello")this.restarting=null,this.hello=r,this.features=new Set(this.hello.features??[]),this.inflater=this.hello.z==="deflate"?new ni: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",p=typeof r.errorCode==="string"?r.errorCode:void 0,l=typeof r.machine==="string"?r.machine:void 0,h=typeof r.thread==="string"?r.thread:void 0;a.reject(new _t(c,{code:p,machine:l,thread:h}))}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 Ca=new TextDecoder;function Xs(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 Qs(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,p=i(o&31);if(p===null)return null;switch(c){case 0:return p;case 1:return-1-p;case 2:{if(t+p>e.length)return null;let l=e.subarray(t,t+p);return t+=p,l}case 3:{if(t+p>e.length)return null;let l=Ca.decode(e.subarray(t,t+p));return t+=p,l}case 4:{if(p>e.length)return null;let l=Array(p);for(let h=0;h=this.b.length)return this.ok=!1,0;let n=this.b[this.i++],i=7*t;if(i>=28&&(n&240)!==0)return this.ok=!1,0;if(e=(e|(n&127)<>>0,n<128)return e}return this.ok=!1,0}nextI32(){let e=this.nextU32();return e>>>1^-(e&1)}}function er(e){let t=0xcbf29ce484222325n,n=0x100000001b3n,i=0xffffffffffffffffn;for(let s=0;stypeof e[b]==="number"?e[b]:v,n=t("l",0),i=t("c",0),s=t("a",255)/255,r=t("m",1),a=t("w",0),o=a/2,c=r===0&&a!==0,p=e.d instanceof Uint8Array?e.d:new Uint8Array(0),l=new Zs(p),h=[],d=[],u=0,f=0;while(l.more()){let b=l.nextU32(),v=h.length,y=1/0,w=1/0,C=-1/0,L=-1/0;if(r===2)u=u+l.nextI32()|0,f=f+l.nextI32()|0,h.push(u,f),y=C=u,w=L=f;else{let A=Math.min(l.nextU32(),1048576);for(let B=0;BC)C=u;if(fL)L=f}}let N=(h.length-v)/2;if(N>0){let A=r===2||N===1?2:r===0?0:1,B=r===0?0:o;d.push({info:b,x0:y-B,y0:w-B,x1:C+B,y1:L+B,at:v,n:N,kind:A})}}return{layer:n,color:i,alpha:s,mode:r,r:o,own:c,pts:new Float32Array(h),pieces:d}}function tr(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 p=n.keys().next().value;if(p!==void 0)n.delete(p);else break}}}}return{key:typeof e.key==="string"?e.key:"",fam:typeof e.fam==="string"?e.fam:"",base:typeof e.base==="string"?e.base:"",box:i(e.box),edge:i(e.edge),thick:typeof e.thick==="number"?e.thick:1600,note:typeof e.note==="string"?e.note:"",warn:typeof e.warn==="number"?e.warn!==0:!1,chunks:r}}function nr(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,p=(e-o)/r,l=(t-c)/a;if(p<0||p>1||l<0||l>1)return null;return{x:Math.max(0,Math.min(1000,Math.round(p*1000))),y:Math.max(0,Math.min(1000,Math.round(l*1000)))}}var ir=[["Enter","Enter"],["Tab","Tab"],["Bksp","Backspace"],["Esc","Escape"],["↑","ArrowUp"],["↓","ArrowDown"],["←","ArrowLeft"],["→","ArrowRight"]];function sr(e){let t=e.trim();if(!t)return"";if(/^[a-zA-Z][a-zA-Z0-9+.-]*:/.test(t))return t;return`https://${t}`}class si{tail=Promise.resolve();enqueue(e){let t=this.tail.then(e,e);return this.tail=t.catch(()=>{}),t}}function rr(e,t,n){let i=!0,s=!1,r=!1,a="",o=!1,c=!1,p=-1,l=null,h=new si,d=document.createElement("div");d.className="bp-pane bp-browser-pane",d.setAttribute("data-testid","pane-browser");let u=document.createElement("div");u.className="bp-pane-bar bp-browser-nav";function f(Q,ge,k){let P=document.createElement("button");if(P.type="button",P.className="bp-v-btn",P.textContent=Q,P.setAttribute("data-testid",ge),k)P.title=k;return P}let b=f("←","browser-back","Back"),v=f("→","browser-forward","Forward"),y=f("↻","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=f("Go","browser-go","Navigate");L.type="submit",w.append(C,L);let N=f("Take over","browser-takeover");N.classList.add("is-primary"),u.append(b,v,y,w,N);let A=document.createElement("div");A.className="bp-browser-drive-bar",A.hidden=!0;let B=document.createElement("div");B.className="bp-browser-keys-row";let M=document.createElement("input");M.type="text",M.className="bp-browser-input",M.placeholder="Type text or press Enter/Tab/Arrows…",M.autocomplete="off",M.spellcheck=!1,M.setAttribute("data-testid","browser-keys");let j=f("Send","browser-type-send");B.append(M,j);let O=document.createElement("div");O.className="bp-browser-quick-keys";for(let[Q,ge]of ir){let k=f(Q,`browser-key-${ge}`);k.addEventListener("click",()=>ee("press",{key:ge})),O.append(k)}A.append(B,O);let x=document.createElement("div");x.className="bp-browser-err",x.setAttribute("data-testid","browser-error"),x.hidden=!0;let Y=document.createElement("div");Y.className="bp-browser-stage",Y.setAttribute("data-testid","browser-stage");let se=document.createElement("img");se.className="bp-browser-img",se.alt="Hub browser screen",se.draggable=!1,se.hidden=!0,se.setAttribute("data-testid","browser-frame");let ne=document.createElement("div");ne.className="bp-pane-empty",ne.setAttribute("data-testid","browser-empty"),ne.textContent="Loading browser screen…",Y.append(se,ne);let he=document.createElement("div");he.className="bp-browser-hint",he.textContent="You have the page: click to tap, scroll to wheel, type in the key box. Hand it back when done.",he.hidden=!0,d.append(u,A,x,Y,he),e.replaceChildren(d);function Se(Q){x.textContent=Q,x.hidden=!Q}function ke(){A.hidden=!s,he.hidden=!s,N.textContent=s?"Hand back":"Take over",N.setAttribute("data-testid",s?"browser-handback":"browser-takeover"),N.classList.toggle("is-on",s),se.classList.toggle("is-driving",s)}function ee(Q,ge={},k){h.enqueue(async()=>{if(!i)return;Se("");try{if(await t.hub.rpc("browser",{thread:n,op:Q,...ge}),!i)return;k?.(),ue()}catch(P){if(!i)return;Se(P instanceof Error?P.message:String(P))}})}function re(Q){ee("toolbar",{command:Q},()=>{s=!0,ke()})}b.addEventListener("click",()=>re("back")),v.addEventListener("click",()=>re("forward")),y.addEventListener("click",()=>re("reload")),w.addEventListener("submit",(Q)=>{Q.preventDefault();let ge=sr(C.value);if(!ge)return;if(C.value=ge,!s)ee("takeover",{},()=>{s=!0,ke()});ee("navigate",{url:ge},()=>{s=!0,ke()})}),N.addEventListener("click",()=>{if(s)ee("handback",{},()=>{s=!1,ke()});else ee("takeover",{},()=>{s=!0,ke(),M.focus()})});function R(){let Q=M.value;if(!Q)return;M.value="",ee("type",{text:Q})}j.addEventListener("click",R),M.addEventListener("keydown",(Q)=>{if(!s)return;if(Q.key==="Enter"){if(Q.preventDefault(),M.value)R();ee("press",{key:"Enter"});return}if(Q.key==="Tab"||Q.key==="Escape"||Q.key==="ArrowUp"||Q.key==="ArrowDown"||Q.key==="ArrowLeft"||Q.key==="ArrowRight"||Q.key==="Backspace"&&M.value==="")Q.preventDefault(),ee("press",{key:Q.key})}),se.addEventListener("click",(Q)=>{if(!s||!r)return;let ge=se.getBoundingClientRect(),k=nr(Q.clientX,Q.clientY,{left:ge.left,top:ge.top,width:ge.width,height:ge.height,naturalWidth:se.naturalWidth,naturalHeight:se.naturalHeight});if(!k)return;ee("click",k)}),se.addEventListener("wheel",(Q)=>{if(!s||!r)return;Q.preventDefault();let ge=Math.round(Q.deltaX),k=Math.round(Q.deltaY);if(ge===0&&k===0)return;ee("scroll",{dx:ge,dy:k})},{passive:!1});async function ue(){if(!i)return;if(o){c=!0;return}o=!0;try{do{c=!1,l=new AbortController;let Q=await fetch(`/bots/${encodeURIComponent(n)}/screen.jpg`,{credentials:"same-origin",cache:"no-store",signal:l.signal});if(!i)return;if(Q.ok){let ge=await Q.blob();if(!i)return;let k=URL.createObjectURL(ge),P=a;if(a=k,se.src=k,se.hidden=!1,ne.hidden=!0,r=!0,P)URL.revokeObjectURL(P)}else if(!r)se.hidden=!0,ne.hidden=!1,ne.textContent="No browser page yet. An agent opens one when it needs the web."}while(i&&c)}catch{if(!i)return;if(!r)se.hidden=!0,ne.hidden=!1,ne.textContent="No browser page yet. An agent opens one when it needs the web."}finally{l=null,o=!1}}let le=t.hub.onFrame((Q)=>{if(!i)return;if(Q.t==="shot"&&Q.bot===n){if(typeof Q.n==="number"){if(Q.n===p)return;p=Q.n}ue()}});return ue(),{destroy(){if(i=!1,le(),l?.abort(),a)URL.revokeObjectURL(a),a=""}}}function U(e,t,n){let i=document.createElement(e);if(t)i.className=t;if(n!==void 0)i.textContent=n;return i}function un(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 or(e){let t=e.lastIndexOf(".");return t>=0?e.slice(t+1).toLowerCase():""}function Pa(e){return["png","jpg","jpeg","gif","webp","svg","bmp","ico"].includes(e)}function ar(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 Sa(e){let t=or(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 lr(e,t,n,i){let s=!0,r="",a="",o=U("div","bp-pane bp-files-pane");o.setAttribute("data-testid","pane-files");let c=U("div","bp-pane-bar"),p=U("div","bp-files-crumbs"),l=U("button","bp-v-btn","Refresh");l.type="button",l.addEventListener("click",()=>void v(r)),c.append(p,l);let h=U("div","bp-files-split"),d=U("div","bp-files-list");d.setAttribute("data-testid","files-list");let u=U("div","bp-files-preview");u.setAttribute("data-testid","files-preview"),u.append(U("div","bp-pane-empty","Select a file to preview")),h.append(d,u),o.append(c,h),e.replaceChildren(o);function f(){p.replaceChildren();let y=U("button","bp-crumb-btn","project");if(y.type="button",y.addEventListener("click",()=>void v("")),p.append(y),!r)return;let w=r.split("/").filter(Boolean),C="";for(let L of w){C=C?`${C}/${L}`:L;let N=C;p.append(U("span","bp-vh-sep","/"));let A=U("button","bp-crumb-btn",L);A.type="button",A.addEventListener("click",()=>void v(N)),p.append(A)}}async function b(y,w,C){a=y,u.replaceChildren();let L=U("div","bp-files-prev-head");L.append(U("span","bp-files-prev-name",y));let N=U("div","bp-files-prev-acts"),A=Sa(w);if(A){let O=U("button","bp-v-btn is-primary",`Open in ${A}`);O.type="button",O.setAttribute("data-testid","files-open-viewer"),O.addEventListener("click",()=>i(A,y)),N.append(O)}let B=`/files/get?thread=${encodeURIComponent(n)}&path=${encodeURIComponent(y)}`,M=U("a","bp-v-btn","Download");M.href=B,M.download=w,N.append(M),L.append(N),u.append(L);let j=or(w);if(Pa(j)){let O=U("div","bp-files-img-wrap"),x=document.createElement("img");x.className="bp-files-img",x.alt=w,x.src=B,O.append(x),u.append(O);return}if(C>524288&&!ar(j)){u.append(U("div","bp-pane-empty",`Binary file (${un(C)}). Use Download to save.`));return}if(ar(j)||C<=65536){let O=U("div","bp-pane-empty","Loading…");u.append(O);try{let x=await fetch(B,{credentials:"same-origin"});if(!s||a!==y)return;if(!x.ok){O.textContent=`Could not load file (${x.status})`;return}if((x.headers.get("content-type")||"").startsWith("image/")){O.remove();let le=document.createElement("img");le.className="bp-files-img",le.alt=w,le.src=B,u.append(le);return}let se=262144,ne=[],he=0,Se=!1;if(x.body){let le=x.body.getReader();try{while(!0){let{done:Q,value:ge}=await le.read();if(Q||!ge)break;if(he+ge.byteLength>se){let k=se-he;if(k>0)ne.push(ge.subarray(0,k)),he+=k;Se=!0,await le.cancel();break}ne.push(ge),he+=ge.byteLength}}finally{le.releaseLock()}}if(!s||a!==y)return;let ke=new Uint8Array(he),ee=0;for(let le of ne)ke.set(le,ee),ee+=le.byteLength;let re=!1;for(let le=0;leL.dir===N.dir?L.name.localeCompare(N.name):L.dir?-1:1),d.replaceChildren(),y){let L=U("button","bp-file-row is-dir");L.type="button",L.append(U("span","bp-file-icon","↰"),U("span","bp-file-name",".."));let N=y.includes("/")?y.slice(0,y.lastIndexOf("/")):"";L.addEventListener("click",()=>void v(N)),d.append(L)}if(C.length===0){d.append(U("div","bp-pane-empty","Empty folder"));return}for(let L of C){let N=y?`${y}/${L.name}`:L.name,A=U("button","bp-file-row"+(L.dir?" is-dir":"")+(N===a?" is-sel":""));A.type="button",A.setAttribute("data-testid",`file-row-${L.name}`),A.append(U("span","bp-file-icon",L.dir?"▸":"·"),U("span","bp-file-name",L.name),U("span","bp-file-size",L.dir?"":un(L.size))),A.addEventListener("click",()=>{if(L.dir)v(N);else d.querySelectorAll(".bp-file-row.is-sel").forEach((B)=>B.classList.remove("is-sel")),A.classList.add("is-sel"),b(N,L.name,L.size)}),d.append(A)}}catch(w){if(!s)return;d.replaceChildren(U("div","bp-pane-empty",w instanceof Error?w.message:String(w)))}}return v(""),{destroy(){s=!1}}}function cr(e,t,n){let i=!0,s=U("div","bp-pane bp-diff-pane");s.setAttribute("data-testid","pane-diff");let r=U("div","bp-pane-bar"),a=U("span","bp-diff-summary","Loading diff…"),o=U("button","bp-v-btn","Refresh");o.type="button",o.addEventListener("click",()=>void p()),r.append(a,o);let c=U("div","bp-diff-body");c.setAttribute("data-testid","diff-body"),s.append(r,c),e.replaceChildren(s);async function p(){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(U("div","bp-pane-empty","This project is not a git repository."));return}let h=typeof l?.diff==="string"?l.diff:"";if(!h.trim()){a.textContent="Clean working tree",c.append(U("div","bp-pane-empty","No uncommitted changes."));return}let d=h.split(` +`),u=0,f=0,b=0,v=document.createDocumentFragment(),y=U("div","bp-diff-file");for(let w of d){if(w.startsWith("diff --git ")){if(y.childNodes.length>0)v.append(y);y=U("div","bp-diff-file"),u++;let C=w.match(/ b\/(.+)$/);y.append(U("div","bp-diff-file-head",C?C[1]:w));continue}if(w.startsWith("index ")||w.startsWith("--- ")||w.startsWith("+++ "))y.append(U("div","bp-diff-line is-meta",w));else if(w.startsWith("@@"))y.append(U("div","bp-diff-line is-hunk",w));else if(w.startsWith("+"))f++,y.append(U("div","bp-diff-line is-add",w));else if(w.startsWith("-"))b++,y.append(U("div","bp-diff-line is-del",w));else y.append(U("div","bp-diff-line",w))}if(y.childNodes.length>0)v.append(y);a.textContent=`${u||1} file${u===1?"":"s"} · +${f} -${b}`,c.append(v)}catch(l){if(!i)return;a.textContent="Diff unavailable",c.append(U("div","bp-pane-empty",l instanceof Error?l.message:String(l)))}}return p(),{destroy(){i=!1}}}function La(e,t){let n=t.rel||"",i=t.manifest||{},s=(p)=>`/files/get?thread=${encodeURIComponent(e)}&path=${encodeURIComponent(`${n}/${p}`)}`,r=(p)=>typeof p==="string"&&p!==""&&!p.startsWith("/")&&!p.split(/[\\/]/).includes(".."),a=(Array.isArray(i.drawings)?i.drawings:[]).filter((p)=>r(p?.file)),o=new Set(a.map((p)=>p.file)),c=a.map((p)=>({title:p.title||p.kind||p.file,file:p.file,url:s(p.file),drawing:!0}));for(let p of Array.isArray(i.files)?i.files:[])if(r(p)&&!o.has(p))c.push({title:p,file:p,url:s(p),drawing:!1});return c}function dr(e,t,n){let i=!0,s="checks",r=U("div","bp-pane bp-review-pane");r.setAttribute("data-testid","pane-review");let a=U("div","bp-pane-bar"),o=U("div","bp-review-tabs"),c=U("button","bp-v-btn is-on","Checks"),p=U("button","bp-v-btn","BOM"),l=U("button","bp-v-btn","Comments"),h=U("button","bp-v-btn","Release");h.setAttribute("data-testid","review-tab-release"),c.type=p.type=l.type=h.type="button",o.append(c,p,l,h);let d=U("button","bp-v-btn","Refresh");d.type="button",d.addEventListener("click",()=>void y()),a.append(o,d);let u=U("div","bp-review-body");u.setAttribute("data-testid","review-body"),r.append(a,u),e.replaceChildren(r);function f(w){s=w,c.classList.toggle("is-on",s==="checks"),p.classList.toggle("is-on",s==="bom"),l.classList.toggle("is-on",s==="comments"),h.classList.toggle("is-on",s==="release"),y()}c.addEventListener("click",()=>f("checks")),p.addEventListener("click",()=>f("bom")),l.addEventListener("click",()=>f("comments")),h.addEventListener("click",()=>f("release"));function b(w){let C=U("div","bp-review-md bp-review-release");C.setAttribute("data-testid","review-release");let L=w.manifest||{};C.append(U("h2","bp-review-h",w.tag||"Release")),C.append(U("p","bp-review-p",[L.commit?`Commit ${L.commit.slice(0,12)}`:"",L.date||""].filter(Boolean).join(" · ")));let N=La(n,w),A=(M,j)=>{if(j.length===0)return;C.append(U("h3","bp-review-h",M));let O=U("table","bp-review-table");for(let x of j){let Y=document.createElement("tr"),se=U("td",void 0,x.title);se.title=x.file;let ne=document.createElement("td"),he=U("a","bp-v-btn","Download");he.href=x.url,he.download=x.file.split("/").pop()||x.file,ne.append(he),Y.append(se,ne),O.append(Y)}C.append(O)};A("Drawings",N.filter((M)=>M.drawing));let B=Array.isArray(L.openFabNotes)?L.openFabNotes:[];if(B.length>0)C.append(U("div","bp-review-gate",`Open fabrication notes, not in the board (agree them with the fabricator): ${B.join(", ")}.`));if(A("Files",N.filter((M)=>!M.drawing)),w.rel){let M=U("a","bp-v-btn","Download all (.zip)");M.href=`/files/zip?thread=${encodeURIComponent(n)}&path=${encodeURIComponent(w.rel)}`,C.append(M)}return C}function v(w){let C=U("div","bp-review-md"),L=w.split(` +`),N=0;while(N{j.preventDefault();let O=B.value.trim();if(!O)return;M.disabled=!0,t.hub.rpc("review.comment",{thread:n,text:O}).then(()=>{B.value="",M.disabled=!1,y()},()=>{M.disabled=!1})}),u.append(A),N.length===0){u.append(U("div","bp-pane-empty","No review comments yet."));return}for(let j of N){let O=U("div","bp-review-comment"+(j.resolved?" is-resolved":"")),x=[j.by||"review",j.file,j.layer,j.item].filter(Boolean).join(" · ");O.append(U("div","bp-review-comment-meta",x),U("div","bp-review-comment-text",j.text)),u.append(O)}return}let w=await t.hub.rpc("review.page",{thread:n,page:s});if(!i)return;let C=w?.report||{};if(u.replaceChildren(),C.line||C.gate){let L=U("div","bp-review-gate",[C.gate,C.line].filter(Boolean).join(" · "));u.append(L)}if(C.err)u.append(U("div","bp-review-err",C.err));if(Array.isArray(C.tasks)&&C.tasks.length>0){let L=U("div","bp-review-tasks");C.tasks.forEach((N,A)=>{let B=U("label","bp-review-task"),M=document.createElement("input");M.type="checkbox",M.checked=!!(N.done??N.checked);let j=typeof N.index==="number"?N.index:A;M.addEventListener("change",()=>{t.hub.rpc("review.tick",{thread:n,index:j}).then(()=>void y(),()=>{})}),B.append(M,U("span",void 0,N.text||N.label||`Item ${A+1}`)),L.append(B)}),u.append(L)}if(s==="release"&&C.release&&C.release.manifest)u.append(b(C.release));else if(C.md&&C.md.trim())u.append(v(C.md));else if(!C.err&&(!C.tasks||C.tasks.length===0))u.append(U("div","bp-pane-empty",s==="release"?"No release yet. A release tags this design and makes its fabrication outputs and drawings in .backplane/releases.":`No ${s==="bom"?"BOM":"design checks"} report available.`))}catch(w){if(!i)return;u.replaceChildren(U("div","bp-pane-empty",w instanceof Error?w.message:String(w)))}}return y(),{destroy(){i=!1}}}function pr(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 ri{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),p=Math.max(o.height,200);this.cx=(t+i)*0.5,this.cy=(n+s)*0.5,this.scale=Math.min(c/r,p/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,p=n*0.5,l=this.scale,h=this.cx,d=this.cy,u=h-c/l,f=h+c/l,b=d-p/l,v=d+p/l,{off:y,dim:w,lift:C}=this.masks,L=[],N=[];for(let B=0;B>>M&1)===1)continue;if(M===C)N.push(B);else L.push(B)}let A=L.concat(N);a.lineCap="round",a.lineJoin="round";for(let B=0;B>>j.layer&1)===1,x=j.alpha*(O?0.25:1);if(x<=0.01)continue;this.drawChunk(a,j,x,u,b,f,v,h,d,l,c,p)}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 B=this.lightTheme?"rgba(27,29,33,0.77)":"rgba(217,221,228,0.77)";for(let M=0;Mr||v.y1a)continue;if(v.n<3)continue;let y=(d[v.at]-o)*p+l,w=(d[v.at+1]-c)*p+h;e.moveTo(y,w);for(let C=1;C0)e.fill()}else if(t.mode===2){let f=Math.max(0.75,t.r*p);e.fillStyle=u,e.beginPath();let b=0;for(let v=0;vr||y.y1a)continue;let w=(d[y.at]-o)*p+l,C=(d[y.at+1]-c)*p+h;e.moveTo(w+f,C),e.arc(w,C,f,0,Math.PI*2),b++}if(b>0)e.fill()}else{e.strokeStyle=u,e.lineWidth=Math.max(1,t.r*2*p),e.beginPath();let f=0;for(let b=0;br||v.y1a)continue;let y=(d[v.at]-o)*p+l,w=(d[v.at+1]-c)*p+h;if(v.n===1)e.moveTo(y,w),e.lineTo(y+0.01,w);else{e.moveTo(y,w);for(let C=1;C0)e.stroke()}}drawLitPieces(e,t,n,i,s,r,a,o,c,p,l,h,d){let u=t.pts,f=pr(t.color,t.alpha);for(let b=0;ba||v.y1o)continue;let y=(u[v.at]-c)*l+h,w=(u[v.at+1]-p)*l+d;if(v.kind===2){let C=Math.max(1.5,t.r*l);e.fillStyle=f,e.beginPath(),e.arc(y,w,C,0,Math.PI*2),e.fill(),e.strokeStyle=i,e.lineWidth=1.5,e.stroke()}else if(v.kind===0&&v.n>=3){e.fillStyle=f,e.beginPath(),e.moveTo(y,w);for(let C=1;C=0;l--){let h=n.chunks[l];if(h.layer<32&&(p>>>h.layer&1)===1)continue;for(let d=0;du.x1+a||ru.y1+a)continue;let f=(u.x1-u.x0+1)*(u.y1-u.y0+1);if(f{if(this.canvas.setPointerCapture(e.pointerId),this.pointers.set(e.pointerId,{x:e.clientX,y:e.clientY}),this.pointers.size===1)this.dragStart={x:e.clientX,y:e.clientY,cx:this.cx,cy:this.cy,moved:!1},this.pinchStart=null;else if(this.pointers.size===2){let[t,n]=Array.from(this.pointers.values());this.pinchStart={dist:Math.hypot(n.x-t.x,n.y-t.y)||1,midX:(t.x+n.x)*0.5,midY:(t.y+n.y)*0.5,scale:this.scale,cx:this.cx,cy:this.cy},this.dragStart=null}};onPointerMove=(e)=>{if(!this.pointers.has(e.pointerId))return;if(this.pointers.set(e.pointerId,{x:e.clientX,y:e.clientY}),this.pointers.size===2&&this.pinchStart){let[t,n]=Array.from(this.pointers.values()),i=Math.hypot(n.x-t.x,n.y-t.y)||1,s=(t.x+n.x)*0.5,r=(t.y+n.y)*0.5,a=i/this.pinchStart.dist,o=Math.max(0.0000001,Math.min(2,this.pinchStart.scale*a)),c=this.canvas.getBoundingClientRect(),p=this.pinchStart.midX-c.left-c.width*0.5,l=this.pinchStart.midY-c.top-c.height*0.5,h=s-c.left-c.width*0.5,d=r-c.top-c.height*0.5;this.scale=o,this.cx=this.pinchStart.cx+p/this.pinchStart.scale-h/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 hr=[{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 ur(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 ai(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 oi{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 Aa=`#version 300 es precision highp float; out vec2 vUv; void main() { @@ -19,7 +20,7 @@ void main() { vUv = vec2(x * 0.5 + 0.5, 1.0 - (y * 0.5 + 0.5)); gl_Position = vec4(x, y, 0.0, 1.0); } -`,ta=`#version 300 es +`,Na=`#version 300 es precision highp float; in vec2 vUv; uniform vec3 uBgTop; @@ -36,7 +37,7 @@ void main() { vec3 lin = mix(uBgTop, uBgBot, clamp(vUv.y, 0.0, 1.0)); outColor = vec4(linearToSrgb(clamp(lin, 0.0, 1.0)), 1.0); } -`,na=`#version 300 es +`,Ma=`#version 300 es precision highp float; layout(location = 0) in vec3 aPos; layout(location = 1) in vec3 aNrm; @@ -54,7 +55,7 @@ void main() { vCol = aCol; gl_Position = uMvp * vec4(aPos, 1.0); } -`,ia=`#version 300 es +`,Ta=`#version 300 es precision highp float; in vec3 vPos; in vec3 vNrm; @@ -150,8 +151,8 @@ void main() { rgb = rgb / (vec3(1.0) + max(rgb - vec3(0.8), vec3(0.0)) * 0.28); outColor = vec4(linearToSrgb(clamp(rgb, 0.0, 1.0)), alpha * uFade); } -`;function Ke(e){let t=e/255;return t<=0.04045?t/12.92:Math.pow((t+0.055)/1.055,2.4)}var sa=[Ke(77),Ke(83),Ke(94)],ra=[Ke(53),Ke(58),Ke(67)],aa=[Ke(245),Ke(246),Ke(248)],oa=[Ke(225),Ke(228),Ke(233)];function Vs(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 Us(e,t,n){let i=Vs(e,e.VERTEX_SHADER,t),s=Vs(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 la(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 ca(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 Ws(e){let t=Math.hypot(e[0],e[1],e[2])||1;return[e[0]/t,e[1]/t,e[2]/t]}function _s(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 Jn{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=Us(n,ea,ta),this.bgVao=n.createVertexArray(),this.uBgTop=n.getUniformLocation(this.bgProg,"uBgTop"),this.uBgBot=n.getUniformLocation(this.bgProg,"uBgBot"),this.prog=Us(n,na,ia),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=Ls(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,p=r>0?new Float32Array(r*12):null,l=a>0?new Float32Array(a*9):null,u=a>0?new Float32Array(a*9):null,d=a>0?new Float32Array(a*12):null,m=0,f=0;for(let y=0;y>>24&255,A=1-C/255,S=(w>>>16&255)/255,T=(w>>>8&255)/255,I=(w&255)/255,P=y*9;if(C===0&&o&&c&&p){let j=m*9;for(let L=0;L<9;L++)o[j+L]=e[P+L],c[j+L]=t[P+L];let G=m*12;for(let L=0;L<3;L++)p[G+L*4]=S,p[G+L*4+1]=T,p[G+L*4+2]=I,p[G+L*4+3]=1;m++}else if(l&&u&&d){let j=f*9;for(let L=0;L<9;L++)l[j+L]=e[P+L],u[j+L]=t[P+L];let G=f*12;for(let L=0;L<3;L++)d[G+L*4]=S,d[G+L*4+1]=T,d[G+L*4+2]=I,d[G+L*4+3]=A;f++}}let b=o&&c&&p?this.createSubBatch(o,c,p,r*3):null,g=l&&u&&d?this.createSubBatch(l,u,d,a*3):null;if(!b&&!g)return null;return{opaque:b,translucent:g,fadeStartMs:i}}deleteSubBatch(e){let t=this.gl;if(!t||!e)return;t.deleteVertexArray(e.vao),t.deleteBuffer(e.posBuf),t.deleteBuffer(e.nrmBuf),t.deleteBuffer(e.colBuf)}deleteBatch(e){if(!e)return;this.deleteSubBatch(e.opaque),this.deleteSubBatch(e.translucent)}clearParts(){for(let e of this.partBatches)this.deleteBatch(e);this.partBatches=[]}fit(){this.setView("fit")}setView(e){let t=35*Math.PI/180;this.dist=this.radius/Math.sin(t*0.5)*1.15,this.target=[this.center[0],this.center[1],this.center[2]];let{yaw:n,pitch:i}=Os(e);this.yaw=n,this.pitch=i,this.scheduleDraw()}snapPng(){return this.draw(performance.now()),new Promise((e)=>{this.canvas.toBlob((t)=>e(t),"image/png")})}scheduleDraw(){if(this.dirty)return;this.dirty=!0,this.rafId=requestAnimationFrame((e)=>{if(this.dirty=!1,this.rafId=0,this.draw(e))this.scheduleDraw()})}drawSubBatch(e){if(!e||!this.gl)return;this.gl.bindVertexArray(e.vao),this.gl.drawArrays(this.gl.TRIANGLES,0,e.vertCount)}draw(e){let t=this.gl;if(!t||!this.prog)return!1;let n=this.canvas.getBoundingClientRect(),i=Math.max(1,Math.round(n.width)),s=Math.max(1,Math.round(n.height)),r=Math.min(window.devicePixelRatio||1,2),a=Math.round(i*r),o=Math.round(s*r);if(this.canvas.width!==a||this.canvas.height!==o)this.canvas.width=a,this.canvas.height=o;if(t.viewport(0,0,a,o),!this.boardBatch&&this.partBatches.length===0)return!1;if(t.depthMask(!0),t.clear(t.DEPTH_BUFFER_BIT),this.bgProg&&this.bgVao){t.disable(t.DEPTH_TEST),t.disable(t.BLEND),t.depthMask(!1),t.useProgram(this.bgProg);let j=this.lightTheme?aa:sa,G=this.lightTheme?oa:ra;t.uniform3f(this.uBgTop,j[0],j[1],j[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),p=Math.sin(this.pitch),l=Math.cos(this.yaw),u=Math.sin(this.yaw),d=[this.target[0]+this.dist*c*u,this.target[1]-this.dist*c*l,this.target[2]+this.dist*p],m=Ws([this.target[0]-d[0],this.target[1]-d[1],this.target[2]-d[2]]),f=Math.abs(m[2])>0.99?[0,1,0]:[0,0,1],b=Ws(_s(m,f)),g=_s(b,m),y=new Float32Array([b[0],g[0],-m[0],0,b[1],g[1],-m[1],0,b[2],g[2],-m[2],0,-Kn(b,d),-Kn(g,d),Kn(m,d),1]),w=Math.max(0.05,this.dist*0.01),C=Math.max(this.dist*10,this.radius*20),A=ca(35*Math.PI/180,a/o,w,C),S=la(A,y);t.useProgram(this.prog),t.uniformMatrix4fv(this.uMvp,!1,S),t.uniform3f(this.uEye,d[0],d[1],d[2]),t.uniform3f(this.uRight,b[0],b[1],b[2]),t.uniform3f(this.uUp,g[0],g[1],g[2]),t.uniform3f(this.uFwd,m[0],m[1],m[2]);let T=!1,I=[],P=[];for(let j of this.partBatches){let G=e-j.fadeStartMs,L=j.fadeStartMs===0?1:Math.min(1,Math.max(0,G/300));if(L<1){if(T=!0,L>0)P.push({batch:j,fade:L})}else I.push(j)}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 j of I)this.drawSubBatch(j.opaque);if(t.depthMask(!1),t.enable(t.BLEND),t.uniform1f(this.uFade,1),this.boardBatch)this.drawSubBatch(this.boardBatch.translucent);for(let j of I)this.drawSubBatch(j.translucent);for(let{batch:j,fade:G}of P)t.uniform1f(this.uFade,G),this.drawSubBatch(j.opaque),this.drawSubBatch(j.translucent);return t.depthMask(!0),t.bindVertexArray(null),T}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 zs=64,da=16777216;function pa(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 Vt(e){if(!e)return"";let t=e.replace(/\\/g,"/").replace(/\/+$/,""),n=t.lastIndexOf("/");return n>=0?t.slice(n+1):t}function qs(e){switch(e){case"board":return h("viewer.board","Board");case"schematic":return h("viewer.schematic","Schematic");case"3d":return h("viewer.solid","3D");case"gerbers":return h("gpui.gerbers","Gerbers");case"mech":return h("viewer.mech","Mech");case"files":return h("viewer.files","Files");case"diff":return h("viewer.diff","Diff");case"review":return h("viewer.review","Review");case"browser":return h("bots.tab.browser","Browser");case"terminal":return h("viewer.terminal","Terminal");default:return e?e.charAt(0).toUpperCase()+e.slice(1):""}}function Xn(e){return e==="board"||e==="schematic"||e==="gerbers"}function ua(e){return e==="files"||e==="diff"||e==="review"||e==="browser"||e==="terminal"}function Yn(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 p=document.createElement("div");p.className="bp-v-banner",p.hidden=!0;let l=document.createElement("div");l.className="bp-v-stage-wrap";let u=document.createElement("div");u.className="bp-v-stage";let d=document.createElement("div");d.className="bp-v-overlay",d.hidden=!0;let m=document.createElement("div");m.className="bp-v-layers",m.hidden=!0;let f=document.createElement("div");f.className="bp-v-info",f.hidden=!0,l.append(u,d,m,f);let b=document.createElement("div");b.className="bp-history-bar",b.setAttribute("data-testid","viewer-history-bar"),b.hidden=!0,e.replaceChildren(n,c,p,l,b);let g="",y="",w=0,C=!1,A=new Set,S=[],T=0,I=new Map,P=new Map,j={},G=[],L="",Y="",re=!1,se=!1,be=0,Pe=!1,Ee=0,ee="",ae=0,R=null,ue=null,le=null,Q=null,me=null,k=new qn,x=0,H=!1,B="",K="",ie="",we="";document.addEventListener("click",(O)=>{if(!H)return;if(O.target instanceof Node&&b.contains(O.target))return;H=!1,Ae()}),document.addEventListener("keydown",(O)=>{if(H&&O.key==="Escape")H=!1,Ae()});function D(){if(x)window.clearInterval(x),x=0;k.playing=!1}function ne(){let O=y==="3d"||y==="mech";if(c.hidden=!O,!O)return;if(c.childElementCount>0)return;for(let W of Gs){let U=document.createElement("button");U.type="button",U.className="bp-v-btn",U.textContent=W.label,U.setAttribute("data-testid",`solid-view-${W.id}`),U.addEventListener("click",()=>{le?.setView(W.id)}),c.append(U)}let _=document.createElement("button");_.type="button",_.className="bp-v-btn",_.textContent="Snap view",_.setAttribute("data-testid","solid-snap"),_.addEventListener("click",()=>{if(!le)return;le.snapPng().then((W)=>{if(!W)return;let U=URL.createObjectURL(W),z=document.createElement("a");z.href=U;let Z=(je()||y||"view").replace(/[^a-zA-Z0-9._-]/g,"_");z.download=`${Z}-snap.png`,z.click(),setTimeout(()=>URL.revokeObjectURL(U),1000)})}),c.append(_)}async function Ne(){if(!g||y!=="board"&&y!=="schematic")return;Ae();let O=k.compareRequest();if(!O){B="",K="",ie="",we="",await lt(!1);return}let _=`${y}|${O.commit}|${O.bits}|${Y}`;if(_===we&&A.size>0){Re(k.highlightEdits?`Comparing against ${k.activeRef()?.label||O.commit.slice(0,7)} (edits highlighted)`:`Comparing against ${k.activeRef()?.label||O.commit.slice(0,7)}`,!1);return}let W=++w;A.clear(),I.clear(),Ye(),C=!0,B="",K=O.commit,ie="",we=_;try{let U=Y||(y==="schematic"?j.sch:j.pcb)||"";if(!U){let Ce=await t.hub.rpc("viewer.files",{thread:g});if(W!==w)return;j=Ce||{},He(),U=(y==="schematic"?j.sch:j.pcb)||""}if(!U)throw Error(`Unable to resolve ${y} file path for compare`);let z=await t.hub.rpc("viewer.compare",{thread:g,kind:y,commit:O.commit,bits:O.bits,...Y?{path:Y}:{}});if(W!==w)return;let Z=typeof z?.root==="string"?z.root:"",J=y==="schematic"?"1":"0";B=Z?`${J}|${Z}|diff -`:`${J}|`,K=O.commit,ie=U.startsWith("/")||/^[A-Za-z]:[\\/]/.test(U)||!Z?U:`${Z.replace(/\/+$/,"")}/${U.replace(/^\/+/,"")}`,C=!1;let ve=S;Ye();for(let Ce of ve)if(Ce.kind==="bin")qe(Ce.buf);else _e(Ce.key,Ce.none,Ce.retryable,Ce.big);Re(k.highlightEdits?`Comparing against ${k.activeRef()?.label||O.commit.slice(0,7)} (edits highlighted)`:`Viewing snapshot: ${k.activeRef()?.label||O.commit.slice(0,7)}`,!1)}catch(U){if(W!==w)return;C=!1,B="",K="",ie="",we="",Ye(),Re(U instanceof Error?U.message:String(U),!0)}}function Ae(){let O=y==="board"||y==="schematic";if(b.hidden=!O,!O)return;let _=document.createElement("div");_.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=k.refs.length===0||k.index>=k.refs.length-1,W.setAttribute("data-testid","history-prev"),W.addEventListener("click",()=>{if(D(),k.step(1))Ne()});let U=document.createElement("button");U.type="button",U.className="bp-v-btn"+(k.playing?" is-on":""),U.textContent=k.playing?"⏸":"▶",U.title=k.playing?"Pause history":"Play history",U.disabled=k.refs.length===0,U.setAttribute("data-testid","history-play"),U.addEventListener("click",()=>{if(k.playing){D(),Ae();return}if(k.refs.length===0)return;if(k.playing=!0,k.isLive())k.index=k.refs.length-1,Ne();else Ae();x=window.setInterval(()=>{if(!k.playing||y!=="board"&&y!=="schematic"){D(),Ae();return}if(k.step(-1))Ne();else D(),Ae()},1400)});let z=document.createElement("button");z.type="button",z.className="bp-v-btn",z.textContent=">",z.title="Newer snapshot",z.disabled=k.isLive(),z.setAttribute("data-testid","history-next"),z.addEventListener("click",()=>{if(D(),k.step(-1))Ne()});let Z=document.createElement("button");Z.type="button",Z.className="bp-v-btn"+(k.isLive()?" is-on":""),Z.textContent="Live",Z.setAttribute("data-testid","history-live"),Z.addEventListener("click",()=>{if(D(),k.goLive())Re("",!1),Ne()});let J=document.createElement("span");J.className="bp-history-label",J.setAttribute("data-testid","history-label");let ve=k.activeRef();J.textContent=ve?ve.label||ve.commit.slice(0,7):k.refs.length>0?`Live (${k.refs.length} saved)`:"Live",_.append(W,U,z,Z,J);let Ce=document.createElement("div");Ce.className="bp-history-group";let Te=document.createElement("button");Te.type="button",Te.className="bp-v-btn"+(k.highlightEdits?" is-on":""),Te.textContent="Highlight edits",Te.disabled=k.refs.length===0,Te.setAttribute("data-testid","history-highlight"),Te.addEventListener("click",()=>{D(),k.toggleHighlight(),Ne()});let De=document.createElement("div");De.className="bp-history-menu-wrap";let Be=document.createElement("button");if(Be.type="button",Be.className="bp-v-btn"+(H||!k.isLive()?" is-on":""),Be.disabled=k.refs.length===0,Be.setAttribute("data-testid","history-compare"),Be.setAttribute("aria-haspopup","menu"),Be.setAttribute("aria-expanded",String(H)),Be.textContent=ve?`Compare: ${ve.label||ve.commit.slice(0,7)} ▾`:"Compare ▾",Be.addEventListener("click",(ke)=>{ke.stopPropagation(),H=!H,Ae()}),De.append(Be),H&&k.refs.length>0){let ke=document.createElement("div");ke.className="bp-history-menu",ke.setAttribute("role","menu"),ke.setAttribute("data-testid","history-compare-menu");let Ve=(Ue,Ge,zt)=>{let Ze=document.createElement("button");Ze.type="button",Ze.className="bp-history-menu-item"+(zt?" is-active":""),Ze.setAttribute("role","menuitem"),Ze.setAttribute("data-commit",Ge),Ze.textContent=Ue,Ze.addEventListener("click",()=>{if(H=!1,D(),k.selectCommit(Ge)){if(k.isLive())Re("",!1);Ne()}else Ae()}),ke.append(Ze)};Ve("Live (working tree)","",k.isLive());for(let Ue of k.refs)Ve(Ue.label||Ue.commit.slice(0,7),Ue.commit,ve?.commit===Ue.commit);De.append(ke)}Ce.append(Te,De),b.replaceChildren(_,Ce)}async function Me(O){if(!O)return;try{let _=await t.hub.rpc("viewer.refs",{thread:O});if(O!==g)return;k.setRefs(Array.isArray(_?.refs)?_.refs:[]),Ae()}catch{if(O!==g)return;k.setRefs([]),Ae()}}function q(){return document.documentElement.classList.contains("light")}let he=new MutationObserver(()=>{let O=q();ue?.setTheme(O),le?.setTheme(O),me?.setTheme(O)});he.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]});function oe(O,_="",W=!1,U=""){if(O==="none"){d.hidden=!0,d.replaceChildren();return}d.hidden=!1,d.className=`bp-v-overlay is-${O}`;let z=document.createElement("div");z.className="bp-v-state-card";let Z=document.createElement("div");if(Z.className="bp-v-state-msg",Z.textContent=_,z.append(Z),W){let J=document.createElement("button");J.type="button",J.className="bp-v-btn is-primary",J.textContent=h("tools.retry","Retry"),J.addEventListener("click",()=>void lt(!0)),z.append(J)}if(U){let J=document.createElement("div");J.className="bp-v-state-msg",J.textContent=h("gpui.c.solid.big.next","Loading it may take a while and a lot of memory.");let ve=document.createElement("button");ve.type="button",ve.className="bp-v-btn is-primary",ve.textContent=h("gpui.c.solid.load.big","Load it anyway"),ve.addEventListener("click",()=>{oe("loading",h("gpui.c.solid.loading.big","Loading it anyway…")),t.hub.rpc("kicad.big",{key:U}).catch(()=>oe("error",_,!1,U))}),z.append(J,ve)}d.replaceChildren(z)}function Re(O,_){p.textContent=O,p.hidden=!O,p.classList.toggle("is-warn",_)}function je(){if(Y)return Vt(Y);if(y==="board"||y==="3d")return Vt(j.pcb);if(y==="schematic")return Vt(j.sch);if(y==="mech")return Vt(L);return""}function He(){s.textContent=qs(y);let O=je();if(r.hidden=!O,a.hidden=!O,a.textContent=O,o.replaceChildren(),y==="mech"&&G.length>1){let W=document.createElement("select");W.className="bp-v-select",W.setAttribute("aria-label",h("viewer.mech","Mech"));for(let U of G){let z=document.createElement("option");z.value=U,z.textContent=Vt(U),z.selected=U===L,W.append(z)}W.addEventListener("change",()=>{L=W.value,He(),lt(!1)}),o.append(W)}if(Xn(y)){let W=document.createElement("button");W.type="button",W.className="bp-v-btn"+(Pe?" is-on":""),W.textContent=R?.layerHead||"Layers",W.setAttribute("data-testid","viewer-layers-btn"),W.addEventListener("click",()=>{if(Pe=!Pe,m.hidden=!Pe,W.classList.toggle("is-on",Pe),Pe)fe("","")}),o.append(W)}if(y==="board"||y==="schematic"||y==="3d"||y==="mech"||y==="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",()=>{ue?.fit(),le?.fit()}),o.append(W)}if((y==="board"||y==="schematic")&&t.hub.hasFeature("follow")){let W=document.createElement("button");W.type="button",W.className="bp-v-btn"+(re&&!se?" is-on":""),W.textContent=re?se?h("gpui.follow.paused","Follow (paused)"):"Follow agent":"Follow agent",W.setAttribute("data-testid","viewer-follow-btn"),W.addEventListener("click",()=>void st()),o.append(W)}let _=document.createElement("button");_.type="button",_.className="bp-v-btn bp-v-close",_.textContent="✕",_.title=h("common.close","Close"),_.setAttribute("aria-label",h("common.close","Close")),_.setAttribute("data-testid","viewer-close-btn"),_.addEventListener("click",()=>t.closeViewer()),o.append(_)}function ge(){if(!R){m.replaceChildren();return}let O=document.createDocumentFragment(),_=document.createElement("div");_.className="bp-v-layers-head";let W=document.createElement("span");if(W.textContent=R.layerHead||"Layers",_.append(W),R.layerReset){let J=document.createElement("button");J.type="button",J.className="bp-v-btn",J.textContent="Reset",J.addEventListener("click",()=>void fe("reset","")),_.append(J)}if(O.append(_),R.layerModes){let J=document.createElement("div");J.className="bp-v-layers-modes",["All","Dim","Only"].forEach((ve,Ce)=>{let Te=document.createElement("button");Te.type="button",Te.className="bp-v-btn"+(R?.layerMode===Ce?" is-on":""),Te.textContent=ve,Te.addEventListener("click",()=>void fe("mode",String(Ce))),J.append(Te)}),O.append(J)}let U=ue?.presentColors()??new Map,z=(R.layerList||[]).concat(R.layerMarks||[]),Z=document.createElement("div");Z.className="bp-v-layers-list";for(let J of z){let ve=U.get(J.layer);if(ve===void 0)continue;let Ce=document.createElement("div");Ce.className="bp-v-layer-row"+(J.active?" is-focus":"");let Te=document.createElement("input");Te.type="checkbox",Te.checked=J.on!==!1,Te.addEventListener("change",()=>void fe("toggle",String(J.layer)));let De=document.createElement("span");De.className="bp-v-layer-swatch";let Be=ve>>>16&255,ke=ve>>>8&255,Ve=ve&255;De.style.background=J.on!==!1?`rgb(${Be},${ke},${Ve})`:`rgba(${Be},${ke},${Ve},0.2)`;let Ue=document.createElement("button");Ue.type="button",Ue.className="bp-v-layer-name",Ue.textContent=J.name,Ue.addEventListener("click",()=>void fe("pick",String(J.layer))),Ce.append(Te,De,Ue),Z.append(Ce)}O.append(Z),m.replaceChildren(O)}async function fe(O,_){if(!Xn(y))return;let W=w;try{let U=await t.hub.rpc("viewer.layers",{kind:y,present:ae,off:Ee,focus:ee,...O?{action:O,value:_}:{}});if(W!==w||!U)return;Ee=Number(U.own)||0,ee=typeof U.focus==="string"?U.focus:"",R=U;let z={off:Number(U.off)||0,dim:Number(U.dim)||0,lift:typeof U.lift==="number"?U.lift:255};if(ue?.setLayers(z),He(),Pe)ge()}catch{}}async function tt(){if(!re||se||!g||!t.hub.hasFeature("follow"))return;se=!0,He();try{await t.hub.rpc("viewer.follow",{thread:g,action:"pause"})}catch{}}async function st(){if(!g||!t.hub.hasFeature("follow"))return;let O=!re?"on":se?"resume":"off";try{let _=await t.hub.rpc("viewer.follow",{thread:g,action:O});if(re=!!_.on,se=!!_.paused,He(),_.on&&!_.paused&&_.focus&&Array.isArray(_.focus.box)&&_.focus.box.length===4&&(_.seq||0)>be)be=_.seq||be,ue?.zoomToBoxMm([_.focus.box[0],_.focus.box[1],_.focus.box[2],_.focus.box[3]])}catch{}}function Je(){f.hidden=!0,f.replaceChildren(),ue?.setHighlights([])}function de(O){let _=O.split(";").filter(Boolean),W=_.shift()||O,U=[],z="",Z="";for(let De of _){if(De.startsWith("g="))continue;let Be=De.indexOf("=");if(Be>0){let ke=De.slice(0,Be),Ve=De.slice(Be+1);if((ke==="ref"||ke==="symbol")&&!z)z=Ve;if(ke==="net"&&!Z)Z=Ve;U.push([ke,Ve])}else U.push([De,""])}let J=document.createElement("div");J.className="bp-v-info-head";let ve=document.createElement("span");ve.className="bp-v-info-title",ve.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",Je),J.append(ve,Ce);let Te=document.createElement("div");Te.className="bp-v-info-rows";for(let[De,Be]of U){let ke=document.createElement("span");ke.className="bp-v-info-chip",ke.textContent=Be?`${De}: ${Be}`:De,Te.append(ke)}return f.replaceChildren(J,...U.length>0?[Te]:[]),f.hidden=!1,{ref:z||void 0,net:Z||void 0}}async function St(O){if(!O){Je();return}let _=Array.from(A)[0]||"";if(!_)return;let W=w;try{let U=await t.hub.rpc("viewer.info",{key:_,at:O.at,idx:O.idx});if(W!==w)return;let z=typeof U.info==="string"?U.info:"";if(!z){Je();return}let{ref:Z,net:J}=de(z),ve=[];if(Z)ve.push(["ref",Z]);if(J)ve.push(["net",J]);let Ce=[[O.at,O.idx]];for(let[Te,De]of ve){let Be=await t.hub.rpc("viewer.probe",{key:_,name:Te,value:De});if(W!==w)return;if(Array.isArray(Be.matches))for(let ke of Be.matches)Ce.push(ke)}ue?.setHighlights(Ce)}catch{Je()}}function Xe(){Q?.destroy(),Q=null,me?.destroy(),me=null,ue?.destroy(),ue=null,le?.destroy(),le=null,u.replaceChildren(),Pe=!1,m.hidden=!0,f.hidden=!0,f.replaceChildren(),Re("",!1),oe("none")}function Ye(){S=[],T=0}async function lt(O){if(!g||!y)return;let _=++w;if(A.clear(),C=!1,Ye(),Xe(),He(),ne(),Ae(),(y==="board"||y==="schematic")&&g)Me(g);if(ua(y)){if(t.hub.rpc("viewer.watch",{thread:g,kind:""}).catch(()=>{}),y==="files")Q=Ds(u,t,g,(z,Z)=>{if(y=z,Y=Z,z==="mech")L=Z;lt(!1)});else if(y==="diff")Q=Hs(u,t,g);else if(y==="review")Q=Fs(u,t,g);else if(y==="browser")Q=Is(u,t,g);else if(y==="terminal")oe("loading","Loading terminal…"),import("/assets/terminal.js").then((Z)=>{if(_!==w)return;if(oe("none"),Z?.mountTerminalPane)me=Z.mountTerminalPane(u,t,g,q());else oe("error","Terminal chunk missing",!0)},(Z)=>{if(_!==w)return;oe("error",Z instanceof Error?Z.message:String(Z),!0)});return}if(oe("loading","Loading…"),!j.root)try{let z=await t.hub.rpc("viewer.files",{thread:g});if(_!==w)return;j=z||{},He()}catch{}if(y==="gerbers"&&j.hasGerbers===!1){oe("empty","No Gerbers in this project",!1);return}let W=q();if(y==="3d"||y==="mech")le=new Jn(u,{onStatus:(z,Z)=>{if(Z)oe("none"),Re(z,!1);else if(z)oe("loading",z);else oe("none"),Re("",!1)},onUserMove:()=>void tt()}),le.setTheme(W);else if(y==="board"||y==="schematic"||y==="gerbers")ue=new _n(u,{onPick:(z)=>void St(z),onUserMove:()=>void tt()}),ue.setTheme(W);else{oe("empty",`${qs(y)} is not available in this viewer`,!1);return}let U={thread:g};if(O)U.force=!0;if(y==="mech"){if(G.length===0)try{let z=await t.hub.rpc("mech.list",{thread:g});if(_!==w)return;if(G=Array.isArray(z.parts)?z.parts:[],!L)L=z.primary||G[0]||"";He()}catch(z){if(_!==w)return;oe("error",z instanceof Error?z.message:String(z),!0);return}if(!L){oe("empty",h("gpui.rail.no.mech","No mechanical parts in this project"),!1);return}U.kind="3d",U.path=L}else{if(U.kind=y,Y&&(y==="board"||y==="schematic"))U.path=Y;if(y==="3d"&&!O&&le){let z=le.keptToken();if(z)U.kept=z}if((y==="board"||y==="schematic"||y==="gerbers")&&!O&&t.hub.hasFeature("keptChunks"))U.keptChunks=Array.from(P.keys())}C=!0,B="",K="",ie="",we="";try{let z=await t.hub.rpc("viewer.watch",U);if(_!==w)return;A=new Set(Array.isArray(z.keys)?z.keys:[]),C=!1;let Z=S;Ye();for(let J of Z)if(J.kind==="bin")qe(J.buf);else _e(J.key,J.none,J.retryable,J.big)}catch(z){if(_!==w)return;C=!1,A.clear(),Ye();let Z=z instanceof Error?z.message:String(z),J=/no gerbers|not in this project|another machine/i.test(Z);oe(J?"empty":"error",Z,!J)}}function _e(O,_,W,U=!1){if(C){if(S.length{if(O.t==="plot"&&typeof O.none==="string"&&typeof O.key==="string")_e(O.key,O.none,O.retryable===!0)}),_t=Jt(()=>{if(y)He()}),Oe=(O)=>{if(O.key==="Escape"&&y&&!f.hidden)Je()};return window.addEventListener("keydown",Oe),{open(O,_){if(_!==g){if(g=_,j={},G=[],L="",I.clear(),re=!1,se=!1,be=0,Ee=0,ee="",ae=0,R=null,t.hub.hasFeature("follow"))t.hub.rpc("viewer.follow",{thread:_}).then((W)=>{if(_!==g)return;if(re=!!W.on,se=!!W.paused,be=Number(W.seq)||0,y)He()}).catch(()=>{})}if(O!==y)D(),k.goLive(),Ee=0,ee="",ae=0,R=null;y=O,Y="",lt(!1)},reconcileHas(O){if(y&&!pa(y,O))t.closeViewer()},close(){if(w++,C=!1,D(),H=!1,B="",K="",ie="",we="",k.goLive(),c.hidden=!0,b.hidden=!0,Ye(),g)t.hub.rpc("viewer.watch",{thread:g,kind:""}).catch(()=>{});y="",A.clear(),Xe()}}}var Ks="http://www.w3.org/2000/svg";function Ut(e){let t=document.createElementNS(Ks,"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(Ks,"path");i.setAttribute("d",n),t.appendChild(i)}return t}function ma(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 Js(e,t){if(!e)return!0;if(t==="board"||t==="3d")return e.board!==!1;if(t==="schematic")return e.schematic!==!1;if(t==="mech")return e.mech!==!1;if(t==="gerbers")return e.gerbers!==!1;return!0}var Wt="dark",ln=(()=>{try{return ms(localStorage.getItem("bp.theme.pref"))}catch{return"auto"}})(),Zn=null,Pt=(()=>{try{return hs(localStorage.getItem("bp.locale"))}catch{return"auto"}})();function Qs(){let e=Ht(ln,Wt);document.documentElement.classList.toggle("light",e==="light");try{localStorage.setItem("bp.theme",e)}catch{}}function Xs(e){if(!e)return;Wt=e==="light"?"light":"dark",Qs()}function Ys(){if(Pt!=="auto")gt(Pt);else if(Zn)gt(Zn);else if(typeof navigator<"u"&&navigator.language){if(!gt(navigator.language))gt("en")}}function ha(){return`web-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`}function Zs(){let e=document.getElementById("root");if(!e)return;try{if(localStorage.getItem("bp.theme")==="light")Wt="light";if(Ht(ln,Wt)==="light")document.documentElement.classList.add("light");if(Pt!=="auto")gt(Pt)}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 p=document.createElement("span");p.className="bp-crumb-thread",p.setAttribute("data-testid","thread-title");let l=document.createElement("span");l.className="bp-plan-top-badge bp-hidden",l.setAttribute("data-testid","plan-top-badge"),i.append(s,r,a,o,c,p,l);let u=document.createElement("div");u.className="bp-top-state bp-hide-phone bp-hidden";let d=document.createElement("span");d.className="bp-top-state-lbl",d.textContent="STATE";let m=document.createElement("span");m.className="bp-dot bp-dot-idle";let f=document.createElement("span");f.className="bp-top-state-word",u.append(d,m,f);let b=document.createElement("div");b.className="bp-top-acts bp-hide-phone bp-hidden";let g=document.createElement("button");g.type="button",g.className="bp-btn-ghost bp-top-act";let y=document.createElement("span");y.textContent=h("menu.pin","Pin"),g.append(Ut(["M12 17v5","M9 3h6l1 7 3 3H5l3-3 1-7z"]),y);let w=document.createElement("button");w.type="button",w.className="bp-btn-ghost bp-top-act";let C=document.createElement("span");C.textContent=h("menu.settle","Settle"),w.append(Ut(["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 S=document.createElement("button");S.type="button",S.className="bp-btn-ghost bp-top-act",S.textContent="▾",S.title="Thread menu",S.setAttribute("aria-label","Thread menu"),S.setAttribute("data-testid","thread-menu-btn");let T=document.createElement("div");T.className="bp-popover bp-hidden",T.setAttribute("data-testid","thread-menu"),A.append(S,T),b.append(g,w,A);let I=document.createElement("div");I.className="bp-top-right";let P=document.createElement("button");P.type="button",P.className="bp-btn-ghost bp-top-act bp-hide-tablet",P.setAttribute("data-testid","improvements-btn");let j=document.createElement("span");j.textContent=h("gpui.improvements","Improvements"),P.append(Ut(["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"]),j);let G=document.createElement("button");G.type="button",G.className="bp-cmd-box bp-hide-tablet",G.textContent="> Jump or run a command";let L=document.createElement("button");L.type="button",L.className="icon bp-top-icon",L.title="Search",L.setAttribute("aria-label","Search"),L.appendChild(Ut(["M11 19a8 8 0 1 0 0-16 8 8 0 0 0 0 16z","M21 21l-4.3-4.3"]));let Y=document.createElement("button");Y.type="button",Y.className="icon bp-top-icon",Y.title=h("palette.settings","Settings"),Y.setAttribute("aria-label",h("palette.settings","Settings")),Y.setAttribute("data-testid","settings-btn"),Y.appendChild(Ut(["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"])),I.append(P,G,L,Y),t.append(n,i,u,b,I);let re=document.createElement("div");re.className="bp-body";let se=document.createElement("aside");se.className="bp-sidebar",se.setAttribute("data-testid","sidebar");let be=document.createElement("main");be.className="bp-center";let Pe=document.createElement("div");Pe.className="bp-right-area bp-hidden",Pe.setAttribute("data-testid","right-area");let Ee=document.createElement("div");Ee.className="bp-right-top";let ee=document.createElement("section");ee.className="bp-viewer-pane bp-hidden",ee.setAttribute("data-testid","viewer-pane"),Ee.appendChild(ee),Pe.appendChild(Ee);let ae=document.createElement("nav");ae.className="bp-rail",ae.setAttribute("aria-label","Viewer rail"),ae.setAttribute("data-testid","viewer-rail"),re.append(se,be,Pe,ae),e.append(t,re);let R=new Un,ue=null,le=new Set,Q=0,me=null,k=[],x=[],H=[],B=[],K=[],ie=[],we=[],D="",ne=0,Ne=0,Ae=null,Me=null,q="",he=null,oe=20,Re={},je=new Map;function He(v,E){je.delete(v),je.set(v,E);while(je.size>oe){let M=je.keys().next().value;if(M!==void 0)je.delete(M);else break}}let ge=new Gn(se,{onSelectThread:(v)=>{if(v===D&&Ae!==null){se.classList.remove("bp-sidebar-open");return}Ge(v)},onNewThread:(v)=>{qt(v)},onSelectBot:(v)=>{Ge(v.thread)},onQuickOpenViewer:(v,E)=>{let M=x.find((F)=>F.project===v&&!F.archived&&!F.swarm);(async()=>{if(M)await Ge(M.id);else await qt(v);if(D)q=E,ze.setActive(E),he?.open(E,D)})()},onThreadAct:(v,E)=>{rt(v,E)},onSnoozeRow:(v)=>{R.rpc("sidebar.act",{action:"row-snooze",value:v}).then(()=>ke()).catch(()=>{})},onToggleSection:(v)=>{if(le.has(v))le.delete(v);else le.add(v);ke()},onToggleProjectFold:(v)=>{R.rpc("sidebar.act",{action:"project-fold",value:v}).then(()=>ke()).catch(()=>{})},onCollapseSidebar:()=>{se.classList.remove("bp-sidebar-open"),se.classList.add("bp-sidebar-collapsed")},onNeedAct:async(v)=>{let E=sn(v,!1);if(!E)return;if(E.kind==="thread"){Ge(E.id);return}if(E.kind!=="call")return;let M=us(await R.rpc(E.method,E.params));if(M?.kind==="thread")Ge(M.id);ke()},hasRoomView:!1,onAddProject:()=>qe.open({mode:"folder"}),onSettleSwarm:(v)=>{R.rpc("sidebar.act",{action:"swarm-settle",value:v}).then(()=>ke()).catch(()=>{})}}),fe=new fn(be,{onLoadOlder:()=>{Qn()},onGoToEntry:(v)=>{Ze(v)},onOpenAccounts:()=>{_()},onAnswerAsk:(v,E)=>{R.rpc("ask.answer",{ask:v,answer:E}).catch((M)=>{de.showError(M instanceof Error?M.message:"Could not send answer")})},onToggleReview:(v)=>{if(!D)return;let E=ne;R.rpc("thread.review",{thread:D,on:v}).then((M)=>{if(E===ne)fe.setReview(M.review??null)}).catch(()=>{})},onUnansweredAction:(v,E)=>{if(!D)return;if(v==="again"||v==="thread-again")R.rpc("thread.again",{thread:D,value:E}).catch(()=>{});else R.rpc("thread.act",{thread:D,action:v,value:E}).catch(()=>{})},onReplyEntry:(v)=>{if(!R.hasFeature("reply")){let E=(v.text||"").split(` +`;function Ke(e){let t=e/255;return t<=0.04045?t/12.92:Math.pow((t+0.055)/1.055,2.4)}var Ba=[Ke(77),Ke(83),Ke(94)],Ia=[Ke(53),Ke(58),Ke(67)],Ra=[Ke(245),Ke(246),Ke(248)],ja=[Ke(225),Ke(228),Ke(233)];function mr(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 br(e,t,n){let i=mr(e,e.VERTEX_SHADER,t),s=mr(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 Ha(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 Da(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 gr(e){let t=Math.hypot(e[0],e[1],e[2])||1;return[e[0]/t,e[1]/t,e[2]/t]}function fr(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 li(e,t){return e[0]*t[0]+e[1]*t[1]+e[2]*t[2]}class ci{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=br(n,Aa,Na),this.bgVao=n.createVertexArray(),this.uBgTop=n.getUniformLocation(this.bgProg,"uBgTop"),this.uBgBot=n.getUniformLocation(this.bgProg,"uBgBot"),this.prog=br(n,Ma,Ta),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=er(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,p=r>0?new Float32Array(r*12):null,l=a>0?new Float32Array(a*9):null,h=a>0?new Float32Array(a*9):null,d=a>0?new Float32Array(a*12):null,u=0,f=0;for(let y=0;y>>24&255,L=1-C/255,N=(w>>>16&255)/255,A=(w>>>8&255)/255,B=(w&255)/255,M=y*9;if(C===0&&o&&c&&p){let j=u*9;for(let x=0;x<9;x++)o[j+x]=e[M+x],c[j+x]=t[M+x];let O=u*12;for(let x=0;x<3;x++)p[O+x*4]=N,p[O+x*4+1]=A,p[O+x*4+2]=B,p[O+x*4+3]=1;u++}else if(l&&h&&d){let j=f*9;for(let x=0;x<9;x++)l[j+x]=e[M+x],h[j+x]=t[M+x];let O=f*12;for(let x=0;x<3;x++)d[O+x*4]=N,d[O+x*4+1]=A,d[O+x*4+2]=B,d[O+x*4+3]=L;f++}}let b=o&&c&&p?this.createSubBatch(o,c,p,r*3):null,v=l&&h&&d?this.createSubBatch(l,h,d,a*3):null;if(!b&&!v)return null;return{opaque:b,translucent:v,fadeStartMs:i}}deleteSubBatch(e){let t=this.gl;if(!t||!e)return;t.deleteVertexArray(e.vao),t.deleteBuffer(e.posBuf),t.deleteBuffer(e.nrmBuf),t.deleteBuffer(e.colBuf)}deleteBatch(e){if(!e)return;this.deleteSubBatch(e.opaque),this.deleteSubBatch(e.translucent)}clearParts(){for(let e of this.partBatches)this.deleteBatch(e);this.partBatches=[]}fit(){this.setView("fit")}setView(e){let t=35*Math.PI/180;this.dist=this.radius/Math.sin(t*0.5)*1.15,this.target=[this.center[0],this.center[1],this.center[2]];let{yaw:n,pitch:i}=ur(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 j=this.lightTheme?Ra:Ba,O=this.lightTheme?ja:Ia;t.uniform3f(this.uBgTop,j[0],j[1],j[2]),t.uniform3f(this.uBgBot,O[0],O[1],O[2]),t.bindVertexArray(this.bgVao),t.drawArrays(t.TRIANGLE_STRIP,0,4),t.bindVertexArray(null)}let c=Math.cos(this.pitch),p=Math.sin(this.pitch),l=Math.cos(this.yaw),h=Math.sin(this.yaw),d=[this.target[0]+this.dist*c*h,this.target[1]-this.dist*c*l,this.target[2]+this.dist*p],u=gr([this.target[0]-d[0],this.target[1]-d[1],this.target[2]-d[2]]),f=Math.abs(u[2])>0.99?[0,1,0]:[0,0,1],b=gr(fr(u,f)),v=fr(b,u),y=new Float32Array([b[0],v[0],-u[0],0,b[1],v[1],-u[1],0,b[2],v[2],-u[2],0,-li(b,d),-li(v,d),li(u,d),1]),w=Math.max(0.05,this.dist*0.01),C=Math.max(this.dist*10,this.radius*20),L=Da(35*Math.PI/180,a/o,w,C),N=Ha(L,y);t.useProgram(this.prog),t.uniformMatrix4fv(this.uMvp,!1,N),t.uniform3f(this.uEye,d[0],d[1],d[2]),t.uniform3f(this.uRight,b[0],b[1],b[2]),t.uniform3f(this.uUp,v[0],v[1],v[2]),t.uniform3f(this.uFwd,u[0],u[1],u[2]);let A=!1,B=[],M=[];for(let j of this.partBatches){let O=e-j.fadeStartMs,x=j.fadeStartMs===0?1:Math.min(1,Math.max(0,O/300));if(x<1){if(A=!0,x>0)M.push({batch:j,fade:x})}else B.push(j)}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 j of B)this.drawSubBatch(j.opaque);if(t.depthMask(!1),t.enable(t.BLEND),t.uniform1f(this.uFade,1),this.boardBatch)this.drawSubBatch(this.boardBatch.translucent);for(let j of B)this.drawSubBatch(j.translucent);for(let{batch:j,fade:O}of M)t.uniform1f(this.uFade,O),this.drawSubBatch(j.opaque),this.drawSubBatch(j.translucent);return t.depthMask(!0),t.bindVertexArray(null),A}onPointerDown=(e)=>{if(this.canvas.setPointerCapture(e.pointerId),this.pointers.set(e.pointerId,{x:e.clientX,y:e.clientY,button:e.button,shift:e.shiftKey}),this.pointers.size===2){let[t,n]=Array.from(this.pointers.values());this.pinchDist=Math.hypot(n.x-t.x,n.y-t.y)||1}};onPointerMove=(e)=>{let t=this.pointers.get(e.pointerId);if(!t)return;let n=e.clientX-t.x,i=e.clientY-t.y;if(t.x=e.clientX,t.y=e.clientY,this.pointers.size===2){let[s,r]=Array.from(this.pointers.values()),a=Math.hypot(r.x-s.x,r.y-s.y)||1;if(this.pinchDist>0)this.dist=Math.max(this.radius*0.05,Math.min(this.radius*20,this.dist*(this.pinchDist/a)));this.pinchDist=a,this.cbs.onUserMove?.(),this.scheduleDraw();return}if(t.button===2||t.button===1||t.shift){let s=this.dist*0.0014,r=Math.cos(this.yaw),a=Math.sin(this.yaw);this.target[0]-=n*r*s,this.target[1]-=n*a*s,this.target[2]+=i*s}else this.yaw+=n*0.008,this.pitch=Math.max(-Math.PI*0.49,Math.min(Math.PI*0.49,this.pitch+i*0.008));this.cbs.onUserMove?.(),this.scheduleDraw()};onPointerUp=(e)=>{if(this.pointers.delete(e.pointerId),this.pointers.size<2)this.pinchDist=0};onWheel=(e)=>{e.preventDefault();let t=e.deltaY<0?0.8620689655172414:1.16;this.dist=Math.max(this.radius*0.05,Math.min(this.radius*20,this.dist*t)),this.cbs.onUserMove?.(),this.scheduleDraw()};onDblClick=()=>{this.fit()};onContextMenu=(e)=>{e.preventDefault()};destroy(){if(this.rafId)cancelAnimationFrame(this.rafId);if(this.resizeObs.disconnect(),this.canvas.removeEventListener("pointerdown",this.onPointerDown),this.canvas.removeEventListener("pointermove",this.onPointerMove),this.canvas.removeEventListener("pointerup",this.onPointerUp),this.canvas.removeEventListener("pointercancel",this.onPointerUp),this.canvas.removeEventListener("wheel",this.onWheel),this.canvas.removeEventListener("dblclick",this.onDblClick),this.canvas.removeEventListener("contextmenu",this.onContextMenu),this.deleteBatch(this.boardBatch),this.clearParts(),this.gl){if(this.bgVao)this.gl.deleteVertexArray(this.bgVao);if(this.bgProg)this.gl.deleteProgram(this.bgProg);if(this.prog)this.gl.deleteProgram(this.prog)}this.worker?.terminate(),this.canvas.remove()}}var vr=64,Fa=16777216;function $a(e,t){switch(e){case"board":case"3d":return t.board!==!1;case"schematic":return t.schematic!==!1;case"mech":return t.mech!==!1;case"gerbers":return t.gerbers!==!1;default:return!0}}function zt(e){if(!e)return"";let t=e.replace(/\\/g,"/").replace(/\/+$/,""),n=t.lastIndexOf("/");return n>=0?t.slice(n+1):t}function yr(e){switch(e){case"board":return m("viewer.board","Board");case"schematic":return m("viewer.schematic","Schematic");case"3d":return m("viewer.solid","3D");case"gerbers":return m("gpui.gerbers","Gerbers");case"mech":return m("viewer.mech","Mech");case"files":return m("viewer.files","Files");case"diff":return m("viewer.diff","Diff");case"review":return m("viewer.review","Review");case"browser":return m("bots.tab.browser","Browser");case"terminal":return m("viewer.terminal","Terminal");default:return e?e.charAt(0).toUpperCase()+e.slice(1):""}}function di(e){return e==="board"||e==="schematic"||e==="gerbers"}function Oa(e){return e==="files"||e==="diff"||e==="review"||e==="browser"||e==="terminal"}function pi(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 p=document.createElement("div");p.className="bp-v-banner",p.hidden=!0;let l=document.createElement("div");l.className="bp-v-stage-wrap";let h=document.createElement("div");h.className="bp-v-stage";let d=document.createElement("div");d.className="bp-v-overlay",d.hidden=!0;let u=document.createElement("div");u.className="bp-v-layers",u.hidden=!0;let f=document.createElement("div");f.className="bp-v-info",f.hidden=!0,l.append(h,d,u,f);let b=document.createElement("div");b.className="bp-history-bar",b.setAttribute("data-testid","viewer-history-bar"),b.hidden=!0,e.replaceChildren(n,c,p,l,b);let v="",y="",w=0,C=!1,L=new Set,N=[],A=0,B=new Map,M=new Map,j={},O=[],x="",Y="",se=!1,ne=!1,he=0,Se=!1,ke=0,ee="",re=0,R=null,ue=null,le=null,Q=null,ge=null,k=new oi,P=0,F=!1,I="",J="",ie="",Ee="";document.addEventListener("click",(V)=>{if(!F)return;if(V.target instanceof Node&&b.contains(V.target))return;F=!1,Ae()}),document.addEventListener("keydown",(V)=>{if(F&&V.key==="Escape")F=!1,Ae()});function D(){if(P)window.clearInterval(P),P=0;k.playing=!1}function te(){let V=y==="3d"||y==="mech";if(c.hidden=!V,!V)return;if(c.childElementCount>0)return;for(let _ of hr){let G=document.createElement("button");G.type="button",G.className="bp-v-btn",G.textContent=_.label,G.setAttribute("data-testid",`solid-view-${_.id}`),G.addEventListener("click",()=>{le?.setView(_.id)}),c.append(G)}let W=document.createElement("button");W.type="button",W.className="bp-v-btn",W.textContent="Snap view",W.setAttribute("data-testid","solid-snap"),W.addEventListener("click",()=>{if(!le)return;le.snapPng().then((_)=>{if(!_)return;let G=URL.createObjectURL(_),z=document.createElement("a");z.href=G;let ae=(De()||y||"view").replace(/[^a-zA-Z0-9._-]/g,"_");z.download=`${ae}-snap.png`,z.click(),setTimeout(()=>URL.revokeObjectURL(G),1000)})}),c.append(W)}async function Me(){if(!v||y!=="board"&&y!=="schematic")return;Ae();let V=k.compareRequest();if(!V){I="",J="",ie="",Ee="",await ct(!1);return}let W=`${y}|${V.commit}|${V.bits}|${Y}`;if(W===Ee&&L.size>0){He(k.highlightEdits?`Comparing against ${k.activeRef()?.label||V.commit.slice(0,7)} (edits highlighted)`:`Comparing against ${k.activeRef()?.label||V.commit.slice(0,7)}`,!1);return}let _=++w;L.clear(),B.clear(),ye(),C=!0,I="",J=V.commit,ie="",Ee=W;try{let G=Y||(y==="schematic"?j.sch:j.pcb)||"";if(!G){let xe=await t.hub.rpc("viewer.files",{thread:v});if(_!==w)return;j=xe||{},Fe(),G=(y==="schematic"?j.sch:j.pcb)||""}if(!G)throw Error(`Unable to resolve ${y} file path for compare`);let z=await t.hub.rpc("viewer.compare",{thread:v,kind:y,commit:V.commit,bits:V.bits,...Y?{path:Y}:{}});if(_!==w)return;let ae=typeof z?.root==="string"?z.root:"",K=y==="schematic"?"1":"0";I=ae?`${K}|${ae}|diff +`:`${K}|`,J=V.commit,ie=G.startsWith("/")||/^[A-Za-z]:[\\/]/.test(G)||!ae?G:`${ae.replace(/\/+$/,"")}/${G.replace(/^\/+/,"")}`,C=!1;let we=N;ye();for(let xe of we)if(xe.kind==="bin")Ze(xe.buf);else Je(xe.key,xe.none,xe.retryable,xe.big);He(k.highlightEdits?`Comparing against ${k.activeRef()?.label||V.commit.slice(0,7)} (edits highlighted)`:`Viewing snapshot: ${k.activeRef()?.label||V.commit.slice(0,7)}`,!1)}catch(G){if(_!==w)return;C=!1,I="",J="",ie="",Ee="",ye(),He(G instanceof Error?G.message:String(G),!0)}}function Ae(){let V=y==="board"||y==="schematic";if(b.hidden=!V,!V)return;let W=document.createElement("div");W.className="bp-history-group";let _=document.createElement("button");_.type="button",_.className="bp-v-btn",_.textContent="<",_.title="Older snapshot",_.disabled=k.refs.length===0||k.index>=k.refs.length-1,_.setAttribute("data-testid","history-prev"),_.addEventListener("click",()=>{if(D(),k.step(1))Me()});let G=document.createElement("button");G.type="button",G.className="bp-v-btn"+(k.playing?" is-on":""),G.textContent=k.playing?"⏸":"▶",G.title=k.playing?"Pause history":"Play history",G.disabled=k.refs.length===0,G.setAttribute("data-testid","history-play"),G.addEventListener("click",()=>{if(k.playing){D(),Ae();return}if(k.refs.length===0)return;if(k.playing=!0,k.isLive())k.index=k.refs.length-1,Me();else Ae();P=window.setInterval(()=>{if(!k.playing||y!=="board"&&y!=="schematic"){D(),Ae();return}if(k.step(-1))Me();else D(),Ae()},1400)});let z=document.createElement("button");z.type="button",z.className="bp-v-btn",z.textContent=">",z.title="Newer snapshot",z.disabled=k.isLive(),z.setAttribute("data-testid","history-next"),z.addEventListener("click",()=>{if(D(),k.step(-1))Me()});let ae=document.createElement("button");ae.type="button",ae.className="bp-v-btn"+(k.isLive()?" is-on":""),ae.textContent="Live",ae.setAttribute("data-testid","history-live"),ae.addEventListener("click",()=>{if(D(),k.goLive())He("",!1),Me()});let K=document.createElement("span");K.className="bp-history-label",K.setAttribute("data-testid","history-label");let we=k.activeRef();K.textContent=we?we.label||we.commit.slice(0,7):k.refs.length>0?`Live (${k.refs.length} saved)`:"Live",W.append(_,G,z,ae,K);let xe=document.createElement("div");xe.className="bp-history-group";let Ne=document.createElement("button");Ne.type="button",Ne.className="bp-v-btn"+(k.highlightEdits?" is-on":""),Ne.textContent="Highlight edits",Ne.disabled=k.refs.length===0,Ne.setAttribute("data-testid","history-highlight"),Ne.addEventListener("click",()=>{D(),k.toggleHighlight(),Me()});let $e=document.createElement("div");$e.className="bp-history-menu-wrap";let Re=document.createElement("button");if(Re.type="button",Re.className="bp-v-btn"+(F||!k.isLive()?" is-on":""),Re.disabled=k.refs.length===0,Re.setAttribute("data-testid","history-compare"),Re.setAttribute("aria-haspopup","menu"),Re.setAttribute("aria-expanded",String(F)),Re.textContent=we?`Compare: ${we.label||we.commit.slice(0,7)} ▾`:"Compare ▾",Re.addEventListener("click",(ve)=>{ve.stopPropagation(),F=!F,Ae()}),$e.append(Re),F&&k.refs.length>0){let ve=document.createElement("div");ve.className="bp-history-menu",ve.setAttribute("role","menu"),ve.setAttribute("data-testid","history-compare-menu");let Ue=(Oe,Mt,bn)=>{let et=document.createElement("button");et.type="button",et.className="bp-history-menu-item"+(bn?" is-active":""),et.setAttribute("role","menuitem"),et.setAttribute("data-commit",Mt),et.textContent=Oe,et.addEventListener("click",()=>{if(F=!1,D(),k.selectCommit(Mt)){if(k.isLive())He("",!1);Me()}else Ae()}),ve.append(et)};Ue("Live (working tree)","",k.isLive());for(let Oe of k.refs)Ue(Oe.label||Oe.commit.slice(0,7),Oe.commit,we?.commit===Oe.commit);$e.append(ve)}xe.append(Ne,$e),b.replaceChildren(W,xe)}async function Te(V){if(!V)return;try{let W=await t.hub.rpc("viewer.refs",{thread:V});if(V!==v)return;k.setRefs(Array.isArray(W?.refs)?W.refs:[]),Ae()}catch{if(V!==v)return;k.setRefs([]),Ae()}}function q(){return document.documentElement.classList.contains("light")}let fe=new MutationObserver(()=>{let V=q();ue?.setTheme(V),le?.setTheme(V),ge?.setTheme(V)});fe.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]});function oe(V,W="",_=!1,G=""){if(V==="none"){d.hidden=!0,d.replaceChildren();return}d.hidden=!1,d.className=`bp-v-overlay is-${V}`;let z=document.createElement("div");z.className="bp-v-state-card";let ae=document.createElement("div");if(ae.className="bp-v-state-msg",ae.textContent=W,z.append(ae),_){let K=document.createElement("button");K.type="button",K.className="bp-v-btn is-primary",K.textContent=m("tools.retry","Retry"),K.addEventListener("click",()=>void ct(!0)),z.append(K)}if(G){let K=document.createElement("div");K.className="bp-v-state-msg",K.textContent=m("gpui.c.solid.big.next","Loading it may take a while and a lot of memory.");let we=document.createElement("button");we.type="button",we.className="bp-v-btn is-primary",we.textContent=m("gpui.c.solid.load.big","Load it anyway"),we.addEventListener("click",()=>{oe("loading",m("gpui.c.solid.loading.big","Loading it anyway…")),t.hub.rpc("kicad.big",{key:G}).catch(()=>oe("error",W,!1,G))}),z.append(K,we)}d.replaceChildren(z)}function He(V,W){p.textContent=V,p.hidden=!V,p.classList.toggle("is-warn",W)}function De(){if(Y)return zt(Y);if(y==="board"||y==="3d")return zt(j.pcb);if(y==="schematic")return zt(j.sch);if(y==="mech")return zt(x);return""}function Fe(){s.textContent=yr(y);let V=De();if(r.hidden=!V,a.hidden=!V,a.textContent=V,o.replaceChildren(),y==="mech"&&O.length>1){let _=document.createElement("select");_.className="bp-v-select",_.setAttribute("aria-label",m("viewer.mech","Mech"));for(let G of O){let z=document.createElement("option");z.value=G,z.textContent=zt(G),z.selected=G===x,_.append(z)}_.addEventListener("change",()=>{x=_.value,Fe(),ct(!1)}),o.append(_)}if(di(y)){let _=document.createElement("button");_.type="button",_.className="bp-v-btn"+(Se?" is-on":""),_.textContent=R?.layerHead||"Layers",_.setAttribute("data-testid","viewer-layers-btn"),_.addEventListener("click",()=>{if(Se=!Se,u.hidden=!Se,_.classList.toggle("is-on",Se),Se)Ge("","")}),o.append(_)}if(y==="board"||y==="schematic"||y==="3d"||y==="mech"||y==="gerbers"){let _=document.createElement("button");_.type="button",_.className="bp-v-btn",_.textContent="Fit",_.setAttribute("data-testid","viewer-fit-btn"),_.addEventListener("click",()=>{ue?.fit(),le?.fit()}),o.append(_)}if((y==="board"||y==="schematic")&&t.hub.hasFeature("follow")){let _=document.createElement("button");_.type="button",_.className="bp-v-btn"+(se&&!ne?" is-on":""),_.textContent=se?ne?m("gpui.follow.paused","Follow (paused)"):"Follow agent":"Follow agent",_.setAttribute("data-testid","viewer-follow-btn"),_.addEventListener("click",()=>void Jt()),o.append(_)}let W=document.createElement("button");W.type="button",W.className="bp-v-btn bp-v-close",W.textContent="✕",W.title=m("common.close","Close"),W.setAttribute("aria-label",m("common.close","Close")),W.setAttribute("data-testid","viewer-close-btn"),W.addEventListener("click",()=>t.closeViewer()),o.append(W)}function Be(){if(!R){u.replaceChildren();return}let V=document.createDocumentFragment(),W=document.createElement("div");W.className="bp-v-layers-head";let _=document.createElement("span");if(_.textContent=R.layerHead||"Layers",W.append(_),R.layerReset){let K=document.createElement("button");K.type="button",K.className="bp-v-btn",K.textContent="Reset",K.addEventListener("click",()=>void Ge("reset","")),W.append(K)}if(V.append(W),R.layerModes){let K=document.createElement("div");K.className="bp-v-layers-modes",["All","Dim","Only"].forEach((we,xe)=>{let Ne=document.createElement("button");Ne.type="button",Ne.className="bp-v-btn"+(R?.layerMode===xe?" is-on":""),Ne.textContent=we,Ne.addEventListener("click",()=>void Ge("mode",String(xe))),K.append(Ne)}),V.append(K)}let G=ue?.presentColors()??new Map,z=(R.layerList||[]).concat(R.layerMarks||[]),ae=document.createElement("div");ae.className="bp-v-layers-list";for(let K of z){let we=G.get(K.layer);if(we===void 0)continue;let xe=document.createElement("div");xe.className="bp-v-layer-row"+(K.active?" is-focus":"");let Ne=document.createElement("input");Ne.type="checkbox",Ne.checked=K.on!==!1,Ne.addEventListener("change",()=>void Ge("toggle",String(K.layer)));let $e=document.createElement("span");$e.className="bp-v-layer-swatch";let Re=we>>>16&255,ve=we>>>8&255,Ue=we&255;$e.style.background=K.on!==!1?`rgb(${Re},${ve},${Ue})`:`rgba(${Re},${ve},${Ue},0.2)`;let Oe=document.createElement("button");Oe.type="button",Oe.className="bp-v-layer-name",Oe.textContent=K.name,Oe.addEventListener("click",()=>void Ge("pick",String(K.layer))),xe.append(Ne,$e,Oe),ae.append(xe)}V.append(ae),u.replaceChildren(V)}async function Ge(V,W){if(!di(y))return;let _=w;try{let G=await t.hub.rpc("viewer.layers",{kind:y,present:re,off:ke,focus:ee,...V?{action:V,value:W}:{}});if(_!==w||!G)return;ke=Number(G.own)||0,ee=typeof G.focus==="string"?G.focus:"",R=G;let z={off:Number(G.off)||0,dim:Number(G.dim)||0,lift:typeof G.lift==="number"?G.lift:255};if(ue?.setLayers(z),Fe(),Se)Be()}catch{}}async function _e(){if(!se||ne||!v||!t.hub.hasFeature("follow"))return;ne=!0,Fe();try{await t.hub.rpc("viewer.follow",{thread:v,action:"pause"})}catch{}}async function Jt(){if(!v||!t.hub.hasFeature("follow"))return;let V=!se?"on":ne?"resume":"off";try{let W=await t.hub.rpc("viewer.follow",{thread:v,action:V});if(se=!!W.on,ne=!!W.paused,Fe(),W.on&&!W.paused&&W.focus&&Array.isArray(W.focus.box)&&W.focus.box.length===4&&(W.seq||0)>he)he=W.seq||he,ue?.zoomToBoxMm([W.focus.box[0],W.focus.box[1],W.focus.box[2],W.focus.box[3]])}catch{}}function st(){f.hidden=!0,f.replaceChildren(),ue?.setHighlights([])}function Yt(V){let W=V.split(";").filter(Boolean),_=W.shift()||V,G=[],z="",ae="";for(let $e of W){if($e.startsWith("g="))continue;let Re=$e.indexOf("=");if(Re>0){let ve=$e.slice(0,Re),Ue=$e.slice(Re+1);if((ve==="ref"||ve==="symbol")&&!z)z=Ue;if(ve==="net"&&!ae)ae=Ue;G.push([ve,Ue])}else G.push([$e,""])}let K=document.createElement("div");K.className="bp-v-info-head";let we=document.createElement("span");we.className="bp-v-info-title",we.textContent=_;let xe=document.createElement("button");xe.type="button",xe.className="bp-v-info-x",xe.textContent="×",xe.setAttribute("aria-label","Clear selection"),xe.addEventListener("click",st),K.append(we,xe);let Ne=document.createElement("div");Ne.className="bp-v-info-rows";for(let[$e,Re]of G){let ve=document.createElement("span");ve.className="bp-v-info-chip",ve.textContent=Re?`${$e}: ${Re}`:$e,Ne.append(ve)}return f.replaceChildren(K,...G.length>0?[Ne]:[]),f.hidden=!1,{ref:z||void 0,net:ae||void 0}}async function At(V){if(!V){st();return}let W=Array.from(L)[0]||"";if(!W)return;let _=w;try{let G=await t.hub.rpc("viewer.info",{key:W,at:V.at,idx:V.idx});if(_!==w)return;let z=typeof G.info==="string"?G.info:"";if(!z){st();return}let{ref:ae,net:K}=Yt(z),we=[];if(ae)we.push(["ref",ae]);if(K)we.push(["net",K]);let xe=[[V.at,V.idx]];for(let[Ne,$e]of we){let Re=await t.hub.rpc("viewer.probe",{key:W,name:Ne,value:$e});if(_!==w)return;if(Array.isArray(Re.matches))for(let ve of Re.matches)xe.push(ve)}ue?.setHighlights(xe)}catch{st()}}function Ce(){Q?.destroy(),Q=null,ge?.destroy(),ge=null,ue?.destroy(),ue=null,le?.destroy(),le=null,h.replaceChildren(),Se=!1,u.hidden=!0,f.hidden=!0,f.replaceChildren(),He("",!1),oe("none")}function ye(){N=[],A=0}async function ct(V){if(!v||!y)return;let W=++w;if(L.clear(),C=!1,ye(),Ce(),Fe(),te(),Ae(),(y==="board"||y==="schematic")&&v)Te(v);if(Oa(y)){if(t.hub.rpc("viewer.watch",{thread:v,kind:""}).catch(()=>{}),y==="files")Q=lr(h,t,v,(z,ae)=>{if(y=z,Y=ae,z==="mech")x=ae;ct(!1)});else if(y==="diff")Q=cr(h,t,v);else if(y==="review")Q=dr(h,t,v);else if(y==="browser")Q=rr(h,t,v);else if(y==="terminal")oe("loading","Loading terminal…"),import("/assets/terminal.js").then((ae)=>{if(W!==w)return;if(oe("none"),ae?.mountTerminalPane)ge=ae.mountTerminalPane(h,t,v,q());else oe("error","Terminal chunk missing",!0)},(ae)=>{if(W!==w)return;oe("error",ae instanceof Error?ae.message:String(ae),!0)});return}if(oe("loading","Loading…"),!j.root)try{let z=await t.hub.rpc("viewer.files",{thread:v});if(W!==w)return;j=z||{},Fe()}catch{}if(y==="gerbers"&&j.hasGerbers===!1){oe("empty","No Gerbers in this project",!1);return}let _=q();if(y==="3d"||y==="mech")le=new ci(h,{onStatus:(z,ae)=>{if(ae)oe("none"),He(z,!1);else if(z)oe("loading",z);else oe("none"),He("",!1)},onUserMove:()=>void _e()}),le.setTheme(_);else if(y==="board"||y==="schematic"||y==="gerbers")ue=new ri(h,{onPick:(z)=>void At(z),onUserMove:()=>void _e()}),ue.setTheme(_);else{oe("empty",`${yr(y)} is not available in this viewer`,!1);return}let G={thread:v};if(V)G.force=!0;if(y==="mech"){if(O.length===0)try{let z=await t.hub.rpc("mech.list",{thread:v});if(W!==w)return;if(O=Array.isArray(z.parts)?z.parts:[],!x)x=z.primary||O[0]||"";Fe()}catch(z){if(W!==w)return;oe("error",z instanceof Error?z.message:String(z),!0);return}if(!x){oe("empty",m("gpui.rail.no.mech","No mechanical parts in this project"),!1);return}G.kind="3d",G.path=x}else{if(G.kind=y,Y&&(y==="board"||y==="schematic"))G.path=Y;if(y==="3d"&&!V&&le){let z=le.keptToken();if(z)G.kept=z}if((y==="board"||y==="schematic"||y==="gerbers")&&!V&&t.hub.hasFeature("keptChunks"))G.keptChunks=Array.from(M.keys())}C=!0,I="",J="",ie="",Ee="";try{let z=await t.hub.rpc("viewer.watch",G);if(W!==w)return;L=new Set(Array.isArray(z.keys)?z.keys:[]),C=!1;let ae=N;ye();for(let K of ae)if(K.kind==="bin")Ze(K.buf);else Je(K.key,K.none,K.retryable,K.big)}catch(z){if(W!==w)return;C=!1,L.clear(),ye();let ae=z instanceof Error?z.message:String(z),K=/no gerbers|not in this project|another machine/i.test(ae);oe(K?"empty":"error",ae,!K)}}function Je(V,W,_,G=!1){if(C){if(N.length{if(V.t==="plot"&&typeof V.none==="string"&&typeof V.key==="string")Je(V.key,V.none,V.retryable===!0)}),rt=en(()=>{if(y)Fe()}),Xt=(V)=>{if(V.key==="Escape"&&y&&!f.hidden)st()};return window.addEventListener("keydown",Xt),{open(V,W){if(W!==v){if(v=W,j={},O=[],x="",B.clear(),se=!1,ne=!1,he=0,ke=0,ee="",re=0,R=null,t.hub.hasFeature("follow"))t.hub.rpc("viewer.follow",{thread:W}).then((_)=>{if(W!==v)return;if(se=!!_.on,ne=!!_.paused,he=Number(_.seq)||0,y)Fe()}).catch(()=>{})}if(V!==y)D(),k.goLive(),ke=0,ee="",re=0,R=null;y=V,Y="",ct(!1)},reconcileHas(V){if(y&&!$a(y,V))t.closeViewer()},close(){if(w++,C=!1,D(),F=!1,I="",J="",ie="",Ee="",k.goLive(),c.hidden=!0,b.hidden=!0,ye(),v)t.hub.rpc("viewer.watch",{thread:v,kind:""}).catch(()=>{});y="",L.clear(),Ce()}}}var wr="http://www.w3.org/2000/svg";function qt(e){let t=document.createElementNS(wr,"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(wr,"path");i.setAttribute("d",n),t.appendChild(i)}return t}function Er(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 Ga(e){if(!e)return"";let t=e<10000000000?e*1000:e,n=Math.max(0,Math.floor((Date.now()-t)/1000));if(n<60)return"now";if(n<3600)return`${Math.floor(n/60)}m`;if(n<86400)return`${Math.floor(n/3600)}h`;return`${Math.floor(n/86400)}d`}function kr(e,t){if(!e)return!0;if(t==="board"||t==="3d")return e.board!==!1;if(t==="schematic")return e.schematic!==!1;if(t==="mech")return e.mech!==!1;if(t==="gerbers")return e.gerbers!==!1;return!0}var Kt="dark",mn=(()=>{try{return $s(localStorage.getItem("bp.theme.pref"))}catch{return"auto"}})(),hi=null,Lt=(()=>{try{return Os(localStorage.getItem("bp.locale"))}catch{return"auto"}})();function Sr(){let e=Gt(mn,Kt);document.documentElement.classList.toggle("light",e==="light");try{localStorage.setItem("bp.theme",e)}catch{}}function Cr(e){if(!e)return;Kt=e==="light"?"light":"dark",Sr()}function xr(){if(Lt!=="auto")vt(Lt);else if(hi)vt(hi);else if(typeof navigator<"u"&&navigator.language){if(!vt(navigator.language))vt("en")}}function Va(){return`web-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`}function Pr(){let e=document.getElementById("root");if(!e)return;try{if(localStorage.getItem("bp.theme")==="light")Kt="light";if(Gt(mn,Kt)==="light")document.documentElement.classList.add("light");if(Lt!=="auto")vt(Lt)}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 p=document.createElement("span");p.className="bp-crumb-thread",p.setAttribute("data-testid","thread-title");let l=document.createElement("span");l.className="bp-plan-top-badge bp-hidden",l.setAttribute("data-testid","plan-top-badge"),i.append(s,r,a,o,c,p,l);let h=document.createElement("div");h.className="bp-top-state bp-hide-phone bp-hidden";let d=document.createElement("span");d.className="bp-top-state-lbl",d.textContent="STATE";let u=document.createElement("span");u.className="bp-dot bp-dot-idle";let f=document.createElement("span");f.className="bp-top-state-word",h.append(d,u,f);let b=document.createElement("div");b.className="bp-top-acts bp-hide-phone bp-hidden";let v=document.createElement("button");v.type="button",v.className="bp-btn-ghost bp-top-act";let y=document.createElement("span");y.textContent=m("menu.pin","Pin"),v.append(qt(["M12 17v5","M9 3h6l1 7 3 3H5l3-3 1-7z"]),y);let w=document.createElement("button");w.type="button",w.className="bp-btn-ghost bp-top-act";let C=document.createElement("span");C.textContent=m("menu.settle","Settle"),w.append(qt(["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 N=document.createElement("button");N.type="button",N.className="bp-btn-ghost bp-top-act",N.textContent="▾",N.title="Thread menu",N.setAttribute("aria-label","Thread menu"),N.setAttribute("data-testid","thread-menu-btn");let A=document.createElement("div");A.className="bp-popover bp-hidden",A.setAttribute("data-testid","thread-menu"),L.append(N,A),b.append(v,w,L);let B=document.createElement("div");B.className="bp-top-right";let M=document.createElement("button");M.type="button",M.className="bp-btn-ghost bp-top-act bp-hide-tablet",M.setAttribute("data-testid","improvements-btn");let j=document.createElement("span");j.textContent=m("gpui.improvements","Improvements"),M.append(qt(["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"]),j);let O=document.createElement("button");O.type="button",O.className="bp-cmd-box bp-hide-tablet",O.textContent="> Jump or run a command";let x=document.createElement("button");x.type="button",x.className="icon bp-top-icon",x.title="Search",x.setAttribute("aria-label","Search"),x.appendChild(qt(["M11 19a8 8 0 1 0 0-16 8 8 0 0 0 0 16z","M21 21l-4.3-4.3"]));let Y=document.createElement("button");Y.type="button",Y.className="icon bp-top-icon",Y.title=m("palette.settings","Settings"),Y.setAttribute("aria-label",m("palette.settings","Settings")),Y.setAttribute("data-testid","settings-btn"),Y.appendChild(qt(["M12 15a3 3 0 1 0 0-6 3 3 0 0 0 0 6z","M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 1 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 1 1-4 0v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 1 1-2.83-2.83l.06-.06a1.65 1.65 0 0 0 .33-1.82 1.65 1.65 0 0 0-1.51-1H3a2 2 0 1 1 0-4h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 1 1 2.83-2.83l.06.06a1.65 1.65 0 0 0 1.82.33H9a1.65 1.65 0 0 0 1-1.51V3a2 2 0 1 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 1 1 2.83 2.83l-.06.06a1.65 1.65 0 0 0-.33 1.82V9c.26.6.85 1 1.51 1H21a2 2 0 1 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z"])),B.append(M,O,x,Y),t.append(n,i,h,b,B);let se=document.createElement("div");se.className="bp-body";let ne=document.createElement("aside");ne.className="bp-sidebar",ne.setAttribute("data-testid","sidebar");let he=document.createElement("main");he.className="bp-center";let Se=document.createElement("div");Se.className="bp-right-area bp-hidden",Se.setAttribute("data-testid","right-area");let ke=document.createElement("div");ke.className="bp-right-top";let ee=document.createElement("section");ee.className="bp-viewer-pane bp-hidden",ee.setAttribute("data-testid","viewer-pane"),ke.appendChild(ee),Se.appendChild(ke);let re=document.createElement("nav");re.className="bp-rail",re.setAttribute("aria-label","Viewer rail"),re.setAttribute("data-testid","viewer-rail"),se.append(ne,he,Se,re),e.append(t,se);let R=new ii,ue=null,le=new Set,Q=0,ge=null,k=[],P=[],F=[],I=[],J=[],ie=[],Ee=[],D="",te=0,Me=0,Ae=null,Te=null,q="",fe=null,oe=20,He={},De=new Map;function Fe(g,E){De.delete(g),De.set(g,E);while(De.size>oe){let S=De.keys().next().value;if(S!==void 0)De.delete(S);else break}}let Be="",Ge=0,_e=new Gn(he,{onNewThread:(g)=>{Tt(g)},onOpenThread:(g)=>{ze(g)},onOpenViewer:(g,E)=>{ze(g).then(()=>{if(D===g)Oe(E)})},onRetry:(g)=>{At(g)}});function Jt(){if(!Be)return;Be="",Ge++,he.classList.remove("bp-home-open"),_e.hide(),Ce.setSelectedProject(""),ve()}function st(g){return k.find((E)=>E.id===g)??k.find((E)=>On(E.id)===g)}async function Yt(g,E){try{let S=await R.rpc("threads.list",{project:g,limit:50,archived:!1});if(E!==Ge||Be!==g)return;let T=(S.threads??[]).filter((H)=>!H.swarm).map((H)=>({id:H.id,title:H.title,dot:Er(H),status:H.status||H.state||"",age:Ga(H.updatedAt),settled:H.settled}));_e.setThreads(T)}catch{if(E===Ge&&Be===g)_e.setThreads([])}}function At(g){if(!g||!R.hasFeature("projecthome"))return!1;Ze.cancel(),de.closeModelPicker(),Be=g;let E=++Ge,S=st(g);return he.classList.add("bp-home-open"),ne.classList.remove("bp-sidebar-open"),_e.show({id:g,title:S?.title??g}),Ce.setSelectedProject(g),ve(),Yt(g,E),R.rpc("project.home",{project:g}).then((T)=>{if(E===Ge&&Be===g)_e.setData(Ls(T))}).catch((T)=>{if(E!==Ge||Be!==g)return;_e.setError(T instanceof Error&&T.message?T.message:m("web.home.error","Could not load this project."))}),!0}let Ce=new ei(ne,{onSelectThread:(g)=>{if(g===D&&Ae!==null){Jt(),ne.classList.remove("bp-sidebar-open");return}ze(g)},onNewThread:(g)=>{Tt(g)},onOpenProject:(g)=>At(On(g)),canOpenProject:()=>R.hasFeature("projecthome"),onSelectBot:(g)=>{ze(g.thread)},onQuickOpenViewer:(g,E)=>{let S=P.find((H)=>H.project===g&&!H.archived&&!H.swarm);(async()=>{if(S)await ze(S.id);else await Tt(g);if(D)q=E,G.setActive(E),fe?.open(E,D)})()},onThreadAct:(g,E)=>{dt(g,E)},onSnoozeRow:(g)=>{R.rpc("sidebar.act",{action:"row-snooze",value:g}).then(()=>Ye()).catch(()=>{})},onToggleSection:(g)=>{if(le.has(g))le.delete(g);else le.add(g);Ye()},onToggleProjectFold:(g)=>{R.rpc("sidebar.act",{action:"project-fold",value:g}).then(()=>Ye()).catch(()=>{})},onCollapseSidebar:()=>{ne.classList.remove("bp-sidebar-open"),ne.classList.add("bp-sidebar-collapsed")},onNeedAct:async(g)=>{let E=dn(g,!1);if(!E)return;if(E.kind==="thread"){ze(E.id);return}if(E.kind!=="call")return;let S=Fs(await R.rpc(E.method,E.params));if(S?.kind==="thread")ze(S.id);Ye()},hasRoomView:!1,onAddProject:()=>_.open({mode:"folder"}),onSettleSwarm:(g)=>{R.rpc("sidebar.act",{action:"swarm-settle",value:g}).then(()=>Ye()).catch(()=>{})}}),ye=new Pn(he,{onLoadOlder:()=>{bi()},onGoToEntry:(g)=>{mi(g)},onOpenAccounts:()=>{xe()},onAnswerAsk:(g,E)=>{R.rpc("ask.answer",{ask:g,answer:E}).catch((S)=>{de.showError(S instanceof Error?S.message:"Could not send answer")})},onToggleReview:(g)=>{if(!D)return;let E=te;R.rpc("thread.review",{thread:D,on:g}).then((S)=>{if(E===te)ye.setReview(S.review??null)}).catch(()=>{})},onUnansweredAction:(g,E)=>{if(!D)return;if(g==="again"||g==="thread-again")R.rpc("thread.again",{thread:D,value:E}).catch(()=>{});else R.rpc("thread.act",{thread:D,action:g,value:E}).catch(()=>{})},onReplyEntry:(g)=>{if(!R.hasFeature("reply")){let E=(g.text||"").split(` `)[0]?.slice(0,100)??"";if(E)de.prependDraft(`> ${E} -`);return}if(!v.text||!v.text.trim()||v.live||v.id.startsWith("local-"))return;At({id:v.id,text:v.text,role:v.kind==="user"?"user":"assistant"})},onLoadImage:async(v,E)=>{try{let M={entry:v,path:E};if(R.hasFeature("blobs"))M.metaOnly=!0;let N=await R.rpc("message.image",M);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 tt(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 st(v,E){if(!D)return;let M=ne,N=D;R.rpc(v,E).then((F)=>{if(M!==ne||D!==N)return;if(F.thread){let te=x.findIndex((ye)=>ye.id===F.thread.id);if(te>=0)x[te]=F.thread;else x.unshift(F.thread);ge.setData(k,x,H,B),fe.updateThreadMeta(F.thread),Z(),de.setState(!0,F.thread.state==="working")}}).catch((F)=>{if(M===ne&&D===N)de.showError(F instanceof Error?F.message:"Could not change Plan mode")})}let Je,de=new wn(be,{onSend:(v,E)=>{ti(v,E)},onRunCommand:(v)=>{ni(v)},onInterrupt:()=>{if(D)R.rpc("turn.interrupt",{thread:D}).catch(()=>{})},onQueryMentions:async(v,E)=>{try{return(await R.rpc("mentions.list",{q:v,kind:E,limit:10})).items??[]}catch{return[]}},onToggleVoice:()=>{Je.toggle()},onCyclePlanMode:()=>{let v=x.find((M)=>M.id===D)??null,E=tt(v);if(!E||!D)return;if(E.interaction!=="plan")st("thread.planonce",{thread:D,on:!0});else if(E.once)st("thread.pick",{thread:D,action:"interaction",value:"plan"});else st("thread.pick",{thread:D,action:"interaction",value:"default"})},onSetPlanMode:(v)=>{if(!D)return;if(v==="once")st("thread.planonce",{thread:D,on:!0});else if(v==="always")st("thread.pick",{thread:D,action:"interaction",value:"plan"});else st("thread.pick",{thread:D,action:"interaction",value:"default"})},getFavoriteModels:()=>K,onLoadModelPicker:async()=>{if(!D)return null;return R.rpc("thread.picker",{thread:D})},onSelectModel:async(v,E)=>{if(!D)return;let M=ne,N=D;try{let F=await R.rpc("thread.model",{thread:N,provider:v,model:E});if(M!==ne||D!==N)return;if(F.thread){let te=x.findIndex((ye)=>ye.id===F.thread.id);if(te>=0)x[te]=F.thread;else x.unshift(F.thread);ge.setData(k,x,H,B),fe.updateThreadMeta(F.thread),Z(),de.setState(!0,F.thread.state==="working")}}catch(F){if(M===ne&&D===N)de.showError(F instanceof Error?F.message:"Could not switch model")}},onSelectEffort:async(v)=>{if(!D)return;let E=ne,M=D;try{let N=await R.rpc("thread.pick",{thread:M,action:"effort",value:v});if(E!==ne||D!==M)return;if(N.thread){let F=x.findIndex((te)=>te.id===N.thread.id);if(F>=0)x[F]=N.thread;else x.unshift(N.thread);ge.setData(k,x,H,B),fe.updateThreadMeta(N.thread),Z()}}catch(N){if(E===ne&&D===M)de.showError(N instanceof Error?N.message:"Could not set effort")}},onToggleFavorite:async(v,E,M)=>{let N=await R.rpc("models.favorite",{provider:v,model:E,on:M});if(Array.isArray(N.favorites))return K=N.favorites,K;return null}});Je=new On(R,{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 St(){let v=q!=="",E=Xe.isOpen();Pe.classList.toggle("bp-hidden",!v&&!E),Pe.classList.toggle("bp-has-viewer",v),Pe.classList.toggle("bp-has-mgmt",E)}let Xe=new Ln(Ee,Pe,{hub:R,getThreadId:()=>D,getThreadGen:()=>ne,onSendText:(v)=>{ti(v)},onOpenChange:()=>St()});function Ye(v){let E=window.prompt("Rename thread",v.title||"");if(!E||!E.trim())return;R.rpc("thread.act",{thread:v.id,action:"rename",title:E.trim()}).then((M)=>{if(M.thread)x=x.map((N)=>N.id===M.thread.id?M.thread:N),Z(),ke()}).catch((M)=>{de.showError(M instanceof Error?M.message:"Could not rename thread")})}function lt(v){switch(v.type){case"thread":Ge(v.id);break;case"rail":if(!D&&v.id!=="terminal")break;if(q===v.id)J();else ve(v.id);break;case"thread-act":if(D)rt(D,v.action);break;case"new-thread":qt(v.projectId);break;case"rename":{let E=x.find((M)=>M.id===D);if(E)Ye(E);break}case"prev-thread":case"next-thread":{let E=x.filter((te)=>!te.archived&&!te.swarm);if(E.length<2)break;let M=E.findIndex((te)=>te.id===D),N=v.type==="next-thread"?1:-1,F=E[(M<0?0:M+N+E.length)%E.length];if(F)Ge(F.id);break}case"command":if(v.runDirectly)ni(v.word);else de.setDraft(`${v.word} `),de.focus();break;case"improvements":z();break;case"settings":Oe.open();break;case"sidebar":se.classList.toggle("bp-sidebar-open"),se.classList.toggle("bp-sidebar-collapsed");break}}let _e=new Nn(e,{getState:()=>({selectedThreadId:D,threads:x,projects:k,bots:H,railItems:ie,commands:we}),onSearch:async(v)=>{if(!R.hasFeature("search"))return{threads:[],projects:[],messages:[]};return R.rpc("search",{q:v,limit:20})},onExecute:lt}),qe=new hn(e,{hub:R,onProjectAdded:(v)=>{if(ke(),v.id)qt(v.id)},onCloneDone:(v)=>{if(ke(),v.thread)Ge(v.thread)}}),ze=new Tn(ae,(v)=>{if(v==="commands"){_e.open();return}if(!D)return;if(q===v)J();else ve(v)}),ct=null,_t=null,Oe=new Dn(e,{onLoadDevices:async()=>(await R.rpc("devices.page",{})).rows??[],onDevicesAct:async(v,E)=>{await R.rpc("devices.page.act",{action:v,value:E})},onGetHome:()=>ct,onMoveHomeHere:async()=>{await R.rpc("home.move",{to:"back"})},onGetNoProvider:()=>_t,onGetThemePref:()=>ln,onSetThemePref:(v)=>{ln=v;try{if(v==="auto")localStorage.removeItem("bp.theme.pref");else localStorage.setItem("bp.theme.pref",v)}catch{}Qs()},onGetHubTheme:()=>Wt,onGetLocalePref:()=>Pt,onSetLocalePref:(v)=>{Pt=v;try{if(v==="auto")localStorage.removeItem("bp.locale");else localStorage.setItem("bp.locale",v)}catch{}Ys()},onLogout:()=>Pi(()=>{R.disconnect(),window.location.replace("/")})});function O(v){if(_t=v,fe.setNoProvider(v),Oe.isOpen())Oe.refresh()}function _(){Oe.openToAccounts()}function W(v,E){let M=v instanceof Error?v.message:E,N=v instanceof Ot?v:null,F=N?.code,te=N?.machine,ye=F==="no_provider_remote"&&te?h("provider.notice.senderr.remote","No AI provider connected on {machine}. Open Settings → Accounts on {machine} to connect Claude, Codex, Antigravity, or another provider.").replaceAll("{machine}",te):M;de.showError(ye,cs(M,F)?{label:h("provider.notice.button","Open Settings → Accounts"),onClick:_}:void 0)}g.addEventListener("click",()=>{let v=x.find((E)=>E.id===D);if(v)rt(v.id,v.pinned?"unpin":"pin")}),w.addEventListener("click",()=>{let v=x.find((E)=>E.id===D);if(v)rt(v.id,v.settled?"unsettle":"settle")});let U=new Fn(e,(v,E)=>E?R.rpc("thread.context.mcp",{thread:v,...E}):R.rpc("thread.context",{thread:v}));S.addEventListener("click",(v)=>{v.stopPropagation();let E=x.find((F)=>F.id===D);if(!E)return;if(!T.classList.contains("bp-hidden")){T.classList.add("bp-hidden");return}let M=[{label:"Rename…",run:()=>Ye(E)},{label:E.pinned?h("menu.unpin","Unpin"):h("menu.pin","Pin"),run:()=>{rt(E.id,E.pinned?"unpin":"pin")}},{label:E.settled?h("phone.unsettle","Unsettle"):h("menu.settle","Settle"),run:()=>{rt(E.id,E.settled?"unsettle":"settle")}},{label:E.archived?"Unarchive":"Archive",run:()=>{rt(E.id,E.archived?"unarchive":"archive")}},{label:"Delete",danger:!0,run:()=>{if(window.confirm("Delete this thread?"))rt(E.id,"delete")}}];if(R.hasFeature("threadContext"))M.unshift({label:h("thread.context.title","Context & Prompt"),run:()=>U.open(E.id)});let N=document.createDocumentFragment();for(let F of M){let te=document.createElement("button");te.type="button",te.className="bp-popover-item"+(F.danger?" danger":""),te.textContent=F.label,te.addEventListener("click",()=>{T.classList.add("bp-hidden"),F.run()}),N.appendChild(te)}T.replaceChildren(N),T.classList.remove("bp-hidden")}),document.addEventListener("click",()=>T.classList.add("bp-hidden"));async function z(){let v=document.createElement("div");v.className="bp-modal-backdrop",v.setAttribute("data-testid","improvements-modal");let E=document.createElement("div");E.className="bp-modal";let M=document.createElement("div");M.className="bp-modal-head";let N=document.createElement("h2");N.textContent=h("gpui.improvements","Improvements");let F=document.createElement("button");F.type="button",F.className="icon",F.textContent="×",F.addEventListener("click",()=>v.remove()),M.append(N,F);let te=document.createElement("div");te.className="bp-modal-body",te.textContent="Loading…",E.append(M,te),v.appendChild(E),v.addEventListener("click",(ye)=>{if(ye.target===v)v.remove()}),e.appendChild(v);try{let ye=await R.rpc("improvements.projects",{}),Fe=ye.projects??[];if(Fe.length===0){te.textContent="No projects available for Improvements.";return}let at=document.createDocumentFragment();for(let Le of Fe){let ce=document.createElement("div");ce.className="bp-set-row";let nt=document.createElement("div");nt.className="bp-set-info",nt.textContent=Le.title||Le.name||Le.id;let ot=document.createElement("button");ot.type="button",ot.className=Le.id===ye.project?"primary":"",ot.textContent=Le.id===ye.project?"Active":"Select",ot.addEventListener("click",()=>{R.rpc("improvements.project",{project:Le.id}).then(()=>v.remove()).catch(()=>{})}),ce.append(nt,ot),at.appendChild(ce)}te.replaceChildren(at)}catch(ye){te.textContent=ye instanceof Error?ye.message:"Could not load Improvements."}}P.addEventListener("click",()=>{z()}),G.addEventListener("click",()=>_e.open()),L.addEventListener("click",()=>_e.open()),Y.addEventListener("click",()=>{Oe.open()}),n.addEventListener("click",()=>{se.classList.toggle("bp-sidebar-open"),se.classList.toggle("bp-sidebar-collapsed")});function Z(){let v=x.find((N)=>N.id===D)??null,E=v?k.find((N)=>N.id===v.project):void 0;o.textContent=E?.title??"",a.classList.toggle("bp-hidden",!E),c.classList.toggle("bp-hidden",!v),p.textContent=v?v.title||"Untitled thread":"";let M=tt(v);if(de.setPlanMode(M),!M||M.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",M.phase==="executing"),l.title=h("gpui.planmode.tip","Plan before acting (1 turn, always, or off)"),l.textContent=M.phase==="armed"&&M.once?h("gpui.planmode.top.once","Plan (1 turn)"):M.phase==="armed"?h("gpui.mgmt.plan.tab","Plan"):M.phase==="planning"?h("gpui.planmode.top.planning","Planning"):M.phase==="pending"?h("gpui.planmode.top.pending","Review plan"):h("gpui.planmode.top.executing","Building plan");if(u.classList.toggle("bp-hidden",!v),b.classList.toggle("bp-hidden",!v),v){m.className=`bp-dot ${ma(v)}`,f.textContent=v.status||v.state||"idle",y.textContent=v.pinned?h("menu.unpin","Unpin"):h("menu.pin","Pin"),C.textContent=v.settled?h("phone.unsettle","Unsettle"):h("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 J(v=!0){if(Ne++,q="",ze.setActive(""),ee.classList.add("bp-hidden"),he?.close(),St(),v&&D&&R.getState()==="connected")R.rpc("viewer.watch",{thread:D,kind:""}).catch(()=>{})}function ve(v){if(Ne++,q=v,ze.setActive(v),ee.classList.remove("bp-hidden"),St(),!he&&typeof Yn==="function")he=Yn(ee,{hub:R,getThreadId:()=>D,closeViewer:()=>J(!0)});if(he)he.open(v,D);else{let E=document.createElement("div");E.className="bp-viewer-placeholder";let M=document.createElement("div");M.className="bp-viewer-bar";let N=document.createElement("span");N.textContent=v.toUpperCase();let F=document.createElement("button");F.type="button",F.className="icon",F.textContent="×",F.addEventListener("click",()=>J(!0)),M.append(N,F);let te=document.createElement("div");te.className="bp-dim bp-viewer-msg",te.textContent=`Viewer pane (${v}).`,E.append(M,te),ee.replaceChildren(E)}}async function Ce(v,E){if(!v||!R.hasFeature("rail")){if(E===ne)ie=[],ze.setItems([]);return}let M=++Ne;try{let N=await R.rpc("viewer.rail",{thread:v,page:q});if(E!==ne||M!==Ne)return;let F=Array.isArray(N.rail)?N.rail:Array.isArray(N.items)?N.items:[];if(ie=F,ze.setItems(F),N.has){if(he?.reconcileHas?.(N.has),q&&!Js(N.has,q))J(!0)}}catch{if(E===ne&&M===Ne)ie=[],ze.setItems([])}}function Te(v){for(let E of v)if(E.kind==="threads"){for(let M of E.rows)if(!M.off&&(M.nav||M.id)&&!(M.nav||"").startsWith("@room:"))return M.nav||M.id}else if(E.kind==="projects"){for(let M of E.rows)for(let N of M.threads??[])if(!N.off&&(N.nav||N.id)&&!(N.nav||"").startsWith("@room:"))return N.nav||N.id}return""}function De(v,E){for(let M of v)if(M.kind==="threads"){if(M.rows.some((N)=>(N.nav||N.id)===E))return!0}else if(M.kind==="projects"){for(let N of M.rows)if((N.threads??[]).some((F)=>(F.nav||F.id)===E))return!0}return!1}function Be(v){let E=[];for(let M of v){if(M.kind!=="projects")continue;for(let N of M.rows)E.push({id:N.id,title:N.title,css:N.css,color:N.color})}if(E.length>0)k=E}async function ke(){if(!R.hasFeature("sections"))return!1;let v=++Q;try{let E=await R.rpc("sidebar.sections",{open:Array.from(le)});if(v!==Q)return!0;let M=Array.isArray(E.sections)?E.sections:[];return ue=M,Be(M),ge.setData(k,x,H,B),ge.setSections(M,H,B),Z(),!0}catch{return!1}}function Ve(){if(!R.hasFeature("sections"))return;if(me!==null)window.clearTimeout(me);me=window.setTimeout(()=>{me=null,ke()},150)}async function Ue(){if(Ae=null,R.hasFeature("bots"))try{let E=await R.rpc("bots.list",{});H=E.bots??[],B=E.rooms??[]}catch{}if(R.hasFeature("shell")){let E=await R.rpc("shell.sync",{have:Re,settled:25}),M=new Set(E.removed??[]),N=new Set((E.projects??[]).map((F)=>F.id));if(M.size>0||N.size>0)k=[...k.filter((F)=>!M.has(F.id)&&!N.has(F.id)),...E.projects??[]],x=[...x.filter((F)=>!M.has(F.project)&&!N.has(F.project)),...E.threads??[]];else if(Array.isArray(E.threads)&&E.threads.length>0){let F=new Map(x.map((te)=>[te.id,te]));for(let te of E.threads)F.set(te.id,te);x=Array.from(F.values())}if(E.sections!==void 0){let F=Array.isArray(E.sections)?E.sections:Array.isArray(E.sections?.sections)?E.sections.sections:null;if(F)ue=F,Be(F)}if(E.h)Re=E.h;ge.setData(k,x,H,B),ge.setSections(ue,H,B)}else if(R.hasFeature("sections")){let[E,M]=await Promise.all([R.rpc("sidebar.sections",{open:Array.from(le)}).catch(()=>null),R.rpc("threads.list",{limit:200,archived:!1}).catch(()=>({threads:[]}))]);if(x=M.threads??[],E&&Array.isArray(E.sections)){let N=E.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&&!le.has(te.toggle)){le.add(te.toggle);let ye=await R.rpc("sidebar.sections",{open:Array.from(le)}).catch(()=>null);if(ye&&Array.isArray(ye.sections))N=ye.sections}}ue=N,Be(N),ge.setData(k,x,H,B),ge.setSections(N,H,B)}else ue=null,k=(await R.rpc("projects.list",{limit:100})).projects??[],ge.setSections(null,H,B),ge.setData(k,x,H,B);await R.rpc("subscribe",{topic:"lists"}).catch(()=>{})}else{ue=null;let[E,M]=await Promise.all([R.rpc("projects.list",{limit:100}),R.rpc("threads.list",{limit:200,archived:!1})]);k=E.projects??[],x=M.threads??[],ge.setSections(null,H,B),ge.setData(k,x,H,B),await R.rpc("subscribe",{topic:"lists"}).catch(()=>{})}let v=D;if(!v){let E="";try{E=localStorage.getItem("bp.lastThread")||""}catch{}if(E&&(ue&&De(ue,E)||x.some((M)=>M.id===E)))v=E;else if(ue)v=Te(ue);if(!v)v=(x.find((N)=>!N.archived&&!N.swarm&&!N.settled)??x.find((N)=>!N.archived&&!N.swarm))?.id??""}if(v&&(ue&&De(ue,v)||x.some((E)=>E.id===v)))await Ge(v);else D="",ie=[],ze.setItems([]),de.setState(!1,!1),Z()}async function Ge(v){if(D&&D!==v){Je.cancel();let Le=fe.getEntries();if(Le.length>0){let ce=je.get(D);He(D,{entries:Le,ids:ce?.ids??Le.map((nt)=>nt.id),olderCursor:Me,review:ce?.review??null,unanswered:ce?.unanswered??null,rail:ce?.rail??ie,hashes:ce?.hashes??{}})}}let E=++ne;Ne++,At(null);let M=Ae;if(Ae=null,M!==null)R.rpc("unsubscribe",{sub:M}).catch(()=>{});D=v,de.closeModelPicker();let N=je.get(v);Me=N?.olderCursor??null;try{localStorage.setItem("bp.lastThread",v)}catch{}ge.setSelected(v),se.classList.remove("bp-sidebar-open"),Z();let F=x.find((Le)=>Le.id===v)??null;if(N)fe.setThread(F,N.entries,Boolean(N.olderCursor),N.review,N.unanswered),ie=N.rail,ze.setItems(N.rail);else fe.setLoading(F),ie=[],ze.setItems([]);if(de.setState(!0,F?.state==="working"),R.hasFeature("open")){let Le={};if(N){for(let[Ie,Nt]of Object.entries(N.hashes))Le[Ie]=Nt;for(let Ie of N.entries)if(Ie.h)Le[Ie.id]=Ie.h}let ce;try{ce=await R.rpc("thread.open",{thread:v,limit:40,have:Le})}catch(Ie){if(E===ne){let Nt=Ie instanceof Error&&Ie.message?Ie.message:"Could not load messages.";fe.setError(F,Nt,()=>{Ge(v)})}return}if(E!==ne){if(ce.sub!==void 0&&ce.sub!==null)R.rpc("unsubscribe",{sub:ce.sub}).catch(()=>{});return}if(Ae=ce.sub??null,ce.thread){F=ce.thread;let Ie=x.findIndex((Nt)=>Nt.id===ce.thread.id);if(Ie>=0)x[Ie]=ce.thread;else x.unshift(ce.thread);Z(),de.setState(!0,F.state==="working")}if("next"in ce)Me=ce.next??null;let nt=new Map;if(N)for(let Ie of N.entries)nt.set(Ie.id,Ie);for(let Ie of ce.entries??[])nt.set(Ie.id,Ie);let ot=ce.ids??N?.ids??(ce.entries??[]).map((Ie)=>Ie.id),si=ot.map((Ie)=>nt.get(Ie)).filter((Ie)=>Boolean(Ie)),Lt=N?.rail??[];if(ce.rail!==void 0){if(Array.isArray(ce.rail))Lt=ce.rail;else if(Lt=Array.isArray(ce.rail?.rail)?ce.rail.rail:Array.isArray(ce.rail?.items)?ce.rail.items:[],ce.rail?.has){if(he?.reconcileHas?.(ce.rail.has),q&&!Js(ce.rail.has,q))J(!0)}}ie=Lt,ze.setItems(Lt);let cn=N?.review??null;if(R.hasFeature("reviewmode"))try{let Ie=await R.rpc("thread.review",{thread:v});if(E!==ne)return;cn=Ie.review??null}catch{}if(E!==ne)return;let ri="unanswered"in ce?ce.unanswered??null:N?.unanswered??null,er=ce.h??N?.hashes??{};if(He(v,{entries:si,ids:ot,olderCursor:Me,review:cn,unanswered:ri,rail:Lt,hashes:er}),fe.setThread(F,si,Boolean(Me),cn,ri),zt(v,E),q)ve(q);return}let te;try{te=await R.rpc("thread.entries",{thread:v,limit:40})}catch(Le){if(E===ne){let ce=Le instanceof Error&&Le.message?Le.message:"Could not load messages.";fe.setError(F,ce,()=>{Ge(v)})}return}if(E!==ne)return;if(te.thread){let Le=x.findIndex((ce)=>ce.id===te.thread.id);if(Le>=0)x[Le]=te.thread;else x.unshift(te.thread);Z()}Me=te.next??null;let ye=null;if(R.hasFeature("reviewmode"))try{let Le=await R.rpc("thread.review",{thread:v});if(E!==ne)return;ye=Le.review??null}catch{}if(E!==ne)return;let Fe=te.entries??[],at=te.unanswered??null;He(v,{entries:Fe,ids:Fe.map((Le)=>Le.id),olderCursor:Me,review:ye,unanswered:at,rail:N?.rail??[],hashes:N?.hashes??{}}),fe.setThread(F,Fe,Boolean(Me),ye,at);try{let ce=(await R.rpc("subscribe",{topic:"thread",thread:v})).sub??null;if(ce!==null){if(E!==ne){R.rpc("unsubscribe",{sub:ce}).catch(()=>{});return}Ae=ce}}catch{}if(E!==ne)return;if(Ce(v,E),zt(v,E),q)ve(q)}async function zt(v,E){if(!v||!R.hasFeature("mgmt")){if(E===ne)Xe.clear();return}let M=x.find((F)=>F.id===v),N=M?.project?k.find((F)=>F.id===M.project)?.root??"":"";if(!N&&R.hasFeature("viewers"))try{let F=await R.rpc("viewer.files",{thread:v});if(E!==ne)return;N=F.pcb||F.sch||F.root||""}catch{}if(E!==ne)return;if(N)await Xe.watchProject(N);else Xe.clear()}async function Ze(v){let E=ne;for(let M=0;M<25&&E===ne;M++){if(fe.goTo(v))return;if(!Me)return;let N=Me;if(await Qn(),Me===N)return}}async function Qn(){if(!D||!Me){fe.clearLoadingOlder();return}let v=ne,E=D,M=Me;try{let N=await R.rpc("thread.entries",{thread:E,limit:40,before:M});if(v!==ne||D!==E)return;Me=N.next??null,fe.prependEntries(N.entries??[],Boolean(Me))}catch{if(v===ne)fe.clearLoadingOlder()}}async function qt(v){try{let E=await R.rpc("thread.create",{project:v});if(E.thread)x=[E.thread,...x.filter((M)=>M.id!==E.thread.id)],ge.setData(k,x,H,B),ke(),await Ge(E.thread.id),de.focus()}catch(E){W(E,"Could not create thread")}}let bt=null;function ei(v){return(v.split(` -`).map((E)=>E.trim()).find((E)=>E.length>0)??"").slice(0,200)}function At(v){bt=v,de.setReply(v?{who:v.role==="user"?h("secret.you","You"):h("model.col.agent","Agent"),line:ei(v.text)}:null,()=>{if(bt)Ze(bt.id)},()=>At(null))}async function ti(v,E=[]){if(!D)return;let M=ne,N=D,F=ha(),te=`local-${F}`,ye=bt&&v.trim()&&R.hasFeature("reply")?bt:null;if(ye)At(null);fe.upsertEntry({id:te,kind:"user",text:v,at:Date.now(),clientId:F,...ye?{replyTo:{id:ye.id,quote:ei(ye.text)}}:{},attachments:E.map((Fe)=>({name:Fe.name,mime:Fe.mime,previewUrl:`data:${Fe.mime};base64,${Fe.data}`}))});try{let Fe={thread:N,text:v,clientId:F};if(E.length>0)Fe.attachments=E;if(ye)Fe.replyTo={id:ye.id,text:ye.text};let at=await R.rpc("message.send",Fe);if(M!==ne||D!==N)return;if(at.entry)fe.upsertEntry(at.entry)}catch(Fe){if(M===ne&&D===N){if(fe.removeEntry(te),de.setDraft(v),ye&&!bt)At(ye);W(Fe,"Failed to send message")}}}async function ni(v){if(!D)return;let E=ne,M=D;try{let N=await R.rpc("composer.run",{thread:M,text:v});if(E!==ne||D!==M)return;if(N.error)de.setDraft(v),W(new Ot(N.error,{code:N.errorCode,machine:N.machine}),N.error);else if(N.kind==="btw"&&typeof N.a==="string")fe.showBtw(N.q??"",N.a);else if(N.kind==="edit"&&typeof N.text==="string")de.setDraft(N.text);else if(N.kind==="project")qe.open({mode:"folder"});else if(N.kind==="clone")qe.open({mode:"clone",repo:N.repo??"",text:N.text??""})}catch(N){if(E===ne&&D===M)de.setDraft(v),W(N,"Command refused")}}async function rt(v,E){try{let M=await R.rpc("thread.act",{thread:v,action:E});if(M.thread){if(x=x.map((N)=>N.id===M.thread.id?M.thread:N),ge.setData(k,x,H,B),M.thread.id===D)fe.updateThreadMeta(M.thread),Z()}ke()}catch(M){de.showError(M instanceof Error?M.message:`Action "${E}" not allowed`)}}function ii(v,E){if(!v||!v.text||E-v.at>=300000)return"";let M=v.build.split("-").pop()??"";if(v.reason==="build"&&M)return h("hub.restarting.build",v.text,{build:M});if(v.reason==="stop")return h("hub.stopped",v.text);return h("hub.restarting",v.text)}function Kt(v){if(v==="connected")ge.setConnStatus(h("gpui.acct.connected","Connected"),"bp-ok");else if(v==="reconnecting"&&ii(R.restarting,Date.now()))ge.setConnStatus(ii(R.restarting,Date.now()),"");else if(v==="reconnecting")ge.setConnStatus("Reconnecting…","bp-warn");else if(v==="revoked")ge.setConnStatus(h("gpui.acct.sign.in.expired","Sign-in expired"),"bp-bad");else ge.setConnStatus("Connecting…","")}Jt(()=>{Kt(R.getState()),j.textContent=h("gpui.improvements","Improvements"),Y.title=h("palette.settings","Settings"),Y.setAttribute("aria-label",h("palette.settings","Settings")),Z(),ge.refreshLocale(),fe.refreshLocale(),de.refreshLocale(),ze.render(),Oe.refreshLocale(),qe.refreshLocale()}),R.onState((v,E)=>{if(v==="connected"&&E){if(E.locale)Zn=E.locale,Ys();if(E.theme)Xs(E.theme);if(E.name)ge.setHostName(E.name);if(Array.isArray(E.favoriteModels))K=E.favoriteModels,de.updateFavoriteModels(K);if(ct=E.home??null,ge.setHome(ct),O(Mn(E.noProvider)),Oe.isOpen())Oe.refresh();Kt(v);let M=typeof E.hubBack==="string"?String(E.hubBack):"";if(M)try{let N=JSON.parse(M);if(N.reason==="crash")ge.setConnStatus(h("hub.back.crash",N.text??""),"bp-warn"),window.setTimeout(()=>Kt(R.getState()),6000)}catch{}if(de.setFeatures(R.hasFeature("images"),R.hasFeature("voice")),Array.isArray(E.commands))we=E.commands,de.setCommands(we);else we=[];Ue(),qe.reconcile()}else Je.cancel(),Kt(v)}),R.onFrame((v)=>{if(v.t==="voice"){Je.handleFrame(v);return}if(v.t==="info"&&v.info&&typeof v.info==="object"){let M=v.info;if(Object.prototype.hasOwnProperty.call(M,"provider.notice"))O(Mn(M["provider.notice"]));Xe.handleInfo(M);return}if(v.t!=="d")return;let E=v;if(E.k==="clone"||E.k==="clone.repos"||E.k==="clone.signin"){qe.handleFrame(E);return}switch(E.k){case"project":{let M=E.project;if(!M)break;let N=k.findIndex((F)=>F.id===M.id);if(N>=0)k[N]=M;else k.unshift(M);ge.setData(k,x,H,B),Z(),Ve();break}case"thread":{let M=E.thread;if(!M)break;let N=x.findIndex((F)=>F.id===M.id);if(N>=0)x[N]=M;else x.unshift(M);if(ge.setData(k,x,H,B),M.id===D)fe.updateThreadMeta(M),Z(),de.setState(!0,M.state==="working");Ve();break}case"thread.removed":{let M=String(E.id??"");x=x.filter((N)=>N.id!==M),ge.setData(k,x,H,B),Ve();break}case"entry":{if(E.thread===D&&E.entry)fe.upsertEntry(E.entry);break}case"text":{if(E.thread===D)fe.appendLiveText(String(E.entry??""),String(E.append??""),Number(E.at??Date.now()));break}case"turn":{if(E.thread===D){let M=String(E.state??"idle");de.setState(!0,M==="working"),Ce(D,ne)}Ve();break}case"btw":{if(E.thread===D)fe.showBtw(String(E.q??""),String(E.a??""));break}case"unanswered":{if(E.thread===D)fe.setUnanswered(E.unanswered??null);break}case"theme":{if(typeof E.theme==="string")Xs(E.theme);break}case"home":{if(ct=E.home??null,ge.setHome(ct),Oe.isOpen())Oe.refresh();break}case"favorites":{if(Array.isArray(E.favorites))K=E.favorites.filter((M)=>typeof M==="string"),de.updateFavoriteModels(K);break}default:break}}),window.addEventListener("keydown",(v)=>{let E=v.key.toLowerCase();if((v.ctrlKey||v.metaKey)&&(E==="k"||v.shiftKey&&E==="p"))if(v.preventDefault(),_e.isOpen())_e.close();else _e.open();else if(v.key==="Escape"){if(_e.isOpen())_e.close();else if(de.isModelPickerOpen())de.closeModelPicker();else if(qe.isOpen())qe.escape();else if(Oe.isOpen())Oe.handleEscape();else if(fe.closePlanRevise());else if(Xe.isOpen())Xe.closePanel()}}),R.connect()}if(document.readyState==="loading")document.addEventListener("DOMContentLoaded",Zs);else Zs(); +`);return}if(!g.text||!g.text.trim()||g.live||g.id.startsWith("local-"))return;Bt({id:g.id,text:g.text,role:g.kind==="user"?"user":"assistant"})},onLoadImage:async(g,E)=>{try{let S={entry:g,path:E};if(R.hasFeature("blobs"))S.metaOnly=!0;let T=await R.rpc("message.image",S);if(T.blob&&T.blob.startsWith("/blob/"))return{url:T.blob};if(T.mime&&T.data)return{mime:T.mime,data:T.data}}catch{}return null}});function ct(g){if(!g)return null;if(g.planMode)return g.planMode;if(g.provider==="claude")return{phase:"off",interaction:"default",once:!1};return null}function Je(g,E){if(!D)return;let S=te,T=D;R.rpc(g,E).then((H)=>{if(S!==te||D!==T)return;if(H.thread){let Z=P.findIndex((me)=>me.id===H.thread.id);if(Z>=0)P[Z]=H.thread;else P.unshift(H.thread);Ce.setData(k,P,F,I),ye.updateThreadMeta(H.thread),ve(),de.setState(!0,H.thread.state==="working")}}).catch((H)=>{if(S===te&&D===T)de.showError(H instanceof Error?H.message:"Could not change Plan mode")})}let Ze,de=new An(he,{onSend:(g,E)=>{fi(g,E)},onRunCommand:(g)=>{vi(g)},onInterrupt:()=>{if(D)R.rpc("turn.interrupt",{thread:D}).catch(()=>{})},onQueryMentions:async(g,E)=>{try{return(await R.rpc("mentions.list",{q:g,kind:E,limit:10})).items??[]}catch{return[]}},onToggleVoice:()=>{Ze.toggle()},onCyclePlanMode:()=>{let g=P.find((S)=>S.id===D)??null,E=ct(g);if(!E||!D)return;if(E.interaction!=="plan")Je("thread.planonce",{thread:D,on:!0});else if(E.once)Je("thread.pick",{thread:D,action:"interaction",value:"plan"});else Je("thread.pick",{thread:D,action:"interaction",value:"default"})},onSetPlanMode:(g)=>{if(!D)return;if(g==="once")Je("thread.planonce",{thread:D,on:!0});else if(g==="always")Je("thread.pick",{thread:D,action:"interaction",value:"plan"});else Je("thread.pick",{thread:D,action:"interaction",value:"default"})},getFavoriteModels:()=>J,onLoadModelPicker:async()=>{if(!D)return null;return R.rpc("thread.picker",{thread:D})},onSelectModel:async(g,E)=>{if(!D)return;let S=te,T=D;try{let H=await R.rpc("thread.model",{thread:T,provider:g,model:E});if(S!==te||D!==T)return;if(H.thread){let Z=P.findIndex((me)=>me.id===H.thread.id);if(Z>=0)P[Z]=H.thread;else P.unshift(H.thread);Ce.setData(k,P,F,I),ye.updateThreadMeta(H.thread),ve(),de.setState(!0,H.thread.state==="working")}}catch(H){if(S===te&&D===T)de.showError(H instanceof Error?H.message:"Could not switch model")}},onSelectEffort:async(g)=>{if(!D)return;let E=te,S=D;try{let T=await R.rpc("thread.pick",{thread:S,action:"effort",value:g});if(E!==te||D!==S)return;if(T.thread){let H=P.findIndex((Z)=>Z.id===T.thread.id);if(H>=0)P[H]=T.thread;else P.unshift(T.thread);Ce.setData(k,P,F,I),ye.updateThreadMeta(T.thread),ve()}}catch(T){if(E===te&&D===S)de.showError(T instanceof Error?T.message:"Could not set effort")}},onToggleFavorite:async(g,E,S)=>{let T=await R.rpc("models.favorite",{provider:g,model:E,on:S});if(Array.isArray(T.favorites))return J=T.favorites,J;return null}});Ze=new ti(R,{getThreadId:()=>D,getDraft:()=>de.getDraft(),getCaret:()=>de.getCaret(),setDraft:(g)=>de.setDraft(g),setRecording:(g)=>de.setVoiceRecording(g),setLevel:(g)=>de.setVoiceLevel(g),showError:(g)=>de.showError(g)});function Nt(){let g=q!=="",E=rt.isOpen();Se.classList.toggle("bp-hidden",!g&&!E),Se.classList.toggle("bp-has-viewer",g),Se.classList.toggle("bp-has-mgmt",E)}let rt=new Hn(ke,Se,{hub:R,getThreadId:()=>D,getThreadGen:()=>te,onSendText:(g)=>{fi(g)},onOpenChange:()=>Nt()});function Xt(g){let E=window.prompt("Rename thread",g.title||"");if(!E||!E.trim())return;R.rpc("thread.act",{thread:g.id,action:"rename",title:E.trim()}).then((S)=>{if(S.thread)P=P.map((T)=>T.id===S.thread.id?S.thread:T),ve(),Ye()}).catch((S)=>{de.showError(S instanceof Error?S.message:"Could not rename thread")})}function V(g){switch(g.type){case"thread":ze(g.id);break;case"rail":if(!D&&g.id!=="terminal")break;if(q===g.id)Ue();else Oe(g.id);break;case"thread-act":if(D)dt(D,g.action);break;case"new-thread":Tt(g.projectId);break;case"rename":{let E=P.find((S)=>S.id===D);if(E)Xt(E);break}case"prev-thread":case"next-thread":{let E=P.filter((Z)=>!Z.archived&&!Z.swarm);if(E.length<2)break;let S=E.findIndex((Z)=>Z.id===D),T=g.type==="next-thread"?1:-1,H=E[(S<0?0:S+T+E.length)%E.length];if(H)ze(H.id);break}case"command":if(g.runDirectly)vi(g.word);else de.setDraft(`${g.word} `),de.focus();break;case"improvements":Re();break;case"settings":K.open();break;case"sidebar":ne.classList.toggle("bp-sidebar-open"),ne.classList.toggle("bp-sidebar-collapsed");break}}let W=new Dn(e,{getState:()=>({selectedThreadId:D,threads:P,projects:k,bots:F,railItems:ie,commands:Ee}),onSearch:async(g)=>{if(!R.hasFeature("search"))return{threads:[],projects:[],messages:[]};return R.rpc("search",{q:g,limit:20})},onExecute:V}),_=new kn(e,{hub:R,onProjectAdded:(g)=>{if(Ye(),g.id)Tt(g.id)},onCloneDone:(g)=>{if(Ye(),g.thread)ze(g.thread)}}),G=new Wn(re,(g)=>{if(g==="commands"){W.open();return}if(!D)return;if(q===g)Ue();else Oe(g)}),z=null,ae=null,K=new Yn(e,{onLoadDevices:async()=>(await R.rpc("devices.page",{})).rows??[],onDevicesAct:async(g,E)=>{await R.rpc("devices.page.act",{action:g,value:E})},onGetHome:()=>z,onMoveHomeHere:async()=>{await R.rpc("home.move",{to:"back"})},onGetNoProvider:()=>ae,onGetThemePref:()=>mn,onSetThemePref:(g)=>{mn=g;try{if(g==="auto")localStorage.removeItem("bp.theme.pref");else localStorage.setItem("bp.theme.pref",g)}catch{}Sr()},onGetHubTheme:()=>Kt,onGetLocalePref:()=>Lt,onSetLocalePref:(g)=>{Lt=g;try{if(g==="auto")localStorage.removeItem("bp.locale");else localStorage.setItem("bp.locale",g)}catch{}xr()},hasRing:()=>R.hasFeature("ringnotes"),onRingList:async(g)=>Ts(await R.rpc("ring.list",{q:g})),onRingHear:async(g,E)=>{await R.rpc("ring.hear",{note:g,engine:E})},onOpenThread:(g)=>{ze(g)},onLogout:()=>Ui(()=>{R.disconnect(),window.location.replace("/")})});function we(g){if(ae=g,ye.setNoProvider(g),K.isOpen())K.refresh()}function xe(){K.openToAccounts()}function Ne(g,E){let S=g instanceof Error?g.message:E,T=g instanceof _t?g:null,H=T?.code,Z=T?.machine,me=H==="no_provider_remote"&&Z?m("provider.notice.senderr.remote","No AI provider connected on {machine}. Open Settings → Accounts on {machine} to connect Claude, Codex, Antigravity, or another provider.").replaceAll("{machine}",Z):S;de.showError(me,Ms(S,H)?{label:m("provider.notice.button","Open Settings → Accounts"),onClick:xe}:void 0)}v.addEventListener("click",()=>{let g=P.find((E)=>E.id===D);if(g)dt(g.id,g.pinned?"unpin":"pin")}),w.addEventListener("click",()=>{let g=P.find((E)=>E.id===D);if(g)dt(g.id,g.settled?"unsettle":"settle")});let $e=new Qn(e,(g,E)=>E?R.rpc("thread.context.mcp",{thread:g,...E}):R.rpc("thread.context",{thread:g}));N.addEventListener("click",(g)=>{g.stopPropagation();let E=P.find((H)=>H.id===D);if(!E)return;if(!A.classList.contains("bp-hidden")){A.classList.add("bp-hidden");return}let S=[{label:"Rename…",run:()=>Xt(E)},{label:E.pinned?m("menu.unpin","Unpin"):m("menu.pin","Pin"),run:()=>{dt(E.id,E.pinned?"unpin":"pin")}},{label:E.settled?m("phone.unsettle","Unsettle"):m("menu.settle","Settle"),run:()=>{dt(E.id,E.settled?"unsettle":"settle")}},{label:E.archived?"Unarchive":"Archive",run:()=>{dt(E.id,E.archived?"unarchive":"archive")}},{label:"Delete",danger:!0,run:()=>{if(window.confirm("Delete this thread?"))dt(E.id,"delete")}}];if(R.hasFeature("threadContext"))S.unshift({label:m("thread.context.title","Context & Prompt"),run:()=>$e.open(E.id)});let T=document.createDocumentFragment();for(let H of S){let Z=document.createElement("button");Z.type="button",Z.className="bp-popover-item"+(H.danger?" danger":""),Z.textContent=H.label,Z.addEventListener("click",()=>{A.classList.add("bp-hidden"),H.run()}),T.appendChild(Z)}A.replaceChildren(T),A.classList.remove("bp-hidden")}),document.addEventListener("click",()=>A.classList.add("bp-hidden"));async function Re(){let g=document.createElement("div");g.className="bp-modal-backdrop",g.setAttribute("data-testid","improvements-modal");let E=document.createElement("div");E.className="bp-modal";let S=document.createElement("div");S.className="bp-modal-head";let T=document.createElement("h2");T.textContent=m("gpui.improvements","Improvements");let H=document.createElement("button");H.type="button",H.className="icon",H.textContent="×",H.addEventListener("click",()=>g.remove()),S.append(T,H);let Z=document.createElement("div");Z.className="bp-modal-body",Z.textContent="Loading…",E.append(S,Z),g.appendChild(E),g.addEventListener("click",(me)=>{if(me.target===g)g.remove()}),e.appendChild(g);try{let me=await R.rpc("improvements.projects",{}),Ve=me.projects??[];if(Ve.length===0){Z.textContent="No projects available for Improvements.";return}let at=document.createDocumentFragment();for(let ot of Ve){let je=document.createElement("div");je.className="bp-set-row";let ce=document.createElement("div");ce.className="bp-set-info",ce.textContent=ot.title||ot.name||ot.id;let Xe=document.createElement("button");Xe.type="button",Xe.className=ot.id===me.project?"primary":"",Xe.textContent=ot.id===me.project?"Active":"Select",Xe.addEventListener("click",()=>{R.rpc("improvements.project",{project:ot.id}).then(()=>g.remove()).catch(()=>{})}),je.append(ce,Xe),at.appendChild(je)}Z.replaceChildren(at)}catch(me){Z.textContent=me instanceof Error?me.message:"Could not load Improvements."}}M.addEventListener("click",()=>{Re()}),O.addEventListener("click",()=>W.open()),x.addEventListener("click",()=>W.open()),Y.addEventListener("click",()=>{K.open()}),n.addEventListener("click",()=>{ne.classList.toggle("bp-sidebar-open"),ne.classList.toggle("bp-sidebar-collapsed")});function ve(){let g=Be?null:P.find((T)=>T.id===D)??null,E=Be?st(Be)??{id:Be,title:Be}:g?st(g.project):void 0;if(Be&&E)_e.setTitle(E.title);o.textContent=E?.title??"",a.classList.toggle("bp-hidden",!E),c.classList.toggle("bp-hidden",!g),p.textContent=g?g.title||"Untitled thread":"";let S=ct(g);if(de.setPlanMode(S),!S||S.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",S.phase==="executing"),l.title=m("gpui.planmode.tip","Plan before acting (1 turn, always, or off)"),l.textContent=S.phase==="armed"&&S.once?m("gpui.planmode.top.once","Plan (1 turn)"):S.phase==="armed"?m("gpui.mgmt.plan.tab","Plan"):S.phase==="planning"?m("gpui.planmode.top.planning","Planning"):S.phase==="pending"?m("gpui.planmode.top.pending","Review plan"):m("gpui.planmode.top.executing","Building plan");if(h.classList.toggle("bp-hidden",!g),b.classList.toggle("bp-hidden",!g),g){u.className=`bp-dot ${Er(g)}`,f.textContent=g.status||g.state||"idle",y.textContent=g.pinned?m("menu.unpin","Unpin"):m("menu.pin","Pin"),C.textContent=g.settled?m("phone.unsettle","Unsettle"):m("menu.settle","Settle");let T=g;de.setModelChip(g.chip||g.model||"default",g.provider,T.ctxPct??T.contextPct),de.setMemory(g.memory)}else de.setModelChip("default"),de.setMemory(null)}function Ue(g=!0){if(Me++,q="",G.setActive(""),ee.classList.add("bp-hidden"),fe?.close(),Nt(),g&&D&&R.getState()==="connected")R.rpc("viewer.watch",{thread:D,kind:""}).catch(()=>{})}function Oe(g){if(Me++,q=g,G.setActive(g),ee.classList.remove("bp-hidden"),Nt(),!fe&&typeof pi==="function")fe=pi(ee,{hub:R,getThreadId:()=>D,closeViewer:()=>Ue(!0)});if(fe)fe.open(g,D);else{let E=document.createElement("div");E.className="bp-viewer-placeholder";let S=document.createElement("div");S.className="bp-viewer-bar";let T=document.createElement("span");T.textContent=g.toUpperCase();let H=document.createElement("button");H.type="button",H.className="icon",H.textContent="×",H.addEventListener("click",()=>Ue(!0)),S.append(T,H);let Z=document.createElement("div");Z.className="bp-dim bp-viewer-msg",Z.textContent=`Viewer pane (${g}).`,E.append(S,Z),ee.replaceChildren(E)}}async function Mt(g,E){if(!g||!R.hasFeature("rail")){if(E===te)ie=[],G.setItems([]);return}let S=++Me;try{let T=await R.rpc("viewer.rail",{thread:g,page:q});if(E!==te||S!==Me)return;let H=Array.isArray(T.rail)?T.rail:Array.isArray(T.items)?T.items:[];if(ie=H,G.setItems(H),T.has){if(fe?.reconcileHas?.(T.has),q&&!kr(T.has,q))Ue(!0)}}catch{if(E===te&&S===Me)ie=[],G.setItems([])}}function bn(g){for(let E of g)if(E.kind==="threads"){for(let S of E.rows)if(!S.off&&(S.nav||S.id)&&!(S.nav||"").startsWith("@room:"))return S.nav||S.id}else if(E.kind==="projects"){for(let S of E.rows)for(let T of S.threads??[])if(!T.off&&(T.nav||T.id)&&!(T.nav||"").startsWith("@room:"))return T.nav||T.id}return""}function et(g,E){for(let S of g)if(S.kind==="threads"){if(S.rows.some((T)=>(T.nav||T.id)===E))return!0}else if(S.kind==="projects"){for(let T of S.rows)if((T.threads??[]).some((H)=>(H.nav||H.id)===E))return!0}return!1}function gn(g){let E=[];for(let S of g){if(S.kind!=="projects")continue;for(let T of S.rows)E.push({id:T.id,title:T.title,css:T.css,color:T.color})}if(E.length>0)k=E}async function Ye(){if(!R.hasFeature("sections"))return!1;let g=++Q;try{let E=await R.rpc("sidebar.sections",{open:Array.from(le)});if(g!==Q)return!0;let S=Array.isArray(E.sections)?E.sections:[];if(ue=S,gn(S),Ce.setData(k,P,F,I),Ce.setSections(S,F,I),ve(),Be)Yt(Be,Ge);return!0}catch{return!1}}function Qt(){if(!R.hasFeature("sections"))return;if(ge!==null)window.clearTimeout(ge);ge=window.setTimeout(()=>{ge=null,Ye()},150)}async function Lr(){if(Ae=null,R.hasFeature("bots"))try{let E=await R.rpc("bots.list",{});F=E.bots??[],I=E.rooms??[]}catch{}if(R.hasFeature("shell")){let E=await R.rpc("shell.sync",{have:He,settled:25}),S=new Set(E.removed??[]),T=new Set((E.projects??[]).map((H)=>H.id));if(S.size>0||T.size>0)k=[...k.filter((H)=>!S.has(H.id)&&!T.has(H.id)),...E.projects??[]],P=[...P.filter((H)=>!S.has(H.project)&&!T.has(H.project)),...E.threads??[]];else if(Array.isArray(E.threads)&&E.threads.length>0){let H=new Map(P.map((Z)=>[Z.id,Z]));for(let Z of E.threads)H.set(Z.id,Z);P=Array.from(H.values())}if(E.sections!==void 0){let H=Array.isArray(E.sections)?E.sections:Array.isArray(E.sections?.sections)?E.sections.sections:null;if(H)ue=H,gn(H)}if(E.h)He=E.h;Ce.setData(k,P,F,I),Ce.setSections(ue,F,I)}else if(R.hasFeature("sections")){let[E,S]=await Promise.all([R.rpc("sidebar.sections",{open:Array.from(le)}).catch(()=>null),R.rpc("threads.list",{limit:200,archived:!1}).catch(()=>({threads:[]}))]);if(P=S.threads??[],E&&Array.isArray(E.sections)){let T=E.sections;if(!T.some((Z)=>Z.kind==="projects"&&Z.rows.length>0)){let Z=T.find((me)=>me.kind==="projects"&&me.fold&&me.toggle&&(me.count??0)>0);if(Z?.toggle&&!le.has(Z.toggle)){le.add(Z.toggle);let me=await R.rpc("sidebar.sections",{open:Array.from(le)}).catch(()=>null);if(me&&Array.isArray(me.sections))T=me.sections}}ue=T,gn(T),Ce.setData(k,P,F,I),Ce.setSections(T,F,I)}else ue=null,k=(await R.rpc("projects.list",{limit:100})).projects??[],Ce.setSections(null,F,I),Ce.setData(k,P,F,I);await R.rpc("subscribe",{topic:"lists"}).catch(()=>{})}else{ue=null;let[E,S]=await Promise.all([R.rpc("projects.list",{limit:100}),R.rpc("threads.list",{limit:200,archived:!1})]);k=E.projects??[],P=S.threads??[],Ce.setSections(null,F,I),Ce.setData(k,P,F,I),await R.rpc("subscribe",{topic:"lists"}).catch(()=>{})}let g=D;if(!g){let E="";try{E=localStorage.getItem("bp.lastThread")||""}catch{}if(E&&(ue&&et(ue,E)||P.some((S)=>S.id===E)))g=E;else if(ue)g=bn(ue);if(!g)g=(P.find((T)=>!T.archived&&!T.swarm&&!T.settled)??P.find((T)=>!T.archived&&!T.swarm))?.id??""}if(g&&(ue&&et(ue,g)||P.some((E)=>E.id===g)))await ze(g,Be!=="");else D="",ie=[],G.setItems([]),de.setState(!1,!1),ve();if(Be)At(Be)}async function ze(g,E=!1){if(!E)Jt();if(D&&D!==g){Ze.cancel();let je=ye.getEntries();if(je.length>0){let ce=De.get(D);Fe(D,{entries:je,ids:ce?.ids??je.map((Xe)=>Xe.id),olderCursor:Te,review:ce?.review??null,unanswered:ce?.unanswered??null,rail:ce?.rail??ie,hashes:ce?.hashes??{}})}}let S=++te;Me++,Bt(null);let T=Ae;if(Ae=null,T!==null)R.rpc("unsubscribe",{sub:T}).catch(()=>{});D=g,de.closeModelPicker();let H=De.get(g);Te=H?.olderCursor??null;try{localStorage.setItem("bp.lastThread",g)}catch{}Ce.setSelected(g),ne.classList.remove("bp-sidebar-open"),ve();let Z=P.find((je)=>je.id===g)??null;if(H)ye.setThread(Z,H.entries,Boolean(H.olderCursor),H.review,H.unanswered),ie=H.rail,G.setItems(H.rail);else ye.setLoading(Z),ie=[],G.setItems([]);if(de.setState(!0,Z?.state==="working"),R.hasFeature("open")){let je={};if(H){for(let[Ie,Rt]of Object.entries(H.hashes))je[Ie]=Rt;for(let Ie of H.entries)if(Ie.h)je[Ie.id]=Ie.h}let ce;try{ce=await R.rpc("thread.open",{thread:g,limit:40,have:je})}catch(Ie){if(S===te){let Rt=Ie instanceof Error&&Ie.message?Ie.message:"Could not load messages.";ye.setError(Z,Rt,()=>{ze(g)})}return}if(S!==te){if(ce.sub!==void 0&&ce.sub!==null)R.rpc("unsubscribe",{sub:ce.sub}).catch(()=>{});return}if(Ae=ce.sub??null,ce.thread){Z=ce.thread;let Ie=P.findIndex((Rt)=>Rt.id===ce.thread.id);if(Ie>=0)P[Ie]=ce.thread;else P.unshift(ce.thread);ve(),de.setState(!0,Z.state==="working")}if("next"in ce)Te=ce.next??null;let Xe=new Map;if(H)for(let Ie of H.entries)Xe.set(Ie.id,Ie);for(let Ie of ce.entries??[])Xe.set(Ie.id,Ie);let wi=ce.ids??H?.ids??(ce.entries??[]).map((Ie)=>Ie.id),Ei=wi.map((Ie)=>Xe.get(Ie)).filter((Ie)=>Boolean(Ie)),It=H?.rail??[];if(ce.rail!==void 0){if(Array.isArray(ce.rail))It=ce.rail;else if(It=Array.isArray(ce.rail?.rail)?ce.rail.rail:Array.isArray(ce.rail?.items)?ce.rail.items:[],ce.rail?.has){if(fe?.reconcileHas?.(ce.rail.has),q&&!kr(ce.rail.has,q))Ue(!0)}}ie=It,G.setItems(It);let fn=H?.review??null;if(R.hasFeature("reviewmode"))try{let Ie=await R.rpc("thread.review",{thread:g});if(S!==te)return;fn=Ie.review??null}catch{}if(S!==te)return;let ki="unanswered"in ce?ce.unanswered??null:H?.unanswered??null,Ar=ce.h??H?.hashes??{};if(Fe(g,{entries:Ei,ids:wi,olderCursor:Te,review:fn,unanswered:ki,rail:It,hashes:Ar}),ye.setThread(Z,Ei,Boolean(Te),fn,ki),ui(g,S),q)Oe(q);return}let me;try{me=await R.rpc("thread.entries",{thread:g,limit:40})}catch(je){if(S===te){let ce=je instanceof Error&&je.message?je.message:"Could not load messages.";ye.setError(Z,ce,()=>{ze(g)})}return}if(S!==te)return;if(me.thread){let je=P.findIndex((ce)=>ce.id===me.thread.id);if(je>=0)P[je]=me.thread;else P.unshift(me.thread);ve()}Te=me.next??null;let Ve=null;if(R.hasFeature("reviewmode"))try{let je=await R.rpc("thread.review",{thread:g});if(S!==te)return;Ve=je.review??null}catch{}if(S!==te)return;let at=me.entries??[],ot=me.unanswered??null;Fe(g,{entries:at,ids:at.map((je)=>je.id),olderCursor:Te,review:Ve,unanswered:ot,rail:H?.rail??[],hashes:H?.hashes??{}}),ye.setThread(Z,at,Boolean(Te),Ve,ot);try{let ce=(await R.rpc("subscribe",{topic:"thread",thread:g})).sub??null;if(ce!==null){if(S!==te){R.rpc("unsubscribe",{sub:ce}).catch(()=>{});return}Ae=ce}}catch{}if(S!==te)return;if(Mt(g,S),ui(g,S),q)Oe(q)}async function ui(g,E){if(!g||!R.hasFeature("mgmt")){if(E===te)rt.clear();return}let S=P.find((H)=>H.id===g),T=S?.project?k.find((H)=>H.id===S.project)?.root??"":"";if(!T&&R.hasFeature("viewers"))try{let H=await R.rpc("viewer.files",{thread:g});if(E!==te)return;T=H.pcb||H.sch||H.root||""}catch{}if(E!==te)return;if(T)await rt.watchProject(T);else rt.clear()}async function mi(g){let E=te;for(let S=0;S<25&&E===te;S++){if(ye.goTo(g))return;if(!Te)return;let T=Te;if(await bi(),Te===T)return}}async function bi(){if(!D||!Te){ye.clearLoadingOlder();return}let g=te,E=D,S=Te;try{let T=await R.rpc("thread.entries",{thread:E,limit:40,before:S});if(g!==te||D!==E)return;Te=T.next??null,ye.prependEntries(T.entries??[],Boolean(Te))}catch{if(g===te)ye.clearLoadingOlder()}}async function Tt(g){try{let E=await R.rpc("thread.create",{project:g});if(E.thread)P=[E.thread,...P.filter((S)=>S.id!==E.thread.id)],Ce.setData(k,P,F,I),Ye(),await ze(E.thread.id),de.focus()}catch(E){Ne(E,"Could not create thread")}}let gt=null;function gi(g){return(g.split(` +`).map((E)=>E.trim()).find((E)=>E.length>0)??"").slice(0,200)}function Bt(g){gt=g,de.setReply(g?{who:g.role==="user"?m("secret.you","You"):m("model.col.agent","Agent"),line:gi(g.text)}:null,()=>{if(gt)mi(gt.id)},()=>Bt(null))}async function fi(g,E=[]){if(!D)return;let S=te,T=D,H=Va(),Z=`local-${H}`,me=gt&&g.trim()&&R.hasFeature("reply")?gt:null;if(me)Bt(null);ye.upsertEntry({id:Z,kind:"user",text:g,at:Date.now(),clientId:H,...me?{replyTo:{id:me.id,quote:gi(me.text)}}:{},attachments:E.map((Ve)=>({name:Ve.name,mime:Ve.mime,previewUrl:`data:${Ve.mime};base64,${Ve.data}`}))});try{let Ve={thread:T,text:g,clientId:H};if(E.length>0)Ve.attachments=E;if(me)Ve.replyTo={id:me.id,text:me.text};let at=await R.rpc("message.send",Ve);if(S!==te||D!==T)return;if(at.entry)ye.upsertEntry(at.entry)}catch(Ve){if(S===te&&D===T){if(ye.removeEntry(Z),de.setDraft(g),me&&!gt)Bt(me);Ne(Ve,"Failed to send message")}}}async function vi(g){if(!D)return;let E=te,S=D;try{let T=await R.rpc("composer.run",{thread:S,text:g});if(E!==te||D!==S)return;if(T.error)de.setDraft(g),Ne(new _t(T.error,{code:T.errorCode,machine:T.machine}),T.error);else if(T.kind==="btw"&&typeof T.a==="string")ye.showBtw(T.q??"",T.a);else if(T.kind==="edit"&&typeof T.text==="string")de.setDraft(T.text);else if(T.kind==="project")_.open({mode:"folder"});else if(T.kind==="clone")_.open({mode:"clone",repo:T.repo??"",text:T.text??""})}catch(T){if(E===te&&D===S)de.setDraft(g),Ne(T,"Command refused")}}async function dt(g,E){try{let S=await R.rpc("thread.act",{thread:g,action:E});if(S.thread){if(P=P.map((T)=>T.id===S.thread.id?S.thread:T),Ce.setData(k,P,F,I),S.thread.id===D)ye.updateThreadMeta(S.thread),ve()}Ye()}catch(S){de.showError(S instanceof Error?S.message:`Action "${E}" not allowed`)}}function yi(g,E){if(!g||!g.text||E-g.at>=300000)return"";let S=g.build.split("-").pop()??"";if(g.reason==="build"&&S)return m("hub.restarting.build",g.text,{build:S});if(g.reason==="stop")return m("hub.stopped",g.text);return m("hub.restarting",g.text)}function Zt(g){if(g==="connected")Ce.setConnStatus(m("gpui.acct.connected","Connected"),"bp-ok");else if(g==="reconnecting"&&yi(R.restarting,Date.now()))Ce.setConnStatus(yi(R.restarting,Date.now()),"");else if(g==="reconnecting")Ce.setConnStatus("Reconnecting…","bp-warn");else if(g==="revoked")Ce.setConnStatus(m("gpui.acct.sign.in.expired","Sign-in expired"),"bp-bad");else Ce.setConnStatus("Connecting…","")}en(()=>{Zt(R.getState()),j.textContent=m("gpui.improvements","Improvements"),Y.title=m("palette.settings","Settings"),Y.setAttribute("aria-label",m("palette.settings","Settings")),ve(),Ce.refreshLocale(),ye.refreshLocale(),de.refreshLocale(),G.render(),K.refreshLocale(),_e.refreshLocale(),_.refreshLocale()}),R.onState((g,E)=>{if(g==="connected"&&E){if(E.locale)hi=E.locale,xr();if(E.theme)Cr(E.theme);if(E.name)Ce.setHostName(E.name);if(Array.isArray(E.favoriteModels))J=E.favoriteModels,de.updateFavoriteModels(J);if(z=E.home??null,Ce.setHome(z),we(Vn(E.noProvider)),K.isOpen())K.refresh();Zt(g);let S=typeof E.hubBack==="string"?String(E.hubBack):"";if(S)try{let T=JSON.parse(S);if(T.reason==="crash")Ce.setConnStatus(m("hub.back.crash",T.text??""),"bp-warn"),window.setTimeout(()=>Zt(R.getState()),6000)}catch{}if(de.setFeatures(R.hasFeature("images"),R.hasFeature("voice")),Array.isArray(E.commands))Ee=E.commands,de.setCommands(Ee);else Ee=[];Lr(),_.reconcile()}else Ze.cancel(),Zt(g)}),R.onFrame((g)=>{if(g.t==="voice"){Ze.handleFrame(g);return}if(g.t==="info"&&g.info&&typeof g.info==="object"){let S=g.info;if(Object.prototype.hasOwnProperty.call(S,"provider.notice"))we(Vn(S["provider.notice"]));rt.handleInfo(S);return}if(g.t!=="d")return;let E=g;if(E.k==="clone"||E.k==="clone.repos"||E.k==="clone.signin"){_.handleFrame(E);return}switch(E.k){case"project":{let S=E.project;if(!S)break;let T=k.findIndex((H)=>H.id===S.id);if(T>=0)k[T]=S;else k.unshift(S);Ce.setData(k,P,F,I),ve(),Qt();break}case"thread":{let S=E.thread;if(!S)break;let T=P.findIndex((H)=>H.id===S.id);if(T>=0)P[T]=S;else P.unshift(S);if(Ce.setData(k,P,F,I),S.id===D)ye.updateThreadMeta(S),ve(),de.setState(!0,S.state==="working");Qt();break}case"thread.removed":{let S=String(E.id??"");P=P.filter((T)=>T.id!==S),Ce.setData(k,P,F,I),Qt();break}case"entry":{if(E.thread===D&&E.entry)ye.upsertEntry(E.entry);break}case"text":{if(E.thread===D)ye.appendLiveText(String(E.entry??""),String(E.append??""),Number(E.at??Date.now()));break}case"turn":{if(E.thread===D){let S=String(E.state??"idle");de.setState(!0,S==="working"),Mt(D,te)}Qt();break}case"btw":{if(E.thread===D)ye.showBtw(String(E.q??""),String(E.a??""));break}case"unanswered":{if(E.thread===D)ye.setUnanswered(E.unanswered??null);break}case"theme":{if(typeof E.theme==="string")Cr(E.theme);break}case"home":{if(z=E.home??null,Ce.setHome(z),K.isOpen())K.refresh();break}case"favorites":{if(Array.isArray(E.favorites))J=E.favorites.filter((S)=>typeof S==="string"),de.updateFavoriteModels(J);break}default:break}}),window.addEventListener("keydown",(g)=>{let E=g.key.toLowerCase();if((g.ctrlKey||g.metaKey)&&(E==="k"||g.shiftKey&&E==="p"))if(g.preventDefault(),W.isOpen())W.close();else W.open();else if(g.key==="Escape"){if(W.isOpen())W.close();else if(de.isModelPickerOpen())de.closeModelPicker();else if(_.isOpen())_.escape();else if(K.isOpen())K.handleEscape();else if(ye.closePlanRevise());else if(rt.isOpen())rt.closePanel()}}),R.connect()}if(document.readyState==="loading")document.addEventListener("DOMContentLoaded",Pr);else Pr(); diff --git a/web/dist/assets/pair.js b/web/dist/assets/pair.js index 43bba01ce6..a8a46d3714 100644 --- a/web/dist/assets/pair.js +++ b/web/dist/assets/pair.js @@ -1 +1 @@ -var U={en:{"agy.signout":"Sign out","android.hub.machines.approve":"Approve","android.load.earlier":"load earlier","approval.dismiss":"Dismiss","approval.implement":"Implement","ask.plan":"Proposed plan","bots.new":"New bot","bots.rooms":"Rooms","bots.tab.browser":"Browser","common.cancel":"Cancel","common.close":"Close","common.copy":"Copy","common.delete":"Delete","common.refresh":"Refresh","common.remove":"Remove","common.save":"Save","composer.model.tip":"Choose the model and effort","composer.placeholder":"Ask anything: @bot, >thread, %project, #room, $skill, /btw","composer.send":"Send","composer.stop":"Stop","gpui.acct.connected":"Connected","gpui.acct.not.connected":"Not connected","gpui.acct.sign.in.expired":"Sign-in expired","gpui.ask.plan.ready":"Ready for review","gpui.ask.plan.revise":"Revise","gpui.ask.plan.reviseph":"What should change in the plan?","gpui.ask.plan.sendrev":"Send revision","gpui.b.in.reply.to":"↩ In reply to: {quote}","gpui.b.replying.to":"↩ Replying to: {line}","gpui.bots.recall.off":"Off","gpui.bots.recall.on":"On","gpui.c.solid.big.next":"Loading it may take a while and a lot of memory.","gpui.c.solid.load.big":"Load it anyway","gpui.c.solid.loading.big":"Loading it anyway…","gpui.c.term.collapse":"Collapse","gpui.c.term.expand":"Expand","gpui.commands":"Commands","gpui.e.open.folder":"Open folder","gpui.filter.projects.and.threads":"Filter projects and threads","gpui.fold.or.unfold.the.sidebar":"Fold or unfold the sidebar","gpui.follow.paused":"Following paused","gpui.follow.wait":"Following: waiting for the agent's next edit","gpui.gerbers":"Gerbers","gpui.improvements":"Improvements","gpui.jump.to.a.thread.run":"Jump to a thread, run a command or find what was said","gpui.mgmt.bom.dnp":"DNP","gpui.mgmt.bom.nompn":"no MPN","gpui.mgmt.checks.all":"All","gpui.mgmt.checks.fix":"Fix with agent","gpui.mgmt.checks.run":"Run","gpui.mgmt.close":"Close the panel","gpui.mgmt.fab.apply":"Apply","gpui.mgmt.fab.changed":"Changed since you last looked","gpui.mgmt.fab.derived":"* worked out from the fab's page (a mil in mm, a ring from a diameter). Dimmed: the rigid board's value, where this board's page says nothing else. A date opens the page it was read from.","gpui.mgmt.fab.extra":"Costs more","gpui.mgmt.fab.findings":"Findings","gpui.mgmt.fab.free":"Base price","gpui.mgmt.fab.judge":"Datasheets","gpui.mgmt.fab.limit":"Limit","gpui.mgmt.fab.readcol":"Read","gpui.mgmt.fab.refresh":"Refresh","gpui.mgmt.fab.reviewbtn":"Review","gpui.mgmt.fab.seen":"Seen","gpui.mgmt.fab.thefab":"The fab","gpui.mgmt.fab.use":"Use","gpui.mgmt.life.nopart":"No reading of this part yet.","gpui.mgmt.life.reading":"Reading its history…","gpui.mgmt.plan.addnote":"Add note","gpui.mgmt.plan.all":"Approve all","gpui.mgmt.plan.before":"Plan before routing","gpui.mgmt.plan.compact":"Compact","gpui.mgmt.plan.done":"done","gpui.mgmt.plan.drawn":"The plan's corridors and planes are drawn on the board while this panel is open. Close it to hide them.","gpui.mgmt.plan.edited":"Edited","gpui.mgmt.plan.elsewhere":"A routing plan for {board} awaits your approval","gpui.mgmt.plan.emptysub":"Layers, corridors, and planes appear here once a plan is proposed.","gpui.mgmt.plan.expand":"Expand","gpui.mgmt.plan.fit":"Fit","gpui.mgmt.plan.grid.all":"All layers","gpui.mgmt.plan.grid.pair":"Side by side","gpui.mgmt.plan.grid.single":"Single","gpui.mgmt.plan.hide":"Hide done","gpui.mgmt.plan.hint":"Drag waypoints to steer · Click + on edge to insert · Right-click vertex to remove","gpui.mgmt.plan.keysnote":"On this KiCad version, approve from this panel: in plan view KiCad's A, R and W keys aren't the plan's yet (A opens Add Footprint). Update KiCad.","gpui.mgmt.plan.layer":"Approve layer","gpui.mgmt.plan.layer.short":"Layer","gpui.mgmt.plan.lock":"Lock","gpui.mgmt.plan.locked":"Locked","gpui.mgmt.plan.noboard":"No routing plan for this board.","gpui.mgmt.plan.noitems":"No corridors or planes on this layer","gpui.mgmt.plan.note.placeholder":"Steering note for router…","gpui.mgmt.plan.nothing":"Nothing awaits your approval","gpui.mgmt.plan.offwords":"Agents route as you ask. Turn it on to have them propose a routing plan first and route only what you approve here.","gpui.mgmt.plan.onwords":"Before routing a board with 4 or more copper layers or more than 60 nets, the agent proposes corridors and plane regions here. It routes only what you approve.","gpui.mgmt.plan.reading":"Reading the routing plan…","gpui.mgmt.plan.reference":"over {layer}","gpui.mgmt.plan.refused":"KiCad refused","gpui.mgmt.plan.reject":"Reject","gpui.mgmt.plan.rejectlayer":"Reject layer","gpui.mgmt.plan.reqplain":"Approval requested","gpui.mgmt.plan.requested":"Approval requested: {what}","gpui.mgmt.plan.saved":"saved plan","gpui.mgmt.plan.show":"Show done","gpui.mgmt.plan.st.approved":"Approved","gpui.mgmt.plan.st.awaiting":"Awaiting review","gpui.mgmt.plan.st.blocked":"Blocked","gpui.mgmt.plan.st.empty":"Empty","gpui.mgmt.plan.st.partial":"Partial","gpui.mgmt.plan.st.rejected":"Rejected","gpui.mgmt.plan.st.routed":"Routed","gpui.mgmt.plan.st.routing":"Routing","gpui.mgmt.plan.st.verified":"Verified","gpui.mgmt.plan.stackup.short":"Stackup","gpui.mgmt.plan.stop":"Stop routing","gpui.mgmt.plan.sync":"Link zoom","gpui.mgmt.plan.tab":"Plan","gpui.mgmt.plan.unlock":"Unlock","gpui.mgmt.plan.verify":"Verify","gpui.mgmt.plan.view.canvas":"Canvas","gpui.mgmt.plan.view.list":"List","gpui.mgmt.plan.view.split":"Split","gpui.mgmt.plan.width":"Width","gpui.next.thread":"Next thread","gpui.no.models":"No models","gpui.nothing.matches":"Nothing matches","gpui.picker.favorite.add":"Add to favorites","gpui.picker.favorite.remove":"Remove from favorites","gpui.picker.favorites":"Favorites","gpui.planmode.bar.always":"Plan mode — explores and proposes a plan before editing","gpui.planmode.bar.executing":"Building the approved plan","gpui.planmode.bar.once":"Plan mode (1 turn) — explores and proposes a plan before editing","gpui.planmode.bar.pending":"Proposed plan awaits review below","gpui.planmode.bar.planning":"Planning — drafting a plan before edits","gpui.planmode.chip.building":"Building","gpui.planmode.chip.once":"Plan · 1t","gpui.planmode.scope.always":"Always","gpui.planmode.scope.once":"1 turn","gpui.planmode.tip":"Plan before acting (1 turn, always, or off)","gpui.planmode.top.executing":"Building plan","gpui.planmode.top.once":"Plan (1 turn)","gpui.planmode.top.pending":"Review plan","gpui.planmode.top.planning":"Planning","gpui.previous.thread":"Previous thread","gpui.rail.no.board":"No board in this project","gpui.rail.no.mech":"No mechanical parts in this project","gpui.rail.no.schematic":"No schematic in this project","gpui.rail.split.needs.both":"Split needs a board and a schematic","gpui.search.models":"Search models","gpui.settings.group.agents":"Agents and tools","gpui.settings.group.general":"General","home.away":"Home ({name}) is away","home.away.queued":"Home ({name}) is away · {n} queued","home.away.since":"Home ({name}) is away since {time}","home.away.since.queued":"Home ({name}) is away since {time} · {n} queued","home.machine":"Home machine","home.move.failed":"Home move failed","home.move.failed.note":"Home move failed: {note}","home.move.here":"Make this machine the home","home.moving":"Moving home to {to}…","home.moving.step":"Moving home to {to}: {step}","hub.back.crash":"Backplane is back after it stopped unexpectedly","hub.restarting":"Restarting Backplane…","hub.restarting.build":"Restarting Backplane… (new build {build})","hub.stopped":"Backplane stopped","ios.hub.address.field":"Hub address","menu.pin":"Pin","menu.settle":"Settle","menu.unpin":"Unpin","menu.wake":"Wake","model.col.agent":"Agent","model.col.effort":"Effort","native.pair.connect":"Connect","native.thread.model":"Model","notify.settled":"Settled","palette.archive":"Archive thread","palette.command.placeholder":"Type a command or a thread","palette.diff":"Diff: what this thread changed","palette.newthread":"New thread","palette.settings":"Settings","palette.terminal":"Terminal","palette.unarchive":"Unarchive thread","phone.unsettle":"Unsettle","provider.notice.button":"Open Settings → Accounts","provider.notice.head":"No AI provider connected","provider.notice.senderr":"No AI provider connected yet. Open Settings → Accounts to connect Claude, Codex, Antigravity, or another provider.","provider.notice.senderr.remote":"No AI provider connected on {machine}. Open Settings → Accounts on {machine} to connect Claude, Codex, Antigravity, or another provider.","provider.notice.text.none":"Connect Claude, Codex, Antigravity, or another provider to start chatting.","provider.notice.text.signedout":"Sign in to Claude, Codex, or another provider in Settings → Accounts to start chatting.","reply.action":"Reply","reply.cancel":"Cancel reply","reply.to":"In reply to:","rooms.new":"New room","secret.you":"You","settings.appearance":"Appearance","settings.lang":"Language","settings.lang.auto":"Automatic","settings.lang.en":"English","settings.lang.es":"Español","settings.lang.ja":"日本語","settings.theme":"Theme","settings.theme.dark":"Dark","settings.theme.light":"Light","sheet.rename":"Rename thread","sidebar.add.project":"Add project","sidebar.search.projects":"Search projects","thread.context.base":"Backplane","thread.context.copied":"Prompt copied.","thread.context.copy":"Copy prompt","thread.context.disable":"Disable","thread.context.enable":"Enable","thread.context.index":"Available skills index","thread.context.injected.label":"Injected project instructions","thread.context.instructions":"Instructions","thread.context.mcp":"Project MCPs","thread.context.native.note":"Backplane’s launch prompt. Native files are loaded by the provider.","thread.context.none.instructions":"No project instructions found.","thread.context.none.mcp":"No project MCP configurations found.","thread.context.reading":"Reading thread context…","thread.context.size":"{bytes} B · ≈{tokens} tokens","thread.context.skills":"Skills","thread.context.system":"System Prompt","thread.context.title":"Context & Prompt","thread.context.trust":"Trust and enable","thread.new":"New thread","tools.pinned":"Pinned","tools.retry":"Retry","tour.title.bots":"Bots","viewer.board":"Board","viewer.diff":"Diff","viewer.files":"Files","viewer.mech":"Mech","viewer.review":"Review","viewer.schematic":"Schematic","viewer.solid":"3D","web.chat.answer.btn":"Answer","web.chat.answer.placeholder":"Type answer…","web.chat.answered":"Answered: {answer}","web.chat.choose":"Choose a project thread on the left to begin.","web.chat.empty":"No messages yet. Type below to start a turn.","web.chat.finished":"Finished {time}","web.chat.finished.dur":"Finished {time} · {dur}","web.chat.loading":"Loading messages…","web.chat.review.mode":"Review mode","web.chat.streaming":"Streaming…","web.clone.add.dir":"Add {dir}","web.clone.back":"Back","web.clone.change.folder":"Change folder","web.clone.cloned":"Cloned {repo} into {dest}","web.clone.cloning":"Cloning {repo} into {dest}","web.clone.copied":"Copied","web.clone.first":"First message: {text}","web.clone.folder.name":"Folder name","web.clone.go":"Clone","web.clone.loading":"Loading…","web.clone.no.folders":"No folders here","web.clone.open.project":"Open the project","web.clone.open.thread":"Open the thread","web.clone.private":"private","web.clone.repo.placeholder":"https or ssh URL, or owner/repo","web.clone.retry":"Try again","web.clone.same":"Already cloned there: it is added as it is.","web.clone.signin":"Sign in to GitHub","web.clone.signin.done":"Signed in to GitHub","web.clone.signin.enter":"Enter this code on GitHub:","web.clone.signin.wait":"Starting GitHub sign-in…","web.clone.start.thread":"Start a thread","web.clone.stopped":"Stopped cloning {repo}","web.clone.tab":"Clone from git","web.clone.up":"Up","web.clone.use.dir":"Use {dir}","web.composer.attach":"Attach image","web.composer.maximages":"At most {max} images per message.","web.composer.unsupported":"Unsupported image type: {type}","web.composer.voice":"Voice dictation","web.logout.failed":"Could not confirm sign-out. Try again.","web.pair.approve.in":"Approve on desktop or paired phone · expires in {time}","web.pair.approved":"Approved. Opening Backplane…","web.pair.cancelled":"Cancelled.","web.pair.code":"Comparison code","web.pair.denied":"Pairing request was denied.","web.pair.expired":"Pairing code expired. Request a new code to try again.","web.pair.failed":"Pairing request failed ({status})","web.pair.name":"Browser name","web.pair.nocode":"Hub did not return a comparison code.","web.pair.ratelimited":"Too many pairing attempts. Wait a moment and try again.","web.pair.request":"Request pairing","web.pair.requesting":"Requesting pairing code…","web.pair.subtitle":"Pair this browser with your hub. Approve the 6-digit code in Backplane › Settings › Devices.","web.pair.unreachable":"Could not reach the hub. Check your tailnet connection.","web.plan.awaiting":"{n} awaiting approval","web.plan.net.one":"1 net","web.plan.nets":"{n} nets","web.settings.providers":"AI providers","web.settings.providers.browser":"Connect a provider in the Backplane desktop or mobile app under Settings → Accounts."},es:{"agy.signout":"Cerrar sesión","android.hub.machines.approve":"Aprobar","android.load.earlier":"cargar anteriores","approval.dismiss":"Descartar","approval.implement":"Implementar","ask.plan":"Plan propuesto","bots.new":"Nuevo bot","bots.rooms":"Salas","bots.tab.browser":"Navegador","common.cancel":"Cancelar","common.close":"Cerrar","common.copy":"Copiar","common.delete":"Eliminar","common.refresh":"Actualizar","common.remove":"Quitar","common.save":"Guardar","composer.model.tip":"Elegir el modelo y el esfuerzo","composer.placeholder":"Pregunta lo que sea: @bot, >hilo, %proyecto, #sala, $skill, /btw","composer.send":"Enviar","composer.stop":"Detener","gpui.acct.connected":"Conectado","gpui.acct.not.connected":"No conectado","gpui.acct.sign.in.expired":"Sesión caducada","gpui.ask.plan.ready":"Listo para revisar","gpui.ask.plan.revise":"Revisar","gpui.ask.plan.reviseph":"¿Qué debería cambiar en el plan?","gpui.ask.plan.sendrev":"Enviar revisión","gpui.b.in.reply.to":"↩ En respuesta a: {quote}","gpui.b.replying.to":"↩ Respondiendo a: {line}","gpui.bots.recall.off":"Desactivado","gpui.bots.recall.on":"Activado","gpui.c.solid.big.next":"Cargarlo puede tardar y usar mucha memoria.","gpui.c.solid.load.big":"Cargarlo de todos modos","gpui.c.solid.loading.big":"Cargándolo de todos modos…","gpui.c.term.collapse":"Contraer","gpui.c.term.expand":"Expandir","gpui.commands":"Comandos","gpui.e.open.folder":"Abrir carpeta","gpui.filter.projects.and.threads":"Filtrar proyectos e hilos","gpui.fold.or.unfold.the.sidebar":"Plegar o desplegar la barra lateral","gpui.follow.paused":"Seguimiento en pausa","gpui.follow.wait":"Siguiendo: esperando la próxima edición del agente","gpui.gerbers":"Gerbers","gpui.improvements":"Mejoras","gpui.jump.to.a.thread.run":"Saltar a un hilo, ejecutar un comando o buscar lo dicho","gpui.mgmt.bom.dnp":"DNP","gpui.mgmt.bom.nompn":"sin MPN","gpui.mgmt.checks.all":"Todas","gpui.mgmt.checks.fix":"Corregir con agente","gpui.mgmt.checks.run":"Ejecutar","gpui.mgmt.close":"Cerrar el panel","gpui.mgmt.fab.apply":"Aplicar","gpui.mgmt.fab.changed":"Cambió desde la última vez que miraste","gpui.mgmt.fab.derived":"* calculado desde la página del fabricante (un mil en mm, un anillo desde un diámetro). Atenuado: el valor de la placa rígida, cuando la página de esta placa no dice otra cosa. Una fecha abre la página de la que se leyó.","gpui.mgmt.fab.extra":"Cuesta más","gpui.mgmt.fab.findings":"Hallazgos","gpui.mgmt.fab.free":"Precio base","gpui.mgmt.fab.judge":"Hojas de datos","gpui.mgmt.fab.limit":"Límite","gpui.mgmt.fab.readcol":"Leído","gpui.mgmt.fab.refresh":"Actualizar","gpui.mgmt.fab.reviewbtn":"Revisar","gpui.mgmt.fab.seen":"Visto","gpui.mgmt.fab.thefab":"El fabricante","gpui.mgmt.fab.use":"Usar","gpui.mgmt.life.nopart":"Sin lectura de esta pieza aún.","gpui.mgmt.life.reading":"Leyendo su historial…","gpui.mgmt.plan.addnote":"Añadir nota","gpui.mgmt.plan.all":"Aprobar todo","gpui.mgmt.plan.before":"Planificar antes de rutear","gpui.mgmt.plan.compact":"Compacto","gpui.mgmt.plan.done":"hecho","gpui.mgmt.plan.drawn":"Los corredores y planos del plan se dibujan en la placa mientras este panel está abierto. Ciérralo para ocultarlos.","gpui.mgmt.plan.edited":"Editado","gpui.mgmt.plan.elsewhere":"Un plan de ruteo para {board} espera tu aprobación","gpui.mgmt.plan.emptysub":"Las capas, corredores y planos aparecerán aquí cuando se proponga un plan.","gpui.mgmt.plan.expand":"Expandir","gpui.mgmt.plan.fit":"Ajustar","gpui.mgmt.plan.grid.all":"Todas las capas","gpui.mgmt.plan.grid.pair":"Lado a lado","gpui.mgmt.plan.grid.single":"Única","gpui.mgmt.plan.hide":"Ocultar hechos","gpui.mgmt.plan.hint":"Arrastra vértices para guiar · Clic en + del borde para insertar · Clic derecho en vértice para quitar","gpui.mgmt.plan.keysnote":"En esta versión de KiCad, aprueba desde este panel: en la vista de plan las teclas A, R y W de KiCad aún no son del plan (A abre Añadir Huella). Actualiza KiCad.","gpui.mgmt.plan.layer":"Aprobar capa","gpui.mgmt.plan.layer.short":"Capa","gpui.mgmt.plan.lock":"Bloquear","gpui.mgmt.plan.locked":"Bloqueado","gpui.mgmt.plan.noboard":"No hay plan de ruteo para esta placa.","gpui.mgmt.plan.noitems":"Sin corredores ni planos en esta capa","gpui.mgmt.plan.note.placeholder":"Nota de guiado para el router…","gpui.mgmt.plan.nothing":"Nada espera tu aprobación","gpui.mgmt.plan.offwords":"Los agentes rutean como les pidas. Actívalo para que primero propongan un plan de ruteo y ruteen solo lo que apruebes aquí.","gpui.mgmt.plan.onwords":"Antes de rutear una placa con 4 o más capas de cobre o más de 60 redes, el agente propone aquí corredores y regiones de plano. Solo rutea lo que apruebes.","gpui.mgmt.plan.reading":"Leyendo el plan de ruteo…","gpui.mgmt.plan.reference":"sobre {layer}","gpui.mgmt.plan.refused":"KiCad lo rechazó","gpui.mgmt.plan.reject":"Rechazar","gpui.mgmt.plan.rejectlayer":"Rechazar capa","gpui.mgmt.plan.reqplain":"Aprobación solicitada","gpui.mgmt.plan.requested":"Aprobación solicitada: {what}","gpui.mgmt.plan.saved":"plan guardado","gpui.mgmt.plan.show":"Mostrar hechos","gpui.mgmt.plan.st.approved":"Aprobado","gpui.mgmt.plan.st.awaiting":"Esperando revisión","gpui.mgmt.plan.st.blocked":"Bloqueado","gpui.mgmt.plan.st.empty":"Vacío","gpui.mgmt.plan.st.partial":"Parcial","gpui.mgmt.plan.st.rejected":"Rechazado","gpui.mgmt.plan.st.routed":"Ruteado","gpui.mgmt.plan.st.routing":"Ruteando","gpui.mgmt.plan.st.verified":"Verificado","gpui.mgmt.plan.stackup.short":"Apilamiento","gpui.mgmt.plan.stop":"Detener ruteo","gpui.mgmt.plan.sync":"Vincular zoom","gpui.mgmt.plan.tab":"Plan","gpui.mgmt.plan.unlock":"Desbloquear","gpui.mgmt.plan.verify":"Verificar","gpui.mgmt.plan.view.canvas":"Lienzo","gpui.mgmt.plan.view.list":"Lista","gpui.mgmt.plan.view.split":"Dividido","gpui.mgmt.plan.width":"Ancho","gpui.next.thread":"Hilo siguiente","gpui.no.models":"Sin modelos","gpui.nothing.matches":"Nada coincide","gpui.picker.favorite.add":"Añadir a favoritos","gpui.picker.favorite.remove":"Quitar de favoritos","gpui.picker.favorites":"Favoritos","gpui.planmode.bar.always":"Modo plan — explora y propone un plan antes de editar","gpui.planmode.bar.executing":"Ejecutando el plan aprobado","gpui.planmode.bar.once":"Modo plan (1 turno) — explora y propone un plan antes de editar","gpui.planmode.bar.pending":"El plan propuesto espera revisión abajo","gpui.planmode.bar.planning":"Planificando — redactando un plan antes de editar","gpui.planmode.chip.building":"Ejecutando","gpui.planmode.chip.once":"Plan · 1t","gpui.planmode.scope.always":"Siempre","gpui.planmode.scope.once":"1 turno","gpui.planmode.tip":"Planificar antes de actuar (1 turno, siempre u off)","gpui.planmode.top.executing":"Ejecutando plan","gpui.planmode.top.once":"Plan (1 turno)","gpui.planmode.top.pending":"Revisar plan","gpui.planmode.top.planning":"Planificando","gpui.previous.thread":"Hilo anterior","gpui.rail.no.board":"Este proyecto no tiene placa","gpui.rail.no.mech":"Este proyecto no tiene piezas mecánicas","gpui.rail.no.schematic":"Este proyecto no tiene esquema","gpui.rail.split.needs.both":"La vista dividida requiere una placa y un esquema","gpui.search.models":"Buscar modelos","gpui.settings.group.agents":"Agentes y herramientas","gpui.settings.group.general":"General","home.away":"El inicio ({name}) no está disponible","home.away.queued":"El inicio ({name}) no está disponible · {n} en cola","home.away.since":"El inicio ({name}) no está disponible desde las {time}","home.away.since.queued":"El inicio ({name}) no está disponible desde las {time} · {n} en cola","home.machine":"Máquina de inicio","home.move.failed":"No se pudo mover el inicio","home.move.failed.note":"No se pudo mover el inicio: {note}","home.move.here":"Hacer de esta máquina el inicio","home.moving":"Moviendo el inicio a {to}…","home.moving.step":"Moviendo el inicio a {to}: {step}","hub.back.crash":"Backplane volvió tras detenerse de forma inesperada","hub.restarting":"Reiniciando Backplane…","hub.restarting.build":"Reiniciando Backplane… (nueva compilación {build})","hub.stopped":"Backplane se detuvo","ios.hub.address.field":"Dirección del hub","menu.pin":"Fijar","menu.settle":"Cerrar","menu.unpin":"Desfijar","menu.wake":"Despertar","model.col.agent":"Agente","model.col.effort":"Esfuerzo","native.pair.connect":"Conectar","native.thread.model":"Modelo","notify.settled":"Cerrado","palette.archive":"Archivar hilo","palette.command.placeholder":"Escribe un comando o un hilo","palette.diff":"Diff: qué cambió este hilo","palette.newthread":"Nuevo hilo","palette.settings":"Ajustes","palette.terminal":"Terminal","palette.unarchive":"Desarchivar hilo","phone.unsettle":"Reabrir","provider.notice.button":"Abrir Configuración → Cuentas","provider.notice.head":"No hay ningún proveedor de IA conectado","provider.notice.senderr":"Aún no hay ningún proveedor de IA conectado. Abre Configuración → Cuentas para conectar Claude, Codex, Antigravity u otro proveedor.","provider.notice.senderr.remote":"No hay ningún proveedor de IA conectado en {machine}. Abre Configuración → Cuentas en {machine} para conectar Claude, Codex, Antigravity u otro proveedor.","provider.notice.text.none":"Conecta Claude, Codex, Antigravity u otro proveedor para empezar a chatear.","provider.notice.text.signedout":"Inicia sesión en Claude, Codex u otro proveedor en Configuración → Cuentas para empezar a chatear.","reply.action":"Responder","reply.cancel":"Cancelar respuesta","reply.to":"En respuesta a:","rooms.new":"Nueva sala","secret.you":"Tú","settings.appearance":"Apariencia","settings.lang":"Idioma","settings.lang.auto":"Automático","settings.lang.en":"English","settings.lang.es":"Español","settings.lang.ja":"日本語","settings.theme":"Tema","settings.theme.dark":"Oscuro","settings.theme.light":"Claro","sheet.rename":"Renombrar hilo","sidebar.add.project":"Añadir proyecto","sidebar.search.projects":"Buscar proyectos","thread.context.base":"Backplane","thread.context.copied":"Se copiaron las instrucciones.","thread.context.copy":"Copiar instrucciones","thread.context.disable":"Desactivar","thread.context.enable":"Activar","thread.context.index":"Índice de habilidades disponibles","thread.context.injected.label":"Instrucciones del proyecto añadidas","thread.context.instructions":"Instrucciones","thread.context.mcp":"MCP del proyecto","thread.context.native.note":"Instrucciones de inicio de Backplane. El proveedor carga los archivos nativos.","thread.context.none.instructions":"No se encontraron instrucciones del proyecto.","thread.context.none.mcp":"No se encontraron configuraciones MCP del proyecto.","thread.context.reading":"Leyendo el contexto del hilo…","thread.context.size":"{bytes} B · ≈{tokens} tokens","thread.context.skills":"Habilidades","thread.context.system":"Instrucciones del sistema","thread.context.title":"Contexto e instrucciones","thread.context.trust":"Confiar y activar","thread.new":"Nuevo hilo","tools.pinned":"Fijado","tools.retry":"Reintentar","tour.title.bots":"Bots","viewer.board":"Placa","viewer.diff":"Diff","viewer.files":"Archivos","viewer.mech":"Mech","viewer.review":"Revisión","viewer.schematic":"Esquemático","viewer.solid":"3D","web.chat.answer.btn":"Responder","web.chat.answer.placeholder":"Escribe una respuesta…","web.chat.answered":"Respondido: {answer}","web.chat.choose":"Elige un hilo de proyecto a la izquierda para empezar.","web.chat.empty":"Aún no hay mensajes. Escribe abajo para iniciar un turno.","web.chat.finished":"Terminado {time}","web.chat.finished.dur":"Terminado {time} · {dur}","web.chat.loading":"Cargando mensajes…","web.chat.review.mode":"Modo de revisión","web.chat.streaming":"Transmitiendo…","web.clone.add.dir":"Añadir {dir}","web.clone.back":"Atrás","web.clone.change.folder":"Cambiar carpeta","web.clone.cloned":"{repo} clonado en {dest}","web.clone.cloning":"Clonando {repo} en {dest}","web.clone.copied":"Copiado","web.clone.first":"Primer mensaje: {text}","web.clone.folder.name":"Nombre de la carpeta","web.clone.go":"Clonar","web.clone.loading":"Cargando…","web.clone.no.folders":"No hay carpetas aquí","web.clone.open.project":"Abrir el proyecto","web.clone.open.thread":"Abrir el hilo","web.clone.private":"privado","web.clone.repo.placeholder":"URL https o ssh, o propietario/repositorio","web.clone.retry":"Reintentar","web.clone.same":"Ya está clonado ahí: se añade tal cual.","web.clone.signin":"Iniciar sesión en GitHub","web.clone.signin.done":"Sesión iniciada en GitHub","web.clone.signin.enter":"Introduce este código en GitHub:","web.clone.signin.wait":"Iniciando sesión en GitHub…","web.clone.start.thread":"Empezar un hilo","web.clone.stopped":"Se detuvo la clonación de {repo}","web.clone.tab":"Clonar desde git","web.clone.up":"Subir","web.clone.use.dir":"Usar {dir}","web.composer.attach":"Adjuntar imagen","web.composer.maximages":"Como máximo {max} imágenes por mensaje.","web.composer.unsupported":"Tipo de imagen no compatible: {type}","web.composer.voice":"Dictado por voz","web.logout.failed":"No se pudo confirmar el cierre de sesión. Inténtalo de nuevo.","web.pair.approve.in":"Aprueba en el escritorio o en un teléfono vinculado · caduca en {time}","web.pair.approved":"Aprobado. Abriendo Backplane…","web.pair.cancelled":"Cancelado.","web.pair.code":"Código de comparación","web.pair.denied":"Se rechazó la solicitud de vinculación.","web.pair.expired":"El código de vinculación caducó. Solicita uno nuevo para intentarlo otra vez.","web.pair.failed":"Falló la solicitud de vinculación ({status})","web.pair.name":"Nombre del navegador","web.pair.nocode":"El hub no devolvió un código de comparación.","web.pair.ratelimited":"Demasiados intentos de vinculación. Espera un momento e inténtalo de nuevo.","web.pair.request":"Solicitar vinculación","web.pair.requesting":"Solicitando código de vinculación…","web.pair.subtitle":"Vincula este navegador con tu hub. Aprueba el código de 6 dígitos en Backplane › Ajustes › Dispositivos.","web.pair.unreachable":"No se pudo conectar con el hub. Comprueba tu conexión de tailnet.","web.plan.awaiting":"{n} esperando aprobación","web.plan.net.one":"1 red","web.plan.nets":"{n} redes","web.settings.providers":"Proveedores de IA","web.settings.providers.browser":"Conecta un proveedor en la aplicación de escritorio o móvil de Backplane en Configuración → Cuentas."},ja:{"agy.signout":"サインアウト","android.hub.machines.approve":"承認","android.load.earlier":"以前のメッセージを読み込む","approval.dismiss":"閉じる","approval.implement":"実装","ask.plan":"提案されたプラン","bots.new":"新しいボット","bots.rooms":"ルーム","bots.tab.browser":"ブラウザ","common.cancel":"キャンセル","common.close":"閉じる","common.copy":"コピー","common.delete":"削除","common.refresh":"更新","common.remove":"削除","common.save":"保存","composer.model.tip":"モデルと推論の強さを選択","composer.placeholder":"何でも質問:@bot、>thread、%project、#room、$skill、/btw","composer.send":"送信","composer.stop":"停止","gpui.acct.connected":"接続済み","gpui.acct.not.connected":"未接続","gpui.acct.sign.in.expired":"サインインの期限切れ","gpui.ask.plan.ready":"確認待ち","gpui.ask.plan.revise":"修正","gpui.ask.plan.reviseph":"計画のどこを変更しますか?","gpui.ask.plan.sendrev":"修正を送る","gpui.b.in.reply.to":"↩ 返信先:{quote}","gpui.b.replying.to":"↩ 返信中:{line}","gpui.bots.recall.off":"オフ","gpui.bots.recall.on":"オン","gpui.c.solid.big.next":"読み込みには時間と多くのメモリがかかることがあります。","gpui.c.solid.load.big":"それでも読み込む","gpui.c.solid.loading.big":"それでも読み込み中…","gpui.c.term.collapse":"折りたたむ","gpui.c.term.expand":"展開","gpui.commands":"コマンド","gpui.e.open.folder":"フォルダを開く","gpui.filter.projects.and.threads":"プロジェクトとスレッドを絞り込む","gpui.fold.or.unfold.the.sidebar":"サイドバーを折りたたむ/開く","gpui.follow.paused":"追従を一時停止中","gpui.follow.wait":"追従中: エージェントの次の編集を待っています","gpui.gerbers":"ガーバー","gpui.improvements":"改善","gpui.jump.to.a.thread.run":"スレッドへ移動、コマンドを実行、または発言を検索","gpui.mgmt.bom.dnp":"実装しない","gpui.mgmt.bom.nompn":"MPNなし","gpui.mgmt.checks.all":"すべて","gpui.mgmt.checks.fix":"エージェントに直してもらう","gpui.mgmt.checks.run":"実行","gpui.mgmt.close":"パネルを閉じる","gpui.mgmt.fab.apply":"適用","gpui.mgmt.fab.changed":"前回見てから変わったところ","gpui.mgmt.fab.derived":"* 製造元のページから計算した値です(milをmmに、径からランドを)。薄い色の項目はリジッド基板の値です(この基板のページに記載がないもの)。日付を押すと読んだページが開きます。","gpui.mgmt.fab.extra":"追加料金","gpui.mgmt.fab.findings":"指摘","gpui.mgmt.fab.free":"基本料金","gpui.mgmt.fab.judge":"データシート","gpui.mgmt.fab.limit":"項目","gpui.mgmt.fab.readcol":"読んだ日","gpui.mgmt.fab.refresh":"再読み込み","gpui.mgmt.fab.reviewbtn":"レビュー","gpui.mgmt.fab.seen":"確認済み","gpui.mgmt.fab.thefab":"製造元","gpui.mgmt.fab.use":"使う","gpui.mgmt.life.nopart":"この部品の記録はまだありません。","gpui.mgmt.life.reading":"履歴を読んでいます…","gpui.mgmt.plan.addnote":"メモを追加","gpui.mgmt.plan.all":"すべて承認","gpui.mgmt.plan.before":"配線前に計画する","gpui.mgmt.plan.compact":"標準","gpui.mgmt.plan.done":"完了","gpui.mgmt.plan.drawn":"計画の配線経路とプレーンは、このパネルを開いている間だけ基板上に表示されます。閉じると消えます。","gpui.mgmt.plan.edited":"編集済み","gpui.mgmt.plan.elsewhere":"{board}の配線計画が承認を待っています","gpui.mgmt.plan.emptysub":"計画が提案されると、レイヤー・コリドー・ベタ領域がここに表示されます。","gpui.mgmt.plan.expand":"拡大","gpui.mgmt.plan.fit":"全体表示","gpui.mgmt.plan.grid.all":"全レイヤー","gpui.mgmt.plan.grid.pair":"並べて表示","gpui.mgmt.plan.grid.single":"単一","gpui.mgmt.plan.hide":"完了を隠す","gpui.mgmt.plan.hint":"頂点をドラッグして誘導 · 辺の + をクリックで追加 · 頂点を右クリックで削除","gpui.mgmt.plan.keysnote":"このバージョンのKiCadでは、このパネルから承認してください。プランビューでのKiCadのA・R・Wキーはまだ計画のものではありません(Aはフットプリントの追加を開きます)。KiCadを更新してください。","gpui.mgmt.plan.layer":"層を承認","gpui.mgmt.plan.layer.short":"レイヤー","gpui.mgmt.plan.lock":"ロック","gpui.mgmt.plan.locked":"ロック中","gpui.mgmt.plan.noboard":"この基板の配線計画はありません。","gpui.mgmt.plan.noitems":"このレイヤーにコリドーまたはプレーンがありません","gpui.mgmt.plan.note.placeholder":"ルーターへの指示メモ…","gpui.mgmt.plan.nothing":"承認待ちはありません","gpui.mgmt.plan.offwords":"エージェントは指示どおりに配線します。オンにすると、まず配線計画を提案し、ここで承認したものだけを配線します。","gpui.mgmt.plan.onwords":"銅箔層が4層以上、またはネットが60本を超える基板では、配線の前にエージェントがここで配線経路とプレーン領域を提案します。承認したものだけを配線します。","gpui.mgmt.plan.reading":"配線計画を読んでいます…","gpui.mgmt.plan.reference":"基準 {layer}","gpui.mgmt.plan.refused":"KiCad が拒否しました","gpui.mgmt.plan.reject":"却下","gpui.mgmt.plan.rejectlayer":"レイヤーを却下","gpui.mgmt.plan.reqplain":"承認が求められています","gpui.mgmt.plan.requested":"承認が求められています: {what}","gpui.mgmt.plan.saved":"保存された計画","gpui.mgmt.plan.show":"完了を表示","gpui.mgmt.plan.st.approved":"承認済み","gpui.mgmt.plan.st.awaiting":"承認待ち","gpui.mgmt.plan.st.blocked":"ブロック","gpui.mgmt.plan.st.empty":"空","gpui.mgmt.plan.st.partial":"一部完了","gpui.mgmt.plan.st.rejected":"却下","gpui.mgmt.plan.st.routed":"配線済み","gpui.mgmt.plan.st.routing":"配線中","gpui.mgmt.plan.st.verified":"検証済み","gpui.mgmt.plan.stackup.short":"スタックアップ","gpui.mgmt.plan.stop":"配線を止める","gpui.mgmt.plan.sync":"ズーム連動","gpui.mgmt.plan.tab":"計画","gpui.mgmt.plan.unlock":"ロック解除","gpui.mgmt.plan.verify":"検証","gpui.mgmt.plan.view.canvas":"キャンバス","gpui.mgmt.plan.view.list":"リスト","gpui.mgmt.plan.view.split":"分割","gpui.mgmt.plan.width":"幅","gpui.next.thread":"次のスレッド","gpui.no.models":"モデルがありません","gpui.nothing.matches":"一致するものはありません","gpui.picker.favorite.add":"お気に入りに追加","gpui.picker.favorite.remove":"お気に入りから外す","gpui.picker.favorites":"お気に入り","gpui.planmode.bar.always":"計画モード — 編集前に調査して計画を提案します","gpui.planmode.bar.executing":"承認された計画を実行しています","gpui.planmode.bar.once":"計画モード (1回) — 編集前に調査して計画を提案します","gpui.planmode.bar.pending":"提案された計画が下のレビューを待っています","gpui.planmode.bar.planning":"計画中 — 編集前の計画を作成しています","gpui.planmode.chip.building":"実行中","gpui.planmode.chip.once":"計画 · 1回","gpui.planmode.scope.always":"常時","gpui.planmode.scope.once":"1回","gpui.planmode.tip":"実行前に計画を作成 (1回・常時・オフ)","gpui.planmode.top.executing":"計画を実行中","gpui.planmode.top.once":"計画 (1回)","gpui.planmode.top.pending":"計画を確認","gpui.planmode.top.planning":"計画中","gpui.previous.thread":"前のスレッド","gpui.rail.no.board":"このプロジェクトには基板がありません","gpui.rail.no.mech":"このプロジェクトには機械部品がありません","gpui.rail.no.schematic":"このプロジェクトには回路図がありません","gpui.rail.split.needs.both":"分割表示には基板と回路図が必要です","gpui.search.models":"モデルを検索","gpui.settings.group.agents":"エージェントとツール","gpui.settings.group.general":"一般","home.away":"ホーム({name})はオフラインです","home.away.queued":"ホーム({name})はオフラインです · {n} 件待機中","home.away.since":"ホーム({name})は {time} からオフラインです","home.away.since.queued":"ホーム({name})は {time} からオフラインです · {n} 件待機中","home.machine":"ホームマシン","home.move.failed":"ホームの移動に失敗しました","home.move.failed.note":"ホームの移動に失敗しました: {note}","home.move.here":"このマシンをホームにする","home.moving":"ホームを {to} へ移動中…","home.moving.step":"ホームを {to} へ移動中: {step}","hub.back.crash":"予期せず停止したBackplaneが戻りました","hub.restarting":"Backplaneを再起動しています…","hub.restarting.build":"Backplaneを再起動しています…(新しいビルド {build})","hub.stopped":"Backplaneは停止しました","ios.hub.address.field":"ハブのアドレス","menu.pin":"ピン留め","menu.settle":"完了","menu.unpin":"ピン留めを解除","menu.wake":"再開","model.col.agent":"エージェント","model.col.effort":"推論の強さ","native.pair.connect":"接続","native.thread.model":"モデル","notify.settled":"完了","palette.archive":"スレッドをアーカイブ","palette.command.placeholder":"コマンドまたはスレッドを入力","palette.diff":"差分:このスレッドの変更","palette.newthread":"新しいスレッド","palette.settings":"設定","palette.terminal":"ターミナル","palette.unarchive":"スレッドのアーカイブを解除","phone.unsettle":"未完了に戻す","provider.notice.button":"設定 → アカウントを開く","provider.notice.head":"AI プロバイダーが接続されていません","provider.notice.senderr":"AI プロバイダーがまだ接続されていません。設定 → アカウントを開いて、Claude、Codex、Antigravity などのプロバイダーを接続してください。","provider.notice.senderr.remote":"{machine} に AI プロバイダーが接続されていません。{machine} で設定 → アカウントを開いて、Claude、Codex、Antigravity などのプロバイダーを接続してください。","provider.notice.text.none":"チャットを始めるには、Claude、Codex、Antigravity などのプロバイダーを接続してください。","provider.notice.text.signedout":"チャットを始めるには、設定 → アカウントで Claude、Codex などのプロバイダーにサインインしてください。","reply.action":"返信","reply.cancel":"返信をやめる","reply.to":"返信先:","rooms.new":"新しいルーム","secret.you":"あなた","settings.appearance":"外観","settings.lang":"言語","settings.lang.auto":"自動","settings.lang.en":"English","settings.lang.es":"Español","settings.lang.ja":"日本語","settings.theme":"テーマ","settings.theme.dark":"ダーク","settings.theme.light":"ライト","sheet.rename":"スレッド名を変更","sidebar.add.project":"プロジェクトを追加","sidebar.search.projects":"プロジェクトを検索","thread.context.base":"Backplane","thread.context.copied":"プロンプトをコピーしました。","thread.context.copy":"プロンプトをコピー","thread.context.disable":"無効にする","thread.context.enable":"有効にする","thread.context.index":"利用可能なスキルの一覧","thread.context.injected.label":"追加されたプロジェクトの指示","thread.context.instructions":"指示","thread.context.mcp":"プロジェクトの MCP","thread.context.native.note":"Backplane が起動時に渡すプロンプトです。ネイティブファイルはプロバイダーが読み込みます。","thread.context.none.instructions":"プロジェクトの指示が見つかりません。","thread.context.none.mcp":"プロジェクトの MCP 設定が見つかりません。","thread.context.reading":"スレッドのコンテキストを読み込み中…","thread.context.size":"{bytes} B・約{tokens}トークン","thread.context.skills":"スキル","thread.context.system":"システムプロンプト","thread.context.title":"コンテキストとプロンプト","thread.context.trust":"承認して有効にする","thread.new":"新しいスレッド","tools.pinned":"固定中","tools.retry":"再試行","tour.title.bots":"ボット","viewer.board":"基板","viewer.diff":"差分","viewer.files":"ファイル","viewer.mech":"Mech","viewer.review":"レビュー","viewer.schematic":"回路図","viewer.solid":"3D","web.chat.answer.btn":"回答","web.chat.answer.placeholder":"回答を入力…","web.chat.answered":"回答済み: {answer}","web.chat.choose":"左側からプロジェクトのスレッドを選んで開始してください。","web.chat.empty":"まだメッセージはありません。下に入力して開始してください。","web.chat.finished":"完了 {time}","web.chat.finished.dur":"完了 {time} · {dur}","web.chat.loading":"メッセージを読み込んでいます…","web.chat.review.mode":"レビューモード","web.chat.streaming":"受信中…","web.clone.add.dir":"{dir} を追加","web.clone.back":"戻る","web.clone.change.folder":"フォルダを変更","web.clone.cloned":"{repo} を {dest} にクローンしました","web.clone.cloning":"{repo} を {dest} にクローン中","web.clone.copied":"コピーしました","web.clone.first":"最初のメッセージ: {text}","web.clone.folder.name":"フォルダ名","web.clone.go":"クローン","web.clone.loading":"読み込み中…","web.clone.no.folders":"フォルダがありません","web.clone.open.project":"プロジェクトを開く","web.clone.open.thread":"スレッドを開く","web.clone.private":"非公開","web.clone.repo.placeholder":"https / ssh の URL、または owner/repo","web.clone.retry":"もう一度","web.clone.same":"すでにそこにクローンされています: そのまま追加します。","web.clone.signin":"GitHub にサインイン","web.clone.signin.done":"GitHub にサインインしました","web.clone.signin.enter":"このコードを GitHub に入力してください:","web.clone.signin.wait":"GitHub のサインインを開始しています…","web.clone.start.thread":"スレッドを開始","web.clone.stopped":"{repo} のクローンを中止しました","web.clone.tab":"git からクローン","web.clone.up":"上へ","web.clone.use.dir":"{dir} を使う","web.composer.attach":"画像を添付","web.composer.maximages":"1 件のメッセージに添付できる画像は最大 {max} 枚です。","web.composer.unsupported":"未対応の画像形式です: {type}","web.composer.voice":"音声入力","web.logout.failed":"サインアウトを確認できませんでした。もう一度お試しください。","web.pair.approve.in":"デスクトップまたはペアリング済みの端末で承認してください · 有効期限 {time}","web.pair.approved":"承認されました。Backplane を開いています…","web.pair.cancelled":"キャンセルしました。","web.pair.code":"確認コード","web.pair.denied":"ペアリングのリクエストが拒否されました。","web.pair.expired":"ペアリングコードの有効期限が切れました。新しいコードをリクエストしてください。","web.pair.failed":"ペアリングのリクエストに失敗しました ({status})","web.pair.name":"ブラウザー名","web.pair.nocode":"ハブから確認コードが返されませんでした。","web.pair.ratelimited":"ペアリングの試行回数が多すぎます。しばらく待ってからやり直してください。","web.pair.request":"ペアリングをリクエスト","web.pair.requesting":"ペアリングコードをリクエストしています…","web.pair.subtitle":"このブラウザーをハブとペアリングします。Backplane › 設定 › デバイス で 6 桁のコードを承認してください。","web.pair.unreachable":"ハブに接続できませんでした。tailnet の接続を確認してください。","web.plan.awaiting":"{n} 件が承認待ち","web.plan.net.one":"1 ネット","web.plan.nets":"{n} ネット","web.settings.providers":"AI プロバイダー","web.settings.providers.browser":"Backplane のデスクトップまたはモバイルアプリの設定 → アカウントからプロバイダーを接続してください。"}};function Q(a,t){if(!t)return a;return a.replace(/\{([a-zA-Z0-9_.-]+)\}/g,(s,r)=>Object.prototype.hasOwnProperty.call(t,r)?String(t[r]):s)}var 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,j]=s,w=d-u*f,g=[],S=(e,i)=>{for(let n=i-1;n>=0;n--)g.push(e>>>n&1)};S(4,4),S(t.length,8);for(let e of t)S(e,8);for(let e=0;e<4&&g.length{if(e<0||i<0||e>=p||i>=p)return;H[e*p+i]=n?1:0,A[e*p+i]=1},N=(e,i)=>{for(let n=-1;n<=7;n++)for(let m=-1;m<=7;m++){let k=e+n,l=i+m,o=n>=0&&n<=6&&m>=0&&m<=6&&(n===0||n===6||m===0||m===6||n>=2&&n<=4&&m>=2&&m<=4);b(k,l,o)}};N(0,0),N(0,p-7),N(p-7,0);for(let e=8;e=1;e-=2){if(e===6)e=5;let i=(e+1&2)===0;for(let n=0;n>>3]>>>7-(E&7)&1,E++;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,S,C,p),a.appendChild(t);let A=null,b=null,N=null,E=0,D=0,R=150,e=1000;function i(){if(E++,N)N.abort(),N=null;if(A!==null)window.clearTimeout(A),A=null;if(b!==null)window.clearInterval(b),b=null}function n(l="",h=!1){i(),f.classList.remove("bp-hidden"),S.classList.add("bp-hidden"),g.disabled=!1,C.textContent=l,C.className=h?"bp-pair-status bp-bad":"bp-pair-status"}function m(){let l=D-Date.now();if(l<=0){n(c("web.pair.expired","Pairing code expired. Request a new code to try again."),!0);return}B.textContent=c("web.pair.approve.in","Approve on desktop or paired phone · expires in {time}",{time:pe(l)})}async function k(l){if(l!==E)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!==E)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!==E)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!==E)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!==E)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=E;e=1000,R=x.pollMs&&x.pollMs>=100?x.pollMs:150,M.textContent=re(v),f.classList.add("bp-hidden"),S.classList.remove("bp-hidden"),C.textContent="",m(),b=window.setInterval(m,1000),A=window.setTimeout(()=>{k(P)},R)}catch{n(c("web.pair.unreachable","Could not reach the hub. Check your tailnet connection."),!0)}})}if(document.readyState==="loading")document.addEventListener("DOMContentLoaded",ee);else ee(); +var U={en:{"agy.signout":"Sign out","android.hub.machines.approve":"Approve","android.load.earlier":"load earlier","approval.dismiss":"Dismiss","approval.implement":"Implement","ask.plan":"Proposed plan","bots.new":"New bot","bots.rooms":"Rooms","bots.tab.browser":"Browser","common.cancel":"Cancel","common.close":"Close","common.copy":"Copy","common.delete":"Delete","common.refresh":"Refresh","common.remove":"Remove","common.save":"Save","common.search":"Search","composer.model.tip":"Choose the model and effort","composer.placeholder":"Ask anything: @bot, >thread, %project, #room, $skill, /btw","composer.send":"Send","composer.stop":"Stop","gpui.acct.connected":"Connected","gpui.acct.not.connected":"Not connected","gpui.acct.sign.in.expired":"Sign-in expired","gpui.ask.plan.ready":"Ready for review","gpui.ask.plan.revise":"Revise","gpui.ask.plan.reviseph":"What should change in the plan?","gpui.ask.plan.sendrev":"Send revision","gpui.assembly":"Assembly","gpui.b.in.reply.to":"↩ In reply to: {quote}","gpui.b.replying.to":"↩ Replying to: {line}","gpui.bots.recall.off":"Off","gpui.bots.recall.on":"On","gpui.c.solid.big.next":"Loading it may take a while and a lot of memory.","gpui.c.solid.load.big":"Load it anyway","gpui.c.solid.loading.big":"Loading it anyway…","gpui.c.term.collapse":"Collapse","gpui.c.term.expand":"Expand","gpui.commands":"Commands","gpui.e.open.folder":"Open folder","gpui.filter.projects.and.threads":"Filter projects and threads","gpui.fold.or.unfold.the.sidebar":"Fold or unfold the sidebar","gpui.follow.paused":"Following paused","gpui.follow.wait":"Following: waiting for the agent's next edit","gpui.gerbers":"Gerbers","gpui.goal.notes":"GOAL & NOTES","gpui.improvements":"Improvements","gpui.jump.to.a.thread.run":"Jump to a thread, run a command or find what was said","gpui.mgmt.bom.dnp":"DNP","gpui.mgmt.bom.nompn":"no MPN","gpui.mgmt.checks.all":"All","gpui.mgmt.checks.fix":"Fix with agent","gpui.mgmt.checks.run":"Run","gpui.mgmt.close":"Close the panel","gpui.mgmt.fab.apply":"Apply","gpui.mgmt.fab.changed":"Changed since you last looked","gpui.mgmt.fab.derived":"* worked out from the fab's page (a mil in mm, a ring from a diameter). Dimmed: the rigid board's value, where this board's page says nothing else. A date opens the page it was read from.","gpui.mgmt.fab.extra":"Costs more","gpui.mgmt.fab.findings":"Findings","gpui.mgmt.fab.free":"Base price","gpui.mgmt.fab.judge":"Datasheets","gpui.mgmt.fab.limit":"Limit","gpui.mgmt.fab.readcol":"Read","gpui.mgmt.fab.refresh":"Refresh","gpui.mgmt.fab.reviewbtn":"Review","gpui.mgmt.fab.seen":"Seen","gpui.mgmt.fab.thefab":"The fab","gpui.mgmt.fab.use":"Use","gpui.mgmt.life.nopart":"No reading of this part yet.","gpui.mgmt.life.reading":"Reading its history…","gpui.mgmt.plan.addnote":"Add note","gpui.mgmt.plan.all":"Approve all","gpui.mgmt.plan.before":"Plan before routing","gpui.mgmt.plan.compact":"Compact","gpui.mgmt.plan.done":"done","gpui.mgmt.plan.drawn":"The plan's corridors and planes are drawn on the board while this panel is open. Close it to hide them.","gpui.mgmt.plan.edited":"Edited","gpui.mgmt.plan.elsewhere":"A routing plan for {board} awaits your approval","gpui.mgmt.plan.emptysub":"Layers, corridors, and planes appear here once a plan is proposed.","gpui.mgmt.plan.expand":"Expand","gpui.mgmt.plan.fit":"Fit","gpui.mgmt.plan.grid.all":"All layers","gpui.mgmt.plan.grid.pair":"Side by side","gpui.mgmt.plan.grid.single":"Single","gpui.mgmt.plan.hide":"Hide done","gpui.mgmt.plan.hint":"Drag waypoints to steer · Click + on edge to insert · Right-click vertex to remove","gpui.mgmt.plan.keysnote":"On this KiCad version, approve from this panel: in plan view KiCad's A, R and W keys aren't the plan's yet (A opens Add Footprint). Update KiCad.","gpui.mgmt.plan.layer":"Approve layer","gpui.mgmt.plan.layer.short":"Layer","gpui.mgmt.plan.lock":"Lock","gpui.mgmt.plan.locked":"Locked","gpui.mgmt.plan.noboard":"No routing plan for this board.","gpui.mgmt.plan.noitems":"No corridors or planes on this layer","gpui.mgmt.plan.note.placeholder":"Steering note for router…","gpui.mgmt.plan.nothing":"Nothing awaits your approval","gpui.mgmt.plan.offwords":"Agents route as you ask. Turn it on to have them propose a routing plan first and route only what you approve here.","gpui.mgmt.plan.onwords":"Before routing a board with 4 or more copper layers or more than 60 nets, the agent proposes corridors and plane regions here. It routes only what you approve.","gpui.mgmt.plan.reading":"Reading the routing plan…","gpui.mgmt.plan.reference":"over {layer}","gpui.mgmt.plan.refused":"KiCad refused","gpui.mgmt.plan.reject":"Reject","gpui.mgmt.plan.rejectlayer":"Reject layer","gpui.mgmt.plan.reqplain":"Approval requested","gpui.mgmt.plan.requested":"Approval requested: {what}","gpui.mgmt.plan.saved":"saved plan","gpui.mgmt.plan.show":"Show done","gpui.mgmt.plan.st.approved":"Approved","gpui.mgmt.plan.st.awaiting":"Awaiting review","gpui.mgmt.plan.st.blocked":"Blocked","gpui.mgmt.plan.st.empty":"Empty","gpui.mgmt.plan.st.partial":"Partial","gpui.mgmt.plan.st.rejected":"Rejected","gpui.mgmt.plan.st.routed":"Routed","gpui.mgmt.plan.st.routing":"Routing","gpui.mgmt.plan.st.verified":"Verified","gpui.mgmt.plan.stackup.short":"Stackup","gpui.mgmt.plan.stop":"Stop routing","gpui.mgmt.plan.sync":"Link zoom","gpui.mgmt.plan.tab":"Plan","gpui.mgmt.plan.unlock":"Unlock","gpui.mgmt.plan.verify":"Verify","gpui.mgmt.plan.view.canvas":"Canvas","gpui.mgmt.plan.view.list":"List","gpui.mgmt.plan.view.split":"Split","gpui.mgmt.plan.width":"Width","gpui.next.thread":"Next thread","gpui.no.goal.yet.ask.an":"No goal yet. Ask an agent to write what this project is for, or edit .backplane/intent.md.","gpui.no.models":"No models","gpui.no.threads.yet":"No threads yet.","gpui.nothing.matches":"Nothing matches","gpui.picker.favorite.add":"Add to favorites","gpui.picker.favorite.remove":"Remove from favorites","gpui.picker.favorites":"Favorites","gpui.planmode.bar.always":"Plan mode — explores and proposes a plan before editing","gpui.planmode.bar.executing":"Building the approved plan","gpui.planmode.bar.once":"Plan mode (1 turn) — explores and proposes a plan before editing","gpui.planmode.bar.pending":"Proposed plan awaits review below","gpui.planmode.bar.planning":"Planning — drafting a plan before edits","gpui.planmode.chip.building":"Building","gpui.planmode.chip.once":"Plan · 1t","gpui.planmode.scope.always":"Always","gpui.planmode.scope.once":"1 turn","gpui.planmode.tip":"Plan before acting (1 turn, always, or off)","gpui.planmode.top.executing":"Building plan","gpui.planmode.top.once":"Plan (1 turn)","gpui.planmode.top.pending":"Review plan","gpui.planmode.top.planning":"Planning","gpui.previous.thread":"Previous thread","gpui.projects.boards":"BOARDS ({n})","gpui.projects.mech":"MECHANICAL ({n})","gpui.projects.threads":"THREADS ({n})","gpui.projects.to.order":"TO ORDER ({n})","gpui.rail.no.board":"No board in this project","gpui.rail.no.mech":"No mechanical parts in this project","gpui.rail.no.schematic":"No schematic in this project","gpui.rail.split.needs.both":"Split needs a board and a schematic","gpui.search.models":"Search models","gpui.settings.group.agents":"Agents and tools","gpui.settings.group.general":"General","home.away":"Home ({name}) is away","home.away.queued":"Home ({name}) is away · {n} queued","home.away.since":"Home ({name}) is away since {time}","home.away.since.queued":"Home ({name}) is away since {time} · {n} queued","home.machine":"Home machine","home.move.failed":"Home move failed","home.move.failed.note":"Home move failed: {note}","home.move.here":"Make this machine the home","home.moving":"Moving home to {to}…","home.moving.step":"Moving home to {to}: {step}","hub.back.crash":"Backplane is back after it stopped unexpectedly","hub.restarting":"Restarting Backplane…","hub.restarting.build":"Restarting Backplane… (new build {build})","hub.stopped":"Backplane stopped","ios.hub.address.field":"Hub address","menu.pin":"Pin","menu.settle":"Settle","menu.unpin":"Unpin","menu.wake":"Wake","model.col.agent":"Agent","model.col.effort":"Effort","native.pair.connect":"Connect","native.thread.model":"Model","notify.settled":"Settled","palette.archive":"Archive thread","palette.command.placeholder":"Type a command or a thread","palette.diff":"Diff: what this thread changed","palette.newthread":"New thread","palette.settings":"Settings","palette.terminal":"Terminal","palette.unarchive":"Unarchive thread","phone.unsettle":"Unsettle","provider.notice.button":"Open Settings → Accounts","provider.notice.head":"No AI provider connected","provider.notice.senderr":"No AI provider connected yet. Open Settings → Accounts to connect Claude, Codex, Antigravity, or another provider.","provider.notice.senderr.remote":"No AI provider connected on {machine}. Open Settings → Accounts on {machine} to connect Claude, Codex, Antigravity, or another provider.","provider.notice.text.none":"Connect Claude, Codex, Antigravity, or another provider to start chatting.","provider.notice.text.signedout":"Sign in to Claude, Codex, or another provider in Settings → Accounts to start chatting.","reply.action":"Reply","reply.cancel":"Cancel reply","reply.to":"In reply to:","ring.hear.again.local":"Hear again (local)","ring.hear.again.openai":"Hear again (OpenAI)","ring.no.recordings.yet":"No recordings yet.","ring.recordings":"Recordings","ring.ring":"Ring","ring.search.what.you.said":"Search what you said","ring.show.all":"Show all","ring.what.happened":"What happened","rooms.new":"New room","secret.you":"You","settings.appearance":"Appearance","settings.lang":"Language","settings.lang.auto":"Automatic","settings.lang.en":"English","settings.lang.es":"Español","settings.lang.ja":"日本語","settings.theme":"Theme","settings.theme.dark":"Dark","settings.theme.light":"Light","sheet.rename":"Rename thread","sidebar.add.project":"Add project","sidebar.search.projects":"Search projects","thread.context.base":"Backplane","thread.context.copied":"Prompt copied.","thread.context.copy":"Copy prompt","thread.context.disable":"Disable","thread.context.enable":"Enable","thread.context.index":"Available skills index","thread.context.injected.label":"Injected project instructions","thread.context.instructions":"Instructions","thread.context.mcp":"Project MCPs","thread.context.native.note":"Backplane’s launch prompt. Native files are loaded by the provider.","thread.context.none.instructions":"No project instructions found.","thread.context.none.mcp":"No project MCP configurations found.","thread.context.reading":"Reading thread context…","thread.context.size":"{bytes} B · ≈{tokens} tokens","thread.context.skills":"Skills","thread.context.system":"System Prompt","thread.context.title":"Context & Prompt","thread.context.trust":"Trust and enable","thread.new":"New thread","tools.pinned":"Pinned","tools.retry":"Retry","tour.title.bots":"Bots","viewer.board":"Board","viewer.diff":"Diff","viewer.files":"Files","viewer.mech":"Mech","viewer.review":"Review","viewer.schematic":"Schematic","viewer.solid":"3D","web.chat.answer.btn":"Answer","web.chat.answer.placeholder":"Type answer…","web.chat.answered":"Answered: {answer}","web.chat.choose":"Choose a project thread on the left to begin.","web.chat.empty":"No messages yet. Type below to start a turn.","web.chat.finished":"Finished {time}","web.chat.finished.dur":"Finished {time} · {dur}","web.chat.loading":"Loading messages…","web.chat.review.mode":"Review mode","web.chat.streaming":"Streaming…","web.clone.add.dir":"Add {dir}","web.clone.back":"Back","web.clone.change.folder":"Change folder","web.clone.cloned":"Cloned {repo} into {dest}","web.clone.cloning":"Cloning {repo} into {dest}","web.clone.copied":"Copied","web.clone.first":"First message: {text}","web.clone.folder.name":"Folder name","web.clone.go":"Clone","web.clone.loading":"Loading…","web.clone.no.folders":"No folders here","web.clone.open.project":"Open the project","web.clone.open.thread":"Open the thread","web.clone.private":"private","web.clone.repo.placeholder":"https or ssh URL, or owner/repo","web.clone.retry":"Try again","web.clone.same":"Already cloned there: it is added as it is.","web.clone.signin":"Sign in to GitHub","web.clone.signin.done":"Signed in to GitHub","web.clone.signin.enter":"Enter this code on GitHub:","web.clone.signin.wait":"Starting GitHub sign-in…","web.clone.start.thread":"Start a thread","web.clone.stopped":"Stopped cloning {repo}","web.clone.tab":"Clone from git","web.clone.up":"Up","web.clone.use.dir":"Use {dir}","web.composer.attach":"Attach image","web.composer.maximages":"At most {max} images per message.","web.composer.unsupported":"Unsupported image type: {type}","web.composer.voice":"Voice dictation","web.home.error":"Could not load this project.","web.home.fold":"Hide threads","web.home.lead":"Lead time: {n} days","web.home.lead.one":"Lead time: 1 day","web.home.loading":"Loading project…","web.home.open":"Open project home","web.home.unfold":"Show threads","web.logout.failed":"Could not confirm sign-out. Try again.","web.pair.approve.in":"Approve on desktop or paired phone · expires in {time}","web.pair.approved":"Approved. Opening Backplane…","web.pair.cancelled":"Cancelled.","web.pair.code":"Comparison code","web.pair.denied":"Pairing request was denied.","web.pair.expired":"Pairing code expired. Request a new code to try again.","web.pair.failed":"Pairing request failed ({status})","web.pair.name":"Browser name","web.pair.nocode":"Hub did not return a comparison code.","web.pair.ratelimited":"Too many pairing attempts. Wait a moment and try again.","web.pair.request":"Request pairing","web.pair.requesting":"Requesting pairing code…","web.pair.subtitle":"Pair this browser with your hub. Approve the 6-digit code in Backplane › Settings › Devices.","web.pair.unreachable":"Could not reach the hub. Check your tailnet connection.","web.plan.awaiting":"{n} awaiting approval","web.plan.net.one":"1 net","web.plan.nets":"{n} nets","web.ring.app.words":"The Pebble app's words","web.ring.count":"{n} recordings","web.ring.count.one":"1 recording","web.ring.error":"Could not load recordings.","web.ring.found":"{found} of {total} have “{q}”.","web.ring.heard.by":"Heard by {model}","web.ring.heard.by.sure":"Heard by {model}, {conf}% sure","web.ring.loading":"Loading recordings…","web.ring.no.words":"(no words)","web.ring.not.heard":"Not heard","web.ring.state.busy":"being heard now","web.ring.state.failed":"not given to Pebble","web.ring.state.heard":"waiting to go to Pebble","web.ring.state.new":"waiting to be heard","web.ring.state.sent":"given to Pebble","web.ring.unavailable":"This hub does not show ring notes to a browser yet. Update it, or open Settings › Ring in the desktop app.","web.settings.providers":"AI providers","web.settings.providers.browser":"Connect a provider in the Backplane desktop or mobile app under Settings → Accounts."},es:{"agy.signout":"Cerrar sesión","android.hub.machines.approve":"Aprobar","android.load.earlier":"cargar anteriores","approval.dismiss":"Descartar","approval.implement":"Implementar","ask.plan":"Plan propuesto","bots.new":"Nuevo bot","bots.rooms":"Salas","bots.tab.browser":"Navegador","common.cancel":"Cancelar","common.close":"Cerrar","common.copy":"Copiar","common.delete":"Eliminar","common.refresh":"Actualizar","common.remove":"Quitar","common.save":"Guardar","common.search":"Buscar","composer.model.tip":"Elegir el modelo y el esfuerzo","composer.placeholder":"Pregunta lo que sea: @bot, >hilo, %proyecto, #sala, $skill, /btw","composer.send":"Enviar","composer.stop":"Detener","gpui.acct.connected":"Conectado","gpui.acct.not.connected":"No conectado","gpui.acct.sign.in.expired":"Sesión caducada","gpui.ask.plan.ready":"Listo para revisar","gpui.ask.plan.revise":"Revisar","gpui.ask.plan.reviseph":"¿Qué debería cambiar en el plan?","gpui.ask.plan.sendrev":"Enviar revisión","gpui.assembly":"Ensamblaje","gpui.b.in.reply.to":"↩ En respuesta a: {quote}","gpui.b.replying.to":"↩ Respondiendo a: {line}","gpui.bots.recall.off":"Desactivado","gpui.bots.recall.on":"Activado","gpui.c.solid.big.next":"Cargarlo puede tardar y usar mucha memoria.","gpui.c.solid.load.big":"Cargarlo de todos modos","gpui.c.solid.loading.big":"Cargándolo de todos modos…","gpui.c.term.collapse":"Contraer","gpui.c.term.expand":"Expandir","gpui.commands":"Comandos","gpui.e.open.folder":"Abrir carpeta","gpui.filter.projects.and.threads":"Filtrar proyectos e hilos","gpui.fold.or.unfold.the.sidebar":"Plegar o desplegar la barra lateral","gpui.follow.paused":"Seguimiento en pausa","gpui.follow.wait":"Siguiendo: esperando la próxima edición del agente","gpui.gerbers":"Gerbers","gpui.goal.notes":"OBJETIVO Y NOTAS","gpui.improvements":"Mejoras","gpui.jump.to.a.thread.run":"Saltar a un hilo, ejecutar un comando o buscar lo dicho","gpui.mgmt.bom.dnp":"DNP","gpui.mgmt.bom.nompn":"sin MPN","gpui.mgmt.checks.all":"Todas","gpui.mgmt.checks.fix":"Corregir con agente","gpui.mgmt.checks.run":"Ejecutar","gpui.mgmt.close":"Cerrar el panel","gpui.mgmt.fab.apply":"Aplicar","gpui.mgmt.fab.changed":"Cambió desde la última vez que miraste","gpui.mgmt.fab.derived":"* calculado desde la página del fabricante (un mil en mm, un anillo desde un diámetro). Atenuado: el valor de la placa rígida, cuando la página de esta placa no dice otra cosa. Una fecha abre la página de la que se leyó.","gpui.mgmt.fab.extra":"Cuesta más","gpui.mgmt.fab.findings":"Hallazgos","gpui.mgmt.fab.free":"Precio base","gpui.mgmt.fab.judge":"Hojas de datos","gpui.mgmt.fab.limit":"Límite","gpui.mgmt.fab.readcol":"Leído","gpui.mgmt.fab.refresh":"Actualizar","gpui.mgmt.fab.reviewbtn":"Revisar","gpui.mgmt.fab.seen":"Visto","gpui.mgmt.fab.thefab":"El fabricante","gpui.mgmt.fab.use":"Usar","gpui.mgmt.life.nopart":"Sin lectura de esta pieza aún.","gpui.mgmt.life.reading":"Leyendo su historial…","gpui.mgmt.plan.addnote":"Añadir nota","gpui.mgmt.plan.all":"Aprobar todo","gpui.mgmt.plan.before":"Planificar antes de rutear","gpui.mgmt.plan.compact":"Compacto","gpui.mgmt.plan.done":"hecho","gpui.mgmt.plan.drawn":"Los corredores y planos del plan se dibujan en la placa mientras este panel está abierto. Ciérralo para ocultarlos.","gpui.mgmt.plan.edited":"Editado","gpui.mgmt.plan.elsewhere":"Un plan de ruteo para {board} espera tu aprobación","gpui.mgmt.plan.emptysub":"Las capas, corredores y planos aparecerán aquí cuando se proponga un plan.","gpui.mgmt.plan.expand":"Expandir","gpui.mgmt.plan.fit":"Ajustar","gpui.mgmt.plan.grid.all":"Todas las capas","gpui.mgmt.plan.grid.pair":"Lado a lado","gpui.mgmt.plan.grid.single":"Única","gpui.mgmt.plan.hide":"Ocultar hechos","gpui.mgmt.plan.hint":"Arrastra vértices para guiar · Clic en + del borde para insertar · Clic derecho en vértice para quitar","gpui.mgmt.plan.keysnote":"En esta versión de KiCad, aprueba desde este panel: en la vista de plan las teclas A, R y W de KiCad aún no son del plan (A abre Añadir Huella). Actualiza KiCad.","gpui.mgmt.plan.layer":"Aprobar capa","gpui.mgmt.plan.layer.short":"Capa","gpui.mgmt.plan.lock":"Bloquear","gpui.mgmt.plan.locked":"Bloqueado","gpui.mgmt.plan.noboard":"No hay plan de ruteo para esta placa.","gpui.mgmt.plan.noitems":"Sin corredores ni planos en esta capa","gpui.mgmt.plan.note.placeholder":"Nota de guiado para el router…","gpui.mgmt.plan.nothing":"Nada espera tu aprobación","gpui.mgmt.plan.offwords":"Los agentes rutean como les pidas. Actívalo para que primero propongan un plan de ruteo y ruteen solo lo que apruebes aquí.","gpui.mgmt.plan.onwords":"Antes de rutear una placa con 4 o más capas de cobre o más de 60 redes, el agente propone aquí corredores y regiones de plano. Solo rutea lo que apruebes.","gpui.mgmt.plan.reading":"Leyendo el plan de ruteo…","gpui.mgmt.plan.reference":"sobre {layer}","gpui.mgmt.plan.refused":"KiCad lo rechazó","gpui.mgmt.plan.reject":"Rechazar","gpui.mgmt.plan.rejectlayer":"Rechazar capa","gpui.mgmt.plan.reqplain":"Aprobación solicitada","gpui.mgmt.plan.requested":"Aprobación solicitada: {what}","gpui.mgmt.plan.saved":"plan guardado","gpui.mgmt.plan.show":"Mostrar hechos","gpui.mgmt.plan.st.approved":"Aprobado","gpui.mgmt.plan.st.awaiting":"Esperando revisión","gpui.mgmt.plan.st.blocked":"Bloqueado","gpui.mgmt.plan.st.empty":"Vacío","gpui.mgmt.plan.st.partial":"Parcial","gpui.mgmt.plan.st.rejected":"Rechazado","gpui.mgmt.plan.st.routed":"Ruteado","gpui.mgmt.plan.st.routing":"Ruteando","gpui.mgmt.plan.st.verified":"Verificado","gpui.mgmt.plan.stackup.short":"Apilamiento","gpui.mgmt.plan.stop":"Detener ruteo","gpui.mgmt.plan.sync":"Vincular zoom","gpui.mgmt.plan.tab":"Plan","gpui.mgmt.plan.unlock":"Desbloquear","gpui.mgmt.plan.verify":"Verificar","gpui.mgmt.plan.view.canvas":"Lienzo","gpui.mgmt.plan.view.list":"Lista","gpui.mgmt.plan.view.split":"Dividido","gpui.mgmt.plan.width":"Ancho","gpui.next.thread":"Hilo siguiente","gpui.no.goal.yet.ask.an":"Sin objetivo aún. Pide a un agente que escriba para qué es este proyecto, o edita .backplane/intent.md.","gpui.no.models":"Sin modelos","gpui.no.threads.yet":"Sin hilos aún.","gpui.nothing.matches":"Nada coincide","gpui.picker.favorite.add":"Añadir a favoritos","gpui.picker.favorite.remove":"Quitar de favoritos","gpui.picker.favorites":"Favoritos","gpui.planmode.bar.always":"Modo plan — explora y propone un plan antes de editar","gpui.planmode.bar.executing":"Ejecutando el plan aprobado","gpui.planmode.bar.once":"Modo plan (1 turno) — explora y propone un plan antes de editar","gpui.planmode.bar.pending":"El plan propuesto espera revisión abajo","gpui.planmode.bar.planning":"Planificando — redactando un plan antes de editar","gpui.planmode.chip.building":"Ejecutando","gpui.planmode.chip.once":"Plan · 1t","gpui.planmode.scope.always":"Siempre","gpui.planmode.scope.once":"1 turno","gpui.planmode.tip":"Planificar antes de actuar (1 turno, siempre u off)","gpui.planmode.top.executing":"Ejecutando plan","gpui.planmode.top.once":"Plan (1 turno)","gpui.planmode.top.pending":"Revisar plan","gpui.planmode.top.planning":"Planificando","gpui.previous.thread":"Hilo anterior","gpui.projects.boards":"PLACAS ({n})","gpui.projects.mech":"MECÁNICO ({n})","gpui.projects.threads":"HILOS ({n})","gpui.projects.to.order":"POR PEDIR ({n})","gpui.rail.no.board":"Este proyecto no tiene placa","gpui.rail.no.mech":"Este proyecto no tiene piezas mecánicas","gpui.rail.no.schematic":"Este proyecto no tiene esquema","gpui.rail.split.needs.both":"La vista dividida requiere una placa y un esquema","gpui.search.models":"Buscar modelos","gpui.settings.group.agents":"Agentes y herramientas","gpui.settings.group.general":"General","home.away":"El inicio ({name}) no está disponible","home.away.queued":"El inicio ({name}) no está disponible · {n} en cola","home.away.since":"El inicio ({name}) no está disponible desde las {time}","home.away.since.queued":"El inicio ({name}) no está disponible desde las {time} · {n} en cola","home.machine":"Máquina de inicio","home.move.failed":"No se pudo mover el inicio","home.move.failed.note":"No se pudo mover el inicio: {note}","home.move.here":"Hacer de esta máquina el inicio","home.moving":"Moviendo el inicio a {to}…","home.moving.step":"Moviendo el inicio a {to}: {step}","hub.back.crash":"Backplane volvió tras detenerse de forma inesperada","hub.restarting":"Reiniciando Backplane…","hub.restarting.build":"Reiniciando Backplane… (nueva compilación {build})","hub.stopped":"Backplane se detuvo","ios.hub.address.field":"Dirección del hub","menu.pin":"Fijar","menu.settle":"Cerrar","menu.unpin":"Desfijar","menu.wake":"Despertar","model.col.agent":"Agente","model.col.effort":"Esfuerzo","native.pair.connect":"Conectar","native.thread.model":"Modelo","notify.settled":"Cerrado","palette.archive":"Archivar hilo","palette.command.placeholder":"Escribe un comando o un hilo","palette.diff":"Diff: qué cambió este hilo","palette.newthread":"Nuevo hilo","palette.settings":"Ajustes","palette.terminal":"Terminal","palette.unarchive":"Desarchivar hilo","phone.unsettle":"Reabrir","provider.notice.button":"Abrir Configuración → Cuentas","provider.notice.head":"No hay ningún proveedor de IA conectado","provider.notice.senderr":"Aún no hay ningún proveedor de IA conectado. Abre Configuración → Cuentas para conectar Claude, Codex, Antigravity u otro proveedor.","provider.notice.senderr.remote":"No hay ningún proveedor de IA conectado en {machine}. Abre Configuración → Cuentas en {machine} para conectar Claude, Codex, Antigravity u otro proveedor.","provider.notice.text.none":"Conecta Claude, Codex, Antigravity u otro proveedor para empezar a chatear.","provider.notice.text.signedout":"Inicia sesión en Claude, Codex u otro proveedor en Configuración → Cuentas para empezar a chatear.","reply.action":"Responder","reply.cancel":"Cancelar respuesta","reply.to":"En respuesta a:","ring.hear.again.local":"Escuchar de nuevo (local)","ring.hear.again.openai":"Escuchar de nuevo (OpenAI)","ring.no.recordings.yet":"Sin grabaciones aún.","ring.recordings":"Grabaciones","ring.ring":"Anillo","ring.search.what.you.said":"Buscar lo que dijiste","ring.show.all":"Mostrar todo","ring.what.happened":"Qué ocurrió","rooms.new":"Nueva sala","secret.you":"Tú","settings.appearance":"Apariencia","settings.lang":"Idioma","settings.lang.auto":"Automático","settings.lang.en":"English","settings.lang.es":"Español","settings.lang.ja":"日本語","settings.theme":"Tema","settings.theme.dark":"Oscuro","settings.theme.light":"Claro","sheet.rename":"Renombrar hilo","sidebar.add.project":"Añadir proyecto","sidebar.search.projects":"Buscar proyectos","thread.context.base":"Backplane","thread.context.copied":"Se copiaron las instrucciones.","thread.context.copy":"Copiar instrucciones","thread.context.disable":"Desactivar","thread.context.enable":"Activar","thread.context.index":"Índice de habilidades disponibles","thread.context.injected.label":"Instrucciones del proyecto añadidas","thread.context.instructions":"Instrucciones","thread.context.mcp":"MCP del proyecto","thread.context.native.note":"Instrucciones de inicio de Backplane. El proveedor carga los archivos nativos.","thread.context.none.instructions":"No se encontraron instrucciones del proyecto.","thread.context.none.mcp":"No se encontraron configuraciones MCP del proyecto.","thread.context.reading":"Leyendo el contexto del hilo…","thread.context.size":"{bytes} B · ≈{tokens} tokens","thread.context.skills":"Habilidades","thread.context.system":"Instrucciones del sistema","thread.context.title":"Contexto e instrucciones","thread.context.trust":"Confiar y activar","thread.new":"Nuevo hilo","tools.pinned":"Fijado","tools.retry":"Reintentar","tour.title.bots":"Bots","viewer.board":"Placa","viewer.diff":"Diff","viewer.files":"Archivos","viewer.mech":"Mech","viewer.review":"Revisión","viewer.schematic":"Esquemático","viewer.solid":"3D","web.chat.answer.btn":"Responder","web.chat.answer.placeholder":"Escribe una respuesta…","web.chat.answered":"Respondido: {answer}","web.chat.choose":"Elige un hilo de proyecto a la izquierda para empezar.","web.chat.empty":"Aún no hay mensajes. Escribe abajo para iniciar un turno.","web.chat.finished":"Terminado {time}","web.chat.finished.dur":"Terminado {time} · {dur}","web.chat.loading":"Cargando mensajes…","web.chat.review.mode":"Modo de revisión","web.chat.streaming":"Transmitiendo…","web.clone.add.dir":"Añadir {dir}","web.clone.back":"Atrás","web.clone.change.folder":"Cambiar carpeta","web.clone.cloned":"{repo} clonado en {dest}","web.clone.cloning":"Clonando {repo} en {dest}","web.clone.copied":"Copiado","web.clone.first":"Primer mensaje: {text}","web.clone.folder.name":"Nombre de la carpeta","web.clone.go":"Clonar","web.clone.loading":"Cargando…","web.clone.no.folders":"No hay carpetas aquí","web.clone.open.project":"Abrir el proyecto","web.clone.open.thread":"Abrir el hilo","web.clone.private":"privado","web.clone.repo.placeholder":"URL https o ssh, o propietario/repositorio","web.clone.retry":"Reintentar","web.clone.same":"Ya está clonado ahí: se añade tal cual.","web.clone.signin":"Iniciar sesión en GitHub","web.clone.signin.done":"Sesión iniciada en GitHub","web.clone.signin.enter":"Introduce este código en GitHub:","web.clone.signin.wait":"Iniciando sesión en GitHub…","web.clone.start.thread":"Empezar un hilo","web.clone.stopped":"Se detuvo la clonación de {repo}","web.clone.tab":"Clonar desde git","web.clone.up":"Subir","web.clone.use.dir":"Usar {dir}","web.composer.attach":"Adjuntar imagen","web.composer.maximages":"Como máximo {max} imágenes por mensaje.","web.composer.unsupported":"Tipo de imagen no compatible: {type}","web.composer.voice":"Dictado por voz","web.home.error":"No se pudo cargar este proyecto.","web.home.fold":"Ocultar hilos","web.home.lead":"Plazo de entrega: {n} días","web.home.lead.one":"Plazo de entrega: 1 día","web.home.loading":"Cargando el proyecto…","web.home.open":"Abrir la página del proyecto","web.home.unfold":"Mostrar hilos","web.logout.failed":"No se pudo confirmar el cierre de sesión. Inténtalo de nuevo.","web.pair.approve.in":"Aprueba en el escritorio o en un teléfono vinculado · caduca en {time}","web.pair.approved":"Aprobado. Abriendo Backplane…","web.pair.cancelled":"Cancelado.","web.pair.code":"Código de comparación","web.pair.denied":"Se rechazó la solicitud de vinculación.","web.pair.expired":"El código de vinculación caducó. Solicita uno nuevo para intentarlo otra vez.","web.pair.failed":"Falló la solicitud de vinculación ({status})","web.pair.name":"Nombre del navegador","web.pair.nocode":"El hub no devolvió un código de comparación.","web.pair.ratelimited":"Demasiados intentos de vinculación. Espera un momento e inténtalo de nuevo.","web.pair.request":"Solicitar vinculación","web.pair.requesting":"Solicitando código de vinculación…","web.pair.subtitle":"Vincula este navegador con tu hub. Aprueba el código de 6 dígitos en Backplane › Ajustes › Dispositivos.","web.pair.unreachable":"No se pudo conectar con el hub. Comprueba tu conexión de tailnet.","web.plan.awaiting":"{n} esperando aprobación","web.plan.net.one":"1 red","web.plan.nets":"{n} redes","web.ring.app.words":"Las palabras de la aplicación Pebble","web.ring.count":"{n} grabaciones","web.ring.count.one":"1 grabación","web.ring.error":"No se pudieron cargar las grabaciones.","web.ring.found":"{found} de {total} contienen “{q}”.","web.ring.heard.by":"Transcrito por {model}","web.ring.heard.by.sure":"Transcrito por {model}, {conf}% de certeza","web.ring.loading":"Cargando grabaciones…","web.ring.no.words":"(sin palabras)","web.ring.not.heard":"Sin transcribir","web.ring.state.busy":"transcribiéndose ahora","web.ring.state.failed":"no entregada a Pebble","web.ring.state.heard":"en espera de entrega a Pebble","web.ring.state.new":"en espera de transcripción","web.ring.state.sent":"entregada a Pebble","web.ring.unavailable":"Este hub aún no muestra las notas del anillo en un navegador. Actualízalo o abre Configuración › Anillo en la aplicación de escritorio.","web.settings.providers":"Proveedores de IA","web.settings.providers.browser":"Conecta un proveedor en la aplicación de escritorio o móvil de Backplane en Configuración → Cuentas."},ja:{"agy.signout":"サインアウト","android.hub.machines.approve":"承認","android.load.earlier":"以前のメッセージを読み込む","approval.dismiss":"閉じる","approval.implement":"実装","ask.plan":"提案されたプラン","bots.new":"新しいボット","bots.rooms":"ルーム","bots.tab.browser":"ブラウザ","common.cancel":"キャンセル","common.close":"閉じる","common.copy":"コピー","common.delete":"削除","common.refresh":"更新","common.remove":"削除","common.save":"保存","common.search":"検索","composer.model.tip":"モデルと推論の強さを選択","composer.placeholder":"何でも質問:@bot、>thread、%project、#room、$skill、/btw","composer.send":"送信","composer.stop":"停止","gpui.acct.connected":"接続済み","gpui.acct.not.connected":"未接続","gpui.acct.sign.in.expired":"サインインの期限切れ","gpui.ask.plan.ready":"確認待ち","gpui.ask.plan.revise":"修正","gpui.ask.plan.reviseph":"計画のどこを変更しますか?","gpui.ask.plan.sendrev":"修正を送る","gpui.assembly":"アセンブリ","gpui.b.in.reply.to":"↩ 返信先:{quote}","gpui.b.replying.to":"↩ 返信中:{line}","gpui.bots.recall.off":"オフ","gpui.bots.recall.on":"オン","gpui.c.solid.big.next":"読み込みには時間と多くのメモリがかかることがあります。","gpui.c.solid.load.big":"それでも読み込む","gpui.c.solid.loading.big":"それでも読み込み中…","gpui.c.term.collapse":"折りたたむ","gpui.c.term.expand":"展開","gpui.commands":"コマンド","gpui.e.open.folder":"フォルダを開く","gpui.filter.projects.and.threads":"プロジェクトとスレッドを絞り込む","gpui.fold.or.unfold.the.sidebar":"サイドバーを折りたたむ/開く","gpui.follow.paused":"追従を一時停止中","gpui.follow.wait":"追従中: エージェントの次の編集を待っています","gpui.gerbers":"ガーバー","gpui.goal.notes":"目標とメモ","gpui.improvements":"改善","gpui.jump.to.a.thread.run":"スレッドへ移動、コマンドを実行、または発言を検索","gpui.mgmt.bom.dnp":"実装しない","gpui.mgmt.bom.nompn":"MPNなし","gpui.mgmt.checks.all":"すべて","gpui.mgmt.checks.fix":"エージェントに直してもらう","gpui.mgmt.checks.run":"実行","gpui.mgmt.close":"パネルを閉じる","gpui.mgmt.fab.apply":"適用","gpui.mgmt.fab.changed":"前回見てから変わったところ","gpui.mgmt.fab.derived":"* 製造元のページから計算した値です(milをmmに、径からランドを)。薄い色の項目はリジッド基板の値です(この基板のページに記載がないもの)。日付を押すと読んだページが開きます。","gpui.mgmt.fab.extra":"追加料金","gpui.mgmt.fab.findings":"指摘","gpui.mgmt.fab.free":"基本料金","gpui.mgmt.fab.judge":"データシート","gpui.mgmt.fab.limit":"項目","gpui.mgmt.fab.readcol":"読んだ日","gpui.mgmt.fab.refresh":"再読み込み","gpui.mgmt.fab.reviewbtn":"レビュー","gpui.mgmt.fab.seen":"確認済み","gpui.mgmt.fab.thefab":"製造元","gpui.mgmt.fab.use":"使う","gpui.mgmt.life.nopart":"この部品の記録はまだありません。","gpui.mgmt.life.reading":"履歴を読んでいます…","gpui.mgmt.plan.addnote":"メモを追加","gpui.mgmt.plan.all":"すべて承認","gpui.mgmt.plan.before":"配線前に計画する","gpui.mgmt.plan.compact":"標準","gpui.mgmt.plan.done":"完了","gpui.mgmt.plan.drawn":"計画の配線経路とプレーンは、このパネルを開いている間だけ基板上に表示されます。閉じると消えます。","gpui.mgmt.plan.edited":"編集済み","gpui.mgmt.plan.elsewhere":"{board}の配線計画が承認を待っています","gpui.mgmt.plan.emptysub":"計画が提案されると、レイヤー・コリドー・ベタ領域がここに表示されます。","gpui.mgmt.plan.expand":"拡大","gpui.mgmt.plan.fit":"全体表示","gpui.mgmt.plan.grid.all":"全レイヤー","gpui.mgmt.plan.grid.pair":"並べて表示","gpui.mgmt.plan.grid.single":"単一","gpui.mgmt.plan.hide":"完了を隠す","gpui.mgmt.plan.hint":"頂点をドラッグして誘導 · 辺の + をクリックで追加 · 頂点を右クリックで削除","gpui.mgmt.plan.keysnote":"このバージョンのKiCadでは、このパネルから承認してください。プランビューでのKiCadのA・R・Wキーはまだ計画のものではありません(Aはフットプリントの追加を開きます)。KiCadを更新してください。","gpui.mgmt.plan.layer":"層を承認","gpui.mgmt.plan.layer.short":"レイヤー","gpui.mgmt.plan.lock":"ロック","gpui.mgmt.plan.locked":"ロック中","gpui.mgmt.plan.noboard":"この基板の配線計画はありません。","gpui.mgmt.plan.noitems":"このレイヤーにコリドーまたはプレーンがありません","gpui.mgmt.plan.note.placeholder":"ルーターへの指示メモ…","gpui.mgmt.plan.nothing":"承認待ちはありません","gpui.mgmt.plan.offwords":"エージェントは指示どおりに配線します。オンにすると、まず配線計画を提案し、ここで承認したものだけを配線します。","gpui.mgmt.plan.onwords":"銅箔層が4層以上、またはネットが60本を超える基板では、配線の前にエージェントがここで配線経路とプレーン領域を提案します。承認したものだけを配線します。","gpui.mgmt.plan.reading":"配線計画を読んでいます…","gpui.mgmt.plan.reference":"基準 {layer}","gpui.mgmt.plan.refused":"KiCad が拒否しました","gpui.mgmt.plan.reject":"却下","gpui.mgmt.plan.rejectlayer":"レイヤーを却下","gpui.mgmt.plan.reqplain":"承認が求められています","gpui.mgmt.plan.requested":"承認が求められています: {what}","gpui.mgmt.plan.saved":"保存された計画","gpui.mgmt.plan.show":"完了を表示","gpui.mgmt.plan.st.approved":"承認済み","gpui.mgmt.plan.st.awaiting":"承認待ち","gpui.mgmt.plan.st.blocked":"ブロック","gpui.mgmt.plan.st.empty":"空","gpui.mgmt.plan.st.partial":"一部完了","gpui.mgmt.plan.st.rejected":"却下","gpui.mgmt.plan.st.routed":"配線済み","gpui.mgmt.plan.st.routing":"配線中","gpui.mgmt.plan.st.verified":"検証済み","gpui.mgmt.plan.stackup.short":"スタックアップ","gpui.mgmt.plan.stop":"配線を止める","gpui.mgmt.plan.sync":"ズーム連動","gpui.mgmt.plan.tab":"計画","gpui.mgmt.plan.unlock":"ロック解除","gpui.mgmt.plan.verify":"検証","gpui.mgmt.plan.view.canvas":"キャンバス","gpui.mgmt.plan.view.list":"リスト","gpui.mgmt.plan.view.split":"分割","gpui.mgmt.plan.width":"幅","gpui.next.thread":"次のスレッド","gpui.no.goal.yet.ask.an":"目標はまだありません。このプロジェクトの目的をエージェントに書いてもらうか、.backplane/intent.md を編集してください。","gpui.no.models":"モデルがありません","gpui.no.threads.yet":"スレッドはまだありません。","gpui.nothing.matches":"一致するものはありません","gpui.picker.favorite.add":"お気に入りに追加","gpui.picker.favorite.remove":"お気に入りから外す","gpui.picker.favorites":"お気に入り","gpui.planmode.bar.always":"計画モード — 編集前に調査して計画を提案します","gpui.planmode.bar.executing":"承認された計画を実行しています","gpui.planmode.bar.once":"計画モード (1回) — 編集前に調査して計画を提案します","gpui.planmode.bar.pending":"提案された計画が下のレビューを待っています","gpui.planmode.bar.planning":"計画中 — 編集前の計画を作成しています","gpui.planmode.chip.building":"実行中","gpui.planmode.chip.once":"計画 · 1回","gpui.planmode.scope.always":"常時","gpui.planmode.scope.once":"1回","gpui.planmode.tip":"実行前に計画を作成 (1回・常時・オフ)","gpui.planmode.top.executing":"計画を実行中","gpui.planmode.top.once":"計画 (1回)","gpui.planmode.top.pending":"計画を確認","gpui.planmode.top.planning":"計画中","gpui.previous.thread":"前のスレッド","gpui.projects.boards":"基板({n})","gpui.projects.mech":"機構部品({n})","gpui.projects.threads":"スレッド({n})","gpui.projects.to.order":"注文するもの({n})","gpui.rail.no.board":"このプロジェクトには基板がありません","gpui.rail.no.mech":"このプロジェクトには機械部品がありません","gpui.rail.no.schematic":"このプロジェクトには回路図がありません","gpui.rail.split.needs.both":"分割表示には基板と回路図が必要です","gpui.search.models":"モデルを検索","gpui.settings.group.agents":"エージェントとツール","gpui.settings.group.general":"一般","home.away":"ホーム({name})はオフラインです","home.away.queued":"ホーム({name})はオフラインです · {n} 件待機中","home.away.since":"ホーム({name})は {time} からオフラインです","home.away.since.queued":"ホーム({name})は {time} からオフラインです · {n} 件待機中","home.machine":"ホームマシン","home.move.failed":"ホームの移動に失敗しました","home.move.failed.note":"ホームの移動に失敗しました: {note}","home.move.here":"このマシンをホームにする","home.moving":"ホームを {to} へ移動中…","home.moving.step":"ホームを {to} へ移動中: {step}","hub.back.crash":"予期せず停止したBackplaneが戻りました","hub.restarting":"Backplaneを再起動しています…","hub.restarting.build":"Backplaneを再起動しています…(新しいビルド {build})","hub.stopped":"Backplaneは停止しました","ios.hub.address.field":"ハブのアドレス","menu.pin":"ピン留め","menu.settle":"完了","menu.unpin":"ピン留めを解除","menu.wake":"再開","model.col.agent":"エージェント","model.col.effort":"推論の強さ","native.pair.connect":"接続","native.thread.model":"モデル","notify.settled":"完了","palette.archive":"スレッドをアーカイブ","palette.command.placeholder":"コマンドまたはスレッドを入力","palette.diff":"差分:このスレッドの変更","palette.newthread":"新しいスレッド","palette.settings":"設定","palette.terminal":"ターミナル","palette.unarchive":"スレッドのアーカイブを解除","phone.unsettle":"未完了に戻す","provider.notice.button":"設定 → アカウントを開く","provider.notice.head":"AI プロバイダーが接続されていません","provider.notice.senderr":"AI プロバイダーがまだ接続されていません。設定 → アカウントを開いて、Claude、Codex、Antigravity などのプロバイダーを接続してください。","provider.notice.senderr.remote":"{machine} に AI プロバイダーが接続されていません。{machine} で設定 → アカウントを開いて、Claude、Codex、Antigravity などのプロバイダーを接続してください。","provider.notice.text.none":"チャットを始めるには、Claude、Codex、Antigravity などのプロバイダーを接続してください。","provider.notice.text.signedout":"チャットを始めるには、設定 → アカウントで Claude、Codex などのプロバイダーにサインインしてください。","reply.action":"返信","reply.cancel":"返信をやめる","reply.to":"返信先:","ring.hear.again.local":"もう一度聞き取る (ローカル)","ring.hear.again.openai":"もう一度聞き取る (OpenAI)","ring.no.recordings.yet":"録音はまだありません。","ring.recordings":"録音","ring.ring":"リング","ring.search.what.you.said":"話した内容を検索","ring.show.all":"すべて表示","ring.what.happened":"どうなったか","rooms.new":"新しいルーム","secret.you":"あなた","settings.appearance":"外観","settings.lang":"言語","settings.lang.auto":"自動","settings.lang.en":"English","settings.lang.es":"Español","settings.lang.ja":"日本語","settings.theme":"テーマ","settings.theme.dark":"ダーク","settings.theme.light":"ライト","sheet.rename":"スレッド名を変更","sidebar.add.project":"プロジェクトを追加","sidebar.search.projects":"プロジェクトを検索","thread.context.base":"Backplane","thread.context.copied":"プロンプトをコピーしました。","thread.context.copy":"プロンプトをコピー","thread.context.disable":"無効にする","thread.context.enable":"有効にする","thread.context.index":"利用可能なスキルの一覧","thread.context.injected.label":"追加されたプロジェクトの指示","thread.context.instructions":"指示","thread.context.mcp":"プロジェクトの MCP","thread.context.native.note":"Backplane が起動時に渡すプロンプトです。ネイティブファイルはプロバイダーが読み込みます。","thread.context.none.instructions":"プロジェクトの指示が見つかりません。","thread.context.none.mcp":"プロジェクトの MCP 設定が見つかりません。","thread.context.reading":"スレッドのコンテキストを読み込み中…","thread.context.size":"{bytes} B・約{tokens}トークン","thread.context.skills":"スキル","thread.context.system":"システムプロンプト","thread.context.title":"コンテキストとプロンプト","thread.context.trust":"承認して有効にする","thread.new":"新しいスレッド","tools.pinned":"固定中","tools.retry":"再試行","tour.title.bots":"ボット","viewer.board":"基板","viewer.diff":"差分","viewer.files":"ファイル","viewer.mech":"Mech","viewer.review":"レビュー","viewer.schematic":"回路図","viewer.solid":"3D","web.chat.answer.btn":"回答","web.chat.answer.placeholder":"回答を入力…","web.chat.answered":"回答済み: {answer}","web.chat.choose":"左側からプロジェクトのスレッドを選んで開始してください。","web.chat.empty":"まだメッセージはありません。下に入力して開始してください。","web.chat.finished":"完了 {time}","web.chat.finished.dur":"完了 {time} · {dur}","web.chat.loading":"メッセージを読み込んでいます…","web.chat.review.mode":"レビューモード","web.chat.streaming":"受信中…","web.clone.add.dir":"{dir} を追加","web.clone.back":"戻る","web.clone.change.folder":"フォルダを変更","web.clone.cloned":"{repo} を {dest} にクローンしました","web.clone.cloning":"{repo} を {dest} にクローン中","web.clone.copied":"コピーしました","web.clone.first":"最初のメッセージ: {text}","web.clone.folder.name":"フォルダ名","web.clone.go":"クローン","web.clone.loading":"読み込み中…","web.clone.no.folders":"フォルダがありません","web.clone.open.project":"プロジェクトを開く","web.clone.open.thread":"スレッドを開く","web.clone.private":"非公開","web.clone.repo.placeholder":"https / ssh の URL、または owner/repo","web.clone.retry":"もう一度","web.clone.same":"すでにそこにクローンされています: そのまま追加します。","web.clone.signin":"GitHub にサインイン","web.clone.signin.done":"GitHub にサインインしました","web.clone.signin.enter":"このコードを GitHub に入力してください:","web.clone.signin.wait":"GitHub のサインインを開始しています…","web.clone.start.thread":"スレッドを開始","web.clone.stopped":"{repo} のクローンを中止しました","web.clone.tab":"git からクローン","web.clone.up":"上へ","web.clone.use.dir":"{dir} を使う","web.composer.attach":"画像を添付","web.composer.maximages":"1 件のメッセージに添付できる画像は最大 {max} 枚です。","web.composer.unsupported":"未対応の画像形式です: {type}","web.composer.voice":"音声入力","web.home.error":"このプロジェクトを読み込めませんでした。","web.home.fold":"スレッドを隠す","web.home.lead":"リードタイム: {n} 日","web.home.lead.one":"リードタイム: 1 日","web.home.loading":"プロジェクトを読み込み中…","web.home.open":"プロジェクトホームを開く","web.home.unfold":"スレッドを表示","web.logout.failed":"サインアウトを確認できませんでした。もう一度お試しください。","web.pair.approve.in":"デスクトップまたはペアリング済みの端末で承認してください · 有効期限 {time}","web.pair.approved":"承認されました。Backplane を開いています…","web.pair.cancelled":"キャンセルしました。","web.pair.code":"確認コード","web.pair.denied":"ペアリングのリクエストが拒否されました。","web.pair.expired":"ペアリングコードの有効期限が切れました。新しいコードをリクエストしてください。","web.pair.failed":"ペアリングのリクエストに失敗しました ({status})","web.pair.name":"ブラウザー名","web.pair.nocode":"ハブから確認コードが返されませんでした。","web.pair.ratelimited":"ペアリングの試行回数が多すぎます。しばらく待ってからやり直してください。","web.pair.request":"ペアリングをリクエスト","web.pair.requesting":"ペアリングコードをリクエストしています…","web.pair.subtitle":"このブラウザーをハブとペアリングします。Backplane › 設定 › デバイス で 6 桁のコードを承認してください。","web.pair.unreachable":"ハブに接続できませんでした。tailnet の接続を確認してください。","web.plan.awaiting":"{n} 件が承認待ち","web.plan.net.one":"1 ネット","web.plan.nets":"{n} ネット","web.ring.app.words":"Pebble アプリの文字起こし","web.ring.count":"録音 {n} 件","web.ring.count.one":"録音 1 件","web.ring.error":"録音を読み込めませんでした。","web.ring.found":"{total} 件中 {found} 件に「{q}」があります。","web.ring.heard.by":"{model} が認識","web.ring.heard.by.sure":"{model} が認識、確度 {conf}%","web.ring.loading":"録音を読み込み中…","web.ring.no.words":"(言葉なし)","web.ring.not.heard":"未認識","web.ring.state.busy":"認識中","web.ring.state.failed":"Pebble に渡せませんでした","web.ring.state.heard":"Pebble への受け渡し待ち","web.ring.state.new":"認識待ち","web.ring.state.sent":"Pebble に渡しました","web.ring.unavailable":"このハブはまだブラウザーにリングのメモを表示しません。ハブを更新するか、デスクトップアプリの設定 › リングを開いてください。","web.settings.providers":"AI プロバイダー","web.settings.providers.browser":"Backplane のデスクトップまたはモバイルアプリの設定 → アカウントからプロバイダーを接続してください。"}};function 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 H=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=H}Y();function ge(a){return W.add(a),()=>{W.delete(a)}}function me(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!==H;if(H=s,Y(),r)for(let d of W)d(H);return r}function ue(){return H}function c(a,t,s){let d=(U[H]||U.en||{})[a]??U.en?.[a]??t??a;return Q(d,s)}function be(a){if(!a)return"";let t=V.get(a);if(!t)return a;return c(t,a)}var ae=[[1,26,7,1,[]],[2,44,10,1,[6,18]],[3,70,15,1,[6,22]],[4,100,20,1,[6,26]],[5,134,26,1,[6,30]],[6,172,18,2,[6,34]]],G=new Uint8Array(512),_=new Uint8Array(256);{let a=1;for(let t=0;t<255;t++)if(G[t]=a,_[a]=t,a<<=1,a&256)a^=285;for(let t=255;t<512;t++)G[t]=G[t-255]}function J(a,t){return a===0||t===0?0:G[_[a]+_[t]]}function ne(a){let t=new Uint8Array([1]);for(let s=0;s{let g=e-o*n;return Math.ceil((12+t.length*8)/8)<=g});if(!s)return null;let[r,d,m,f,S]=s,w=d-m*f,u=[],E=(e,o)=>{for(let n=o-1;n>=0;n--)u.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&&u.length{if(e<0||o<0||e>=p||o>=p)return;z[e*p+o]=n?1:0,C[e*p+o]=1},N=(e,o)=>{for(let n=-1;n<=7;n++)for(let g=-1;g<=7;g++){let k=e+n,l=o+g,i=n>=0&&n<=6&&g>=0&&g<=6&&(n===0||n===6||g===0||g===6||n>=2&&n<=4&&g>=2&&g<=4);b(k,l,i)}};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 o=(e+1&2)===0;for(let n=0;n>>3]>>>7-(j&7)&1,j++;let i=(g+l&1)===0?h^1:h;z[g*p+l]=i}}}let P=30660;for(let e=0;e<=5;e++)b(8,e,(P>>>14-e&1)===1);b(8,7,(P>>>8&1)===1),b(8,8,(P>>>7&1)===1),b(7,8,(P>>>6&1)===1);for(let e=0;e<=5;e++)b(5-e,8,(P>>>5-e&1)===1);for(let e=0;e<8;e++)b(8,p-1-e,(P>>>e&1)===1);for(let e=0;e<7;e++)b(p-7+e,8,(P>>>14-e&1)===1);return{size:p,modules:z}}function X(a){let t=ie(a);if(!t)return null;let s=2,r=t.size+s*2,d=document.createElementNS("http://www.w3.org/2000/svg","svg");d.setAttribute("viewBox",`0 0 ${r} ${r}`),d.setAttribute("role","img"),d.setAttribute("aria-label",`QR code for ${a}`),d.setAttribute("shape-rendering","crispEdges"),d.classList.add("bp-qr-svg");let m=document.createElementNS("http://www.w3.org/2000/svg","rect");m.setAttribute("width",String(r)),m.setAttribute("height",String(r)),m.setAttribute("fill","#ffffff"),d.appendChild(m);let f="";for(let w=0;w{let h=l.trim();if(!h)return;let i=h.startsWith("https://")?h:`https://${h}`;if(!i.startsWith("https://")||i.length<=8)return;let x=document.createElement("div");x.className="bp-pair-addr-meta";let v=document.createElement("div");v.className="bp-pair-code-label",v.textContent=c("ios.hub.address.field","Hub address");let y=document.createElement("code");y.className="bp-pair-addr-url",y.textContent=i,y.setAttribute("data-testid","pair-address");let R=document.createElement("button");R.type="button",R.className="bp-pair-copy";let O=c("common.copy","Copy");R.textContent=O,R.addEventListener("click",()=>{navigator.clipboard?.writeText(i).then(()=>{R.textContent=c("web.clone.copied","Copied"),window.setTimeout(()=>{R.textContent=O},1200)}).catch(()=>{})}),x.append(v,y,R);let D=document.createDocumentFragment();D.appendChild(x);let K=X(i);if(K){let F=document.createElement("div");F.className="bp-pair-qr",F.setAttribute("data-testid","pair-qr"),F.appendChild(K),D.appendChild(F)}p.replaceChildren(D),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,m,f,E,A,p),a.appendChild(t);let C=null,b=null,N=null,j=0,I=0,P=150,e=1000;function o(){if(j++,N)N.abort(),N=null;if(C!==null)window.clearTimeout(C),C=null;if(b!==null)window.clearInterval(b),b=null}function n(l="",h=!1){o(),f.classList.remove("bp-hidden"),E.classList.add("bp-hidden"),u.disabled=!1,A.textContent=l,A.className=h?"bp-pair-status bp-bad":"bp-pair-status"}function g(){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!==j)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 i=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,i.status===202){C=window.setTimeout(()=>{k(l)},150);return}if(i.status===200||i.status===204){let v={};if(i.status===200)try{v=await i.json()}catch{}if(l!==j)return;let y=(v.state||v.status||"").toLowerCase();if(i.status===204||v.approved===!0||y==="approved"||y==="ok"){o(),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(i.status===429){let v=Number(i.headers.get("Retry-After")||"5"),y=Math.max(2000,(Number.isFinite(v)?v:5)*1000);C=window.setTimeout(()=>{k(l)},y);return}if(i.status===401||i.status===403||i.status===404||i.status===410){let v="";try{let y=await i.json();v=(y.state||y.status||y.error||"").toLowerCase()}catch{}if(l!==j)return;if(v==="denied"||v==="rejected"||i.status===403)n(c("web.pair.denied","Pairing request was denied."),!0);else n(c("web.pair.expired","Pairing code expired. Request a new code to try again."),!0);return}let x=e;e=Math.min(1e4,Math.round(e*1.8)),C=window.setTimeout(()=>{k(l)},x)}catch{if(l!==j)return;let i=e;e=Math.min(1e4,Math.round(e*1.8)),C=window.setTimeout(()=>{k(l)},i)}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();u.disabled=!0,A.textContent=c("web.pair.requesting","Requesting pairing code…"),A.className="bp-pair-status";try{let i=await fetch("/auth/web/request",{method:"POST",credentials:"same-origin",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:h})});if(!i.ok){let O=c("web.pair.failed","Pairing request failed ({status})",{status:i.status});try{let D=await i.json();if(D.error)O=D.error}catch{}if(i.status===429)O=c("web.pair.ratelimited","Too many pairing attempts. Wait a moment and try again.");n(O,!0);return}let x=await i.json(),v=x.code||x.checkCode||"";if(!v){n(c("web.pair.nocode","Hub did not return a comparison code."),!0);return}let y=Date.now();I=x.expiresAt?x.expiresAt<10000000000?x.expiresAt*1000:x.expiresAt:y+(x.expiresIn?x.expiresIn*1000:120000),o();let R=j;e=1000,P=x.pollMs&&x.pollMs>=100?x.pollMs:150,M.textContent=re(v),f.classList.add("bp-hidden"),E.classList.remove("bp-hidden"),A.textContent="",g(),b=window.setInterval(g,1000),C=window.setTimeout(()=>{k(R)},P)}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 37200d4f78..a4aa47c4df 100644 --- a/web/dist/assets/style.css +++ b/web/dist/assets/style.css @@ -2955,6 +2955,213 @@ button.primary.bp-send-btn.is-plan-exec { overflow-y: auto; } +/* Project Home: the page a project's name opens (project-home.ts). It covers the thread and its composer. */ +.bp-center.bp-home-open > :not(.bp-project-home) { display: none !important; } +.bp-project-home { + flex: 1; + min-height: 0; + overflow-y: auto; + background: var(--bg); +} +.bp-home-inner { + max-width: 860px; + margin: 0 auto; + padding: 20px 24px 40px; + display: flex; + flex-direction: column; +} +.bp-home-head { display: flex; flex-direction: column; gap: 3px; } +.bp-home-title { + margin: 0; + font-size: 20px; + font-weight: 700; + color: var(--text); + overflow-wrap: anywhere; +} +.bp-home-root { + font-size: 12px; + color: var(--dim); + font-family: var(--mono); + overflow-wrap: anywhere; +} +.bp-home-bar { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 8px; + padding: 12px 0 4px; +} +button.primary.bp-home-new { + display: inline-flex; + align-items: center; + gap: 6px; + height: 30px; + padding: 0 12px; + font-size: 12px; +} +.bp-home-new-plus { font-size: 15px; line-height: 1; } +.bp-home-section { + margin: 0; + padding: 18px 0 5px; + border-bottom: 1px solid var(--rule); + font-size: 11px; + font-weight: 600; + letter-spacing: 0.06em; + color: var(--faint); +} +.bp-home-empty { + padding: 9px 0; + font-size: 12px; + color: var(--dim); +} +.bp-home-row { + display: flex; + align-items: center; + gap: 8px; + width: 100%; + min-height: 28px; + padding: 3px 8px; + border: 0; + border-bottom: 1px solid var(--line); + background: transparent; + color: var(--text); + font-size: 12px; + text-align: left; +} +button.bp-home-row { cursor: pointer; } +button.bp-home-row:hover { background: var(--raise); } +button.bp-home-row:focus-visible { outline: 1px solid var(--accent); outline-offset: -1px; } +.bp-home-thread { min-height: 30px; font-size: 13px; } +.bp-home-row-main { + flex: 1; + min-width: 0; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} +.bp-home-row-dim { color: var(--dim); flex-shrink: 0; } +.bp-home-row-accent { color: var(--accent); flex-shrink: 0; } +.bp-home-row-faint { + color: var(--faint); + flex-shrink: 1; + min-width: 0; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} +.bp-home-intent { + display: flex; + flex-direction: column; + gap: 4px; + padding: 8px 0; + font-size: 13px; + line-height: 1.45; + overflow-wrap: anywhere; +} +.bp-home-intent-h { padding-top: 4px; font-weight: 700; } +.bp-home-intent-li { display: flex; gap: 8px; } +.bp-home-bullet { color: var(--dim); flex-shrink: 0; } +.bp-home-order { display: flex; flex-direction: column; } +.bp-home-order-note { + padding: 5px 8px; + border-bottom: 1px solid var(--line); + font-size: 12px; + color: var(--dim); +} +.bp-home-order-note.warn { + color: var(--warn); + border-left: 2px solid var(--warn); + background: color-mix(in srgb, var(--warn) 8%, var(--panel)); +} +.bp-home-error { + display: flex; + align-items: center; + justify-content: space-between; + gap: 12px; + margin-top: 12px; + padding: 8px 10px; + border-left: 2px solid var(--bad); + background: color-mix(in srgb, var(--bad) 8%, var(--panel)); + font-size: 12px; +} +.bp-proj-chev { + flex-shrink: 0; + width: 14px; + padding: 0; + border: 0; + background: transparent; + color: var(--faint); + font-size: 10px; + line-height: 1; + cursor: pointer; +} +.bp-proj-chev:hover:not(:disabled) { color: var(--text); } +.bp-proj-chev:disabled { cursor: default; opacity: 0.4; } +.bp-proj-head.active { background: var(--raise); box-shadow: inset 2px 0 0 var(--accent); } +.bp-proj-head.active .bp-proj-toggle { color: var(--accent); } + +/* Settings › Ring: the ring's voice notes (settings.ts renderRingPage). */ +.bp-ring-search { + display: flex; + align-items: center; + gap: 6px; + padding: 4px 0 10px; +} +.bp-ring-search-input { + flex: 1; + min-width: 0; + height: 28px; + padding: 0 8px; + background: var(--panel); + border: 1px solid var(--line); + color: var(--text); + font-size: 12px; +} +.bp-ring-search-input:focus { outline: 0; border-color: var(--accent); } +.bp-ring-count { + padding: 0 0 6px; + border-bottom: 1px solid var(--rule); + font-size: 12px; + color: var(--dim); +} +.bp-ring-note { + display: flex; + flex-direction: column; + gap: 5px; + padding: 11px 0; + border-bottom: 1px solid var(--line); +} +.bp-ring-note.bad { box-shadow: inset 2px 0 0 var(--bad); padding-left: 10px; } +.bp-ring-note-head { + display: flex; + align-items: center; + gap: 8px; + flex-wrap: wrap; +} +.bp-ring-words { + font-size: 13px; + line-height: 1.45; + color: var(--text); + white-space: pre-wrap; + overflow-wrap: anywhere; +} +.bp-ring-words.bp-dim { color: var(--dim); } +.bp-ring-acts { + display: flex; + align-items: center; + flex-wrap: wrap; + gap: 6px; + padding-top: 2px; +} +.bp-ring-audio { height: 28px; max-width: 100%; } + +@media (max-width: 640px) { + .bp-home-inner { padding: 14px 14px 32px; } + .bp-home-row-faint { display: none; } + .bp-home-thread .bp-home-row-faint { display: inline; } + .bp-ring-search { flex-wrap: wrap; } +} + /* Web viewer pane + 1440 / 820 / 390 px responsive styles. Auto-concatenated into web/dist/assets/style.css by web/build.ts. diff --git a/web/dist/manifest.json b/web/dist/manifest.json index fb62806f9f..14141f4222 100644 --- a/web/dist/manifest.json +++ b/web/dist/manifest.json @@ -1,6 +1,6 @@ { "version": 1, - "totalAssetGzipBytes": 226499, + "totalAssetGzipBytes": 235837, "styleTokensSha256": "a4fed1b1c7bc676acc328907343eb5dcf87e426383d05617c632e48c0c3f2b80", "i18nKeys": [ "agy.signout", @@ -19,6 +19,7 @@ "common.refresh", "common.remove", "common.save", + "common.search", "composer.model.tip", "composer.placeholder", "composer.send", @@ -30,6 +31,7 @@ "gpui.ask.plan.revise", "gpui.ask.plan.reviseph", "gpui.ask.plan.sendrev", + "gpui.assembly", "gpui.b.in.reply.to", "gpui.b.replying.to", "gpui.bots.recall.off", @@ -46,6 +48,7 @@ "gpui.follow.paused", "gpui.follow.wait", "gpui.gerbers", + "gpui.goal.notes", "gpui.improvements", "gpui.jump.to.a.thread.run", "gpui.mgmt.bom.dnp", @@ -126,7 +129,9 @@ "gpui.mgmt.plan.view.split", "gpui.mgmt.plan.width", "gpui.next.thread", + "gpui.no.goal.yet.ask.an", "gpui.no.models", + "gpui.no.threads.yet", "gpui.nothing.matches", "gpui.picker.favorite.add", "gpui.picker.favorite.remove", @@ -146,6 +151,10 @@ "gpui.planmode.top.pending", "gpui.planmode.top.planning", "gpui.previous.thread", + "gpui.projects.boards", + "gpui.projects.mech", + "gpui.projects.threads", + "gpui.projects.to.order", "gpui.rail.no.board", "gpui.rail.no.mech", "gpui.rail.no.schematic", @@ -195,6 +204,14 @@ "reply.action", "reply.cancel", "reply.to", + "ring.hear.again.local", + "ring.hear.again.openai", + "ring.no.recordings.yet", + "ring.recordings", + "ring.ring", + "ring.search.what.you.said", + "ring.show.all", + "ring.what.happened", "rooms.new", "secret.you", "settings.appearance", @@ -279,6 +296,13 @@ "web.composer.maximages", "web.composer.unsupported", "web.composer.voice", + "web.home.error", + "web.home.fold", + "web.home.lead", + "web.home.lead.one", + "web.home.loading", + "web.home.open", + "web.home.unfold", "web.logout.failed", "web.pair.approve.in", "web.pair.approved", @@ -297,13 +321,29 @@ "web.plan.awaiting", "web.plan.net.one", "web.plan.nets", + "web.ring.app.words", + "web.ring.count", + "web.ring.count.one", + "web.ring.error", + "web.ring.found", + "web.ring.heard.by", + "web.ring.heard.by.sure", + "web.ring.loading", + "web.ring.no.words", + "web.ring.not.heard", + "web.ring.state.busy", + "web.ring.state.failed", + "web.ring.state.heard", + "web.ring.state.new", + "web.ring.state.sent", + "web.ring.unavailable", "web.settings.providers", "web.settings.providers.browser" ], - "i18nSubsetSha256": "e1e01f4aab8b46aadc56378ef0500fda7c05056b61cd8d7e20899e4b401825d9", + "i18nSubsetSha256": "6e36764b44f9e02d79f1962767de5a6ee5d04d2e6f01d8bbf6454d049483e23d", "inputs": { "web/src/addproject.ts": "06a7ff3e13cd78d993ebca7f638d5d623da06c0099186ad534bae8f184dbe44f", - "web/src/app.ts": "dab89eac7b331589dec115874030207d6e4b218ae3e1bfab044fa951db1ac0b6", + "web/src/app.ts": "8dd026527a0661b6034c6776a4d4dcf18a468d2a913e07cbc93a282c6ca858b7", "web/src/chat.ts": "639e3af0791aedcde788c1a76aee6ea07cf96f5749d6a3564898c2beb8bd7337", "web/src/clone-model.ts": "d265df49436e14f415bbeb2a271ffa3552f9163be62bdc0158cecc10c3cdae45", "web/src/composer.ts": "63a5e9d7acfd321007c0a18880ee0ba055506335fcf4808154febc2b380f91a8", @@ -321,13 +361,16 @@ "web/src/palette-model.ts": "ae359cc71e98e84774428355a5048fd9ba0e1da2d45fa18290b4313c50c50ee4", "web/src/palette.ts": "bcd5c4585f57cc80a9cf29bf1b9da6ebbd33a3ab68f8f2a918c37c58060c8e48", "web/src/plan-canvas.ts": "49a0af6ef960301d4ea75f2fcd48628e01d983431d96329f37e6a3704bafd498", + "web/src/project-home-model.ts": "866d403419cf28df64a914cf20aaceb177203666114d591e14feaa522494f048", + "web/src/project-home.ts": "fd6920d5c9a9b7e6c81a4376b50b8e1981e23c791fbab7a9b431dce2a2086c06", "web/src/provider-notice.ts": "96efd0b9ce7981efadfdbba3e2eac7b7fa00cf18f3126f980b9d087022084e29", "web/src/qr.ts": "04b634557884b8f512a7b03ad9638c1c15a299ffaea0103d1bdeec6338d9b9d3", "web/src/rail.ts": "5fb391094992578cb6f54d35d53559951a584c43fcfc2ee6f4f2cc3897acfe46", - "web/src/settings-model.ts": "19e99d594cf3eebb66b616f81dee5877abddb2d24c1d4e32fa0bc2b205cb268b", - "web/src/settings.ts": "ff87ef3e3554502e43035cfb18df9973836e6a9b2573eef6e8c47bea2a01ec62", - "web/src/shell.css": "7835682f03cff4cc968ccf16350eb53a8f0556906226866fbabdedc91a5d54af", - "web/src/sidebar.ts": "a0f3e1b7fbba5ab4cb57e73e1d92bc73a986f1e30ee59258edd5cefc95da7401", + "web/src/ring-model.ts": "66368ffe8996138d4e73f041e50ac4fa573cf20ee59571af5fd1f320e29a895d", + "web/src/settings-model.ts": "2f8f64cc93ee54c1bf45d918d8568eec2457970db7b3c43e926b2b4c45dcd5f6", + "web/src/settings.ts": "8d4c24f554ba9c7ba4c4a96098fe25eea68b91f41489aee4d2b01b616f41f507", + "web/src/shell.css": "8859e0833ec034ca137745c6863305a9e897c5f72a9c1b2dbec4434dffe11bce", + "web/src/sidebar.ts": "121045bb07d60d7b06393b4c67862d0088991b0737ff52b94add9dd5510ad2b1", "web/src/swarm-need.ts": "503bbf5ffe0389f068847571c792321b0ad5c8d26a18c73b8e41c0a8989e227f", "web/src/thread-context.ts": "b9fbd5b3ef0b1357b5a4444a1e9a0ac0606afe1c8a5377c4777752e918af0ac2", "web/src/user-refs.ts": "56bcf0dc116d5f14260606f07cf9af9becbbd7cbb102dc9e0687a4ea5f894011", @@ -350,7 +393,7 @@ "web/vendor/xterm/addon-fit.js": "bdaefa370b1bfc42ee88d46fe6072400902a4d4b2d45cd93438dda9b23c97089", "web/vendor/xterm/xterm.css": "ba8e6985669488981ccf40c0cefe3aba80722cb6c92de7ad628b0bd717faf2b6", "web/vendor/xterm/xterm.js": "1f991ac3b4b283ebf96e60ae23a00a52765dd3a2e46fa6fdda9f1aab032f7495", - "web/build.ts": "7f3d0d83a46bdea2e8cae217d0ae2cc5de83eac51c3b28e4d9c01a245bd3c7fd", + "web/build.ts": "1e15fdb4ba619837e0db3aa716c958a2c1750bf317c188c4ffa9be2c568ac3e2", "assets/providers/claude.svg": "2d6fda79eb18ddccca35b799eeb3cece0dfabc22520ce3b10abd25668df9fa93", "assets/providers/codex.svg": "71f7c8cae66142a92f69e2681dff60da996b64e1a64495a21e14c1ef40f3b277", "assets/providers/grok.svg": "752909b823c8d6e0262a7495b76a09950bcd11652a46c5796b47499ada6226ec", @@ -364,9 +407,9 @@ }, "outputs": { "assets/app.js": { - "bytes": 409177, - "gzipBytes": 115528, - "sha256": "a729db89b1c16801fbd3170bd3524e861672da5d22c825ce59c7b0a67245599a" + "bytes": 434864, + "gzipBytes": 122455, + "sha256": "7650fc2de412daac4bc5d60cb382555c4d8f8470df5841f437915e7da1ec2621" }, "assets/favicon-light.svg": { "bytes": 1207, @@ -384,14 +427,14 @@ "sha256": "123b6a27f255d339b505c8fd83609674f0bddf9b46c0e907fce23befa96b1eec" }, "assets/pair.js": { - "bytes": 56546, - "gzipBytes": 16971, - "sha256": "9fe98ad951dc2249587934deef6e42a9638caaafd7605244813d0e98b10a8874" + "bytes": 62486, + "gzipBytes": 18662, + "sha256": "2aca9be2863742059403024eca7b5cc265665b2cc99e54ce95cd6c3d6e681c21" }, "assets/style.css": { - "bytes": 94970, - "gzipBytes": 15701, - "sha256": "5acb2a2d1fd314d57f982720ebcdfc2b9cde147123ea63136d3b301ea6f3b21e" + "bytes": 99938, + "gzipBytes": 16421, + "sha256": "65dfec07c0af6a83cf5da4c3c511cd08d842b07eec2dc677af2f26e21eb3ef8a" }, "assets/terminal.js": { "bytes": 296616, diff --git a/web/src/app.ts b/web/src/app.ts index 4f502a5994..e02dca8b1b 100644 --- a/web/src/app.ts +++ b/web/src/app.ts @@ -10,7 +10,10 @@ import { onLocaleChange, setLocale, t } from "./i18n"; import { signOut } from "./logout"; import { MgmtStrip } from "./mgmt"; import { CommandPalette, type PaletteAction, type PaletteSearchResult } from "./palette"; +import { ProjectHomeView, type HomeThreadRow } from "./project-home"; +import { parseProjectHome, rawProjectId } from "./project-home-model"; import { isLocalNoProviderError, parseNoProvider, type NoProviderNotice } from "./provider-notice"; +import { parseRingList } from "./ring-model"; import { RailView, type RailEntry } from "./rail"; import { needAfter, needPress } from "./swarm-need"; import { SettingsModal, type SettingsRow } from "./settings"; @@ -88,6 +91,17 @@ function stateDotClass(th: ThreadItem | null): string { return "bp-dot-idle"; } +/** A thread's age as the sidebar writes it: now, 5m, 3h, 2d. */ +function ageText(ts: number): string { + if (!ts) return ""; + const ms = ts < 10_000_000_000 ? ts * 1000 : ts; + const sec = Math.max(0, Math.floor((Date.now() - ms) / 1000)); + if (sec < 60) return "now"; + if (sec < 3600) return `${Math.floor(sec / 60)}m`; + if (sec < 86400) return `${Math.floor(sec / 3600)}h`; + return `${Math.floor(sec / 86400)}d`; +} + function hasForKind(has: RailHas | undefined, kind: string): boolean { if (!has) return true; if (kind === "board" || kind === "3d") return has.board !== false; @@ -346,15 +360,91 @@ function mountApp(): void { } } + // Project Home: the page a project's name opens (feature `projecthome`); it covers the thread and its composer until a thread is opened + let homeProjectId = ""; + let homeGen = 0; + const projectHome = new ProjectHomeView(centerEl, { + onNewThread: (projectId) => { void createThread(projectId); }, + onOpenThread: (id) => { void openThread(id); }, + onOpenViewer: (threadId, kind) => { + void openThread(threadId).then(() => { + if (selectedThreadId === threadId) openViewer(kind); + }); + }, + onRetry: (projectId) => { void openProjectHome(projectId); }, + }); + + function closeProjectHome(): void { + if (!homeProjectId) return; + homeProjectId = ""; + homeGen++; + centerEl.classList.remove("bp-home-open"); + projectHome.hide(); + sidebar.setSelectedProject(""); + updateHeader(); + } + + /** A project by the id the hub's requests take: a section row's id may carry its place before a `|`. */ + function projectOf(projectId: string): ProjectItem | undefined { + return projects.find((p) => p.id === projectId) ?? projects.find((p) => rawProjectId(p.id) === projectId); + } + + /** The home's thread rows: the hub's own list for the project, in its order. */ + async function loadHomeThreads(projectId: string, gen: number): Promise { + try { + const res = await hub.rpc<{ threads?: ThreadItem[] }>("threads.list", { project: projectId, limit: 50, archived: false }); + if (gen !== homeGen || homeProjectId !== projectId) return; + const rows: HomeThreadRow[] = (res.threads ?? []).filter((th) => !th.swarm).map((th) => ({ + id: th.id, + title: th.title, + dot: stateDotClass(th), + status: th.status || th.state || "", + age: ageText(th.updatedAt), + settled: th.settled, + })); + projectHome.setThreads(rows); + } catch { + if (gen === homeGen && homeProjectId === projectId) projectHome.setThreads([]); + } + } + + /** Opens a project's home. False: this hub has no home to show (an older hub), and the caller does what it did before. */ + function openProjectHome(projectId: string): boolean { + if (!projectId || !hub.hasFeature("projecthome")) return false; + voice.cancel(); + composer.closeModelPicker(); + homeProjectId = projectId; + const gen = ++homeGen; + const proj = projectOf(projectId); + centerEl.classList.add("bp-home-open"); + sidebarEl.classList.remove("bp-sidebar-open"); + projectHome.show({ id: projectId, title: proj?.title ?? projectId }); + sidebar.setSelectedProject(projectId); + updateHeader(); + void loadHomeThreads(projectId, gen); + void hub.rpc("project.home", { project: projectId }) + .then((res) => { + if (gen === homeGen && homeProjectId === projectId) projectHome.setData(parseProjectHome(res)); + }) + .catch((e) => { + if (gen !== homeGen || homeProjectId !== projectId) return; + projectHome.setError(e instanceof Error && e.message ? e.message : t("web.home.error", "Could not load this project.")); + }); + return true; + } + const sidebar = new SidebarView(sidebarEl, { onSelectThread: (id) => { if (id === selectedThreadId && threadSubId !== null) { + closeProjectHome(); sidebarEl.classList.remove("bp-sidebar-open"); return; } void openThread(id); }, onNewThread: (projectId) => { void createThread(projectId); }, + onOpenProject: (projectId) => openProjectHome(rawProjectId(projectId)), + canOpenProject: () => hub.hasFeature("projecthome"), onSelectBot: (bot) => { void openThread(bot.thread); }, onQuickOpenViewer: (projectId, kind) => { const existing = threads.find((th) => th.project === projectId && !th.archived && !th.swarm); @@ -748,6 +838,10 @@ function mountApp(): void { } catch { /* ignore */ } applyEffectiveLocale(); }, + hasRing: () => hub.hasFeature("ringnotes"), + onRingList: async (q) => parseRingList(await hub.rpc("ring.list", { q })), + onRingHear: async (note, engine) => { await hub.rpc("ring.hear", { note, engine }); }, + onOpenThread: (id) => { void openThread(id); }, onLogout: () => signOut(() => { hub.disconnect(); window.location.replace("/"); @@ -899,8 +993,12 @@ function mountApp(): void { }); function updateHeader(): void { - const th = threads.find((x) => x.id === selectedThreadId) ?? null; - const proj = th ? projects.find((p) => p.id === th.project) : undefined; + // a project's home is on show: the bar names the project and offers nothing of a thread + const th = homeProjectId ? null : threads.find((x) => x.id === selectedThreadId) ?? null; + const proj = homeProjectId + ? projectOf(homeProjectId) ?? { id: homeProjectId, title: homeProjectId } + : th ? projectOf(th.project) : undefined; + if (homeProjectId && proj) projectHome.setTitle(proj.title); projCrumb.textContent = proj?.title ?? ""; sep1.classList.toggle("bp-hidden", !proj); sep2.classList.toggle("bp-hidden", !th); @@ -1081,6 +1179,7 @@ function mountApp(): void { sidebar.setData(projects, threads, bots, rooms); sidebar.setSections(list, bots, rooms); updateHeader(); + if (homeProjectId) void loadHomeThreads(homeProjectId, homeGen); return true; } catch { return false; @@ -1212,7 +1311,8 @@ function mountApp(): void { } if (targetId && ((sections && hasSectionThreadId(sections, targetId)) || threads.some((x) => x.id === targetId))) { - await openThread(targetId); + // a reconnect while a project's home is on show: the thread under it is opened again, the home stays + await openThread(targetId, homeProjectId !== ""); } else { selectedThreadId = ""; railItems = []; @@ -1220,9 +1320,12 @@ function mountApp(): void { composer.setState(false, false); updateHeader(); } + // still on show (nothing else was opened meanwhile): what it says is read again + if (homeProjectId) openProjectHome(homeProjectId); } - async function openThread(threadId: string): Promise { + async function openThread(threadId: string, keepHome = false): Promise { + if (!keepHome) closeProjectHome(); if (selectedThreadId && selectedThreadId !== threadId) { voice.cancel(); const held = chat.getEntries(); @@ -1635,6 +1738,7 @@ function mountApp(): void { composer.refreshLocale(); rail.render(); settings.refreshLocale(); + projectHome.refreshLocale(); addProject.refreshLocale(); }); diff --git a/web/src/project-home-model.ts b/web/src/project-home-model.ts new file mode 100644 index 0000000000..4da1c6cfd3 --- /dev/null +++ b/web/src/project-home-model.ts @@ -0,0 +1,112 @@ +// Pure Project Home model: what the hub's `project.home` (feature `projecthome`) says of a project, read defensively, and the few +// text shapes the page draws. Zero DOM imports so it can be unit tested directly with bun test. + +export interface HomePart { + name: string; + kind: string; + path: string; +} + +export interface HomeMech { + path: string; + name: string; + size: number; +} + +export interface ProjectHomeData { + project: string; + root: string; + intent: string; + parts: HomePart[]; + boards: string[]; + mech: HomeMech[]; + /** The longest lead time the last estimate named, in days; 0 when there is none. */ + leadDays: number; + /** What the last estimate warned of, each once. */ + warnings: string[]; +} + +export interface IntentLine { + kind: "h" | "li" | "p"; + text: string; +} + +function str(v: unknown): string { + return typeof v === "string" ? v : ""; +} + +function rec(v: unknown): Record { + return v && typeof v === "object" && !Array.isArray(v) ? (v as Record) : {}; +} + +function list(v: unknown): unknown[] { + return Array.isArray(v) ? v : []; +} + +/** The hub's answer as the page holds it: missing or mistyped fields read as empty, never as an error. */ +export function parseProjectHome(raw: unknown): ProjectHomeData { + const r = rec(raw); + const lead = typeof r.leadDays === "number" && Number.isFinite(r.leadDays) && r.leadDays > 0 ? Math.floor(r.leadDays) : 0; + const warnings: string[] = []; + for (const w of list(r.warnings)) { + const s = str(w).trim(); + if (s && !warnings.includes(s)) warnings.push(s); + } + return { + project: str(r.project), + root: str(r.root), + intent: str(r.intent), + parts: list(r.parts) + .map((p) => rec(p)) + .map((p) => ({ name: str(p.name), kind: str(p.kind), path: str(p.path) })) + .filter((p) => p.name || p.path), + boards: list(r.boards).map(str).filter(Boolean), + mech: list(r.mech) + .map((m) => rec(m)) + .map((m) => ({ path: str(m.path), name: str(m.name), size: typeof m.size === "number" && m.size > 0 ? m.size : 0 })) + .filter((m) => m.name || m.path), + leadDays: lead, + warnings, + }; +} + +/** + * The goal and notes as the person wrote them (`.backplane/intent.md`), a line each: a heading, a list item or text. + * The desktop's `intent_lines` (native/gpui/src/screens/projects.rs): blank lines dropped, 60 lines at most. + */ +export function intentLines(text: string): IntentLine[] { + const out: IntentLine[] = []; + for (const raw of text.split("\n")) { + const line = raw.trimEnd(); + if (!line.trim()) continue; + if (out.length >= 60) break; + const t = line.trimStart(); + if (t.startsWith("#")) { + out.push({ kind: "h", text: t.replace(/^#+/, "").trim() }); + } else if (t.startsWith("- ") || t.startsWith("* ")) { + out.push({ kind: "li", text: t.slice(2).trim() }); + } else { + out.push({ kind: "p", text: t }); + } + } + return out; +} + +/** Whether the intent says anything beyond its headings (the template is headings only). */ +export function intentIsEmpty(text: string): boolean { + return !intentLines(text).some((l) => l.kind !== "h" && l.text.length > 0); +} + +/** A file's size as the desktop writes it: B, KB, MB. */ +export function sizeText(bytes: number): string { + if (!Number.isFinite(bytes) || bytes <= 0) return ""; + if (bytes < 1024) return `${Math.floor(bytes)} B`; + if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(bytes < 10 * 1024 ? 1 : 0)} KB`; + return `${(bytes / (1024 * 1024)).toFixed(1)} MB`; +} + +/** A project's id as the hub's requests take it: a section row's id may carry its place before a `|`. */ +export function rawProjectId(id: string): string { + const idx = id.lastIndexOf("|"); + return idx >= 0 ? id.slice(idx + 1) : id; +} diff --git a/web/src/project-home.ts b/web/src/project-home.ts new file mode 100644 index 0000000000..c69d13ef93 --- /dev/null +++ b/web/src/project-home.ts @@ -0,0 +1,287 @@ +// Project Home: the page a project's name opens (the desktop's project page, native/gpui/src/screens/projects.rs): the project and +// its folder, New thread, its threads, the goal and notes, the mechanical parts, what there is to order (with the last estimate's +// lead time and warnings) and its boards. Everything shown is the hub's (`project.home`, `threads.list`); nothing is priced or bought here. +import { t } from "./i18n"; +import { intentIsEmpty, intentLines, sizeText, type ProjectHomeData } from "./project-home-model"; + +export interface HomeThreadRow { + id: string; + title: string; + /** The dot's class (`bp-dot-work`, `bp-dot-need`, …), as the top bar draws the thread's state. */ + dot: string; + /** The state's word, for the dot's tooltip. */ + status: string; + age: string; + settled?: boolean; +} + +export interface ProjectHomeCallbacks { + onNewThread: (projectId: string) => void; + onOpenThread: (threadId: string) => void; + /** A board or model row: its viewer, on the project's newest thread. */ + onOpenViewer: (threadId: string, kind: "board" | "mech") => void; + onRetry: (projectId: string) => void; +} + +function el(tag: K, cls: string, text?: string): HTMLElementTagNameMap[K] { + const e = document.createElement(tag); + if (cls) e.className = cls; + if (text !== undefined) e.textContent = text; + return e; +} + +export class ProjectHomeView { + private root: HTMLElement; + private titleEl: HTMLElement; + private rootEl: HTMLElement; + private newBtn: HTMLButtonElement; + private newLbl: HTMLElement; + private threadsEl: HTMLElement; + private bodyEl: HTMLElement; + private cb: ProjectHomeCallbacks; + + private projectId = ""; + private data: ProjectHomeData | null = null; + private threads: HomeThreadRow[] | null = null; + private error = ""; + + constructor(container: HTMLElement, cb: ProjectHomeCallbacks) { + this.cb = cb; + this.root = el("section", "bp-project-home bp-hidden"); + this.root.setAttribute("data-testid", "project-home"); + + const inner = el("div", "bp-home-inner"); + const head = el("header", "bp-home-head"); + this.titleEl = el("h1", "bp-home-title"); + this.titleEl.setAttribute("data-testid", "project-home-title"); + this.rootEl = el("div", "bp-home-root"); + head.append(this.titleEl, this.rootEl); + + const bar = el("div", "bp-home-bar"); + this.newBtn = el("button", "primary bp-home-new"); + this.newBtn.type = "button"; + this.newBtn.setAttribute("data-testid", "project-home-new-thread"); + const plus = el("span", "bp-home-new-plus", "+"); + plus.setAttribute("aria-hidden", "true"); + this.newLbl = el("span", "", t("thread.new", "New thread")); + this.newBtn.append(plus, this.newLbl); + this.newBtn.addEventListener("click", () => { + if (this.projectId) this.cb.onNewThread(this.projectId); + }); + bar.appendChild(this.newBtn); + + this.threadsEl = el("div", "bp-home-threads"); + this.bodyEl = el("div", "bp-home-body"); + inner.append(head, bar, this.threadsEl, this.bodyEl); + this.root.appendChild(inner); + container.appendChild(this.root); + } + + public isOpen(): boolean { + return this.projectId !== ""; + } + + /** The page for a project: its name at once, the rest when the hub answers (`setData`, `setThreads`). */ + public show(project: { id: string; title: string }): void { + if (this.projectId !== project.id) { + this.data = null; + this.threads = null; + this.root.scrollTop = 0; + } + this.error = ""; + this.projectId = project.id; + this.titleEl.textContent = project.title || project.id; + this.root.classList.remove("bp-hidden"); + this.render(); + } + + public hide(): void { + this.projectId = ""; + this.root.classList.add("bp-hidden"); + } + + public setTitle(title: string): void { + if (title) this.titleEl.textContent = title; + } + + public setData(data: ProjectHomeData): void { + this.data = data; + this.error = ""; + this.render(); + } + + public setThreads(rows: HomeThreadRow[]): void { + this.threads = rows; + this.render(); + } + + public setError(message: string): void { + this.error = message; + this.render(); + } + + public refreshLocale(): void { + this.newLbl.textContent = t("thread.new", "New thread"); + if (this.isOpen()) this.render(); + } + + private section(title: string): HTMLElement { + return el("h2", "bp-home-section", title); + } + + private render(): void { + this.rootEl.textContent = this.data?.root ?? ""; + this.rootEl.classList.toggle("bp-hidden", !this.data?.root); + this.renderThreads(); + this.renderBody(); + } + + private renderThreads(): void { + const frag = document.createDocumentFragment(); + const rows = this.threads; + if (rows) { + frag.appendChild(this.section(t("gpui.projects.threads", "THREADS ({n})", { n: rows.length }))); + if (rows.length === 0) { + frag.appendChild(el("div", "bp-home-empty", t("gpui.no.threads.yet", "No threads yet."))); + } + for (const r of rows) { + const row = el("button", "bp-home-row bp-home-thread" + (r.settled ? " bp-dim" : "")); + row.type = "button"; + row.setAttribute("data-testid", `project-home-thread-${r.id}`); + const dot = el("span", `bp-dot ${r.dot}`); + if (r.status) dot.title = r.status; + const title = el("span", "bp-home-row-main", r.title || "Untitled thread"); + const age = el("span", "bp-home-row-faint", r.age); + row.append(dot, title, age); + row.addEventListener("click", () => this.cb.onOpenThread(r.id)); + frag.appendChild(row); + } + } + this.threadsEl.replaceChildren(frag); + } + + private renderBody(): void { + const frag = document.createDocumentFragment(); + const d = this.data; + + if (this.error) { + const box = el("div", "bp-home-error"); + box.setAttribute("data-testid", "project-home-error"); + box.appendChild(el("span", "", this.error)); + const retry = el("button", "bp-btn-ghost", t("tools.retry", "Retry")); + retry.type = "button"; + const pid = this.projectId; + retry.addEventListener("click", () => this.cb.onRetry(pid)); + box.appendChild(retry); + frag.appendChild(box); + } + if (!d) { + if (!this.error) frag.appendChild(el("div", "bp-home-empty", t("web.home.loading", "Loading project…"))); + this.bodyEl.replaceChildren(frag); + return; + } + + // the goal and notes + frag.appendChild(this.section(t("gpui.goal.notes", "GOAL & NOTES"))); + const intent = el("div", "bp-home-intent"); + intent.setAttribute("data-testid", "project-home-intent"); + if (intentIsEmpty(d.intent)) { + frag.appendChild(el( + "div", + "bp-home-empty", + t("gpui.no.goal.yet.ask.an", "No goal yet. Ask an agent to write what this project is for, or edit .backplane/intent.md."), + )); + } else { + for (const l of intentLines(d.intent)) { + if (l.kind === "h") { + intent.appendChild(el("div", "bp-home-intent-h", l.text)); + } else if (l.kind === "li") { + const li = el("div", "bp-home-intent-li"); + const bullet = el("span", "bp-home-bullet", "•"); + bullet.setAttribute("aria-hidden", "true"); + li.append(bullet, el("span", "", l.text)); + intent.appendChild(li); + } else { + intent.appendChild(el("div", "", l.text)); + } + } + frag.appendChild(intent); + } + + const top = this.threads?.[0]?.id ?? ""; + + // the mechanical parts: the assembly (the file with the most in it) first + if (d.mech.length > 0) { + frag.appendChild(this.section(t("gpui.projects.mech", "MECHANICAL ({n})", { n: d.mech.length }))); + d.mech.forEach((m, i) => { + const first = i === 0 && d.mech.length > 1; + const row = this.fileRow(top, "mech", `project-home-mech-${i}`); + row.title = m.path; + row.appendChild(el("span", "bp-home-row-main", m.name || m.path)); + if (first) row.appendChild(el("span", "bp-home-row-accent", t("gpui.assembly", "Assembly"))); + row.appendChild(el("span", "bp-home-row-faint", sizeText(m.size))); + frag.appendChild(row); + }); + } + + // what there is to order, and what the last estimate said beyond a price + if (d.parts.length > 0) { + frag.appendChild(this.section(t("gpui.projects.to.order", "TO ORDER ({n})", { n: d.parts.length }))); + const card = el("div", "bp-home-order"); + card.setAttribute("data-testid", "project-home-order"); + d.parts.forEach((p, i) => { + const row = el("div", "bp-home-row"); + row.setAttribute("data-testid", `project-home-part-${i}`); + row.append( + el("span", "bp-home-row-main", p.name || p.path), + el("span", "bp-home-row-dim", p.kind), + el("span", "bp-home-row-faint", p.path), + ); + card.appendChild(row); + }); + if (d.leadDays > 0) { + const lead = el( + "div", + "bp-home-order-note", + d.leadDays === 1 + ? t("web.home.lead.one", "Lead time: 1 day") + : t("web.home.lead", "Lead time: {n} days", { n: d.leadDays }), + ); + lead.setAttribute("data-testid", "project-home-lead"); + card.appendChild(lead); + } + for (const w of d.warnings) { + const warn = el("div", "bp-home-order-note warn", w); + warn.setAttribute("data-testid", "project-home-warning"); + card.appendChild(warn); + } + frag.appendChild(card); + } + + // the boards: a row opens Board on the project's newest thread + if (d.boards.length > 0) { + frag.appendChild(this.section(t("gpui.projects.boards", "BOARDS ({n})", { n: d.boards.length }))); + d.boards.forEach((b, i) => { + const row = this.fileRow(top, "board", `project-home-board-${i}`); + row.appendChild(el("span", "bp-home-row-main", b)); + frag.appendChild(row); + }); + } + + this.bodyEl.replaceChildren(frag); + } + + /** A file's row: a button that opens its viewer on `thread`, or plain text when the project has no thread to open it on. */ + private fileRow(thread: string, kind: "board" | "mech", testId: string): HTMLElement { + if (!thread) { + const row = el("div", "bp-home-row"); + row.setAttribute("data-testid", testId); + return row; + } + const row = el("button", "bp-home-row bp-home-open"); + row.type = "button"; + row.setAttribute("data-testid", testId); + row.addEventListener("click", () => this.cb.onOpenViewer(thread, kind)); + return row; + } +} diff --git a/web/src/ring-model.ts b/web/src/ring-model.ts new file mode 100644 index 0000000000..45f008fb50 --- /dev/null +++ b/web/src/ring-model.ts @@ -0,0 +1,109 @@ +// Pure Ring notes model (Settings › Ring): the hub's `ring.list` answer read defensively, the same-origin address that plays a +// recording, and the words each note's line is made of (voice/ringpage.rs draws the same on the desktop and the phones). +// Zero DOM imports so it can be unit tested directly with bun test. + +export interface RingNote { + id: string; + /** When it was said, unix seconds. */ + said: number; + gesture: string; + words: string; + model: string; + conf: number | null; + unsure: string; + state: string; + error: string; + thread: string; + play: string; + heard: number; +} + +export interface RingList { + total: number; + notes: RingNote[]; + /** The note the hub is hearing now ("" for none). */ + busy: string; +} + +/** A text the page shows: a catalog key, its English, and what fills its `{}`. */ +export interface RingText { + key: string; + fallback: string; + vars?: Record; +} + +function str(v: unknown): string { + return typeof v === "string" ? v : ""; +} + +function num(v: unknown): number { + return typeof v === "number" && Number.isFinite(v) ? v : 0; +} + +export function parseRingList(raw: unknown): RingList { + const r = raw && typeof raw === "object" ? (raw as Record) : {}; + const notes: RingNote[] = []; + for (const x of Array.isArray(r.notes) ? r.notes : []) { + if (!x || typeof x !== "object") continue; + const n = x as Record; + const id = str(n.id); + if (!id) continue; + notes.push({ + id, + said: num(n.said), + gesture: str(n.gesture), + words: str(n.words), + model: str(n.model), + conf: typeof n.conf === "number" && Number.isFinite(n.conf) ? n.conf : null, + unsure: str(n.unsure), + state: str(n.state), + error: str(n.error), + thread: str(n.thread), + play: str(n.play), + heard: num(n.heard), + }); + } + return { total: Math.max(num(r.total), notes.length), notes, busy: str(r.busy) }; +} + +/** + * The address this page plays a recording from: the hub's link names the hub as the Pebble app reaches it, the browser asks its own + * origin for the same path and key (`/ring/audio/?k=`). Anything else plays nothing. + */ +export function ringAudioPath(play: string): string { + const m = /\/ring\/audio\/(n[0-9a-f]{16})(?:\.m4a)?\?k=([0-9a-fA-F]+)$/.exec(play); + return m ? `/ring/audio/${m[1]}?k=${m[2]}` : ""; +} + +/** Who heard the note's words. */ +export function ringHeardText(n: Pick): RingText { + if (!n.model) return { key: "web.ring.not.heard", fallback: "Not heard" }; + if (n.model === "ring") return { key: "web.ring.app.words", fallback: "The Pebble app's words" }; + if (n.conf !== null) { + return { key: "web.ring.heard.by.sure", fallback: "Heard by {model}, {conf}% sure", vars: { model: n.model, conf: Math.round(n.conf) } }; + } + return { key: "web.ring.heard.by", fallback: "Heard by {model}", vars: { model: n.model } }; +} + +/** Where the note is on its way to Pebble; `busy`: this page asked for it to be heard again and the answer is not in yet. */ +export function ringStateText(state: string, busy: boolean): RingText { + if (busy) return { key: "web.ring.state.busy", fallback: "being heard now" }; + switch (state) { + case "sent": return { key: "web.ring.state.sent", fallback: "given to Pebble" }; + case "new": return { key: "web.ring.state.new", fallback: "waiting to be heard" }; + case "heard": return { key: "web.ring.state.heard", fallback: "waiting to go to Pebble" }; + case "failed": return { key: "web.ring.state.failed", fallback: "not given to Pebble" }; + default: return { key: "", fallback: state }; + } +} + +/** The line over the list: how many there are, or how many of them the search found. */ +export function ringCountText(total: number, found: number, q: string): RingText { + if (total <= 0) return { key: "ring.no.recordings.yet", fallback: "No recordings yet." }; + if (q.trim()) { + return { key: "web.ring.found", fallback: "{found} of {total} have “{q}”.", vars: { found, total, q: q.trim() } }; + } + return total === 1 + ? { key: "web.ring.count.one", fallback: "1 recording" } + : { key: "web.ring.count", fallback: "{n} recordings", vars: { n: total } }; +} diff --git a/web/src/settings-model.ts b/web/src/settings-model.ts index d924456cef..19500c60a0 100644 --- a/web/src/settings-model.ts +++ b/web/src/settings-model.ts @@ -3,7 +3,7 @@ export type WebThemePref = "auto" | "dark" | "light"; export type WebLocalePref = "auto" | "en" | "es" | "ja"; -export type SettingsPageId = "appearance" | "providers" | "devices" | "home"; +export type SettingsPageId = "appearance" | "providers" | "ring" | "devices" | "home"; export type SettingsGroupId = "general" | "ai" | "connect"; export interface SettingsGroupMeta { @@ -16,7 +16,7 @@ export interface SettingsPageMeta { group: SettingsGroupId; title: string; subtitle: string; - icon: "sun" | "cpu" | "link" | "globe"; + icon: "sun" | "cpu" | "mic" | "link" | "globe"; keywords: string[]; } @@ -57,6 +57,14 @@ export const SETTINGS_PAGES: readonly SettingsPageMeta[] = [ icon: "cpu", keywords: ["accounts", "claude", "codex", "antigravity", "grok", "openai", "anthropic", "signin", "login", "model"], }, + { + id: "ring", + group: "ai", + title: "Ring", + subtitle: "Voice notes from your Pebble ring. Its webhook is set up in the desktop or mobile app.", + icon: "mic", + keywords: ["pebble", "index", "voice", "note", "notes", "recording", "recordings", "play", "hear", "transcribe", "search"], + }, { id: "devices", group: "connect", diff --git a/web/src/settings.ts b/web/src/settings.ts index 2b76bc6ac6..298c04e2bc 100644 --- a/web/src/settings.ts +++ b/web/src/settings.ts @@ -1,7 +1,7 @@ // Grouped, searchable Web Settings modal: // General (Appearance: Theme & Language), Agents and tools (AI providers), // Connect (Devices & browser, Home machine). -import { t, trs } from "./i18n"; +import { getLocale, t, trs } from "./i18n"; import type { NoProviderNotice } from "./provider-notice"; import { SETTINGS_GROUPS, @@ -16,6 +16,15 @@ import { type WebLocalePref, type WebThemePref, } from "./settings-model"; +import { + ringAudioPath, + ringCountText, + ringHeardText, + ringStateText, + type RingList, + type RingNote, + type RingText, +} from "./ring-model"; import type { HomeInfo } from "./ws"; export interface SettingsRowButton { @@ -46,6 +55,19 @@ export interface SettingsCallbacks { onGetHubTheme?: () => "dark" | "light"; onGetLocalePref?: () => WebLocalePref; onSetLocalePref?: (pref: WebLocalePref) => void; + /** Settings › Ring: whether this hub lets a browser read the ring's recordings (feature `ringnotes`). */ + hasRing?: () => boolean; + /** The recordings, newest first; `q` narrows them to what was said. */ + onRingList?: (q: string) => Promise; + /** Hear a recording again with the local engine or OpenAI. */ + onRingHear?: (note: string, engine: "local" | "openai") => Promise; + /** Where a note went: its thread. */ + onOpenThread?: (threadId: string) => void; +} + +/** A model text in the page's language. */ +function ringT(x: RingText): string { + return x.key ? t(x.key, x.fallback, x.vars) : x.fallback; } function makeNavIcon(kind: SettingsPageMeta["icon"]): SVGSVGElement { @@ -81,6 +103,10 @@ function makeNavIcon(kind: SettingsPageMeta["icon"]): SVGSVGElement { add("path", { d: "M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71" }); add("path", { d: "M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71" }); break; + case "mic": + add("rect", { x: "9", y: "2", width: "6", height: "12" }); + add("path", { d: "M5 11a7 7 0 0 0 14 0M12 18v4M8 22h8" }); + break; case "globe": add("circle", { cx: "12", cy: "12", r: "10" }); add("path", { d: "M2 12h20M12 2a15.3 15.3 0 0 1 4 10 15.3 15.3 0 0 1-4 10 15.3 15.3 0 0 1-4-10 15.3 15.3 0 0 1 4-10z" }); @@ -126,6 +152,8 @@ function pageTitle(id: SettingsPageId, fallback: string): string { return t("settings.appearance", fallback); case "providers": return t("web.settings.providers", fallback); + case "ring": + return t("ring.ring", fallback); case "devices": return fallback; case "home": @@ -156,6 +184,25 @@ export class SettingsModal { private devicesError = ""; private loadGen = 0; + private ringLoaded = false; + private ringLoading = false; + private ringList: RingList = { total: 0, notes: [], busy: "" }; + /** The page's own parts while it is on show, so a new answer changes their words in place (a recording that plays keeps playing). */ + private ringCountEl: HTMLElement | null = null; + private ringErrorEl: HTMLElement | null = null; + private ringRows = new Map(); + /** The search the rows on show were drawn for. */ + private ringShownQuery = ""; + private ringError = ""; + /** The search as it was last sent, and as it is being typed. */ + private ringQuery = ""; + private ringDraft = ""; + private ringGen = 0; + /** Notes this page asked to be heard again, until the hub says it is hearing one (or has had the time to). */ + private ringBusy = new Set(); + private ringPolls = 0; + private ringTimers: number[] = []; + constructor(root: HTMLElement, cb: SettingsCallbacks) { this.cb = cb; @@ -285,6 +332,7 @@ export class SettingsModal { this.backdrop.classList.remove("bp-hidden"); this.render(); void this.loadDevices(); + if (this.activePage === "ring") void this.loadRing(); window.setTimeout(() => { if (this.openState) this.searchInput.focus(); }, 0); @@ -307,6 +355,12 @@ export class SettingsModal { this.searchBrowseAll = false; this.syncSearchClear(); this.backdrop.classList.add("bp-hidden"); + for (const id of this.ringTimers) window.clearTimeout(id); + this.ringTimers = []; + this.ringBusy.clear(); + this.ringPolls = 0; + // a recording stops with the page that plays it + if (this.activePage === "ring") this.paneEl.replaceChildren(); } public refreshLocale(): void { @@ -357,6 +411,109 @@ export class SettingsModal { } } + /** Settings › Ring: the recordings as the hub lists them now (the search as last sent). */ + private async loadRing(): Promise { + if (!this.cb.onRingList || !(this.cb.hasRing?.() ?? false)) return; + const gen = ++this.ringGen; + this.ringLoading = !this.ringLoaded; + if (this.ringLoading) this.showRing(); + try { + const list = await this.cb.onRingList(this.ringQuery); + if (gen !== this.ringGen) return; + this.ringList = list; + this.ringError = ""; + // a note this page sent to be heard stays busy while the hub hears one; once it hears none, it is done (or was refused) + if (!list.busy) this.ringBusy.clear(); + // the hub is hearing: read again until it is not (a bounded number of times) + if (list.busy && this.openState && this.ringPolls < 40) { + this.ringPolls++; + this.ringLater(3000); + } else if (!list.busy) { + this.ringPolls = 0; + } + } catch (e) { + if (gen !== this.ringGen) return; + this.ringError = e instanceof Error && e.message ? e.message : t("web.ring.error", "Could not load recordings."); + } finally { + if (gen === this.ringGen) { + this.ringLoaded = true; + this.ringLoading = false; + this.showRing(); + } + } + } + + /** The list is read again in `ms` (while Settings is open). */ + private ringLater(ms: number): void { + const id = window.setTimeout(() => { + this.ringTimers = this.ringTimers.filter((x) => x !== id); + if (this.openState) void this.loadRing(); + }, ms); + this.ringTimers.push(id); + } + + private ringIsBusy(id: string): boolean { + return this.ringBusy.has(id) || this.ringList.busy === id; + } + + /** + * The Ring page as it is now. The same notes as are on show: their words change in place, so a recording that plays keeps + * playing and the search field keeps its caret. Other notes (a search, a new recording): the page is drawn again. + */ + private showRing(): void { + if (!this.openState || this.activePage !== "ring" || (this.query.trim() && this.searchBrowseAll)) return; + const ids = this.ringList.notes.map((n) => n.id); + const shown = Array.from(this.ringRows.keys()); + const same = this.ringCountEl?.isConnected === true && this.ringShownQuery === this.ringQuery + && ids.length === shown.length && ids.every((id, i) => id === shown[i]); + if (!same) { + this.renderPane(); + return; + } + if (this.ringCountEl) this.ringCountEl.textContent = this.ringCountLine(); + if (this.ringErrorEl) { + this.ringErrorEl.textContent = this.ringError; + this.ringErrorEl.classList.toggle("bp-hidden", !this.ringError); + } + for (const n of this.ringList.notes) this.fillRingNote(n); + } + + private ringCountLine(): string { + return this.ringLoading + ? t("web.ring.loading", "Loading recordings…") + : ringT(ringCountText(this.ringList.total, this.ringList.notes.length, this.ringQuery)); + } + + /** A note's words, who heard them and where it is, into its row. */ + private fillRingNote(n: RingNote): void { + const r = this.ringRows.get(n.id); + if (!r) return; + const busy = this.ringIsBusy(n.id); + r.state.className = "bp-status-pill " + (busy ? "accent" : n.state === "sent" ? "ok" : n.state === "failed" ? "bad" : "warn"); + r.state.textContent = ringT(ringStateText(n.state, busy)); + r.words.className = "bp-ring-words" + (n.words ? "" : " bp-dim"); + r.words.textContent = n.words || t("web.ring.no.words", "(no words)"); + r.meta.textContent = [ringT(ringHeardText(n)), n.unsure, n.error].filter(Boolean).join(" · "); + for (const b of r.hear) b.disabled = busy; + } + + private async hearRing(note: string, engine: "local" | "openai"): Promise { + if (!this.cb.onRingHear || this.ringIsBusy(note)) return; + this.ringBusy.add(note); + this.ringError = ""; + this.showRing(); + try { + await this.cb.onRingHear(note, engine); + // the hub hears it in its own time: the list is read again shortly (and on, while the hub says it is hearing) + this.ringPolls = 0; + this.ringLater(1500); + } catch (e) { + this.ringBusy.delete(note); + this.ringError = e instanceof Error && e.message ? e.message : t("web.ring.error", "Could not load recordings."); + this.showRing(); + } + } + private buildSearchItems(): SettingsSearchItem[] { const home = this.cb.onGetHome?.() ?? null; const noProvider = this.cb.onGetNoProvider?.() ?? null; @@ -392,6 +549,14 @@ export class SettingsModal { rowDetail: "Connect Claude, Codex, Antigravity, or other AI providers in Settings → Accounts.", keywords: ["accounts", "claude", "codex", "antigravity", "grok", "openai", "signin"], }, + { + pageId: "ring", + pageTitle: pageTitle("ring", "Ring"), + groupLabel: aiLbl, + rowTitle: t("ring.recordings", "Recordings"), + rowDetail: "Read, search, play and hear again the voice notes from your Pebble ring.", + keywords: ["pebble", "voice", "note", "recording", "play", "hear", "transcribe"], + }, { pageId: "devices", pageTitle: devicesTitle, @@ -513,6 +678,7 @@ export class SettingsModal { this.activePage = p.id; this.searchBrowseAll = false; this.render(); + if (p.id === "ring") void this.loadRing(); }); frag.appendChild(btn); } @@ -548,6 +714,9 @@ export class SettingsModal { case "providers": this.renderProvidersPage(frag); break; + case "ring": + this.renderRingPage(frag); + break; case "devices": this.renderDevicesPage(frag); break; @@ -598,6 +767,7 @@ export class SettingsModal { this.activePage = pageId; this.searchBrowseAll = false; this.render(); + if (pageId === "ring") void this.loadRing(); }); secBar.append(secHead, openPageBtn); frag.appendChild(secBar); @@ -607,6 +777,11 @@ export class SettingsModal { this.renderAppearancePage(frag, matchedTitles); } else if (pageId === "providers") { this.renderProvidersPage(frag); + } else if (pageId === "ring") { + const note = document.createElement("div"); + note.className = "bp-settings-empty"; + note.textContent = "Read, search, play and hear again the voice notes from your Pebble ring."; + frag.appendChild(note); } else if (pageId === "devices") { this.renderDevicesPage(frag, matchedTitles); } else if (pageId === "home") { @@ -907,6 +1082,137 @@ export class SettingsModal { } } + private renderRingPage(frag: DocumentFragment): void { + const sec = document.createElement("section"); + sec.className = "bp-settings-section"; + sec.setAttribute("data-testid", "settings-ring"); + + if (!this.cb.onRingList || !(this.cb.hasRing?.() ?? false)) { + const empty = document.createElement("div"); + empty.className = "bp-settings-empty"; + empty.textContent = t("web.ring.unavailable", "This hub does not show ring notes to a browser yet. Update it, or open Settings › Ring in the desktop app."); + sec.appendChild(empty); + frag.appendChild(sec); + return; + } + + // the search: what was said, sent on Enter or Search + const bar = document.createElement("form"); + bar.className = "bp-ring-search"; + const input = document.createElement("input"); + input.type = "search"; + input.className = "bp-ring-search-input"; + input.placeholder = t("ring.search.what.you.said", "Search what you said"); + input.setAttribute("aria-label", t("ring.search.what.you.said", "Search what you said")); + input.setAttribute("data-testid", "ring-search"); + input.value = this.ringDraft; + input.addEventListener("input", () => { this.ringDraft = input.value; }); + const go = document.createElement("button"); + go.type = "submit"; + go.className = "primary"; + go.textContent = t("common.search", "Search"); + bar.append(input, go); + if (this.ringQuery) { + const all = document.createElement("button"); + all.type = "button"; + all.className = "bp-btn-ghost"; + all.textContent = t("ring.show.all", "Show all"); + all.addEventListener("click", () => { + this.ringDraft = ""; + this.ringQuery = ""; + void this.loadRing(); + }); + bar.appendChild(all); + } + bar.addEventListener("submit", (e) => { + e.preventDefault(); + this.ringQuery = this.ringDraft.trim(); + void this.loadRing(); + }); + sec.appendChild(bar); + + const err = document.createElement("div"); + err.className = "bp-settings-notice bad" + (this.ringError ? "" : " bp-hidden"); + err.setAttribute("data-testid", "ring-error"); + err.textContent = this.ringError; + sec.appendChild(err); + this.ringErrorEl = err; + + const count = document.createElement("div"); + count.className = "bp-ring-count"; + count.setAttribute("data-testid", "ring-count"); + count.textContent = this.ringCountLine(); + sec.appendChild(count); + this.ringCountEl = count; + + this.ringRows.clear(); + this.ringShownQuery = this.ringQuery; + for (const n of this.ringList.notes) sec.appendChild(this.renderRingNote(n)); + frag.appendChild(sec); + } + + private renderRingNote(n: RingNote): HTMLElement { + const row = document.createElement("div"); + row.className = "bp-ring-note" + (n.state === "failed" ? " bad" : ""); + row.setAttribute("data-testid", `ring-note-${n.id}`); + + const head = document.createElement("div"); + head.className = "bp-ring-note-head"; + const when = document.createElement("span"); + when.className = "bp-settings-row-title"; + const said = n.said > 0 ? new Date(n.said * 1000).toLocaleString(getLocale(), { dateStyle: "medium", timeStyle: "short" }) : ""; + when.textContent = [said, n.gesture].filter(Boolean).join(" · "); + const state = document.createElement("span"); + head.append(when, state); + const words = document.createElement("div"); + const meta = document.createElement("div"); + meta.className = "bp-settings-row-detail"; + const hear: HTMLButtonElement[] = []; + + const acts = document.createElement("div"); + acts.className = "bp-ring-acts"; + const src = ringAudioPath(n.play); + if (src) { + const audio = document.createElement("audio"); + audio.className = "bp-ring-audio"; + audio.controls = true; + audio.preload = "none"; + audio.src = src; + audio.setAttribute("data-testid", `ring-audio-${n.id}`); + acts.appendChild(audio); + for (const [engine, label] of [ + ["local", t("ring.hear.again.local", "Hear again (local)")], + ["openai", t("ring.hear.again.openai", "Hear again (OpenAI)")], + ] as const) { + const b = document.createElement("button"); + b.type = "button"; + b.className = "bp-btn-ghost"; + b.textContent = label; + b.setAttribute("data-testid", `ring-hear-${engine}-${n.id}`); + hear.push(b); + b.addEventListener("click", () => { void this.hearRing(n.id, engine); }); + acts.appendChild(b); + } + } + if (n.thread && this.cb.onOpenThread) { + const b = document.createElement("button"); + b.type = "button"; + b.className = "bp-btn-ghost"; + b.textContent = t("ring.what.happened", "What happened"); + b.addEventListener("click", () => { + this.close(); + this.cb.onOpenThread?.(n.thread); + }); + acts.appendChild(b); + } + + row.append(head, words, meta); + if (acts.childElementCount > 0) row.appendChild(acts); + this.ringRows.set(n.id, { state, words, meta, hear }); + this.fillRingNote(n); + return row; + } + private renderHomePage(frag: DocumentFragment): void { const home = this.cb.onGetHome?.() ?? null; const sec = document.createElement("section"); diff --git a/web/src/shell.css b/web/src/shell.css index d85e8f62ad..bef4ed0105 100644 --- a/web/src/shell.css +++ b/web/src/shell.css @@ -2861,3 +2861,210 @@ button.primary.bp-send-btn.is-plan-exec { border-top: 1px solid var(--rule); overflow-y: auto; } + +/* Project Home: the page a project's name opens (project-home.ts). It covers the thread and its composer. */ +.bp-center.bp-home-open > :not(.bp-project-home) { display: none !important; } +.bp-project-home { + flex: 1; + min-height: 0; + overflow-y: auto; + background: var(--bg); +} +.bp-home-inner { + max-width: 860px; + margin: 0 auto; + padding: 20px 24px 40px; + display: flex; + flex-direction: column; +} +.bp-home-head { display: flex; flex-direction: column; gap: 3px; } +.bp-home-title { + margin: 0; + font-size: 20px; + font-weight: 700; + color: var(--text); + overflow-wrap: anywhere; +} +.bp-home-root { + font-size: 12px; + color: var(--dim); + font-family: var(--mono); + overflow-wrap: anywhere; +} +.bp-home-bar { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 8px; + padding: 12px 0 4px; +} +button.primary.bp-home-new { + display: inline-flex; + align-items: center; + gap: 6px; + height: 30px; + padding: 0 12px; + font-size: 12px; +} +.bp-home-new-plus { font-size: 15px; line-height: 1; } +.bp-home-section { + margin: 0; + padding: 18px 0 5px; + border-bottom: 1px solid var(--rule); + font-size: 11px; + font-weight: 600; + letter-spacing: 0.06em; + color: var(--faint); +} +.bp-home-empty { + padding: 9px 0; + font-size: 12px; + color: var(--dim); +} +.bp-home-row { + display: flex; + align-items: center; + gap: 8px; + width: 100%; + min-height: 28px; + padding: 3px 8px; + border: 0; + border-bottom: 1px solid var(--line); + background: transparent; + color: var(--text); + font-size: 12px; + text-align: left; +} +button.bp-home-row { cursor: pointer; } +button.bp-home-row:hover { background: var(--raise); } +button.bp-home-row:focus-visible { outline: 1px solid var(--accent); outline-offset: -1px; } +.bp-home-thread { min-height: 30px; font-size: 13px; } +.bp-home-row-main { + flex: 1; + min-width: 0; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} +.bp-home-row-dim { color: var(--dim); flex-shrink: 0; } +.bp-home-row-accent { color: var(--accent); flex-shrink: 0; } +.bp-home-row-faint { + color: var(--faint); + flex-shrink: 1; + min-width: 0; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} +.bp-home-intent { + display: flex; + flex-direction: column; + gap: 4px; + padding: 8px 0; + font-size: 13px; + line-height: 1.45; + overflow-wrap: anywhere; +} +.bp-home-intent-h { padding-top: 4px; font-weight: 700; } +.bp-home-intent-li { display: flex; gap: 8px; } +.bp-home-bullet { color: var(--dim); flex-shrink: 0; } +.bp-home-order { display: flex; flex-direction: column; } +.bp-home-order-note { + padding: 5px 8px; + border-bottom: 1px solid var(--line); + font-size: 12px; + color: var(--dim); +} +.bp-home-order-note.warn { + color: var(--warn); + border-left: 2px solid var(--warn); + background: color-mix(in srgb, var(--warn) 8%, var(--panel)); +} +.bp-home-error { + display: flex; + align-items: center; + justify-content: space-between; + gap: 12px; + margin-top: 12px; + padding: 8px 10px; + border-left: 2px solid var(--bad); + background: color-mix(in srgb, var(--bad) 8%, var(--panel)); + font-size: 12px; +} +.bp-proj-chev { + flex-shrink: 0; + width: 14px; + padding: 0; + border: 0; + background: transparent; + color: var(--faint); + font-size: 10px; + line-height: 1; + cursor: pointer; +} +.bp-proj-chev:hover:not(:disabled) { color: var(--text); } +.bp-proj-chev:disabled { cursor: default; opacity: 0.4; } +.bp-proj-head.active { background: var(--raise); box-shadow: inset 2px 0 0 var(--accent); } +.bp-proj-head.active .bp-proj-toggle { color: var(--accent); } + +/* Settings › Ring: the ring's voice notes (settings.ts renderRingPage). */ +.bp-ring-search { + display: flex; + align-items: center; + gap: 6px; + padding: 4px 0 10px; +} +.bp-ring-search-input { + flex: 1; + min-width: 0; + height: 28px; + padding: 0 8px; + background: var(--panel); + border: 1px solid var(--line); + color: var(--text); + font-size: 12px; +} +.bp-ring-search-input:focus { outline: 0; border-color: var(--accent); } +.bp-ring-count { + padding: 0 0 6px; + border-bottom: 1px solid var(--rule); + font-size: 12px; + color: var(--dim); +} +.bp-ring-note { + display: flex; + flex-direction: column; + gap: 5px; + padding: 11px 0; + border-bottom: 1px solid var(--line); +} +.bp-ring-note.bad { box-shadow: inset 2px 0 0 var(--bad); padding-left: 10px; } +.bp-ring-note-head { + display: flex; + align-items: center; + gap: 8px; + flex-wrap: wrap; +} +.bp-ring-words { + font-size: 13px; + line-height: 1.45; + color: var(--text); + white-space: pre-wrap; + overflow-wrap: anywhere; +} +.bp-ring-words.bp-dim { color: var(--dim); } +.bp-ring-acts { + display: flex; + align-items: center; + flex-wrap: wrap; + gap: 6px; + padding-top: 2px; +} +.bp-ring-audio { height: 28px; max-width: 100%; } + +@media (max-width: 640px) { + .bp-home-inner { padding: 14px 14px 32px; } + .bp-home-row-faint { display: none; } + .bp-home-thread .bp-home-row-faint { display: inline; } + .bp-ring-search { flex-wrap: wrap; } +} diff --git a/web/src/sidebar.ts b/web/src/sidebar.ts index e758efca79..08fc19688c 100644 --- a/web/src/sidebar.ts +++ b/web/src/sidebar.ts @@ -143,6 +143,10 @@ export interface SidebarSection { export interface SidebarCallbacks { onSelectThread: (threadId: string) => void; onNewThread: (projectId: string) => void; + /** A project's name: its home. False (or no handler): this hub has none, and the name folds the project as before. */ + onOpenProject?: (projectId: string) => boolean; + /** Whether a project's name opens a home at all (the name's tooltip says so only then). */ + canOpenProject?: () => boolean; onSelectBot: (bot: BotItem) => void; onSelectRoom?: (room: RoomItem) => void; onNewBot?: () => void; @@ -345,6 +349,7 @@ export class SidebarView { private sections: SidebarSection[] | null = null; private projects: ProjectItem[] = []; + private selectedProjectId = ""; private threads: ThreadItem[] = []; private bots: BotItem[] = []; private rooms: RoomItem[] = []; @@ -512,6 +517,27 @@ export class SidebarView { this.render(); } + /** The project whose home is on show ("" for none): its head is marked, and no thread row is. */ + public setSelectedProject(projectId: string): void { + if (this.selectedProjectId === projectId) return; + this.selectedProjectId = projectId; + this.render(); + } + + /** The chevron beside a project's name: it folds and unfolds the project's threads. */ + private makeFoldChevron(folded: boolean, projectId: string): HTMLButtonElement { + const chev = document.createElement("button"); + chev.type = "button"; + chev.className = "bp-proj-chev" + (folded ? " folded" : ""); + chev.textContent = folded ? "▸" : "▾"; + const label = folded ? t("web.home.unfold", "Show threads") : t("web.home.fold", "Hide threads"); + chev.title = label; + chev.setAttribute("aria-label", label); + chev.setAttribute("aria-expanded", folded ? "false" : "true"); + chev.setAttribute("data-testid", `project-fold-${projectId}`); + return chev; + } + public focusFilter(): void { this.filterInput.focus(); } @@ -777,7 +803,7 @@ export class SidebarView { const el = document.createElement("div"); el.className = "bp-thread-row" + (isInbox ? " bp-inbox-row" : "") + - (row.id === this.selectedThreadId || rawThreadId(row.id) === this.selectedThreadId ? " active" : "") + + (!this.selectedProjectId && (row.id === this.selectedThreadId || rawThreadId(row.id) === this.selectedThreadId) ? " active" : "") + (row.off ? " bp-dim" : ""); el.setAttribute("data-thread-id", row.id); el.setAttribute("data-testid", `thread-row-${row.id}`); @@ -1091,9 +1117,19 @@ export class SidebarView { nameSpan.className = "bp-proj-name"; nameSpan.textContent = proj.title || proj.id; toggle.append(icon, nameSpan); - if (proj.fold === "project-fold" && proj.nav) { - toggle.addEventListener("click", () => this.cb.onToggleProjectFold?.(proj.nav!)); - } + const canFold = proj.fold === "project-fold" && Boolean(proj.nav); + const fold = (): void => { if (canFold) this.cb.onToggleProjectFold?.(proj.nav!); }; + // the name opens the project's home; the chevron beside it folds its threads (an older hub has no home: the name folds) + if (!proj.off && this.cb.canOpenProject?.()) toggle.title = t("web.home.open", "Open project home"); + toggle.setAttribute("data-testid", `project-open-${proj.id}`); + if (this.selectedProjectId && rawThreadId(proj.id) === this.selectedProjectId) header.classList.add("active"); + toggle.addEventListener("click", () => { + if (proj.off || !this.cb.onOpenProject?.(proj.id)) fold(); + }); + const chev = this.makeFoldChevron(Boolean(proj.folded), proj.id); + if (canFold) chev.addEventListener("click", (e) => { e.stopPropagation(); fold(); }); + else chev.disabled = true; + header.appendChild(chev); const meta = document.createElement("div"); meta.className = "bp-proj-meta"; @@ -1256,11 +1292,20 @@ export class SidebarView { nameSpan.className = "bp-proj-name"; nameSpan.textContent = proj.title || proj.id; toggle.append(folder, nameSpan); - toggle.addEventListener("click", () => { + const fold = (): void => { if (this.collapsedProjects.has(proj.id)) this.collapsedProjects.delete(proj.id); else this.collapsedProjects.add(proj.id); this.render(); + }; + if (this.cb.canOpenProject?.()) toggle.title = t("web.home.open", "Open project home"); + toggle.setAttribute("data-testid", `project-open-${proj.id}`); + if (this.selectedProjectId && proj.id === this.selectedProjectId) header.classList.add("active"); + toggle.addEventListener("click", () => { + if (!this.cb.onOpenProject?.(proj.id)) fold(); }); + const chev = this.makeFoldChevron(collapsed, proj.id); + chev.addEventListener("click", (e) => { e.stopPropagation(); fold(); }); + header.appendChild(chev); const addBtn = document.createElement("button"); addBtn.type = "button"; diff --git a/web/test/project-home.test.ts b/web/test/project-home.test.ts new file mode 100644 index 0000000000..5c87ac623b --- /dev/null +++ b/web/test/project-home.test.ts @@ -0,0 +1,68 @@ +import { describe, expect, test } from "bun:test"; +import { intentIsEmpty, intentLines, parseProjectHome, rawProjectId, sizeText } from "../src/project-home-model"; + +describe("Project Home model", () => { + test("parseProjectHome reads the hub's answer and treats anything missing as empty", () => { + const d = parseProjectHome({ + project: "p1", + root: "/home/user/lamp", + intent: "# Goal\n\nA lamp.\n", + parts: [{ name: "LED board", kind: "pcb", path: "boards/led/led.fab.json" }, { nope: 1 }, "x"], + boards: ["boards/led/led.kicad_pcb", 7, ""], + mech: [{ path: "mech/lamp.step", name: "lamp.step", size: 90 }, { path: "", name: "" }], + leadDays: 9, + warnings: ["thin board", " fragile ", "thin board", ""], + }); + expect(d.project).toBe("p1"); + expect(d.root).toBe("/home/user/lamp"); + expect(d.parts).toEqual([{ name: "LED board", kind: "pcb", path: "boards/led/led.fab.json" }]); + expect(d.boards).toEqual(["boards/led/led.kicad_pcb"]); + expect(d.mech).toEqual([{ path: "mech/lamp.step", name: "lamp.step", size: 90 }]); + expect(d.leadDays).toBe(9); + expect(d.warnings).toEqual(["thin board", "fragile"]); + + for (const raw of [null, undefined, "x", [], {}]) { + expect(parseProjectHome(raw)).toEqual({ + project: "", root: "", intent: "", parts: [], boards: [], mech: [], leadDays: 0, warnings: [], + }); + } + }); + + test("a lead time is whole days above zero, else none", () => { + expect(parseProjectHome({ leadDays: 4.9 }).leadDays).toBe(4); + for (const bad of [0, -3, "9", null, Number.NaN, Number.POSITIVE_INFINITY]) { + expect(parseProjectHome({ leadDays: bad }).leadDays).toBe(0); + } + }); + + test("intentLines reads headings, list items and text as the desktop does", () => { + expect(intentLines("# Goal\n\nA lamp.\n\n# Parts\n\n- LED board\n* Shade\n## Notes")).toEqual([ + { kind: "h", text: "Goal" }, + { kind: "p", text: "A lamp." }, + { kind: "h", text: "Parts" }, + { kind: "li", text: "LED board" }, + { kind: "li", text: "Shade" }, + { kind: "h", text: "Notes" }, + ]); + expect(intentLines("")).toEqual([]); + expect(intentLines(Array.from({ length: 80 }, (_, i) => `line ${i}`).join("\n"))).toHaveLength(60); + }); + + test("an intent of headings only says nothing yet", () => { + expect(intentIsEmpty("# Goal\n\n# Parts\n\n# Notes\n")).toBe(true); + expect(intentIsEmpty("")).toBe(true); + expect(intentIsEmpty("# Goal\n\nA lamp.\n")).toBe(false); + expect(intentIsEmpty("- LED board")).toBe(false); + }); + + test("sizeText and rawProjectId", () => { + expect(sizeText(0)).toBe(""); + expect(sizeText(512)).toBe("512 B"); + expect(sizeText(2048)).toBe("2.0 KB"); + expect(sizeText(200 * 1024)).toBe("200 KB"); + expect(sizeText(3 * 1024 * 1024)).toBe("3.0 MB"); + expect(rawProjectId("bench|p1")).toBe("p1"); + expect(rawProjectId("p1")).toBe("p1"); + expect(rawProjectId("lap~p9")).toBe("lap~p9"); + }); +}); diff --git a/web/test/ring.test.ts b/web/test/ring.test.ts new file mode 100644 index 0000000000..834a8d6f78 --- /dev/null +++ b/web/test/ring.test.ts @@ -0,0 +1,67 @@ +import { describe, expect, test } from "bun:test"; +import { parseRingList, ringAudioPath, ringCountText, ringHeardText, ringStateText } from "../src/ring-model"; +import { interpolate } from "../src/i18n-format"; + +describe("Ring notes model", () => { + test("parseRingList keeps notes that have an id and reads the rest defensively", () => { + const l = parseRingList({ + total: 3, + notes: [ + { id: "n0123456789abcdef", said: 1_790_000_000, gesture: "Hold & talk", words: "Call Sam", model: "parakeet-v2", conf: 91, unsure: "", state: "sent", error: "", thread: "t9", play: "https://hub.example/ring/audio/n0123456789abcdef?k=ab12", heard: 1 }, + { words: "no id" }, + null, + { id: "n1111111111111111" }, + ], + }); + expect(l.total).toBe(3); + expect(l.notes.map((n) => n.id)).toEqual(["n0123456789abcdef", "n1111111111111111"]); + expect(l.notes[0].conf).toBe(91); + expect(l.notes[1]).toEqual({ + id: "n1111111111111111", said: 0, gesture: "", words: "", model: "", conf: null, unsure: "", state: "", error: "", thread: "", play: "", heard: 0, + }); + expect(parseRingList(null)).toEqual({ total: 0, notes: [], busy: "" }); + expect(parseRingList({ busy: "n2222222222222222", notes: [] }).busy).toBe("n2222222222222222"); + expect(l.busy).toBe(""); + expect(parseRingList({ notes: [{ id: "n2222222222222222" }] }).total).toBe(1); + }); + + test("a recording plays from this page's own origin, by its id and key only", () => { + expect(ringAudioPath("https://hub.example:8451/ring/audio/n0123456789abcdef?k=ab12CD")).toBe("/ring/audio/n0123456789abcdef?k=ab12CD"); + expect(ringAudioPath("http://127.0.0.1:3797/ring/audio/n0123456789abcdef.m4a?k=00")).toBe("/ring/audio/n0123456789abcdef?k=00"); + for (const bad of [ + "", + "https://elsewhere.example/audio/n0123456789abcdef?k=ab", + "https://hub.example/ring/audio/n0123456789abcdef", + "https://hub.example/ring/audio/../../file?k=ab", + "https://hub.example/ring/audio/n0123456789abcdef?k=ab&next=//evil.example", + "javascript:alert(1)//ring/audio/n0123456789abcdef?k=zz", + ]) { + expect(ringAudioPath(bad)).toBe(""); + } + }); + + test("who heard a note, and where it is", () => { + expect(ringHeardText({ model: "", conf: null }).fallback).toBe("Not heard"); + expect(ringHeardText({ model: "ring", conf: 80 }).fallback).toBe("The Pebble app's words"); + const sure = ringHeardText({ model: "parakeet-v2", conf: 90.6 }); + expect(interpolate(sure.fallback, sure.vars)).toBe("Heard by parakeet-v2, 91% sure"); + const plain = ringHeardText({ model: "gpt-4o-transcribe", conf: null }); + expect(interpolate(plain.fallback, plain.vars)).toBe("Heard by gpt-4o-transcribe"); + + expect(ringStateText("sent", false).fallback).toBe("given to Pebble"); + expect(ringStateText("new", false).fallback).toBe("waiting to be heard"); + expect(ringStateText("heard", false).fallback).toBe("waiting to go to Pebble"); + expect(ringStateText("failed", false).fallback).toBe("not given to Pebble"); + expect(ringStateText("sent", true).fallback).toBe("being heard now"); + expect(ringStateText("odd", false)).toEqual({ key: "", fallback: "odd" }); + }); + + test("the count line", () => { + expect(ringCountText(0, 0, "").key).toBe("ring.no.recordings.yet"); + expect(ringCountText(1, 1, "").fallback).toBe("1 recording"); + const many = ringCountText(12, 12, ""); + expect(interpolate(many.fallback, many.vars)).toBe("12 recordings"); + const found = ringCountText(12, 2, " sam "); + expect(interpolate(found.fallback, found.vars)).toBe("2 of 12 have “sam”."); + }); +}); diff --git a/web/test/settings.test.ts b/web/test/settings.test.ts index 7ae26221a9..095088c69b 100644 --- a/web/test/settings.test.ts +++ b/web/test/settings.test.ts @@ -65,7 +65,7 @@ describe("Web Settings model", () => { test("defines clean grouped pages with valid group references", () => { const groupIds = new Set(SETTINGS_GROUPS.map((g) => g.id)); expect(SETTINGS_GROUPS.map((g) => g.label)).toEqual(["General", "Agents and tools", "Connect"]); - expect(SETTINGS_PAGES.map((p) => p.id)).toEqual(["appearance", "providers", "devices", "home"]); + expect(SETTINGS_PAGES.map((p) => p.id)).toEqual(["appearance", "providers", "ring", "devices", "home"]); for (const p of SETTINGS_PAGES) { expect(groupIds.has(p.group)).toBe(true); } @@ -73,7 +73,7 @@ describe("Web Settings model", () => { test("filterSettingsNav returns all pages with no hits when query is empty", () => { const res = filterSettingsNav(SETTINGS_PAGES, SAMPLE_ITEMS, " "); - expect(res.map((m) => m.page.id)).toEqual(["appearance", "providers", "devices", "home"]); + expect(res.map((m) => m.page.id)).toEqual(["appearance", "providers", "ring", "devices", "home"]); expect(res.every((m) => m.hits.length === 0)).toBe(true); });