From fbd30b0bd03629dc13ebbeb3e7802c9234dae522 Mon Sep 17 00:00:00 2001 From: Nathan Dane Date: Tue, 3 Nov 2026 13:55:50 +0000 Subject: [PATCH] Panels: inspect and change layouts through commands (#11304) (#11454) * claim: #11218 * Panels: add shared layout rules and retained content runtime * claim: #11304 * Panels: inspect and change layouts through shared commands (#11304) * Panels: account for layout commands in geometry coverage --- apps/solidcraft-cli/tests/run_results.rs | 6 +- .../pending/universal-panel-commands.json | 338 +++ crates/engine/src/batch_preflight.rs | 17 +- crates/engine/src/cmd/mod.rs | 2 + crates/engine/src/cmd/panels.rs | 175 ++ crates/engine/src/fuzz.rs | 8 +- crates/engine/src/lib.rs | 9 + crates/engine/src/panels/commands.rs | 946 +++++++ .../engine/src/panels/commands/catalogue.rs | 158 ++ crates/engine/src/panels/fixtures.rs | 110 + .../engine/src/panels/fixtures/layout-v1.json | 37 + crates/engine/src/panels/geometry.rs | 410 +++ crates/engine/src/panels/mod.rs | 18 + crates/engine/src/panels/model.rs | 480 ++++ crates/engine/src/panels/persistence.rs | 762 +++++ crates/engine/src/panels/reducer.rs | 732 +++++ crates/engine/src/panels/tests.rs | 2476 +++++++++++++++++ crates/engine/src/schema/mod.rs | 1 + crates/engine/src/schema/panels.rs | 298 ++ crates/engine/src/tests.rs | 2 +- crates/mcp/src/backend.rs | 95 +- crates/mcp/src/tests.rs | 309 ++ crates/mcp/src/tools.rs | 50 +- crates/ui-egui/src/agent_cursor.rs | 3 + crates/ui-egui/src/command_help.rs | 20 + crates/ui-egui/src/control.rs | 227 +- crates/ui-egui/src/lib.rs | 14 + crates/ui-egui/src/panel_runtime/app.rs | 211 ++ crates/ui-egui/src/panel_runtime/fixtures.rs | 571 ++++ crates/ui-egui/src/panel_runtime/host.rs | 316 +++ crates/ui-egui/src/panel_runtime/mod.rs | 14 + crates/ui-egui/src/panel_runtime/runtime.rs | 799 ++++++ crates/ui-egui/src/panel_runtime/tests.rs | 1691 +++++++++++ docs/control-protocol.md | 207 ++ docs/panel-foundation.md | 309 ++ docs/ui-kit.md | 9 + tests/kernel-cases/EXEMPT | 20 + 37 files changed, 11837 insertions(+), 13 deletions(-) create mode 100644 assets/locales/pending/universal-panel-commands.json create mode 100644 crates/engine/src/cmd/panels.rs create mode 100644 crates/engine/src/panels/commands.rs create mode 100644 crates/engine/src/panels/commands/catalogue.rs create mode 100644 crates/engine/src/panels/fixtures.rs create mode 100644 crates/engine/src/panels/fixtures/layout-v1.json create mode 100644 crates/engine/src/panels/geometry.rs create mode 100644 crates/engine/src/panels/mod.rs create mode 100644 crates/engine/src/panels/model.rs create mode 100644 crates/engine/src/panels/persistence.rs create mode 100644 crates/engine/src/panels/reducer.rs create mode 100644 crates/engine/src/panels/tests.rs create mode 100644 crates/engine/src/schema/panels.rs create mode 100644 crates/ui-egui/src/panel_runtime/app.rs create mode 100644 crates/ui-egui/src/panel_runtime/fixtures.rs create mode 100644 crates/ui-egui/src/panel_runtime/host.rs create mode 100644 crates/ui-egui/src/panel_runtime/mod.rs create mode 100644 crates/ui-egui/src/panel_runtime/runtime.rs create mode 100644 crates/ui-egui/src/panel_runtime/tests.rs create mode 100644 docs/panel-foundation.md diff --git a/apps/solidcraft-cli/tests/run_results.rs b/apps/solidcraft-cli/tests/run_results.rs index c6e44c689..cb9846bfd 100644 --- a/apps/solidcraft-cli/tests/run_results.rs +++ b/apps/solidcraft-cli/tests/run_results.rs @@ -465,7 +465,11 @@ fn snapshot_runs_its_script_on_the_in_design() { fn unknown_command_suggests_the_closest_id() { let output = cli().args(["exec", "file.open"]).output().unwrap(); assert_eq!(output.status.code(), Some(1)); - assert!(String::from_utf8_lossy(&output.stderr).contains("did you mean `doc.open`?"), "{}", String::from_utf8_lossy(&output.stderr)); + assert!( + String::from_utf8_lossy(&output.stderr).contains("did you mean `doc.open` or `panel.open`?"), + "{}", + String::from_utf8_lossy(&output.stderr) + ); } /// #1833: `--timings` reports each command's time instead of the measurement, `--profile` adds diff --git a/assets/locales/pending/universal-panel-commands.json b/assets/locales/pending/universal-panel-commands.json new file mode 100644 index 000000000..faf5a6540 --- /dev/null +++ b/assets/locales/pending/universal-panel-commands.json @@ -0,0 +1,338 @@ +{ + "en": { + "cmd.layout.apply": "Apply Layout", + "cmd.layout.get": "Inspect Layout", + "cmd.layout.reset": "Reset Layout", + "cmd.layout.save": "Save Layout", + "cmd.layout.workspace.select": "Select Layout Workspace", + "cmd.panel.activate": "Activate Panel Tab", + "cmd.panel.close": "Close Panel", + "cmd.panel.collapse": "Collapse Panel Section", + "cmd.panel.dismiss": "Dismiss Panel Peek", + "cmd.panel.float": "Float Panel", + "cmd.panel.focus": "Focus Panel", + "cmd.panel.list": "List Panels", + "cmd.panel.move": "Move Panel", + "cmd.panel.native_close": "Redock Native Panel Section", + "cmd.panel.open": "Open Panel", + "cmd.panel.peek": "Peek Collapsed Panel", + "cmd.panel.popout": "Pop Out Panel", + "cmd.panel.reset_pair": "Reset Panel Sash", + "cmd.panel.resize": "Resize Panel Section", + "cmd.panel.resize_pair": "Resize Panel Sash", + "help.layout.apply": "Apply a saved layout to the current workspace. Retained editors keep their drafts.", + "help.layout.get": "Read the committed layout and discover registered workspaces.", + "help.layout.reset": "Restore the current workspace's registered default layout. User presets remain available.", + "help.layout.save": "Save the complete layout under a name. Replacing a user preset requires explicit overwrite permission.", + "help.layout.workspace.select": "Select a registered layout workspace and remember the outgoing layout.", + "help.panel.activate": "Select an open panel tab without requesting keyboard focus.", + "help.panel.close": "Close a panel through its content lifecycle guard. Its placement is remembered.", + "help.panel.collapse": "Collapse or expand a panel section while retaining its requested dimensions.", + "help.panel.dismiss": "Dismiss the temporary view of a collapsed panel.", + "help.panel.float": "Move a panel into an explicitly positioned floating section.", + "help.panel.focus": "Focus a panel, reopening its retained state and expanding its section when needed.", + "help.panel.list": "Read registered panel kinds, committed instances, active tabs, availability and host capabilities.", + "help.panel.move": "Move a panel into a new section or join an existing tab group.", + "help.panel.native_close": "Return a native panel section to its remembered dock without cancelling its content.", + "help.panel.open": "Open a panel kind with an explicit instance identity and placement for a new instance.", + "help.panel.peek": "Temporarily show a collapsed panel without changing its saved size or collapse state.", + "help.panel.popout": "Move a panel to a native host when supported. Browser hosts use a floating section.", + "help.panel.reset_pair": "Restore an adjacent dock pair's default size ratio within its shared bounds.", + "help.panel.resize": "Set a panel section's outer width and height within every tab's bounds.", + "help.panel.resize_pair": "Resize adjacent dock sections together while conserving their shared extent." + }, + "ar": { + "cmd.layout.apply": "تطبيق التخطيط", + "cmd.layout.get": "فحص التخطيط", + "cmd.layout.reset": "إعادة ضبط التخطيط", + "cmd.layout.save": "حفظ التخطيط", + "cmd.layout.workspace.select": "اختيار مساحة عمل التخطيط", + "cmd.panel.activate": "تنشيط علامة تبويب اللوحة", + "cmd.panel.close": "إغلاق اللوحة", + "cmd.panel.collapse": "طي قسم اللوحة", + "cmd.panel.dismiss": "إغلاق العرض المؤقت للوحة", + "cmd.panel.float": "تعويم اللوحة", + "cmd.panel.focus": "تركيز اللوحة", + "cmd.panel.list": "سرد اللوحات", + "cmd.panel.move": "نقل اللوحة", + "cmd.panel.native_close": "إعادة إرساء قسم اللوحة من نافذته المستقلة", + "cmd.panel.open": "فتح اللوحة", + "cmd.panel.peek": "عرض اللوحة المطوية مؤقتًا", + "cmd.panel.popout": "نقل اللوحة إلى نافذة مستقلة", + "cmd.panel.reset_pair": "إعادة ضبط فاصل اللوحة", + "cmd.panel.resize": "تغيير حجم قسم اللوحة", + "cmd.panel.resize_pair": "تحريك فاصل اللوحة", + "help.layout.apply": "تطبيق تخطيط محفوظ على مساحة العمل الحالية. تحتفظ أدوات التحرير القائمة بمسوداتها.", + "help.layout.get": "قراءة التخطيط المعتمد وعرض مساحات العمل المسجلة.", + "help.layout.reset": "استعادة التخطيط الافتراضي المسجل لمساحة العمل الحالية. تبقى إعدادات المستخدم المسبقة متاحة.", + "help.layout.save": "حفظ التخطيط الكامل باسم محدد. يتطلب استبدال إعداد مسبق للمستخدم إذنًا صريحًا بالكتابة فوقه.", + "help.layout.workspace.select": "اختيار مساحة عمل تخطيط مسجلة وتذكر التخطيط السابق.", + "help.panel.activate": "اختيار علامة تبويب لوحة مفتوحة دون طلب تركيز لوحة المفاتيح.", + "help.panel.close": "إغلاق اللوحة بعد التحقق من دورة حياة محتواها. يُحفظ موضعها.", + "help.panel.collapse": "طي قسم اللوحة أو توسيعه مع الاحتفاظ بأبعاده المطلوبة.", + "help.panel.dismiss": "إغلاق العرض المؤقت للوحة مطوية.", + "help.panel.float": "نقل لوحة إلى قسم عائم ذي موضع محدد صراحةً.", + "help.panel.focus": "تركيز لوحة وإعادة فتح حالتها المحفوظة وتوسيع قسمها عند الحاجة.", + "help.panel.list": "قراءة أنواع اللوحات المسجلة والمثيلات المعتمدة وعلامات التبويب النشطة والتوافر وإمكانات المضيف.", + "help.panel.move": "نقل لوحة إلى قسم جديد أو ضمها إلى مجموعة علامات تبويب موجودة.", + "help.panel.native_close": "إعادة قسم لوحة من نافذته المستقلة إلى موضع الإرساء المحفوظ دون إلغاء محتواه.", + "help.panel.open": "فتح نوع لوحة بمعرّف مثيل صريح. يتطلب المثيل الجديد تحديد موضعه.", + "help.panel.peek": "إظهار لوحة مطوية مؤقتًا دون تغيير حجمها المحفوظ أو حالة طيها.", + "help.panel.popout": "نقل لوحة إلى نافذة مستقلة عند دعم ذلك. يستخدم مضيف المتصفح قسمًا عائمًا.", + "help.panel.reset_pair": "استعادة نسبة الحجم الافتراضية لقسمي إرساء متجاورين ضمن حدودهما المشتركة.", + "help.panel.resize": "تعيين العرض والارتفاع الخارجيين لقسم اللوحة ضمن حدود جميع علامات التبويب.", + "help.panel.resize_pair": "تغيير حجم قسمي إرساء متجاورين معًا مع الحفاظ على امتدادهما الكلي المشترك." + }, + "de": { + "cmd.layout.apply": "Layout anwenden", + "cmd.layout.get": "Layout prüfen", + "cmd.layout.reset": "Layout zurücksetzen", + "cmd.layout.save": "Layout speichern", + "cmd.layout.workspace.select": "Layout-Arbeitsbereich auswählen", + "cmd.panel.activate": "Panel-Registerkarte aktivieren", + "cmd.panel.close": "Panel schließen", + "cmd.panel.collapse": "Panel-Bereich einklappen", + "cmd.panel.dismiss": "Panel-Vorschau schließen", + "cmd.panel.float": "Panel frei platzieren", + "cmd.panel.focus": "Panel fokussieren", + "cmd.panel.list": "Panels auflisten", + "cmd.panel.move": "Panel verschieben", + "cmd.panel.native_close": "Nativen Panel-Bereich wieder andocken", + "cmd.panel.open": "Panel öffnen", + "cmd.panel.peek": "Eingeklapptes Panel anzeigen", + "cmd.panel.popout": "Panel in eigenes Fenster verschieben", + "cmd.panel.reset_pair": "Panel-Trennlinie zurücksetzen", + "cmd.panel.resize": "Panel-Bereich skalieren", + "cmd.panel.resize_pair": "Panel-Trennlinie verschieben", + "help.layout.apply": "Ein gespeichertes Layout auf den aktuellen Arbeitsbereich anwenden. Geöffnete Editoren behalten ihre Entwürfe.", + "help.layout.get": "Das übernommene Layout lesen und registrierte Arbeitsbereiche anzeigen.", + "help.layout.reset": "Das registrierte Standardlayout des aktuellen Arbeitsbereichs wiederherstellen. Eigene Vorlagen bleiben erhalten.", + "help.layout.save": "Das vollständige Layout unter einem Namen speichern. Eine vorhandene eigene Vorlage wird nur mit ausdrücklicher Erlaubnis überschrieben.", + "help.layout.workspace.select": "Einen registrierten Layout-Arbeitsbereich auswählen und das bisherige Layout merken.", + "help.panel.activate": "Eine geöffnete Panel-Registerkarte auswählen, ohne den Tastaturfokus anzufordern.", + "help.panel.close": "Ein Panel unter Beachtung seines Inhaltslebenszyklus schließen. Seine Platzierung wird gespeichert.", + "help.panel.collapse": "Einen Panel-Bereich ein- oder ausklappen und seine gewünschten Abmessungen beibehalten.", + "help.panel.dismiss": "Die vorübergehende Ansicht eines eingeklappten Panels schließen.", + "help.panel.float": "Ein Panel in einen frei positionierten Bereich verschieben.", + "help.panel.focus": "Ein Panel fokussieren, seinen gespeicherten Zustand bei Bedarf wieder öffnen und seinen Bereich ausklappen.", + "help.panel.list": "Registrierte Panel-Arten, übernommene Instanzen, aktive Registerkarten, Verfügbarkeit und Host-Funktionen lesen.", + "help.panel.move": "Ein Panel in einen neuen Bereich verschieben oder einer vorhandenen Registerkartengruppe hinzufügen.", + "help.panel.native_close": "Einen nativen Panel-Bereich an seine gespeicherte Position zurückbringen, ohne seinen Inhalt abzubrechen.", + "help.panel.open": "Eine Panel-Art mit einer ausdrücklichen Instanzkennung öffnen. Neue Instanzen benötigen eine Platzierung.", + "help.panel.peek": "Ein eingeklapptes Panel vorübergehend anzeigen, ohne seine gespeicherte Größe oder seinen Klappzustand zu ändern.", + "help.panel.popout": "Ein Panel bei Unterstützung in ein natives Fenster verschieben. Im Browser wird ein frei positionierter Bereich verwendet.", + "help.panel.reset_pair": "Das Standardgrößenverhältnis zweier benachbarter Andockbereiche innerhalb ihrer gemeinsamen Grenzen wiederherstellen.", + "help.panel.resize": "Die äußere Breite und Höhe eines Panel-Bereichs innerhalb der Grenzen aller Registerkarten festlegen.", + "help.panel.resize_pair": "Benachbarte Andockbereiche gemeinsam skalieren und ihre gemeinsame Ausdehnung beibehalten." + }, + "he": { + "cmd.layout.apply": "החלת פריסה", + "cmd.layout.get": "בדיקת פריסה", + "cmd.layout.reset": "איפוס פריסה", + "cmd.layout.save": "שמירת פריסה", + "cmd.layout.workspace.select": "בחירת סביבת עבודה לפריסה", + "cmd.panel.activate": "הפעלת לשונית חלונית", + "cmd.panel.close": "סגירת חלונית", + "cmd.panel.collapse": "כיווץ מקטע חלונית", + "cmd.panel.dismiss": "סגירת תצוגה זמנית של חלונית", + "cmd.panel.float": "הצפת חלונית", + "cmd.panel.focus": "מיקוד חלונית", + "cmd.panel.list": "הצגת רשימת חלוניות", + "cmd.panel.move": "העברת חלונית", + "cmd.panel.native_close": "עיגון מחדש של מקטע חלונית מחלון נפרד", + "cmd.panel.open": "פתיחת חלונית", + "cmd.panel.peek": "הצגה זמנית של חלונית מכווצת", + "cmd.panel.popout": "העברת חלונית לחלון נפרד", + "cmd.panel.reset_pair": "איפוס מפריד חלוניות", + "cmd.panel.resize": "שינוי גודל מקטע חלונית", + "cmd.panel.resize_pair": "הזזת מפריד חלוניות", + "help.layout.apply": "החלת פריסה שמורה על סביבת העבודה הנוכחית. העורכים הקיימים שומרים על הטיוטות שלהם.", + "help.layout.get": "קריאת הפריסה שאושרה והצגת סביבות העבודה הרשומות.", + "help.layout.reset": "שחזור פריסת ברירת המחדל הרשומה של סביבת העבודה הנוכחית. הגדרות המשתמש השמורות נשארות זמינות.", + "help.layout.save": "שמירת הפריסה המלאה בשם. החלפת הגדרה שמורה של משתמש מחייבת הרשאה מפורשת לדריסה.", + "help.layout.workspace.select": "בחירת סביבת עבודה רשומה לפריסה ושמירת הפריסה שממנה יוצאים.", + "help.panel.activate": "בחירת לשונית חלונית פתוחה בלי לבקש מיקוד מקלדת.", + "help.panel.close": "סגירת חלונית דרך בדיקת מחזור החיים של התוכן שלה. המיקום שלה נשמר.", + "help.panel.collapse": "כיווץ או הרחבה של מקטע חלונית תוך שמירת המידות המבוקשות.", + "help.panel.dismiss": "סגירת התצוגה הזמנית של חלונית מכווצת.", + "help.panel.float": "העברת חלונית למקטע צף שמיקומו מוגדר במפורש.", + "help.panel.focus": "מיקוד חלונית, פתיחה מחדש של מצבה השמור והרחבת המקטע שלה לפי הצורך.", + "help.panel.list": "קריאת סוגי החלוניות הרשומים, המופעים שאושרו, הלשוניות הפעילות, הזמינות ויכולות המארח.", + "help.panel.move": "העברת חלונית למקטע חדש או צירופה לקבוצת לשוניות קיימת.", + "help.panel.native_close": "החזרת מקטע חלונית מחלון נפרד למיקום העיגון השמור בלי לבטל את התוכן שלו.", + "help.panel.open": "פתיחת סוג חלונית עם מזהה מופע מפורש. מופע חדש דורש מיקום.", + "help.panel.peek": "הצגה זמנית של חלונית מכווצת בלי לשנות את הגודל השמור או את מצב הכיווץ שלה.", + "help.panel.popout": "העברת חלונית לחלון נפרד כאשר יש תמיכה בכך. במארח דפדפן נעשה שימוש במקטע צף.", + "help.panel.reset_pair": "שחזור יחס הגדלים המוגדר כברירת מחדל לשני מקטעי עיגון סמוכים, במסגרת הגבולות המשותפים שלהם.", + "help.panel.resize": "הגדרת הרוחב והגובה החיצוניים של מקטע חלונית במסגרת המגבלות של כל הלשוניות.", + "help.panel.resize_pair": "שינוי גודלם של מקטעי עיגון סמוכים יחד תוך שמירה על האורך הכולל המשותף שלהם." + }, + "ja": { + "cmd.layout.apply": "レイアウトを適用", + "cmd.layout.get": "レイアウトを確認", + "cmd.layout.reset": "レイアウトをリセット", + "cmd.layout.save": "レイアウトを保存", + "cmd.layout.workspace.select": "レイアウトのワークスペースを選択", + "cmd.panel.activate": "パネルのタブをアクティブ化", + "cmd.panel.close": "パネルを閉じる", + "cmd.panel.collapse": "パネルのセクションを折りたたむ", + "cmd.panel.dismiss": "パネルの一時表示を閉じる", + "cmd.panel.float": "パネルをフロート表示", + "cmd.panel.focus": "パネルにフォーカス", + "cmd.panel.list": "パネルを一覧表示", + "cmd.panel.move": "パネルを移動", + "cmd.panel.native_close": "別ウィンドウのパネルを再ドッキング", + "cmd.panel.open": "パネルを開く", + "cmd.panel.peek": "折りたたんだパネルを一時表示", + "cmd.panel.popout": "パネルを別ウィンドウに移動", + "cmd.panel.reset_pair": "パネルの区切りをリセット", + "cmd.panel.resize": "パネルのセクションのサイズを変更", + "cmd.panel.resize_pair": "パネルの区切りを移動", + "help.layout.apply": "保存したレイアウトを現在のワークスペースに適用します。保持されているエディターの下書きは維持されます。", + "help.layout.get": "確定したレイアウトと登録済みのワークスペースを確認します。", + "help.layout.reset": "現在のワークスペースに登録された既定のレイアウトを復元します。ユーザープリセットは保持されます。", + "help.layout.save": "レイアウト全体に名前を付けて保存します。ユーザープリセットの置き換えには明示的な上書き許可が必要です。", + "help.layout.workspace.select": "登録済みのレイアウト用ワークスペースを選択し、移動前のレイアウトを記憶します。", + "help.panel.activate": "キーボードフォーカスを要求せずに、開いているパネルのタブを選択します。", + "help.panel.close": "内容のライフサイクルの確認を経てパネルを閉じます。配置は記憶されます。", + "help.panel.collapse": "要求された寸法を保持したまま、パネルのセクションを折りたたむか展開します。", + "help.panel.dismiss": "折りたたんだパネルの一時表示を閉じます。", + "help.panel.float": "パネルを明示的に指定した位置のフローティングセクションに移動します。", + "help.panel.focus": "パネルにフォーカスします。必要に応じて保持された状態を再度開き、セクションを展開します。", + "help.panel.list": "登録済みのパネル種類、確定したインスタンス、アクティブなタブ、利用可否、ホストの機能を確認します。", + "help.panel.move": "パネルを新しいセクションに移動するか、既存のタブグループに追加します。", + "help.panel.native_close": "別ウィンドウのパネルセクションを、内容をキャンセルせずに記憶されたドックに戻します。", + "help.panel.open": "パネルの種類と明示的なインスタンス識別子を指定して開きます。新しいインスタンスには配置を指定します。", + "help.panel.peek": "保存されたサイズや折りたたみ状態を変更せずに、折りたたんだパネルを一時表示します。", + "help.panel.popout": "対応している場合はパネルを別ウィンドウに移動します。ブラウザーではフローティングセクションを使用します。", + "help.panel.reset_pair": "隣接するドックのペアを、共通の制約内で既定のサイズ比率に戻します。", + "help.panel.resize": "すべてのタブの制約内で、パネルセクションの外側の幅と高さを設定します。", + "help.panel.resize_pair": "共有する全体の長さを維持しながら、隣接するドックセクションのサイズを同時に変更します。" + }, + "ko": { + "cmd.layout.apply": "레이아웃 적용", + "cmd.layout.get": "레이아웃 확인", + "cmd.layout.reset": "레이아웃 초기화", + "cmd.layout.save": "레이아웃 저장", + "cmd.layout.workspace.select": "레이아웃 작업 공간 선택", + "cmd.panel.activate": "패널 탭 활성화", + "cmd.panel.close": "패널 닫기", + "cmd.panel.collapse": "패널 구역 접기", + "cmd.panel.dismiss": "패널 임시 보기 닫기", + "cmd.panel.float": "패널 띄우기", + "cmd.panel.focus": "패널에 초점 맞추기", + "cmd.panel.list": "패널 목록", + "cmd.panel.move": "패널 이동", + "cmd.panel.native_close": "별도 창의 패널 구역 다시 도킹", + "cmd.panel.open": "패널 열기", + "cmd.panel.peek": "접힌 패널 임시 보기", + "cmd.panel.popout": "패널을 별도 창으로 이동", + "cmd.panel.reset_pair": "패널 구분선 초기화", + "cmd.panel.resize": "패널 구역 크기 조정", + "cmd.panel.resize_pair": "패널 구분선 이동", + "help.layout.apply": "저장된 레이아웃을 현재 작업 공간에 적용합니다. 유지 중인 편집기의 초안은 보존됩니다.", + "help.layout.get": "확정된 레이아웃과 등록된 작업 공간을 확인합니다.", + "help.layout.reset": "현재 작업 공간에 등록된 기본 레이아웃을 복원합니다. 사용자 사전 설정은 유지됩니다.", + "help.layout.save": "전체 레이아웃에 이름을 지정해 저장합니다. 사용자 사전 설정을 바꾸려면 명시적인 덮어쓰기 허용이 필요합니다.", + "help.layout.workspace.select": "등록된 레이아웃 작업 공간을 선택하고 이전 레이아웃을 기억합니다.", + "help.panel.activate": "키보드 초점을 요청하지 않고 열린 패널 탭을 선택합니다.", + "help.panel.close": "콘텐츠 수명 주기 검사를 거쳐 패널을 닫습니다. 배치는 기억됩니다.", + "help.panel.collapse": "요청한 치수를 유지하면서 패널 구역을 접거나 펼칩니다.", + "help.panel.dismiss": "접힌 패널의 임시 보기를 닫습니다.", + "help.panel.float": "패널을 위치가 명시된 부동 구역으로 이동합니다.", + "help.panel.focus": "패널에 초점을 맞춥니다. 필요하면 유지된 상태를 다시 열고 구역을 펼칩니다.", + "help.panel.list": "등록된 패널 종류, 확정된 인스턴스, 활성 탭, 사용 가능 여부와 호스트 기능을 확인합니다.", + "help.panel.move": "패널을 새 구역으로 이동하거나 기존 탭 그룹에 추가합니다.", + "help.panel.native_close": "콘텐츠를 취소하지 않고 별도 창의 패널 구역을 기억된 도킹 위치로 되돌립니다.", + "help.panel.open": "패널 종류와 명시적인 인스턴스 식별자로 패널을 엽니다. 새 인스턴스에는 배치가 필요합니다.", + "help.panel.peek": "저장된 크기나 접힘 상태를 바꾸지 않고 접힌 패널을 임시로 표시합니다.", + "help.panel.popout": "지원되는 경우 패널을 별도 창으로 이동합니다. 브라우저에서는 부동 구역을 사용합니다.", + "help.panel.reset_pair": "인접한 도킹 구역 쌍을 공통 제약 안에서 기본 크기 비율로 복원합니다.", + "help.panel.resize": "모든 탭의 제약 안에서 패널 구역의 바깥 너비와 높이를 설정합니다.", + "help.panel.resize_pair": "공유하는 전체 길이를 유지하면서 인접한 도킹 구역의 크기를 함께 조정합니다." + }, + "vi": { + "cmd.layout.apply": "Áp dụng bố cục", + "cmd.layout.get": "Kiểm tra bố cục", + "cmd.layout.reset": "Đặt lại bố cục", + "cmd.layout.save": "Lưu bố cục", + "cmd.layout.workspace.select": "Chọn không gian làm việc của bố cục", + "cmd.panel.activate": "Kích hoạt thẻ bảng", + "cmd.panel.close": "Đóng bảng", + "cmd.panel.collapse": "Thu gọn vùng bảng", + "cmd.panel.dismiss": "Đóng chế độ xem tạm của bảng", + "cmd.panel.float": "Thả nổi bảng", + "cmd.panel.focus": "Đặt tiêu điểm vào bảng", + "cmd.panel.list": "Liệt kê các bảng", + "cmd.panel.move": "Di chuyển bảng", + "cmd.panel.native_close": "Gắn lại vùng bảng từ cửa sổ riêng", + "cmd.panel.open": "Mở bảng", + "cmd.panel.peek": "Xem tạm bảng đã thu gọn", + "cmd.panel.popout": "Chuyển bảng sang cửa sổ riêng", + "cmd.panel.reset_pair": "Đặt lại thanh chia bảng", + "cmd.panel.resize": "Đổi kích thước vùng bảng", + "cmd.panel.resize_pair": "Di chuyển thanh chia bảng", + "help.layout.apply": "Áp dụng bố cục đã lưu cho không gian làm việc hiện tại. Các trình chỉnh sửa được giữ lại vẫn giữ bản nháp.", + "help.layout.get": "Đọc bố cục đã xác nhận và xem các không gian làm việc đã đăng ký.", + "help.layout.reset": "Khôi phục bố cục mặc định đã đăng ký của không gian làm việc hiện tại. Các thiết lập sẵn của người dùng vẫn được giữ lại.", + "help.layout.save": "Lưu toàn bộ bố cục với một tên. Việc thay thế thiết lập sẵn của người dùng cần được cho phép ghi đè rõ ràng.", + "help.layout.workspace.select": "Chọn không gian làm việc của bố cục đã đăng ký và ghi nhớ bố cục trước đó.", + "help.panel.activate": "Chọn một thẻ bảng đang mở mà không yêu cầu tiêu điểm bàn phím.", + "help.panel.close": "Đóng bảng sau khi kiểm tra vòng đời nội dung. Vị trí của bảng được ghi nhớ.", + "help.panel.collapse": "Thu gọn hoặc mở rộng vùng bảng trong khi giữ nguyên các kích thước đã yêu cầu.", + "help.panel.dismiss": "Đóng chế độ xem tạm thời của bảng đã thu gọn.", + "help.panel.float": "Di chuyển bảng vào một vùng thả nổi có vị trí được chỉ định rõ ràng.", + "help.panel.focus": "Đặt tiêu điểm vào bảng, mở lại trạng thái được giữ và mở rộng vùng của bảng khi cần.", + "help.panel.list": "Đọc các loại bảng đã đăng ký, các phiên bản đã xác nhận, thẻ đang hoạt động, tính khả dụng và khả năng của môi trường chứa.", + "help.panel.move": "Di chuyển bảng vào vùng mới hoặc thêm vào nhóm thẻ hiện có.", + "help.panel.native_close": "Đưa vùng bảng từ cửa sổ riêng về vị trí gắn đã ghi nhớ mà không hủy nội dung.", + "help.panel.open": "Mở một loại bảng với mã phiên bản rõ ràng. Phiên bản mới cần được chỉ định vị trí.", + "help.panel.peek": "Tạm hiển thị bảng đã thu gọn mà không thay đổi kích thước đã lưu hoặc trạng thái thu gọn.", + "help.panel.popout": "Di chuyển bảng sang cửa sổ riêng khi được hỗ trợ. Trình duyệt sử dụng vùng thả nổi.", + "help.panel.reset_pair": "Khôi phục tỷ lệ kích thước mặc định của hai vùng gắn liền kề trong giới hạn chung.", + "help.panel.resize": "Đặt chiều rộng và chiều cao bên ngoài của vùng bảng trong giới hạn của mọi thẻ.", + "help.panel.resize_pair": "Đổi kích thước các vùng gắn liền kề cùng nhau trong khi giữ nguyên tổng chiều dài chung." + }, + "zh": { + "cmd.layout.apply": "应用布局", + "cmd.layout.get": "检查布局", + "cmd.layout.reset": "重置布局", + "cmd.layout.save": "保存布局", + "cmd.layout.workspace.select": "选择布局工作区", + "cmd.panel.activate": "激活面板选项卡", + "cmd.panel.close": "关闭面板", + "cmd.panel.collapse": "折叠面板分区", + "cmd.panel.dismiss": "关闭面板临时预览", + "cmd.panel.float": "浮动面板", + "cmd.panel.focus": "聚焦面板", + "cmd.panel.list": "列出面板", + "cmd.panel.move": "移动面板", + "cmd.panel.native_close": "重新停靠独立窗口中的面板分区", + "cmd.panel.open": "打开面板", + "cmd.panel.peek": "临时预览折叠面板", + "cmd.panel.popout": "将面板移至独立窗口", + "cmd.panel.reset_pair": "重置面板分隔条", + "cmd.panel.resize": "调整面板分区大小", + "cmd.panel.resize_pair": "移动面板分隔条", + "help.layout.apply": "将保存的布局应用到当前工作区。保留的编辑器会继续保留其草稿。", + "help.layout.get": "读取已提交的布局并查看已注册的工作区。", + "help.layout.reset": "恢复当前工作区注册的默认布局。用户预设仍会保留。", + "help.layout.save": "为完整布局命名并保存。替换用户预设需要明确允许覆盖。", + "help.layout.workspace.select": "选择已注册的布局工作区,并记住离开前的布局。", + "help.panel.activate": "选择已打开的面板选项卡,而不请求键盘焦点。", + "help.panel.close": "通过内容生命周期检查后关闭面板。其位置会被记住。", + "help.panel.collapse": "折叠或展开面板分区,同时保留所需尺寸。", + "help.panel.dismiss": "关闭折叠面板的临时视图。", + "help.panel.float": "将面板移至位置明确指定的浮动分区。", + "help.panel.focus": "聚焦面板,必要时重新打开其保留状态并展开分区。", + "help.panel.list": "读取已注册的面板种类、已提交的实例、活动选项卡、可用状态和宿主能力。", + "help.panel.move": "将面板移至新分区,或加入现有的选项卡组。", + "help.panel.native_close": "将独立窗口中的面板分区返回记住的停靠位置,而不取消其内容。", + "help.panel.open": "使用明确的实例标识打开指定种类的面板。新实例需要指定位置。", + "help.panel.peek": "临时显示折叠的面板,而不更改保存的尺寸或折叠状态。", + "help.panel.popout": "支持时将面板移至独立窗口。浏览器宿主会使用浮动分区。", + "help.panel.reset_pair": "在共同约束内恢复相邻停靠分区对的默认尺寸比例。", + "help.panel.resize": "在所有选项卡的约束内设置面板分区的外部宽度和高度。", + "help.panel.resize_pair": "同时调整相邻停靠分区的尺寸,并保持其共同总长度。" + } +} diff --git a/crates/engine/src/batch_preflight.rs b/crates/engine/src/batch_preflight.rs index f16aef3da..638e7c79c 100644 --- a/crates/engine/src/batch_preflight.rs +++ b/crates/engine/src/batch_preflight.rs @@ -33,7 +33,7 @@ impl Refusal { /// The batch reply for a batch refused before its first step: as a failed step's reply, /// with nothing completed, nothing undone and every step not run. pub fn reply(&self, steps: usize) -> Value { - json!({ + let mut reply = json!({ "completed": 0, "results": [], "failed": {"index": self.index, "command": self.command, "error": self.error}, @@ -41,7 +41,11 @@ impl Refusal { "rolled_back": false, "not_run": (0..steps).collect::>(), "note": "nothing was run: the batch was checked before its first step", - }) + }); + if let Some(reason) = crate::panels::commands::structured_error(&self.error) { + reply["failed"]["panel_error"] = reason; + } + reply } } @@ -82,6 +86,15 @@ pub fn contracts(steps: &[Value]) -> Option { /// Step `index`'s refusal when its parameters break the typed contract of its command `id`. fn contract_refusal(index: usize, id: &str, step: &Value) -> Option { + if crate::panels::commands::is_command(id) { + let empty = json!({}); + let params = step.get("params").filter(|p| !p.is_null()).unwrap_or(&empty); + return crate::panels::commands::parse_command(id, params).err().map(|reason| Refusal { + index, + command: Some(id.into()), + error: crate::panels::commands::error_text(reason), + }); + } let first = crate::schema::issues(id, step.get("params").unwrap_or(&Value::Null)).into_iter().next()?; Some(Refusal { index, command: Some(id.to_string()), error: crate::params::bad(id, first.message).to_string() }) } diff --git a/crates/engine/src/cmd/mod.rs b/crates/engine/src/cmd/mod.rs index 9cff4d96d..7ce27d82b 100644 --- a/crates/engine/src/cmd/mod.rs +++ b/crates/engine/src/cmd/mod.rs @@ -87,6 +87,7 @@ pub(crate) use measure_sel::{measure_items, shape_of}; pub(crate) use measure_shape::Shape; #[cfg(test)] mod kernel_heal_tests; +mod panels; mod parameter_sweep; mod parameters; mod plastic; @@ -340,6 +341,7 @@ pub fn command_specs() -> Vec<&'static CommandSpec> { v.extend(joints::COMMANDS.iter()); v.extend(clearance::COMMANDS.iter()); v.extend(motion::COMMANDS.iter()); + v.extend(panels::COMMANDS.iter()); v.extend(config::COMMANDS.iter()); v.extend(parts::COMMANDS.iter()); v.extend(bom::COMMANDS.iter()); diff --git a/crates/engine/src/cmd/panels.rs b/crates/engine/src/cmd/panels.rs new file mode 100644 index 000000000..67badaf06 --- /dev/null +++ b/crates/engine/src/cmd/panels.rs @@ -0,0 +1,175 @@ +//! Registry metadata for externally injected application-layout commands. +use super::CommandSpec; +use crate::schema::panels as wire; + +fn unavailable(_: &mut crate::Session, _: &serde_json::Value) -> crate::Result { + Err(crate::EngineError::Panel(crate::panels::error(crate::panels::Rule::Capability, "application layout backend was not injected"))) +} + +macro_rules! command { + ($id:literal, $icon:literal, $label:literal, $input:ty, $output:ty, $params:literal) => { + CommandSpec::new($id, $label, crate::checked!($id, unavailable)) + .icon($icon) + .noundo() + .doc_only() + .contract(&wire::CommandContract::<$input>::new($id)) + .output(wire::strict_output::<$output>) + .params($params) + }; +} + +pub static COMMANDS: &[CommandSpec] = &[ + command!( + "layout.apply", + "open", + "Apply Layout", + wire::Apply, + crate::panels::LayoutReply, + "name, expected_revision?: apply preset to current workspace through retained runtime" + ), + command!("layout.get", "list", "Inspect Layout", wire::Empty, wire::GetReply, "{}: committed state and registered workspace summaries"), + command!( + "layout.reset", + "restore", + "Reset Layout", + wire::Revision, + crate::panels::LayoutReply, + "expected_revision?: restore current workspace's registered default" + ), + command!( + "layout.save", + "save", + "Save Layout", + wire::Save, + wire::SaveReply, + "name, overwrite?: false, expected_revision?: save complete envelope in injected catalogue" + ), + command!( + "layout.workspace.select", + "display", + "Select Layout Workspace", + wire::WorkspaceSelect, + wire::WorkspaceReply, + "workspace, expected_revision?: atomically remember outgoing and replace with destination" + ), + command!( + "panel.activate", + "activate", + "Activate Panel Tab", + wire::Select, + crate::panels::LayoutReply, + "target or legacy id, expected_revision?: activate open tab without focus" + ), + command!( + "panel.close", + "close", + "Close Panel", + wire::Select, + crate::panels::LayoutReply, + "target or legacy id, expected_revision?: explicit guarded close" + ), + command!( + "panel.collapse", + "fold", + "Collapse Panel Section", + wire::Collapse, + crate::panels::LayoutReply, + "target or legacy id, collapsed, expected_revision?" + ), + command!( + "panel.dismiss", + "close", + "Dismiss Panel Peek", + wire::Revision, + crate::panels::LayoutReply, + "expected_revision?: dismiss temporary collapsed-panel presentation" + ), + command!( + "panel.float", + "move", + "Float Panel", + wire::Move, + crate::panels::LayoutReply, + "target or legacy id, destination: new_section with floating location, expected_revision?" + ), + command!( + "panel.focus", + "fit", + "Focus Panel", + wire::Select, + crate::panels::LayoutReply, + "target or legacy id, expected_revision?: reopen retained state, activate and request focus" + ), + command!( + "panel.list", + "list", + "List Panels", + wire::Empty, + wire::ListReply, + "{}: committed state, active tabs, capabilities, availability and registered kinds" + ), + command!( + "panel.move", + "move", + "Move Panel", + wire::Move, + crate::panels::LayoutReply, + "target or legacy id, destination: new_section or join_tab, expected_revision?" + ), + command!( + "panel.native_close", + "restore", + "Redock Native Panel Section", + wire::Select, + crate::panels::LayoutReply, + "target: native_host, expected_revision?: native close redocks without cancelling content" + ), + command!( + "panel.open", + "open", + "Open Panel", + wire::Open, + crate::panels::LayoutReply, + "kind, instance, destination?: required for new instance, expected_revision?" + ), + command!( + "panel.peek", + "eye", + "Peek Collapsed Panel", + wire::Select, + crate::panels::LayoutReply, + "target or legacy id, expected_revision?: transient presentation without resizing" + ), + command!( + "panel.popout", + "display", + "Pop Out Panel", + wire::Move, + crate::panels::LayoutReply, + "target or legacy id, destination: new_section with window location, expected_revision?: web lowers to floating" + ), + command!( + "panel.reset_pair", + "restore", + "Reset Panel Sash", + wire::ResetPair, + crate::panels::LayoutReply, + "first, second, expected_revision?: reset adjacent dock pair to registered default ratio" + ), + command!( + "panel.resize", + "scale", + "Resize Panel Section", + wire::Resize, + crate::panels::LayoutReply, + "target or legacy id, size: {width,height}, expected_revision?" + ), + command!( + "panel.resize_pair", + "scale", + "Resize Panel Sash", + wire::ResizePair, + crate::panels::LayoutReply, + "first, second, first_size, second_size, expected_revision?: conserve adjacent dock pair extent" + ), +]; diff --git a/crates/engine/src/fuzz.rs b/crates/engine/src/fuzz.rs index 36313f57e..5d2a7bda0 100644 --- a/crates/engine/src/fuzz.rs +++ b/crates/engine/src/fuzz.rs @@ -81,9 +81,11 @@ fn classify(e: &EngineError) -> Outcome { let msg = e.to_string(); match e { EngineError::Internal(..) => Outcome::new("panic", msg), - EngineError::BadParams { .. } | EngineError::Disabled(..) | EngineError::Refused { .. } | EngineError::UnknownCommand(_) => { - Outcome::new("rejected", msg) - } + EngineError::Panel(_) + | EngineError::BadParams { .. } + | EngineError::Disabled(..) + | EngineError::Refused { .. } + | EngineError::UnknownCommand(_) => Outcome::new("rejected", msg), // A failed boolean is a failure even when it says "not supported": those are the cases // to fix. Features the kernel doesn't do yet are limitations. // Picks the generator got wrong (a centroid off its face). diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 152c65f96..e4581a0cc 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -21,6 +21,7 @@ pub mod frames; pub mod fuzz; pub mod licences; pub mod occurrences; +pub mod panels; pub mod params; pub mod product_scene; pub mod recovery; @@ -66,6 +67,8 @@ pub const MAX_LINE: usize = 16 << 20; #[derive(Debug, thiserror::Error)] pub enum EngineError { + #[error("{text}", text = panels::commands::error_text(.0.clone()))] + Panel(#[from] panels::PanelError), #[error("unknown command `{0}`{hint}", hint = cmd::did_you_mean(.0))] UnknownCommand(String), #[error("`{0}` is not available right now: {1}")] @@ -1610,6 +1613,12 @@ impl Session { /// the model up to date before anything reads it. pub fn execute(&mut self, id: &str, params: &Value) -> Result { let spec = find_command(id).ok_or_else(|| EngineError::UnknownCommand(id.to_string()))?; + if panels::commands::is_command(spec.id) { + // Layout is application state. Even a missing capability must not + // clear live links, map picks, snapshot, evaluate or refresh a design. + panels::commands::parse_command(spec.id, params)?; + return Err(EngineError::Panel(panels::error(panels::Rule::Capability, "application layout backend was not injected"))); + } // The command, the evaluation it causes and the refresh after it: one profiler span. let _span = solidcraft_profile::span("command", spec.id); let host_viewport = self.render_viewport.clone(); diff --git a/crates/engine/src/panels/commands.rs b/crates/engine/src/panels/commands.rs new file mode 100644 index 000000000..486d23841 --- /dev/null +++ b/crates/engine/src/panels/commands.rs @@ -0,0 +1,946 @@ +//! Application-owned command execution shared by UI, control and headless MCP. +//! No Session, document, geometry, dialogs or camera are reachable here. +mod catalogue; + +use std::collections::BTreeMap; +use std::sync::Arc; + +use serde::de::DeserializeOwned; +use serde_json::{Value, json}; + +use super::*; +use crate::schema::panels as wire; + +pub const MAX_USER_PRESETS: usize = 64; +pub const MAX_WORKSPACES: usize = 64; +pub const MAX_CATALOGUE_BYTES: usize = 4 * 1024 * 1024; +pub const MAX_CATALOGUE_METADATA_BYTES: usize = 16 * 1024; +/// Framing is bounded separately from the aggregate payload/metadata budgets. +pub const MAX_CATALOGUE_SNAPSHOT_BYTES: usize = MAX_CATALOGUE_BYTES + MAX_CATALOGUE_METADATA_BYTES + 8192; +pub const MAX_COMMAND_BYTES: usize = 16 * 1024; + +/// Full envelope plus bounded rejected recovery intent. Arc makes catalogue +/// preparation bounded without copying each maximum-sized envelope 64 times. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct StoredEnvelope { + bytes: Arc<[u8]>, + rejected: Option>, +} +impl StoredEnvelope { + pub fn new(envelope: &LayoutEnvelope, rejected: Option<&[u8]>, registry: &PanelRegistry) -> PanelResult { + if rejected.is_some_and(|bytes| bytes.len() > MAX_ENVELOPE_BYTES) { + return Err(error(Rule::CollectionLimit, "rejected recovery byte cap")); + } + Ok(Self { bytes: encode(envelope, registry)?.into(), rejected: rejected.map(Arc::from) }) + } + /// Exact retained inspection, including saved instances whose kinds are now + /// absent. This is not a live-layout admission check; stage with + /// `project_envelope` before submitting through the authoritative sink. + pub fn envelope(&self, registry: &PanelRegistry, workspace: &WorkspaceId) -> PanelResult { + decode_retained(&self.bytes, registry, workspace) + } + /// Explicitly stage current-registry quarantine before a guarded live use. + /// Exact inspection above deliberately keeps absent-kind saved instances. + pub fn project_envelope(&self, registry: &PanelRegistry, workspace: &WorkspaceId) -> PanelResult { + project_retained_record(&self.bytes, registry, workspace) + } + /// Hydration retains the original validated bytes. In particular, optional + /// order/projection metadata is not filled and recounted against the cap. + fn from_record(bytes: &[u8], rejected: Option<&[u8]>, registry: &PanelRegistry) -> PanelResult { + if rejected.is_some_and(|bytes| bytes.len() > MAX_ENVELOPE_BYTES) { + return Err(error(Rule::CollectionLimit, "rejected recovery byte cap")); + } + decode_retained_record(bytes, registry)?; + Ok(Self { bytes: Arc::from(bytes), rejected: rejected.map(Arc::from) }) + } + pub fn rejected(&self) -> Option<&[u8]> { + self.rejected.as_deref() + } + pub fn bytes(&self) -> &[u8] { + &self.bytes + } +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct WorkspaceDescriptor { + pub id: WorkspaceId, + pub title_key: String, + pub default_preset: String, +} + +/// Fields are private: registrations and prepared updates must obey aggregate +/// bounds before cloning or publishing. There is no independently stored selection. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct CatalogueState { + workspaces: BTreeMap, + builtins: BTreeMap, + users: BTreeMap, + remembered: BTreeMap, +} +impl CatalogueState { + pub fn summaries(&self) -> Vec { + self.workspaces + .values() + .map(|item| wire::WorkspaceSummary { + id: item.id.clone(), + title_key: item.title_key.clone(), + default_preset: item.default_preset.clone(), + has_remembered_layout: self.remembered.contains_key(&item.id), + }) + .collect() + } + pub fn user_count(&self) -> usize { + self.users.len() + } + pub fn user_presets(&self) -> impl Iterator { + self.users.iter().map(|(name, record)| (name.as_str(), record)) + } + pub fn remembered(&self, workspace: &WorkspaceId) -> Option<&StoredEnvelope> { + self.remembered.get(workspace) + } + pub fn preset(&self, name: &str) -> PanelResult<&StoredEnvelope> { + self.builtins.get(name).or_else(|| self.users.get(name)).ok_or_else(|| error(Rule::MissingTarget, "layout preset not registered")) + } + fn validate(&self) -> PanelResult<()> { + if self.users.keys().any(|name| self.builtins.contains_key(name)) { + return Err(error(Rule::DuplicateId, "user preset collides with immutable built-in")); + } + if self.users.len() > MAX_USER_PRESETS + || self.builtins.len() > MAX_USER_PRESETS + || self.workspaces.len() > MAX_WORKSPACES + || self.remembered.len() > MAX_WORKSPACES + { + return Err(error(Rule::CollectionLimit, "layout catalogue count cap")); + } + let mut metadata = 0_usize; + for (id, item) in &self.workspaces { + valid_id(&id.0)?; + valid_id(&item.title_key)?; + if item.id != *id || !self.builtins.contains_key(&item.default_preset) { + return Err(error(Rule::MissingTarget, "workspace requires a registered immutable default")); + } + metadata = metadata.saturating_add(id.0.len() + item.title_key.len() + item.default_preset.len()); + } + let mut bytes = 0_usize; + for (name, stored) in self.builtins.iter().chain(&self.users) { + if preset_name(name)? != *name { + return Err(error(Rule::Schema, "preset name must be normalised")); + } + metadata = metadata.saturating_add(name.len()); + bytes = bytes.saturating_add(stored.bytes.len() + stored.rejected.as_ref().map_or(0, |r| r.len())); + } + for (id, stored) in &self.remembered { + valid_id(&id.0)?; + metadata = metadata.saturating_add(id.0.len()); + bytes = bytes.saturating_add(stored.bytes.len() + stored.rejected.as_ref().map_or(0, |r| r.len())); + } + if metadata > MAX_CATALOGUE_METADATA_BYTES || bytes > MAX_CATALOGUE_BYTES { + return Err(error(Rule::CollectionLimit, "aggregate layout catalogue byte cap")); + } + Ok(()) + } +} + +pub struct PreparedCatalogue(CatalogueState); +impl PreparedCatalogue { + pub fn new(state: CatalogueState) -> PanelResult { + state.validate()?; + Ok(Self(state)) + } + pub fn state(&self) -> &CatalogueState { + &self.0 + } + pub fn into_state(self) -> CatalogueState { + self.0 + } +} + +/// Prepare MUST stage every fallible storage operation. Publish MUST be infallible. +/// The executor holds the exclusive catalogue borrow across guarded dispatch. +pub trait LayoutCatalogue { + fn state(&self) -> &CatalogueState; + fn prepare(&mut self, next: CatalogueState) -> PanelResult; + fn publish(&mut self, prepared: PreparedCatalogue); +} + +#[derive(Default)] +pub struct InMemoryCatalogue { + state: CatalogueState, + /// Failure-injectable storage staging; no state has been published on failure. + pub fail_stage: bool, +} +impl LayoutCatalogue for InMemoryCatalogue { + fn state(&self) -> &CatalogueState { + &self.state + } + fn prepare(&mut self, next: CatalogueState) -> PanelResult { + if self.fail_stage { + return Err(error(Rule::Capability, "layout storage staging unavailable")); + } + PreparedCatalogue::new(next) + } + fn publish(&mut self, prepared: PreparedCatalogue) { + self.state = prepared.into_state(); + } +} +impl InMemoryCatalogue { + /// Hydration builds a validated candidate, without live dispatch or changing + /// the mutability of saved user presets. Production storage remains external. + pub fn from_snapshot(bytes: &[u8], registry: &PanelRegistry) -> PanelResult { + Ok(Self { state: CatalogueState::hydrate(bytes, registry)?, fail_stage: false }) + } + /// Explicit fixture/peer registration, never populated with invented products. + pub fn register_builtin(&mut self, name: &str, envelope: &LayoutEnvelope, registry: &PanelRegistry) -> PanelResult<()> { + let name = preset_name(name)?; + if self.state.builtins.contains_key(&name) || self.state.users.contains_key(&name) { + return Err(error(Rule::DuplicateId, "preset already registered")); + } + let stored = StoredEnvelope::new(envelope, None, registry)?; + let mut next = self.state.clone(); + next.builtins.insert(name, stored); + let prepared = self.prepare(next)?; + self.publish(prepared); + Ok(()) + } + pub fn register_workspace(&mut self, descriptor: WorkspaceDescriptor) -> PanelResult<()> { + valid_id(&descriptor.id.0)?; + valid_id(&descriptor.title_key)?; + if self.state.workspaces.contains_key(&descriptor.id) { + return Err(error(Rule::DuplicateId, "workspace already registered")); + } + let mut next = self.state.clone(); + next.workspaces.insert(descriptor.id.clone(), descriptor); + let prepared = self.prepare(next)?; + self.publish(prepared); + Ok(()) + } + pub fn remember(&mut self, envelope: &LayoutEnvelope, rejected: Option<&[u8]>, registry: &PanelRegistry) -> PanelResult<()> { + let stored = StoredEnvelope::new(envelope, rejected, registry)?; + let mut next = self.state.clone(); + next.remembered.insert(envelope.layout.workspace.clone(), stored); + let prepared = self.prepare(next)?; + self.publish(prepared); + Ok(()) + } +} + +pub fn preset_name(raw: &str) -> PanelResult { + // Bound BEFORE trimming, allocating or iterating over scalars. + if raw.len() > 1024 { + return Err(error(Rule::CollectionLimit, "raw preset name byte cap")); + } + let name = raw.trim(); + if name.is_empty() || name.len() > 256 || name.chars().count() > 64 || raw.chars().any(char::is_control) { + return Err(error(Rule::Schema, "preset name requires 1..64 Unicode scalars without controls")); + } + Ok(name.into()) +} + +pub fn is_command(id: &str) -> bool { + crate::find_command(id).is_some_and(|spec| IDS.contains(&spec.id)) +} +pub const IDS: &[&str] = &[ + "layout.apply", + "layout.get", + "layout.reset", + "layout.save", + "layout.workspace.select", + "panel.activate", + "panel.close", + "panel.collapse", + "panel.dismiss", + "panel.float", + "panel.focus", + "panel.list", + "panel.move", + "panel.native_close", + "panel.open", + "panel.peek", + "panel.popout", + "panel.reset_pair", + "panel.resize", + "panel.resize_pair", +]; + +#[derive(Debug)] +pub enum PanelCommand { + List, + Get, + Open(wire::Open), + Select { operation: &'static str, params: wire::Select }, + Move { operation: &'static str, params: wire::Move }, + Resize(wire::Resize), + Collapse(wire::Collapse), + Dismiss(wire::Revision), + ResizePair(wire::ResizePair), + ResetPair(wire::ResetPair), + Save(wire::Save), + Apply(wire::Apply), + Reset(wire::Revision), + Workspace(wire::WorkspaceSelect), +} +fn read(value: &Value) -> PanelResult { + serde_json::from_value(value.clone()).map_err(|_| error(Rule::Schema, "invalid panel command fields or types")) +} +pub fn parse_command(id: &str, params: &Value) -> PanelResult { + // Keep the engine/control convention: absent/null params mean an empty form. + let empty = json!({}); + let params = if params.is_null() { &empty } else { params }; + if !params.is_object() { + return Err(error(Rule::Schema, "panel command parameters must be an object")); + } + bounded_json(params)?; + // Capped writer protects direct callers as well as transports, before clone. + struct Counter(usize); + impl std::io::Write for Counter { + fn write(&mut self, bytes: &[u8]) -> std::io::Result { + self.0 = self.0.saturating_add(bytes.len()); + if self.0 > MAX_COMMAND_BYTES { + return Err(std::io::Error::other("command byte cap")); + } + Ok(bytes.len()) + } + fn flush(&mut self) -> std::io::Result<()> { + Ok(()) + } + } + serde_json::to_writer(Counter(0), params).map_err(|_| error(Rule::CollectionLimit, "panel command byte cap"))?; + let id = crate::find_command(id).map(|s| s.id).ok_or_else(|| error(Rule::MissingTarget, "unknown panel command"))?; + let command = match id { + "panel.list" => { + let _: wire::Empty = read(params)?; + PanelCommand::List + } + "layout.get" => { + let _: wire::Empty = read(params)?; + PanelCommand::Get + } + "panel.open" => PanelCommand::Open(read(params)?), + "panel.close" | "panel.activate" | "panel.focus" | "panel.peek" | "panel.native_close" => { + PanelCommand::Select { operation: id, params: read(params)? } + } + "panel.move" | "panel.float" | "panel.popout" => PanelCommand::Move { operation: id, params: read(params)? }, + "panel.resize" => PanelCommand::Resize(read(params)?), + "panel.collapse" => PanelCommand::Collapse(read(params)?), + "panel.dismiss" => PanelCommand::Dismiss(read(params)?), + "panel.resize_pair" => PanelCommand::ResizePair(read(params)?), + "panel.reset_pair" => PanelCommand::ResetPair(read(params)?), + "layout.save" => PanelCommand::Save(read(params)?), + "layout.apply" => PanelCommand::Apply(read(params)?), + "layout.reset" => PanelCommand::Reset(read(params)?), + "layout.workspace.select" => PanelCommand::Workspace(read(params)?), + _ => return Err(error(Rule::MissingTarget, "not an application layout command")), + }; + // Validate hostile values even when no application capability is injected. + validate_command(&command)?; + Ok(command) +} + +fn validate_selector(target: &Option, id: &Option) -> PanelResult<()> { + match (target, id) { + (Some(target), None) => match target { + wire::Target::Instance(id) => valid_id(&id.0), + wire::Target::Section(id) => valid_id(&id.0), + wire::Target::Workspace(id) => valid_id(&id.0), + wire::Target::NativeHost(id) => valid_id(&id.0), + }, + (None, Some(id)) => valid_id(id), + _ => Err(error(Rule::Schema, "supply exactly one typed target or legacy id")), + } +} +fn validate_destination(destination: Destination) -> PanelResult<()> { + match destination { + Destination::NewSection { section, index, location, size } => { + valid_id(§ion.0)?; + location.validate()?; + size.validate()?; + if index > MAX_SECTIONS { + return Err(error(Rule::Bounds, "section index cap")); + } + } + Destination::JoinTab { section, index } => { + valid_id(§ion.0)?; + if index >= MAX_TABS { + return Err(error(Rule::Bounds, "tab index cap")); + } + } + } + Ok(()) +} +fn validate_command(command: &PanelCommand) -> PanelResult<()> { + match command { + PanelCommand::Open(p) => { + valid_id(&p.kind.0)?; + valid_id(&p.instance.0)?; + if let Some(destination) = &p.destination { + validate_destination(destination.clone().into())?; + } + } + PanelCommand::Select { params, .. } => validate_selector(¶ms.target, ¶ms.id)?, + PanelCommand::Move { params, .. } => { + validate_selector(¶ms.target, ¶ms.id)?; + validate_destination(params.destination.clone().into())?; + } + PanelCommand::Resize(p) => { + validate_selector(&p.target, &p.id)?; + Size::from(p.size).validate()?; + } + PanelCommand::Collapse(p) => validate_selector(&p.target, &p.id)?, + PanelCommand::ResizePair(p) => { + valid_id(&p.first.0)?; + valid_id(&p.second.0)?; + Size::from(p.first_size).validate()?; + Size::from(p.second_size).validate()?; + } + PanelCommand::ResetPair(p) => { + valid_id(&p.first.0)?; + valid_id(&p.second.0)?; + } + PanelCommand::Save(p) => { + preset_name(&p.name)?; + } + PanelCommand::Apply(p) => { + preset_name(&p.name)?; + } + PanelCommand::Workspace(p) => valid_id(&p.workspace.0)?, + _ => {} + } + Ok(()) +} + +pub struct PanelCommandContext<'a> { + pub sink: &'a mut dyn ActionSink, + pub registry: &'a PanelRegistry, + pub catalogue: &'a mut dyn LayoutCatalogue, + /// Web popout is an explicit host policy, never inferred from no native support. + pub web: bool, +} + +fn target(target: Option, legacy: Option, layout: &Layout, registry: &PanelRegistry) -> PanelResult { + if let Some(target) = target { + return Ok(target.into()); + } + let id = legacy.ok_or_else(|| error(Rule::Schema, "target required"))?; + let instance = InstanceId::new(id.clone())?; + if layout.instance(&instance).is_ok() { + return Ok(LayoutTarget::Instance(instance)); + } + let kind = PanelKind::new(id)?; + let spec = registry.get(&kind)?; + if spec.features.multi_instance { + return Err(error(Rule::ExactlyOnce, "kind selector is ambiguous for multi-instance panels; supply typed instance")); + } + let matches: Vec<_> = layout.instances.iter().filter(|p| p.kind == kind).collect(); + if matches.len() != 1 { + return Err(error(Rule::MissingTarget, "kind requires one canonical retained instance")); + } + Ok(LayoutTarget::Instance(matches.first().ok_or_else(|| error(Rule::MissingTarget, "canonical instance absent"))?.id.clone())) +} +fn instance(target: LayoutTarget, layout: &Layout) -> PanelResult { + match target { + LayoutTarget::Instance(id) => { + layout.instance(&id)?; + Ok(id) + } + _ => Err(error(Rule::Schema, "operation requires instance target")), + } +} +fn section(target: LayoutTarget, layout: &Layout) -> PanelResult { + match target { + LayoutTarget::Section(id) => { + layout.section(&id)?; + Ok(id) + } + LayoutTarget::Instance(id) => Ok(layout.containing(&id)?.id.clone()), + _ => Err(error(Rule::Schema, "operation requires section or open instance target")), + } +} +fn revision(expected: Option, state: &LayoutReply) -> PanelResult<()> { + if expected.is_some_and(|r| r != state.revision) { + return Err(error(Rule::Revision, "stale layout revision")); + } + Ok(()) +} + +fn lower(command: PanelCommand, state: &LayoutReply, registry: &PanelRegistry, web: bool) -> PanelResult { + let layout = &state.layout; + Ok(match command { + PanelCommand::Open(p) => { + revision(p.expected_revision, state)?; + Mutation::Open { kind: p.kind, instance: p.instance, destination: p.destination.map(Into::into) } + } + PanelCommand::Select { operation, params: p } => { + revision(p.expected_revision, state)?; + let selected = target(p.target, p.id, layout, registry)?; + if operation == "panel.native_close" { + let LayoutTarget::NativeHost(host) = selected else { + return Err(error(Rule::Schema, "native close requires typed native_host target")); + }; + Mutation::NativeClose { host } + } else { + let instance = instance(selected, layout)?; + match operation { + "panel.close" => Mutation::Close { instance }, + "panel.focus" => Mutation::Focus { instance }, + "panel.activate" => Mutation::Activate { instance }, + "panel.peek" => Mutation::Peek { instance }, + _ => return Err(error(Rule::Schema, "unknown target operation")), + } + } + } + PanelCommand::Move { operation, params: p } => { + revision(p.expected_revision, state)?; + let instance = instance(target(p.target, p.id, layout, registry)?, layout)?; + let mut destination: Destination = p.destination.into(); + if operation == "panel.float" && !matches!(&destination, Destination::NewSection { location: SectionLocation::Floating { .. }, .. }) { + return Err(error(Rule::Placement, "panel.float requires new_section with floating location")); + } + if operation == "panel.popout" { + if !registry.get(&layout.instance(&instance)?.kind)?.features.popout { + return Err(error(Rule::FeatureDisabled, "panel cannot pop out")); + } + match &mut destination { + Destination::NewSection { location, .. } => match location { + SectionLocation::Window { origin, .. } => { + if web { + *location = SectionLocation::Floating { origin: *origin }; + } + } + _ => return Err(error(Rule::Placement, "panel.popout requires new_section with window location")), + }, + _ => return Err(error(Rule::Placement, "panel.popout requires a new section")), + } + } + Mutation::Move { instance, destination } + } + PanelCommand::Resize(p) => { + revision(p.expected_revision, state)?; + Mutation::SetSize { section: section(target(p.target, p.id, layout, registry)?, layout)?, size: p.size.into() } + } + PanelCommand::Collapse(p) => { + revision(p.expected_revision, state)?; + Mutation::Collapse { section: section(target(p.target, p.id, layout, registry)?, layout)?, collapsed: p.collapsed } + } + PanelCommand::Dismiss(p) => { + revision(p.expected_revision, state)?; + Mutation::DismissPeek + } + PanelCommand::ResizePair(p) => { + revision(p.expected_revision, state)?; + Mutation::ResizePair { first: p.first, second: p.second, first_size: p.first_size.into(), second_size: p.second_size.into() } + } + PanelCommand::ResetPair(p) => { + revision(p.expected_revision, state)?; + Mutation::ResetPair { first: p.first, second: p.second } + } + _ => return Err(error(Rule::Capability, "catalogue/query commands require individual transactions")), + }) +} + +fn current_envelope(catalogue: &CatalogueState, state: &LayoutReply, registry: &PanelRegistry) -> PanelResult<(LayoutEnvelope, Option>)> { + let workspace = &state.layout.workspace; + match catalogue.remembered.get(workspace) { + Some(stored) => { + Ok((with_live_layout(&stored.project_envelope(registry, workspace)?, state.layout.clone(), registry)?, stored.rejected.clone())) + } + None => Ok((LayoutEnvelope::new(state.layout.clone()), None)), + } +} + +/// Preserve all opaque sidecars. Reusing an identity with different opaque intent +/// is an error, never silently resolved by choosing one preset's value. +fn merge_envelopes(current: &LayoutEnvelope, mut next: LayoutEnvelope, registry: &PanelRegistry) -> PanelResult { + next.layout.workspace = current.layout.workspace.clone(); + for item in ¤t.quarantine { + if next.layout.instances.iter().any(|known| known.id == item.instance) { + return Err(error(Rule::DuplicateId, "preset collides with quarantined identity")); + } + match next.quarantine.iter().find(|q| q.instance == item.instance) { + Some(existing) if existing != item => return Err(error(Rule::DuplicateId, "quarantine sidecar collision")), + Some(_) => {} + None => next.quarantine.push(item.clone()), + } + } + for (id, data) in ¤t.retained_data { + if next.retained_data.get(id).is_some_and(|existing| existing != data) { + return Err(error(Rule::DuplicateId, "retained data collision")); + } + if let (Ok(old), Ok(new)) = (current.layout.instance(id), next.layout.instance(id)) + && old.kind != new.kind + { + return Err(error(Rule::DuplicateId, "retained instance kind collision")); + } + next.retained_data.insert(id.clone(), data.clone()); + } + for (id, snapshot) in ¤t.section_snapshots { + if next.section_snapshots.get(id).is_some_and(|existing| existing != snapshot) { + return Err(error(Rule::DuplicateId, "section sidecar collision")); + } + next.section_snapshots.insert(id.clone(), snapshot.clone()); + } + // Preserve dormant gaps from current; subsequent refresh overlays live order. + let dormant: std::collections::BTreeSet<_> = next.quarantine.iter().filter_map(|q| q.section.clone()).collect(); + let live: std::collections::BTreeSet<_> = next.layout.sections.iter().map(|s| s.id.clone()).collect(); + let mut order: Vec<_> = current.section_order.iter().filter(|id| dormant.contains(*id) || live.contains(*id)).cloned().collect(); + for id in &next.section_order { + if !order.contains(id) { + order.push(id.clone()); + } + } + next.section_order = order; + let layout = next.layout.clone(); + with_live_layout(&next, layout, registry) +} + +fn stage_current( + context: &mut PanelCommandContext<'_>, + state: &LayoutReply, + action: &LayoutAction, + envelope: &LayoutEnvelope, + recovery: Option>, + mut next: CatalogueState, +) -> PanelResult<(LayoutReply, CatalogueState)> { + let projected = context.sink.project(action.clone())?; + let envelope = with_live_layout(envelope, projected, context.registry)?; + let stored = StoredEnvelope::new(&envelope, recovery.as_deref(), context.registry)?; + next.remembered.insert(envelope.layout.workspace.clone(), stored); + let prepared = context.catalogue.prepare(next)?; + // Inspect can change through external adapters between planning and dispatch. + // Every action below includes the inspected revision; no stale catalogue publishes. + if context.sink.inspect().revision != state.revision { + return Err(error(Rule::Revision, "layout changed during storage staging")); + } + let committed = if *action == LayoutAction::Inspect { + let current = context.sink.inspect(); + revision(Some(state.revision), ¤t)?; + current + } else { + context.sink.dispatch(action.clone())? + }; + context.catalogue.publish(prepared); + Ok((committed, context.catalogue.state().clone())) +} + +pub fn execute_command(command: PanelCommand, context: &mut PanelCommandContext<'_>) -> PanelResult { + validate_command(&command)?; + let state = context.sink.inspect(); + match command { + PanelCommand::List => return value(wire::ListReply { state, kinds: context.registry.specs().cloned().collect() }), + PanelCommand::Get => return value(wire::GetReply { state, workspaces: context.catalogue.state().summaries() }), + PanelCommand::Workspace(ref p) if p.workspace == state.layout.workspace => { + revision(p.expected_revision, &state)?; + return value(wire::WorkspaceReply { + previous_workspace: state.layout.workspace.clone(), + source: wire::WorkspaceSource::Unchanged, + state, + }); + } + _ => {} + } + let mut next = context.catalogue.state().clone(); + let (current, recovery) = current_envelope(&next, &state, context.registry)?; + match command { + PanelCommand::Save(p) => { + revision(p.expected_revision, &state)?; + let name = preset_name(&p.name)?; + if next.builtins.contains_key(&name) { + return Err(error(Rule::Capability, "built-in presets are immutable")); + } + let overwritten = next.users.contains_key(&name); + if overwritten && !p.overwrite { + return Err(error(Rule::DuplicateId, "preset exists; overwrite must be explicit")); + } + if !overwritten && next.users.len() >= MAX_USER_PRESETS { + return Err(error(Rule::CollectionLimit, "user preset count cap")); + } + next.users.insert(name.clone(), StoredEnvelope::new(¤t, recovery.as_deref(), context.registry)?); + let action = LayoutAction::Inspect; + let (state, _) = stage_current(context, &state, &action, ¤t, recovery, next)?; + value(wire::SaveReply { name, overwritten, state }) + } + PanelCommand::Apply(p) => { + revision(p.expected_revision, &state)?; + let stored = next.preset(&preset_name(&p.name)?)?; + let mut envelope: LayoutEnvelope = + serde_json::from_slice(stored.bytes()).map_err(|_| error(Rule::Schema, "invalid registered envelope"))?; + // Decode using its original workspace before rebinding to the current one. + envelope = stored.project_envelope(context.registry, &envelope.layout.workspace)?; + let mut envelope = merge_envelopes(¤t, envelope, context.registry)?; + restore_quarantine(&mut envelope, context.registry)?; + let recovery = merge_recovery(recovery, stored.rejected.clone())?; + let action = LayoutAction::Replace { expected_revision: Some(state.revision), layout: envelope.layout.clone() }; + value(stage_current(context, &state, &action, &envelope, recovery, next)?.0) + } + PanelCommand::Reset(p) => { + revision(p.expected_revision, &state)?; + let descriptor = next + .workspaces + .get(&state.layout.workspace) + .ok_or_else(|| error(Rule::Capability, "selected workspace has no registered default"))?; + let stored = next.preset(&descriptor.default_preset)?; + let raw: LayoutEnvelope = serde_json::from_slice(stored.bytes()).map_err(|_| error(Rule::Schema, "invalid default envelope"))?; + let mut envelope = merge_envelopes(¤t, stored.project_envelope(context.registry, &raw.layout.workspace)?, context.registry)?; + restore_quarantine(&mut envelope, context.registry)?; + let recovery = merge_recovery(recovery, stored.rejected.clone())?; + let action = LayoutAction::Replace { expected_revision: Some(state.revision), layout: envelope.layout.clone() }; + value(stage_current(context, &state, &action, &envelope, recovery, next)?.0) + } + PanelCommand::Workspace(p) => { + revision(p.expected_revision, &state)?; + let previous_workspace = state.layout.workspace.clone(); + if p.workspace == previous_workspace { + return value(wire::WorkspaceReply { previous_workspace, source: wire::WorkspaceSource::Unchanged, state }); + } + let descriptor = next.workspaces.get(&p.workspace).ok_or_else(|| error(Rule::MissingTarget, "workspace not registered"))?; + let (stored, source) = match next.remembered.get(&p.workspace) { + Some(stored) => (stored, wire::WorkspaceSource::Remembered), + None => (next.preset(&descriptor.default_preset)?, wire::WorkspaceSource::DefaultPreset), + }; + let raw: LayoutEnvelope = serde_json::from_slice(stored.bytes()).map_err(|_| error(Rule::Schema, "invalid workspace envelope"))?; + let mut envelope = stored.project_envelope(context.registry, &raw.layout.workspace)?; + envelope.layout.workspace = p.workspace; + restore_quarantine(&mut envelope, context.registry)?; + let incoming_recovery = stored.rejected.clone(); + next.remembered.insert(previous_workspace.clone(), StoredEnvelope::new(¤t, recovery.as_deref(), context.registry)?); + let action = LayoutAction::Replace { expected_revision: Some(state.revision), layout: envelope.layout.clone() }; + let (state, _) = stage_current(context, &state, &action, &envelope, incoming_recovery, next)?; + value(wire::WorkspaceReply { previous_workspace, source, state }) + } + command => { + let mutation = lower(command, &state, context.registry, context.web)?; + let action = LayoutAction::Apply { expected_revision: Some(state.revision), mutations: vec![mutation] }; + value(stage_current(context, &state, &action, ¤t, recovery, next)?.0) + } + } +} +fn merge_recovery(first: Option>, second: Option>) -> PanelResult>> { + if first.is_some() && second.is_some() && first != second { + return Err(error(Rule::DuplicateId, "rejected recovery intent collision")); + } + Ok(first.or(second)) +} +fn value(value: impl serde::Serialize) -> PanelResult { + serde_json::to_value(value).map_err(|_| error(Rule::Schema, "cannot encode committed layout reply")) +} +pub fn execute(id: &str, params: &Value, context: &mut PanelCommandContext<'_>) -> PanelResult { + execute_command(parse_command(id, params)?, context) +} + +/// A private transaction planner reuses the common executor and the LIVE sink's +/// pure projection. It owns no reducer or LayoutService and cannot publish live +/// effects. Only the final guarded action and prepared catalogue are published. +struct PlanningSink<'a> { + authoritative: &'a dyn ActionSink, + state: LayoutReply, + mutations: Vec, + replaced: bool, +} +impl ActionSink for PlanningSink<'_> { + fn inspect(&self) -> LayoutReply { + self.state.clone() + } + fn project(&self, action: LayoutAction) -> PanelResult { + match action { + LayoutAction::Inspect => Ok(self.state.layout.clone()), + LayoutAction::Replace { expected_revision, layout } => { + revision(expected_revision, &self.state)?; + if !self.mutations.is_empty() { + return Err(error( + Rule::Capability, + "atomic batches cannot combine snapshot replacement and explicit panel mutations; use rollback:false", + )); + } + self.authoritative.project(LayoutAction::Replace { expected_revision: Some(self.state.revision), layout }) + } + LayoutAction::Apply { expected_revision, mutations } => { + revision(expected_revision, &self.state)?; + if self.replaced { + return Err(error( + Rule::Capability, + "atomic batches cannot combine snapshot replacement and explicit panel mutations; use rollback:false", + )); + } + if self.mutations.len().saturating_add(mutations.len()) > MAX_MUTATIONS { + return Err(error(Rule::CollectionLimit, "layout batch mutation cap")); + } + let mut combined = self.mutations.clone(); + combined.extend(mutations); + self.authoritative.project(LayoutAction::Apply { expected_revision: Some(self.state.revision), mutations: combined }) + } + } + } + fn dispatch(&mut self, action: LayoutAction) -> PanelResult { + let layout = self.project(action.clone())?; + match action { + LayoutAction::Apply { mutations, .. } => self.mutations.extend(mutations), + LayoutAction::Replace { .. } => { + self.replaced = true; + self.state.interaction = InteractionState::default(); + } + LayoutAction::Inspect => {} + } + self.state.layout = layout; + Ok(self.state.clone()) + } +} + +/// Pure structural preflight, usable before application context publication. +/// Same-workspace selection remains a no-op and may accompany mutations. +pub fn preflight_batch(steps: &[Value], workspace: &WorkspaceId) -> PanelResult<()> { + if steps.is_empty() || steps.len() > MAX_MUTATIONS { + return Err(error(Rule::CollectionLimit, "layout batch requires 1..64 steps")); + } + let mut selected = workspace.clone(); + let mut replacement = false; + let mut mutation = false; + for step in steps { + let id = + step.get("command").or_else(|| step.get("id")).and_then(Value::as_str).ok_or_else(|| error(Rule::Schema, "batch command required"))?; + let empty = json!({}); + match parse_command(id, step.get("params").unwrap_or(&empty))? { + PanelCommand::List | PanelCommand::Get | PanelCommand::Save(_) => {} + PanelCommand::Apply(_) | PanelCommand::Reset(_) => replacement = true, + PanelCommand::Workspace(params) => { + replacement |= params.workspace != selected; + selected = params.workspace; + } + _ => mutation = true, + } + } + if replacement && mutation { + return Err(error(Rule::Capability, "atomic batches cannot combine snapshot replacement and explicit panel mutations; use rollback:false")); + } + Ok(()) +} + +/// Atomic batches use one Apply or Replace and one catalogue/native/controller +/// preflight. Explicit lifecycle intent is never flattened into a replacement. +pub fn execute_batch(steps: &[Value], context: &mut PanelCommandContext<'_>) -> PanelResult { + if steps.is_empty() || steps.len() > MAX_MUTATIONS { + return Err(error(Rule::CollectionLimit, "layout batch requires 1..64 steps")); + } + let state = context.sink.inspect(); + preflight_batch(steps, &state.layout.workspace)?; + let mut planned = InMemoryCatalogue { state: context.catalogue.state().clone(), fail_stage: false }; + let mut sink = PlanningSink { authoritative: &*context.sink, state: state.clone(), mutations: Vec::new(), replaced: false }; + let mut rows = Vec::new(); + for step in steps { + let id = + step.get("command").or_else(|| step.get("id")).and_then(Value::as_str).ok_or_else(|| error(Rule::Schema, "batch command required"))?; + let id = crate::find_command(id).map(|spec| spec.id).ok_or_else(|| error(Rule::MissingTarget, "batch command not registered"))?; + let empty = json!({}); + let result = execute( + id, + step.get("params").filter(|p| !p.is_null()).unwrap_or(&empty), + &mut PanelCommandContext { sink: &mut sink, registry: context.registry, catalogue: &mut planned, web: context.web }, + )?; + rows.push((id, result)); + } + let action = if sink.replaced { + LayoutAction::Replace { expected_revision: Some(state.revision), layout: sink.state.layout.clone() } + } else if !sink.mutations.is_empty() { + LayoutAction::Apply { expected_revision: Some(state.revision), mutations: sink.mutations.clone() } + } else { + LayoutAction::Inspect + }; + let planned_state = sink.state.clone(); + let changed = planned.state != *context.catalogue.state() || action != LayoutAction::Inspect; + // Release the immutable authoritative borrow before committing through it. + drop(sink); + let committed = if changed { + let (envelope, recovery) = current_envelope(&planned.state, &planned_state, context.registry)?; + stage_current(context, &state, &action, &envelope, recovery, planned.state)?.0 + } else { + context.sink.inspect() + }; + let mut results = Vec::new(); + for (id, mut result) in rows { + match id { + "panel.list" => result = value(wire::ListReply { state: committed.clone(), kinds: context.registry.specs().cloned().collect() })?, + "layout.get" => result = value(wire::GetReply { state: committed.clone(), workspaces: context.catalogue.state().summaries() })?, + "layout.save" | "layout.workspace.select" => result["state"] = value(committed.clone())?, + _ => result = value(committed.clone())?, + } + results.push(result); + } + Ok(json!({"completed":steps.len(),"results":results,"undone":0})) +} + +/// Transport-compatible error text retains the structured foundation identity. +/// Control/MCP also expose this as panel_error beside their usual error string. +pub fn error_text(reason: PanelError) -> String { + serde_json::to_string(&reason).unwrap_or_else(|_| "{\"rule\":\"schema\",\"detail\":\"layout error encoding failed\"}".into()) +} +pub fn structured_error(text: &str) -> Option { + if text.len() > 4096 { + return None; + } + serde_json::from_str::(text).ok().and_then(|reason| value(error(reason.rule, reason.detail)).ok()) +} + +pub fn sequential_failure(index: usize, command: Option<&str>, text: String, results: Vec) -> Value { + let mut failed = json!({"index":index,"command":command,"error":text}); + if let Some(reason) = structured_error(&text) { + failed["panel_error"] = reason; + } + json!({"completed":index,"results":results,"failed":failed,"undone":0,"rolled_back":false}) +} + +/// One owned, persistent in-memory headless backend, outside Session. No kinds, +/// presets or workspace descriptors are invented. Peers/fixtures may inject them. +pub struct InMemoryPanelBackend { + pub service: LayoutService, + pub catalogue: InMemoryCatalogue, +} + +/// In-process layout has no native realization. Even a supplied service with +/// native flags cannot make this adapter claim that it opened an OS window. +struct HeadlessSink<'a>(&'a mut LayoutService); +impl ActionSink for HeadlessSink<'_> { + fn inspect(&self) -> LayoutReply { + let mut state = self.0.inspect(); + state.capabilities.native_windows = false; + state.capabilities.max_native_hosts = 0; + state + } + fn project(&self, action: LayoutAction) -> PanelResult { + let prepared = self.0.prepare(action)?; + if prepared.effects().iter().any(|effect| matches!(effect, HostEffect::CreateNative { .. } | HostEffect::RebindNative { .. })) { + return Err(error(Rule::Capability, "headless has no native host adapter")); + } + Ok(prepared.layout().clone()) + } + fn dispatch(&mut self, action: LayoutAction) -> PanelResult { + self.project(action.clone())?; + let mut state = self.0.dispatch(action)?; + state.capabilities.native_windows = false; + state.capabilities.max_native_hosts = 0; + Ok(state) + } +} +impl InMemoryPanelBackend { + pub fn new(service: LayoutService, catalogue: InMemoryCatalogue) -> Self { + Self { service, catalogue } + } + pub fn empty() -> PanelResult { + Ok(Self::new( + LayoutService::new(PanelRegistry::default(), Layout::empty(WorkspaceId::new("headless")?), HostCapabilities::default())?, + InMemoryCatalogue::default(), + )) + } + pub fn execute(&mut self, id: &str, params: &Value) -> PanelResult { + let registry = self.service.registry().clone(); + execute( + id, + params, + &mut PanelCommandContext { sink: &mut HeadlessSink(&mut self.service), registry: ®istry, catalogue: &mut self.catalogue, web: false }, + ) + } + pub fn batch(&mut self, steps: &[Value]) -> PanelResult { + let registry = self.service.registry().clone(); + execute_batch( + steps, + &mut PanelCommandContext { sink: &mut HeadlessSink(&mut self.service), registry: ®istry, catalogue: &mut self.catalogue, web: false }, + ) + } +} diff --git a/crates/engine/src/panels/commands/catalogue.rs b/crates/engine/src/panels/commands/catalogue.rs new file mode 100644 index 000000000..3c3e07dc6 --- /dev/null +++ b/crates/engine/src/panels/commands/catalogue.rs @@ -0,0 +1,158 @@ +//! Small versioned storage seam for application preferences, not design files. +//! Length-prefixed records keep arbitrary recovery bytes exact and bound every +//! allocation before copying. Envelopes retain their foundation JSON limits. +use super::*; + +const HEADER: &[u8] = b"SCPCAT01"; + +impl CatalogueState { + /// Export all immutable registrations, mutable users and remembered full + /// envelopes. No storage, live action, selection or Session is touched. + pub fn export(&self) -> PanelResult> { + self.validate()?; + let mut writer = Writer(Vec::new()); + writer.put(HEADER)?; + for presets in [&self.builtins, &self.users] { + writer.count(presets.len())?; + for (name, record) in presets { + writer.bytes(name.as_bytes())?; + writer.record(record)?; + } + } + writer.count(self.workspaces.len())?; + for descriptor in self.workspaces.values() { + writer.bytes(descriptor.id.0.as_bytes())?; + writer.bytes(descriptor.title_key.as_bytes())?; + writer.bytes(descriptor.default_preset.as_bytes())?; + } + writer.count(self.remembered.len())?; + for (workspace, record) in &self.remembered { + writer.bytes(workspace.0.as_bytes())?; + writer.record(record)?; + } + Ok(writer.0) + } + + /// Build a private validated candidate. Counts, duplicate identities, + /// names/IDs, envelope node/depth/byte bounds, rejected recovery and total + /// budgets are checked before the result can be published by any catalogue. + pub fn hydrate(bytes: &[u8], registry: &PanelRegistry) -> PanelResult { + if bytes.len() > MAX_CATALOGUE_SNAPSHOT_BYTES { + return Err(error(Rule::CollectionLimit, "catalogue snapshot byte cap")); + } + let mut reader = Reader { bytes, at: 0 }; + if reader.take(HEADER.len())? != HEADER { + return Err(error(Rule::Version, "unsupported catalogue snapshot")); + } + let mut next = Self::default(); + for builtin in [true, false] { + let count = reader.count(MAX_USER_PRESETS)?; + for _ in 0..count { + let name = reader.text(256)?; + if preset_name(&name)? != name { + return Err(error(Rule::Schema, "stored preset name is not normalised")); + } + if next.builtins.contains_key(&name) || next.users.contains_key(&name) { + return Err(error(Rule::DuplicateId, "duplicate stored preset identity")); + } + let record = reader.record(registry)?; + if builtin { + next.builtins.insert(name, record); + } else { + next.users.insert(name, record); + } + } + } + for _ in 0..reader.count(MAX_WORKSPACES)? { + let id = WorkspaceId::new(reader.text(MAX_ID_BYTES)?)?; + let title_key = reader.text(MAX_ID_BYTES)?; + valid_id(&title_key)?; + let default_preset = reader.text(256)?; + if next.workspaces.contains_key(&id) { + return Err(error(Rule::DuplicateId, "duplicate stored workspace identity")); + } + next.workspaces.insert(id.clone(), WorkspaceDescriptor { id, title_key, default_preset }); + } + for _ in 0..reader.count(MAX_WORKSPACES)? { + let workspace = WorkspaceId::new(reader.text(MAX_ID_BYTES)?)?; + if next.remembered.contains_key(&workspace) { + return Err(error(Rule::DuplicateId, "duplicate remembered workspace identity")); + } + let record = reader.record(registry)?; + // A remembered record belongs to its key, unlike a reusable preset. + record.envelope(registry, &workspace)?; + next.remembered.insert(workspace, record); + } + if reader.at != bytes.len() { + return Err(error(Rule::Schema, "trailing catalogue snapshot data")); + } + next.validate()?; + Ok(next) + } +} + +struct Writer(Vec); +impl Writer { + fn put(&mut self, bytes: &[u8]) -> PanelResult<()> { + if self.0.len().saturating_add(bytes.len()) > MAX_CATALOGUE_SNAPSHOT_BYTES { + return Err(error(Rule::CollectionLimit, "catalogue snapshot byte cap")); + } + self.0.extend_from_slice(bytes); + Ok(()) + } + fn count(&mut self, count: usize) -> PanelResult<()> { + let count = u32::try_from(count).map_err(|_| error(Rule::CollectionLimit, "catalogue framing cap"))?; + self.put(&count.to_le_bytes()) + } + fn bytes(&mut self, bytes: &[u8]) -> PanelResult<()> { + self.count(bytes.len())?; + self.put(bytes) + } + fn record(&mut self, record: &StoredEnvelope) -> PanelResult<()> { + self.bytes(record.bytes())?; + match record.rejected() { + Some(rejected) => { + self.put(&[1])?; + self.bytes(rejected) + } + None => self.put(&[0]), + } + } +} + +struct Reader<'a> { + bytes: &'a [u8], + at: usize, +} +impl<'a> Reader<'a> { + fn take(&mut self, count: usize) -> PanelResult<&'a [u8]> { + let end = self.at.checked_add(count).ok_or_else(|| error(Rule::CollectionLimit, "catalogue framing overflow"))?; + let bytes = self.bytes.get(self.at..end).ok_or_else(|| error(Rule::Schema, "truncated catalogue snapshot"))?; + self.at = end; + Ok(bytes) + } + fn count(&mut self, max: usize) -> PanelResult { + let raw = <[u8; 4]>::try_from(self.take(4)?).map_err(|_| error(Rule::Schema, "invalid catalogue length"))?; + let count = usize::try_from(u32::from_le_bytes(raw)).map_err(|_| error(Rule::CollectionLimit, "catalogue length overflow"))?; + if count > max { + return Err(error(Rule::CollectionLimit, "catalogue record/count cap")); + } + Ok(count) + } + fn bytes(&mut self, max: usize) -> PanelResult<&'a [u8]> { + let count = self.count(max)?; + self.take(count) + } + fn text(&mut self, max: usize) -> PanelResult { + std::str::from_utf8(self.bytes(max)?).map(str::to_owned).map_err(|_| error(Rule::Schema, "invalid catalogue UTF-8")) + } + fn record(&mut self, registry: &PanelRegistry) -> PanelResult { + let bytes = self.bytes(MAX_ENVELOPE_BYTES)?; + let rejected = match self.take(1)? { + [0] => None, + [1] => Some(self.bytes(MAX_ENVELOPE_BYTES)?), + _ => return Err(error(Rule::Schema, "invalid catalogue recovery tag")), + }; + StoredEnvelope::from_record(bytes, rejected, registry) + } +} diff --git a/crates/engine/src/panels/fixtures.rs b/crates/engine/src/panels/fixtures.rs new file mode 100644 index 000000000..e32888746 --- /dev/null +++ b/crates/engine/src/panels/fixtures.rs @@ -0,0 +1,110 @@ +//! Executable synthetic contracts for independent host/command/persistence work. +//! These identifiers are fixtures, never production registrations or UI strings. +use std::collections::BTreeMap; + +use super::*; + +pub const FIXTURE_LAYOUT_V1: &[u8] = include_bytes!("fixtures/layout-v1.json"); + +pub fn synthetic_registry() -> PanelResult { + let mut registry = PanelRegistry::default(); + for (kind, multi, pinned) in + [("fixture.application", false, false), ("fixture.editor", false, false), ("fixture.log", true, false), ("fixture.pin", true, true)] + { + let mut allowed_zones: std::collections::BTreeSet<_> = + [Zone::Left, Zone::Right, Zone::Bottom, Zone::Floating, Zone::Window].into_iter().collect(); + if pinned { + allowed_zones.remove(&Zone::Bottom); + } + registry.register(PanelSpec { + kind: PanelKind::new(kind)?, + title_key: "ui.panel".into(), + icon: "panel".into(), + allowed_zones, + default_zone: Zone::Left, + min_size: Size { width: 160.0, height: 120.0 }, + default_size: Size { width: 280.0, height: 240.0 }, + max_size: Size { width: 1200.0, height: 1200.0 }, + edge_rule: if pinned { EdgeRule::PinOuter } else { EdgeRule::None }, + surface: PanelSurface::FollowZone, + features: PanelFeatures { multi_instance: multi, ..PanelFeatures::default() }, + })?; + } + Ok(registry) +} + +pub fn fixture_open(kind: &str, instance: &str, section: &str, zone: Zone, index: usize) -> PanelResult { + Ok(Mutation::Open { + kind: PanelKind::new(kind)?, + instance: InstanceId::new(instance)?, + destination: Some(Destination::NewSection { + section: SectionId::new(section)?, + index, + location: if zone == Zone::Floating { + SectionLocation::Floating { origin: Point { x: 40.0, y: 40.0 } } + } else { + SectionLocation::Dock { zone } + }, + size: Size { width: 280.0, height: 240.0 }, + }), + }) +} + +pub fn fixture_service(native: bool) -> PanelResult { + LayoutService::new( + synthetic_registry()?, + Layout::empty(WorkspaceId::new("fixture.workspace")?), + HostCapabilities { native_windows: native, max_native_hosts: if native { 8 } else { 0 }, persistence: true }, + ) +} + +pub fn transaction(mutations: Vec) -> LayoutAction { + LayoutAction::Apply { expected_revision: None, mutations } +} + +/// Synthetic catalogue shared by command/control/MCP tests; never registered by +/// application startup. Two descriptors may deliberately share one default. +pub fn fixture_command_catalogue(registry: &PanelRegistry) -> PanelResult { + let mut catalogue = commands::InMemoryCatalogue::default(); + let empty = LayoutEnvelope::new(Layout::empty(WorkspaceId::new("fixture.workspace")?)); + catalogue.register_builtin("Fixture default", &empty, registry)?; + for id in ["fixture.workspace", "fixture.other"] { + catalogue.register_workspace(commands::WorkspaceDescriptor { + id: WorkspaceId::new(id)?, + title_key: "ui.panel".into(), + default_preset: "Fixture default".into(), + })?; + } + Ok(catalogue) +} + +pub fn fixture_command_backend() -> PanelResult { + let service = fixture_service(false)?; + let catalogue = fixture_command_catalogue(service.registry())?; + Ok(commands::InMemoryPanelBackend::new(service, catalogue)) +} + +#[derive(Default)] +pub struct FakePersistence { + /// Deliberately separate map demonstrates that layout writes own one key. + pub unrelated_preferences: BTreeMap, + pub layouts: BTreeMap>, + pub fail_save: bool, +} +impl LayoutPersistence for FakePersistence { + fn load(&mut self, workspace: &WorkspaceId) -> PanelResult>> { + valid_id(&workspace.0)?; + Ok(self.layouts.get(workspace).cloned()) + } + fn save(&mut self, workspace: &WorkspaceId, envelope: &[u8]) -> PanelResult<()> { + valid_id(&workspace.0)?; + if envelope.len() > MAX_ENVELOPE_BYTES || (!self.layouts.contains_key(workspace) && self.layouts.len() >= MAX_SECTIONS) { + return Err(error(Rule::CollectionLimit, "fake persistence capacity")); + } + if self.fail_save { + return Err(error(Rule::Capability, "synthetic atomic write failure")); + } + self.layouts.insert(workspace.clone(), envelope.to_vec()); + Ok(()) + } +} diff --git a/crates/engine/src/panels/fixtures/layout-v1.json b/crates/engine/src/panels/fixtures/layout-v1.json new file mode 100644 index 000000000..794c19ed2 --- /dev/null +++ b/crates/engine/src/panels/fixtures/layout-v1.json @@ -0,0 +1,37 @@ +{ + "format": "solidcraft.panel-layout", + "version": 1, + "layout": { + "version": 1, + "workspace": "fixture.workspace", + "instances": [ + { + "id": "editor", + "kind": "fixture.editor", + "requested_open": true, + "memory": { + "section": "editor-section", + "location": { "type": "dock", "zone": "left" }, + "section_index": 0, + "tab_index": 0, + "size": { "width": 280.0, "height": 240.0 }, + "collapsed": false + } + } + ], + "sections": [ + { + "id": "editor-section", + "location": { "type": "dock", "zone": "left" }, + "tabs": ["editor"], + "active": "editor", + "size": { "width": 280.0, "height": 240.0 }, + "collapsed": false + } + ] + }, + "quarantine": [], + "section_snapshots": {}, + "section_order": ["editor-section"], + "retained_data": {} +} diff --git a/crates/engine/src/panels/geometry.rs b/crates/engine/src/panels/geometry.rs new file mode 100644 index 000000000..475855a68 --- /dev/null +++ b/crates/engine/src/panels/geometry.rs @@ -0,0 +1,410 @@ +use schemars::JsonSchema; +use serde::{Deserialize, Serialize}; + +use super::*; + +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize, JsonSchema)] +pub struct Point { + pub x: f32, + pub y: f32, +} +impl Point { + pub fn validate(self) -> PanelResult<()> { + if !self.x.is_finite() || !self.y.is_finite() || self.x.abs() > MAX_LOGICAL || self.y.abs() > MAX_LOGICAL { + return Err(error(Rule::Bounds, "invalid logical position")); + } + Ok(()) + } +} + +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize, JsonSchema)] +pub struct LogicalRect { + pub origin: Point, + pub size: Size, +} +impl LogicalRect { + pub fn validate(self) -> PanelResult<()> { + self.origin.validate()?; + self.size.validate()?; + if (self.origin.x + self.size.width).abs() > MAX_LOGICAL || (self.origin.y + self.size.height).abs() > MAX_LOGICAL { + return Err(error(Rule::Bounds, "logical rectangle extent out of range")); + } + Ok(()) + } + pub fn contains(self, p: Point) -> bool { + p.x >= self.origin.x && p.y >= self.origin.y && p.x <= self.origin.x + self.size.width && p.y <= self.origin.y + self.size.height + } + pub fn contains_rect(self, other: Self) -> bool { + self.contains(other.origin) && self.contains(Point { x: other.origin.x + other.size.width, y: other.origin.y + other.size.height }) + } +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)] +#[serde(rename_all = "snake_case")] +pub enum Flow { + Tall, + Wide, +} +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)] +#[serde(rename_all = "snake_case")] +pub enum SizeClass { + Compact, + Regular, + Wide, +} +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)] +#[serde(rename_all = "snake_case")] +pub enum Direction { + Ltr, + Rtl, +} +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)] +#[serde(rename_all = "snake_case")] +pub enum PhysicalEdge { + Left, + Right, + Bottom, +} + +impl Direction { + pub fn edge(self, zone: Zone) -> PanelResult { + match (self, zone) { + (Self::Ltr, Zone::Left) | (Self::Rtl, Zone::Right) => Ok(PhysicalEdge::Left), + (Self::Ltr, Zone::Right) | (Self::Rtl, Zone::Left) => Ok(PhysicalEdge::Right), + (_, Zone::Bottom) => Ok(PhysicalEdge::Bottom), + _ => Err(error(Rule::Placement, "free host has no logical dock edge")), + } + } +} + +/// Usable logical units: egui applies scale exactly once, outside this contract. +/// Free/native flow starts at aspect 1, switches Tall->Wide above 1.1, Wide->Tall +/// below 0.9, and retains the previous flow inside that band. +pub fn responsive(zone: Zone, usable: Size, previous: Option) -> PanelResult<(Flow, SizeClass)> { + usable.validate()?; + let aspect = usable.width / usable.height; + let flow = match zone { + Zone::Left | Zone::Right => Flow::Tall, + Zone::Bottom => Flow::Wide, + Zone::Floating | Zone::Window => match previous { + Some(Flow::Tall) if aspect <= 1.1 => Flow::Tall, + Some(Flow::Wide) if aspect >= 0.9 => Flow::Wide, + _ if aspect >= 1.0 => Flow::Wide, + _ => Flow::Tall, + }, + }; + let shorter = usable.width.min(usable.height); + let class = if shorter < 240.0 { + SizeClass::Compact + } else if shorter <= 480.0 { + SizeClass::Regular + } else { + SizeClass::Wide + }; + Ok((flow, class)) +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)] +#[serde(rename_all = "snake_case")] +pub enum InputRole { + Surface, + Header, + Tab, + Sash, + Action, + Rail, + Overlay, +} + +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)] +pub struct InputRegion { + pub control: ControlId, + pub role: InputRole, + pub bounds: LogicalRect, + pub keyboard_focusable: bool, + /// Translation key or a runtime title resolved by the host. + pub accessible_name: String, +} +impl InputRegion { + pub fn validate(&self) -> PanelResult<()> { + valid_id(&self.control.0)?; + self.bounds.validate()?; + if self.accessible_name.is_empty() || self.accessible_name.len() > 256 { + return Err(error(Rule::Bounds, "accessible name requires 1..256 bytes")); + } + Ok(()) + } +} + +/// Host-resolved geometry has separate outer, body, paint and input bounds. No +/// transparent/full-window input shield is implied by an overlay surface. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)] +pub struct ResolvedPanel { + pub instance: InstanceId, + pub section: SectionId, + pub zone: Zone, + pub outer: LogicalRect, + pub body: LogicalRect, + pub painted: Vec, + pub input: Vec, +} +impl ResolvedPanel { + pub fn validate(&self) -> PanelResult<()> { + valid_id(&self.instance.0)?; + valid_id(&self.section.0)?; + self.outer.validate()?; + self.body.validate()?; + if !self.outer.contains_rect(self.body) { + return Err(error(Rule::Bounds, "usable body outside outer host")); + } + if self.painted.is_empty() || self.painted.len() > MAX_TABS || self.input.len() > MAX_INSTANCES { + return Err(error(Rule::CollectionLimit, "resolved region count")); + } + for rect in &self.painted { + rect.validate()?; + if !self.outer.contains_rect(*rect) { + return Err(error(Rule::Bounds, "paint outside host")); + } + } + let mut ids = std::collections::BTreeSet::new(); + for region in &self.input { + region.validate()?; + if !ids.insert(®ion.control) { + return Err(error(Rule::DuplicateId, "semantic control id repeated")); + } + if !self.painted.iter().any(|r| r.contains_rect(region.bounds)) { + return Err(error(Rule::Bounds, "input must be contained in painted area")); + } + } + Ok(()) + } + pub fn consumes_pointer(&self, at: Point) -> bool { + self.input.iter().any(|r| r.bounds.contains(at)) + } +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)] +#[serde(rename_all = "snake_case")] +pub enum UnpresentedReason { + MinimumOverflow, + Unavailable, + NativeUnsupported, + Collapsed, +} + +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)] +pub struct UnpresentedSection { + pub section: SectionId, + pub reason: UnpresentedReason, +} + +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, JsonSchema)] +pub struct ResolvedLayout { + pub panels: Vec, + /// Accessible rail controls are chrome, never sub-minimum content bodies. + pub rails: Vec, + pub unpresented: Vec, +} +impl ResolvedLayout { + pub fn validate(&self) -> PanelResult<()> { + if self.panels.len() > MAX_SECTIONS || self.rails.len() > MAX_SECTIONS || self.unpresented.len() > MAX_SECTIONS { + return Err(error(Rule::CollectionLimit, "resolved layout cap")); + } + let mut instances = std::collections::BTreeSet::new(); + let mut sections = std::collections::BTreeSet::new(); + let mut rails = std::collections::BTreeSet::new(); + for panel in &self.panels { + panel.validate()?; + if !instances.insert(&panel.instance) || !sections.insert(&panel.section) { + return Err(error(Rule::ExactlyOnce, "duplicate resolved instance/section")); + } + } + for rail in &self.rails { + rail.validate()?; + if rail.role != InputRole::Rail || !rails.insert(&rail.control) { + return Err(error(Rule::DuplicateId, "invalid or duplicate rail control")); + } + } + for record in &self.unpresented { + valid_id(&record.section.0)?; + if !sections.insert(&record.section) { + return Err(error(Rule::ExactlyOnce, "section both presented/unpresented or duplicated")); + } + } + Ok(()) + } +} + +/// Reference geometry for synthetic mounts. Production docking owns its richer +/// resolver; both return the same meaningful geometry contract. No layout writes. +pub fn resolve_geometry(service: &LayoutService, capacity: LogicalRect, direction: Direction, chrome: f32) -> PanelResult { + capacity.validate()?; + if !chrome.is_finite() || chrome < 0.0 || chrome > 256.0 { + return Err(error(Rule::Bounds, "invalid header/footer chrome extent")); + } + let mut result = ResolvedLayout::default(); + let mut left = capacity.origin.x; + let mut right = capacity.origin.x + capacity.size.width; + let mut bottom = capacity.origin.y + capacity.size.height; + let mut left_y = capacity.origin.y; + let mut right_y = capacity.origin.y; + let mut bottom_x = capacity.origin.x; + let mut rail_y = capacity.origin.y; + let mut occupied: Vec = Vec::new(); + for section in &service.layout().sections { + let id = §ion.active; + let zone = section.location.zone(); + let peek = &service.interaction().peek; + let active = peek.as_ref().filter(|p| section.tabs.contains(p)).unwrap_or(id); + let available = service.availability(active) == Availability::Available; + let reason = if !available { + Some(UnpresentedReason::Unavailable) + } else if zone == Zone::Window && !service.capabilities().native_windows { + Some(UnpresentedReason::NativeUnsupported) + } else if section.collapsed && peek.as_ref() != Some(active) { + Some(UnpresentedReason::Collapsed) + } else { + None + }; + if let Some(reason) = reason { + result.unpresented.push(UnpresentedSection { section: section.id.clone(), reason: reason.clone() }); + if reason == UnpresentedReason::Collapsed { + append_rail(&mut result, service, active, capacity, direction, zone, &mut rail_y)?; + } + continue; + } + let size = section.size; + let origin = match §ion.location { + SectionLocation::Floating { origin } | SectionLocation::Window { origin, .. } => *origin, + SectionLocation::Dock { zone } => match direction.edge(*zone)? { + PhysicalEdge::Left => Point { x: left, y: left_y }, + PhysicalEdge::Right => Point { x: right - size.width, y: right_y }, + PhysicalEdge::Bottom => Point { x: bottom_x, y: bottom - size.height }, + }, + }; + let outer = LogicalRect { origin, size }; + let overlaps_dock = zone.docked() + && !section.collapsed + && occupied.iter().any(|r| { + r.origin.x < origin.x + size.width + && origin.x < r.origin.x + r.size.width + && r.origin.y < origin.y + size.height + && origin.y < r.origin.y + r.size.height + }); + if !capacity.contains_rect(outer) || size.height <= chrome || overlaps_dock { + result.unpresented.push(UnpresentedSection { section: section.id.clone(), reason: UnpresentedReason::MinimumOverflow }); + append_rail(&mut result, service, active, capacity, direction, zone, &mut rail_y)?; + continue; + } + if zone.docked() && !section.collapsed { + occupied.push(outer); + match direction.edge(zone)? { + PhysicalEdge::Left => { + left_y += size.height; + left = left.max(origin.x); + } + PhysicalEdge::Right => { + right_y += size.height; + right = right.min(origin.x + size.width); + } + PhysicalEdge::Bottom => { + bottom_x += size.width; + bottom = bottom.min(origin.y + size.height); + } + } + } + let body = + LogicalRect { origin: Point { x: origin.x, y: origin.y + chrome / 2.0 }, size: Size { width: size.width, height: size.height - chrome } }; + let panel = ResolvedPanel { + instance: active.clone(), + section: section.id.clone(), + zone, + outer, + body, + painted: vec![outer], + input: vec![InputRegion { + control: ControlId::new(format!("host.{}", section.id.0).chars().take(MAX_ID_BYTES).collect::())?, + role: InputRole::Surface, + bounds: outer, + keyboard_focusable: true, + accessible_name: service.registry().get(&service.layout().instance(active)?.kind)?.title_key.clone(), + }], + }; + panel.validate()?; + result.panels.push(panel); + } + result.validate()?; + Ok(result) +} + +fn append_rail( + result: &mut ResolvedLayout, + service: &LayoutService, + active: &InstanceId, + capacity: LogicalRect, + direction: Direction, + zone: Zone, + rail_y: &mut f32, +) -> PanelResult<()> { + // Rails are bounded chrome, not below-minimum content bodies. If every entry + // cannot fit, the complete unpresented list remains available to a host's rail. + let width = 32.0_f32.min(capacity.size.width); + let height = 32.0_f32.min(capacity.size.height); + if *rail_y + height <= capacity.origin.y + capacity.size.height { + let right = direction.edge(if zone.docked() { zone } else { Zone::Left })? == PhysicalEdge::Right; + let x = if right { capacity.origin.x + capacity.size.width - width } else { capacity.origin.x }; + result.rails.push(InputRegion { + control: ControlId::new(format!("rail.{}", result.rails.len()))?, + role: InputRole::Rail, + bounds: LogicalRect { origin: Point { x, y: *rail_y }, size: Size { width, height } }, + keyboard_focusable: true, + accessible_name: service.registry().get(&service.layout().instance(active)?.kind)?.title_key.clone(), + }); + *rail_y += height; + } + Ok(()) +} + +/// Surfaces child resolves theme tokens. Invalid authored pairs retain raw import +/// intent and last good tokens; they cannot be reported as accessible by recolouring. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)] +#[serde(tag = "state", rename_all = "snake_case")] +pub enum ContrastOutcome { + Readable { effective_background_alpha: f32 }, + RetainReadableFallback { reason: ContrastFailure }, +} +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)] +#[serde(rename_all = "snake_case")] +pub enum ContrastFailure { + InvalidTokens, + UnreadableAtFullOpacity, +} + +impl ContrastOutcome { + /// The surfaces adapter proves readability. This boundary enforces finite + /// alpha and the policy that effective background alpha may only increase. + pub fn validate(&self, requested_alpha: f32) -> PanelResult<()> { + if !requested_alpha.is_finite() || !(0.0..=1.0).contains(&requested_alpha) { + return Err(error(Rule::Bounds, "invalid requested background alpha")); + } + if let Self::Readable { effective_background_alpha } = self + && (!effective_background_alpha.is_finite() || *effective_background_alpha < requested_alpha || *effective_background_alpha > 1.0) + { + return Err(error(Rule::Bounds, "resolved background alpha must be finite and only raised")); + } + Ok(()) + } +} + +/// Shared surface precedence: Opaque wins, then explicit Translucent, then zone +/// default (bottom/native opaque, sides/free translucent). No colour implementation. +pub fn group_surface<'a>(zone: Zone, specs: impl IntoIterator) -> PanelSurface { + let mut translucent = false; + for spec in specs { + if spec.surface == PanelSurface::Opaque { + return PanelSurface::Opaque; + } + translucent |= spec.surface == PanelSurface::Translucent; + } + if translucent || !matches!(zone, Zone::Bottom | Zone::Window) { PanelSurface::Translucent } else { PanelSurface::Opaque } +} diff --git a/crates/engine/src/panels/mod.rs b/crates/engine/src/panels/mod.rs new file mode 100644 index 000000000..868041315 --- /dev/null +++ b/crates/engine/src/panels/mod.rs @@ -0,0 +1,18 @@ +//! Application/workspace layout, deliberately independent of Session and egui. +//! Consumers must use `LayoutService` (or its `ActionSink`) for committed mutations. +//! The serde values are wire data, not proof of validity; see `validate` and `decode`. +pub mod commands; +mod fixtures; +mod geometry; +mod model; +mod persistence; +mod reducer; + +pub use fixtures::*; +pub use geometry::*; +pub use model::*; +pub use persistence::*; +pub use reducer::*; + +#[cfg(test)] +mod tests; diff --git a/crates/engine/src/panels/model.rs b/crates/engine/src/panels/model.rs new file mode 100644 index 000000000..c9525b503 --- /dev/null +++ b/crates/engine/src/panels/model.rs @@ -0,0 +1,480 @@ +use std::collections::{BTreeMap, BTreeSet}; + +use super::geometry::Point; +use schemars::JsonSchema; +use serde::{Deserialize, Serialize}; + +pub const LAYOUT_VERSION: u32 = 1; +pub const PANEL_API_VERSION: u32 = 1; +pub const MAX_ID_BYTES: usize = 64; +pub const MAX_INSTANCES: usize = 128; +pub const MAX_SECTIONS: usize = 64; +pub const MAX_TABS: usize = 32; +pub const MAX_MUTATIONS: usize = 64; +pub const MAX_LOGICAL: f32 = 32_768.0; +pub const MAX_ENVELOPE_BYTES: usize = 262_144; + +/// Classic is a permanent compatibility contract; this foundation does not +/// select a new preset or migrate existing preferences. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)] +#[serde(rename_all = "snake_case")] +pub enum CompatibilityPreset { + Classic, +} + +/// Stable machine-readable rule names; presentation translates these in the adapter. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)] +#[serde(rename_all = "snake_case")] +pub enum Rule { + Availability, + Bounds, + Capability, + CollectionLimit, + DuplicateId, + ExactlyOnce, + FeatureDisabled, + Id, + IncompatibleTabs, + Lifecycle, + MissingTarget, + PinConflict, + PinOrder, + Placement, + Revision, + Schema, + Version, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema, thiserror::Error)] +#[error("{rule:?}: {detail}")] +pub struct PanelError { + pub rule: Rule, + pub detail: String, +} + +pub type PanelResult = std::result::Result; + +pub fn error(rule: Rule, detail: impl Into) -> PanelError { + // Error replies are bounded too; never echo a hostile payload in full. + PanelError { rule, detail: detail.into().chars().take(256).collect() } +} + +pub fn valid_id(value: &str) -> PanelResult<()> { + if value.is_empty() || value.len() > MAX_ID_BYTES || !value.bytes().all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || b"._-".contains(&c)) { + return Err(error(Rule::Id, "expected a nonempty bounded lowercase identifier")); + } + Ok(()) +} + +macro_rules! identity { + ($($name:ident),+ $(,)?) => {$ ( + #[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize, JsonSchema)] + #[serde(transparent)] + pub struct $name(pub String); + impl $name { + pub fn new(value: impl Into) -> PanelResult { + let value = value.into(); + valid_id(&value)?; + Ok(Self(value)) + } + } + )+}; +} +identity!(PanelKind, InstanceId, SectionId, WorkspaceId, DocumentId, ViewportId, HostId, ControlId); + +/// Leading/trailing logical sides, mirrored by a host for RTL. There is no Top zone. +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize, JsonSchema)] +#[serde(rename_all = "snake_case")] +pub enum Zone { + Left, + Right, + Bottom, + Floating, + Window, +} + +impl Zone { + pub fn docked(self) -> bool { + matches!(self, Self::Left | Self::Right | Self::Bottom) + } +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)] +#[serde(rename_all = "snake_case")] +pub enum EdgeRule { + None, + PinOuter, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)] +#[serde(rename_all = "snake_case")] +pub enum PanelSurface { + FollowZone, + Opaque, + Translucent, +} + +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize, JsonSchema)] +pub struct Size { + pub width: f32, + pub height: f32, +} + +impl Size { + pub fn validate(self) -> PanelResult<()> { + if !self.width.is_finite() + || !self.height.is_finite() + || self.width <= 0.0 + || self.height <= 0.0 + || self.width > MAX_LOGICAL + || self.height > MAX_LOGICAL + { + return Err(error(Rule::Bounds, "outer size must be finite and in (0, 32768] logical units")); + } + Ok(()) + } + pub fn within(self, min: Self, max: Self) -> bool { + self.width >= min.width && self.height >= min.height && self.width <= max.width && self.height <= max.height + } +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)] +pub struct PanelFeatures { + pub collapsible: bool, + pub closable: bool, + pub popout: bool, + pub tabbable: bool, + pub multi_instance: bool, +} + +impl Default for PanelFeatures { + fn default() -> Self { + Self { collapsible: true, closable: true, popout: true, tabbable: true, multi_instance: false } + } +} + +/// Immutable registration metadata. No callbacks, content state or model references. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)] +pub struct PanelSpec { + pub kind: PanelKind, + pub title_key: String, + pub icon: String, + pub allowed_zones: BTreeSet, + pub default_zone: Zone, + pub min_size: Size, + pub default_size: Size, + pub max_size: Size, + pub edge_rule: EdgeRule, + pub surface: PanelSurface, + pub features: PanelFeatures, +} + +#[derive(Clone, Debug, Default)] +pub struct PanelRegistry { + specs: BTreeMap, +} + +impl PanelRegistry { + pub fn register(&mut self, spec: PanelSpec) -> PanelResult<()> { + valid_id(&spec.kind.0)?; + valid_id(&spec.title_key)?; + valid_id(&spec.icon)?; + spec.min_size.validate()?; + spec.max_size.validate()?; + spec.default_size.validate()?; + if !spec.default_size.within(spec.min_size, spec.max_size) { + return Err(error(Rule::Bounds, "min <= default <= max required in both dimensions")); + } + if !spec.allowed_zones.contains(&Zone::Floating) || !spec.allowed_zones.contains(&spec.default_zone) { + return Err(error(Rule::Placement, "Floating and default_zone must be allowed")); + } + if spec.edge_rule == EdgeRule::PinOuter && spec.allowed_zones.contains(&Zone::Bottom) { + return Err(error(Rule::Placement, "PinOuter must exclude Bottom")); + } + if self.specs.contains_key(&spec.kind) { + return Err(error(Rule::DuplicateId, "panel kind already registered")); + } + if self.specs.len() >= MAX_INSTANCES { + return Err(error(Rule::CollectionLimit, "registry full")); + } + self.specs.insert(spec.kind.clone(), spec); + Ok(()) + } + pub fn get(&self, kind: &PanelKind) -> PanelResult<&PanelSpec> { + self.specs.get(kind).ok_or_else(|| error(Rule::MissingTarget, "unregistered panel kind")) + } + pub fn specs(&self) -> impl Iterator { + self.specs.values() + } +} + +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)] +#[serde(tag = "type", rename_all = "snake_case")] +pub enum SectionLocation { + Dock { zone: Zone }, + Floating { origin: Point }, + Window { host: HostId, origin: Point, return_to: DockReturn }, +} + +impl SectionLocation { + pub fn zone(&self) -> Zone { + match self { + Self::Dock { zone } => *zone, + Self::Floating { .. } => Zone::Floating, + Self::Window { .. } => Zone::Window, + } + } + pub fn validate(&self) -> PanelResult<()> { + match self { + Self::Dock { zone } if !zone.docked() => Err(error(Rule::Placement, "dock must name a docked zone")), + Self::Dock { .. } => Ok(()), + Self::Floating { origin } => origin.validate(), + Self::Window { host, origin, return_to } => { + valid_id(&host.0)?; + origin.validate()?; + return_to.validate() + } + } + } +} + +/// Native return destinations never recursively contain another native host. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)] +pub struct DockReturn { + pub zone: Zone, + pub index: usize, + pub size: Size, + pub collapsed: bool, + /// Restore a former tab group when it still occupies the recorded dock. + /// Missing/reparented groups use the nonrecursive dock fallback above. + #[serde(default)] + pub join: Option, +} +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)] +pub struct ReturnTab { + pub section: SectionId, + pub index: usize, +} +impl DockReturn { + pub fn validate(&self) -> PanelResult<()> { + if !self.zone.docked() || self.index > MAX_SECTIONS { + return Err(error(Rule::Placement, "invalid native return destination")); + } + self.size.validate()?; + if let Some(join) = &self.join { + valid_id(&join.section.0)?; + if join.index >= MAX_TABS { + return Err(error(Rule::Bounds, "native return tab index cap")); + } + } + Ok(()) + } +} + +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)] +pub struct Section { + pub id: SectionId, + pub location: SectionLocation, + pub tabs: Vec, + pub active: InstanceId, + /// Desired outer dimensions; overflow resolution never modifies these. + pub size: Size, + pub collapsed: bool, +} + +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)] +pub struct PlacementMemory { + pub section: SectionId, + pub location: SectionLocation, + pub section_index: usize, + pub tab_index: usize, + pub size: Size, + pub collapsed: bool, +} + +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)] +pub struct PanelInstance { + pub id: InstanceId, + pub kind: PanelKind, + pub requested_open: bool, + pub memory: PlacementMemory, +} + +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)] +pub struct Layout { + pub version: u32, + pub workspace: WorkspaceId, + pub instances: Vec, + /// Stable order, outermost first within each logical dock edge. + pub sections: Vec
, +} + +impl Layout { + pub fn empty(workspace: WorkspaceId) -> Self { + Self { version: LAYOUT_VERSION, workspace, instances: Vec::new(), sections: Vec::new() } + } + pub fn instance(&self, id: &InstanceId) -> PanelResult<&PanelInstance> { + self.instances.iter().find(|p| p.id == *id).ok_or_else(|| error(Rule::MissingTarget, "instance not found")) + } + pub fn section(&self, id: &SectionId) -> PanelResult<&Section> { + self.sections.iter().find(|s| s.id == *id).ok_or_else(|| error(Rule::MissingTarget, "section not found")) + } + pub fn containing(&self, id: &InstanceId) -> PanelResult<&Section> { + self.sections.iter().find(|s| s.tabs.contains(id)).ok_or_else(|| error(Rule::MissingTarget, "instance has no open section")) + } +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)] +#[serde(tag = "state", rename_all = "snake_case")] +pub enum Availability { + Available, + Unavailable { reason: String }, +} + +impl Availability { + pub fn require(&self) -> PanelResult<()> { + match self { + Self::Available => Ok(()), + Self::Unavailable { reason } => Err(error(Rule::Availability, reason)), + } + } +} + +/// Missing entries mean available. Availability is live context, never layout persistence. +pub type AvailabilityMap = BTreeMap; + +#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema)] +pub struct HostCapabilities { + pub native_windows: bool, + pub persistence: bool, + pub max_native_hosts: usize, +} + +pub fn tab_bounds(layout: &Layout, registry: &PanelRegistry, section: &Section) -> PanelResult<(Size, Size)> { + let mut min = Size { width: 0.0, height: 0.0 }; + let mut max = Size { width: MAX_LOGICAL, height: MAX_LOGICAL }; + for id in §ion.tabs { + let spec = registry.get(&layout.instance(id)?.kind)?; + min.width = min.width.max(spec.min_size.width); + min.height = min.height.max(spec.min_size.height); + max.width = max.width.min(spec.max_size.width); + max.height = max.height.min(spec.max_size.height); + } + if min.width > max.width || min.height > max.height { + return Err(error(Rule::IncompatibleTabs, "tab size constraints have no intersection")); + } + Ok((min, max)) +} + +/// Bounded semantic validation, also required after serde and every transaction. +pub fn validate(layout: &Layout, registry: &PanelRegistry) -> PanelResult<()> { + if layout.version != LAYOUT_VERSION { + return Err(error(Rule::Version, "unsupported layout version")); + } + valid_id(&layout.workspace.0)?; + if layout.instances.len() > MAX_INSTANCES || layout.sections.len() > MAX_SECTIONS { + return Err(error(Rule::CollectionLimit, "layout collection limit")); + } + let mut instances = BTreeSet::new(); + let mut kinds = BTreeSet::new(); + for p in &layout.instances { + valid_id(&p.id.0)?; + valid_id(&p.kind.0)?; + valid_id(&p.memory.section.0)?; + if !instances.insert(&p.id) { + return Err(error(Rule::DuplicateId, "duplicate instance")); + } + let spec = registry.get(&p.kind)?; + if !spec.features.multi_instance && !kinds.insert(&p.kind) { + return Err(error(Rule::ExactlyOnce, "single-instance kind repeated, including closed instances")); + } + p.memory.location.validate()?; + p.memory.size.validate()?; + if p.memory.tab_index >= MAX_TABS || p.memory.section_index > MAX_SECTIONS { + return Err(error(Rule::Bounds, "invalid placement memory")); + } + if !spec.allowed_zones.contains(&p.memory.location.zone()) { + return Err(error(Rule::Placement, "remembered zone forbidden")); + } + } + let mut sections = BTreeSet::new(); + let mut seen = BTreeSet::new(); + let mut hosts = BTreeSet::new(); + let mut pins = BTreeSet::new(); + let mut edges = BTreeSet::new(); + for s in &layout.sections { + valid_id(&s.id.0)?; + s.location.validate()?; + s.size.validate()?; + if !sections.insert(&s.id) { + return Err(error(Rule::DuplicateId, "duplicate section")); + } + if s.tabs.is_empty() || s.tabs.len() > MAX_TABS { + return Err(error(Rule::CollectionLimit, "section requires 1..32 tabs")); + } + if !s.tabs.contains(&s.active) { + return Err(error(Rule::MissingTarget, "active tab outside section")); + } + if let SectionLocation::Window { host, .. } = &s.location + && !hosts.insert(host) + { + return Err(error(Rule::DuplicateId, "native host reused")); + } + let zone = s.location.zone(); + let first = edges.insert(zone); + for id in &s.tabs { + let instance = layout.instance(id)?; + let spec = registry.get(&instance.kind)?; + if !instance.requested_open || !seen.insert(id) { + return Err(error(Rule::ExactlyOnce, "closed or duplicate presented instance")); + } + if !spec.allowed_zones.contains(&zone) { + return Err(error(Rule::Placement, "panel zone forbidden")); + } + if s.tabs.len() > 1 && !spec.features.tabbable { + return Err(error(Rule::FeatureDisabled, "panel cannot join tabs")); + } + if s.collapsed && !spec.features.collapsible { + return Err(error(Rule::FeatureDisabled, "panel cannot collapse")); + } + if zone == Zone::Window && !spec.features.popout { + return Err(error(Rule::FeatureDisabled, "panel cannot pop out")); + } + if spec.edge_rule == EdgeRule::PinOuter && matches!(zone, Zone::Left | Zone::Right) { + if !pins.insert(zone) { + return Err(error(Rule::PinConflict, "competing pins on logical edge, including same tab group")); + } + if !first { + return Err(error(Rule::PinOrder, "pinned section must be outermost")); + } + } + } + let (min, max) = tab_bounds(layout, registry, s)?; + if !s.size.within(min, max) { + return Err(error(Rule::Bounds, "section outside intersected tab bounds")); + } + if let SectionLocation::Window { return_to, .. } = &s.location { + for id in &s.tabs { + let spec = registry.get(&layout.instance(id)?.kind)?; + if !spec.allowed_zones.contains(&return_to.zone) + || !return_to.size.within(spec.min_size, spec.max_size) + || (return_to.collapsed && !spec.features.collapsible) + { + return Err(error(Rule::Placement, "native return violates member constraints")); + } + } + } + } + for p in &layout.instances { + // Diagnose impossible tab groups before their shared size can make an + // individual member's remembered size appear invalid. + let spec = registry.get(&p.kind)?; + if !p.memory.size.within(spec.min_size, spec.max_size) { + return Err(error(Rule::Bounds, "invalid placement memory")); + } + if p.requested_open != seen.contains(&p.id) { + return Err(error(Rule::ExactlyOnce, "open instance must appear exactly once")); + } + } + Ok(()) +} diff --git a/crates/engine/src/panels/persistence.rs b/crates/engine/src/panels/persistence.rs new file mode 100644 index 000000000..43446e9bc --- /dev/null +++ b/crates/engine/src/panels/persistence.rs @@ -0,0 +1,762 @@ +use schemars::JsonSchema; +use serde::{Deserialize, Serialize}; + +use super::*; + +pub const ENVELOPE_FORMAT: &str = "solidcraft.panel-layout"; +pub const ENVELOPE_VERSION: u32 = 1; + +/// Unknown panel wire values are retained verbatim as JSON values, including +/// fields a future content adapter understands. Total encoded envelope is capped. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)] +pub struct QuarantinedPanel { + pub instance: InstanceId, + pub kind: PanelKind, + pub instance_data: serde_json::Value, + pub section: Option, +} + +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)] +pub struct SectionSnapshot { + pub data: serde_json::Value, + /// Latest complete rank; also permits reading earlier v1 envelopes without + /// the envelope's explicit complete section_order list. + pub index: usize, + /// Last materialized section, so a live user edit can be distinguished from + /// the fallback active tab/order produced while some members are dormant. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub projected: Option
, +} + +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)] +pub struct LayoutEnvelope { + pub format: String, + pub version: u32, + pub layout: Layout, + pub quarantine: Vec, + /// Shared, lossless section order/activation/future fields, stored once even + /// when many unknown tabs refer to the same section. Retained after restore. + #[serde(default)] + pub section_snapshots: std::collections::BTreeMap, + /// Latest complete section ordering, including currently dormant sections. + /// Retained snapshots alone cannot rank surviving sections without this list. + #[serde(default)] + pub section_order: Vec, + /// Original unknown wire data remains available after registry reappearance. + /// A content/persistence adapter may explicitly consume it; restoring placement + /// alone must not erase a future field that this foundation cannot interpret. + #[serde(default)] + pub retained_data: std::collections::BTreeMap, +} +impl LayoutEnvelope { + pub fn new(layout: Layout) -> Self { + let section_order = layout.sections.iter().map(|section| section.id.clone()).collect(); + Self { + format: ENVELOPE_FORMAT.into(), + version: ENVELOPE_VERSION, + layout, + quarantine: Vec::new(), + section_snapshots: std::collections::BTreeMap::new(), + section_order, + retained_data: std::collections::BTreeMap::new(), + } + } +} + +#[derive(Clone, Debug)] +pub struct LoadOutcome { + pub envelope: LayoutEnvelope, + /// Adapter reports this once; fallback never blocks startup or touches other preferences. + pub notice: Option, + /// Bounded corrupt/future input, available to a recovery adapter before replacement. + pub rejected: Option>, +} + +/// Implementations read/write ONLY the workspace panel-layout preference key. +/// `save` must replace atomically, preserving unrelated preferences. Production +/// preference migration is intentionally outside the foundation. +pub trait LayoutPersistence { + fn load(&mut self, workspace: &WorkspaceId) -> PanelResult>>; + fn save(&mut self, workspace: &WorkspaceId, envelope: &[u8]) -> PanelResult<()>; +} + +pub fn encode(envelope: &LayoutEnvelope, registry: &PanelRegistry) -> PanelResult> { + validate_envelope(envelope, registry)?; + encode_record(envelope) +} + +fn encode_record(envelope: &LayoutEnvelope) -> PanelResult> { + let mut writer = BoundedEnvelopeWriter { bytes: Vec::new() }; + serde_json::to_writer(&mut writer, envelope).map_err(|_| error(Rule::CollectionLimit, "cannot encode panel envelope within byte cap"))?; + // Aggregated opaque entries must also fit the decoder's global node/depth + // budget. Never persist bytes that this same version would reject on reopen. + let value: serde_json::Value = serde_json::from_slice(&writer.bytes).map_err(|_| error(Rule::Schema, "invalid encoded panel envelope"))?; + bounded_json(&value)?; + Ok(writer.bytes) +} + +struct BoundedEnvelopeWriter { + bytes: Vec, +} +impl std::io::Write for BoundedEnvelopeWriter { + fn write(&mut self, bytes: &[u8]) -> std::io::Result { + if self.bytes.len().saturating_add(bytes.len()) > MAX_ENVELOPE_BYTES { + return Err(std::io::Error::new(std::io::ErrorKind::InvalidData, "panel envelope byte cap")); + } + self.bytes.extend_from_slice(bytes); + Ok(bytes.len()) + } + fn flush(&mut self) -> std::io::Result<()> { + Ok(()) + } +} + +fn validate_envelope(envelope: &LayoutEnvelope, registry: &PanelRegistry) -> PanelResult<()> { + if envelope.format != ENVELOPE_FORMAT { + return Err(error(Rule::Schema, "unknown panel envelope format")); + } + if envelope.version != ENVELOPE_VERSION { + return Err(error(Rule::Version, "unknown panel envelope version")); + } + validate(&envelope.layout, registry)?; + validate_envelope_metadata(envelope) +} + +fn validate_envelope_metadata(envelope: &LayoutEnvelope) -> PanelResult<()> { + if envelope.quarantine.len() + envelope.layout.instances.len() > MAX_INSTANCES { + return Err(error(Rule::CollectionLimit, "quarantine instance cap")); + } + if envelope.retained_data.len() > MAX_INSTANCES { + return Err(error(Rule::CollectionLimit, "retained data cap")); + } + for (id, data) in &envelope.retained_data { + valid_id(&id.0)?; + bounded_json(data)?; + } + if envelope.section_snapshots.len() > MAX_SECTIONS { + return Err(error(Rule::CollectionLimit, "section snapshot cap")); + } + validate_section_order(&envelope.section_order)?; + for (id, snapshot) in &envelope.section_snapshots { + validate_snapshot(id, snapshot)?; + } + let mut ids = std::collections::BTreeSet::new(); + for item in &envelope.quarantine { + bounded_json(&item.instance_data)?; + valid_id(&item.instance.0)?; + valid_id(&item.kind.0)?; + if !ids.insert(&item.instance) || envelope.layout.instances.iter().any(|p| p.id == item.instance) { + return Err(error(Rule::DuplicateId, "quarantine identity or index invalid")); + } + let instance: PanelInstance = + serde_json::from_value(item.instance_data.clone()).map_err(|_| error(Rule::Schema, "invalid quarantined instance"))?; + if instance.id != item.instance || instance.kind != item.kind { + return Err(error(Rule::Id, "quarantine identity mismatch")); + } + if instance.requested_open != item.section.is_some() { + return Err(error(Rule::ExactlyOnce, "quarantine open/section mismatch")); + } + valid_id(&instance.memory.section.0)?; + instance.memory.location.validate()?; + instance.memory.size.validate()?; + if instance.memory.section_index > MAX_SECTIONS || instance.memory.tab_index >= MAX_TABS { + return Err(error(Rule::CollectionLimit, "quarantine placement cap")); + } + if let Some(id) = &item.section { + let snapshot = envelope.section_snapshots.get(id).ok_or_else(|| error(Rule::MissingTarget, "quarantined section snapshot absent"))?; + let section: Section = serde_json::from_value(snapshot.data.clone()).map_err(|_| error(Rule::Schema, "invalid quarantined section"))?; + if !section.tabs.contains(&item.instance) { + return Err(error(Rule::ExactlyOnce, "quarantined instance absent from section snapshot")); + } + } + } + Ok(()) +} + +fn validate_section_order(order: &[SectionId]) -> PanelResult<()> { + if order.len() > MAX_SECTIONS { + return Err(error(Rule::CollectionLimit, "complete section order cap")); + } + let mut seen = std::collections::BTreeSet::new(); + for id in order { + valid_id(&id.0)?; + if !seen.insert(id) { + return Err(error(Rule::DuplicateId, "duplicate complete section rank")); + } + } + Ok(()) +} + +fn validate_section_record(section: &Section) -> PanelResult<()> { + valid_id(§ion.id.0)?; + section.location.validate()?; + section.size.validate()?; + if section.tabs.is_empty() || section.tabs.len() > MAX_TABS || !section.tabs.contains(§ion.active) { + return Err(error(Rule::CollectionLimit, "section snapshot tabs/active bound")); + } + let mut seen = std::collections::BTreeSet::new(); + for id in §ion.tabs { + valid_id(&id.0)?; + if !seen.insert(id) { + return Err(error(Rule::ExactlyOnce, "section snapshot duplicate tab")); + } + } + Ok(()) +} + +fn validate_snapshot(id: &SectionId, snapshot: &SectionSnapshot) -> PanelResult<()> { + valid_id(&id.0)?; + bounded_json(&snapshot.data)?; + let section: Section = serde_json::from_value(snapshot.data.clone()).map_err(|_| error(Rule::Schema, "invalid shared section snapshot"))?; + if section.id != *id || snapshot.index > MAX_SECTIONS { + return Err(error(Rule::Id, "section snapshot identity/index mismatch")); + } + validate_section_record(§ion)?; + if let Some(projected) = &snapshot.projected { + if projected.id != *id { + return Err(error(Rule::Id, "projected section identity mismatch")); + } + validate_section_record(projected)?; + } + Ok(()) +} + +/// Overlay the live relative order on its previous slots, keeping dormant gaps. +/// New live entries attach before their next surviving live neighbour, rather +/// than consuming a dormant slot or reversing a run of newly added entries. +fn merge_visible_order(saved: &[T], live: &[T], dormant: &std::collections::BTreeSet) -> Vec { + let survivors: std::collections::BTreeSet<_> = saved.iter().filter(|id| live.contains(id)).cloned().collect(); + let mut live_survivors = live.iter().filter(|id| survivors.contains(*id)); + let mut merged = Vec::new(); + for id in saved { + if dormant.contains(id) && !live.contains(id) { + merged.push(id.clone()); + } else if survivors.contains(id) + && let Some(next) = live_survivors.next() + { + merged.push(next.clone()); + } + } + for (index, id) in live.iter().enumerate() { + if survivors.contains(id) { + continue; + } + let before = live.iter().skip(index + 1).find(|next| survivors.contains(*next)); + let at = before.and_then(|next| merged.iter().position(|old| old == next)).unwrap_or(merged.len()); + merged.insert(at, id.clone()); + } + merged +} + +/// Refresh live semantics before a new quarantine episode, or before a direct +/// restoration after the caller has edited the known layout. Opaque data stays +/// shared; only semantic fields supplied by the current layout are refreshed. +fn refresh_section_memory( + envelope: &mut LayoutEnvelope, + raw: Option<&serde_json::Value>, + capture: &std::collections::BTreeSet, +) -> PanelResult<()> { + if envelope.section_snapshots.len() > MAX_SECTIONS || envelope.quarantine.len() > MAX_INSTANCES { + return Err(error(Rule::CollectionLimit, "section memory collection cap")); + } + validate_section_order(&envelope.section_order)?; + for (id, snapshot) in &envelope.section_snapshots { + validate_snapshot(id, snapshot)?; + } + let dormant_sections: std::collections::BTreeSet<_> = envelope.quarantine.iter().filter_map(|item| item.section.clone()).collect(); + let live_order: Vec<_> = envelope.layout.sections.iter().map(|section| section.id.clone()).collect(); + let mut saved_order = envelope.section_order.clone(); + if saved_order.is_empty() { + // Read earlier v1 envelopes without the complete rank list. Sort missing + // ranks before insertion, never in instance/quarantine processing order. + saved_order = live_order.clone(); + let mut missing = Vec::new(); + for id in &dormant_sections { + let snapshot = envelope.section_snapshots.get(id).ok_or_else(|| error(Rule::MissingTarget, "dormant section snapshot missing"))?; + if !saved_order.contains(id) { + missing.push((snapshot.index, id.clone())); + } + } + missing.sort(); + for (index, id) in missing { + saved_order.insert(index.min(saved_order.len()), id); + } + } else if dormant_sections.iter().any(|id| !saved_order.contains(id)) { + return Err(error(Rule::MissingTarget, "complete order omits a dormant section")); + } + envelope.section_order = merge_visible_order(&saved_order, &live_order, &dormant_sections); + validate_section_order(&envelope.section_order)?; + for (index, section) in envelope.layout.sections.iter().enumerate() { + let previous = envelope.section_snapshots.get(§ion.id); + if previous.is_none() && !capture.contains(§ion.id) { + continue; + } + let current = match raw { + Some(raw) => raw + .get("layout") + .and_then(|layout| layout.get("sections")) + .and_then(|sections| sections.get(index)) + .cloned() + .ok_or_else(|| error(Rule::Schema, "saved section raw data missing"))?, + None => serde_json::to_value(section).map_err(|_| error(Rule::Schema, "cannot encode live section semantics"))?, + }; + let (mut data, projected) = match previous { + Some(previous) => (previous.data.clone(), previous.projected.clone()), + None => (serde_json::json!({}), None), + }; + let dormant_tabs: std::collections::BTreeSet<_> = + envelope.quarantine.iter().filter(|item| item.section.as_ref() == Some(§ion.id)).map(|item| item.instance.clone()).collect(); + let previous_section: Option
= previous + .map(|snapshot| serde_json::from_value(snapshot.data.clone()).map_err(|_| error(Rule::Schema, "invalid section memory"))) + .transpose()?; + let tabs = match &previous_section { + Some(saved) if !dormant_tabs.is_empty() => merge_visible_order(&saved.tabs, §ion.tabs, &dormant_tabs), + _ => section.tabs.clone(), + }; + if tabs.len() > MAX_TABS { + return Err(error(Rule::CollectionLimit, "complete tab order cap")); + } + let active = match &previous_section { + Some(saved) + if dormant_tabs.contains(&saved.active) + && !section.tabs.contains(&saved.active) + && !projected.as_ref().is_some_and(|last| last.active != section.active) => + { + saved.active.clone() + } + _ => section.active.clone(), + }; + // Overlay current fields, preserving opaque keys absent from the typed + // layout. A current raw value for the same key is the latest saved intent. + let object = data.as_object_mut().ok_or_else(|| error(Rule::Schema, "section memory must be an object"))?; + let current = current.as_object().ok_or_else(|| error(Rule::Schema, "saved section must be an object"))?; + for (key, value) in current { + object.insert(key.clone(), value.clone()); + } + object.insert("tabs".into(), serde_json::to_value(tabs).map_err(|_| error(Rule::Schema, "cannot encode complete tab order"))?); + object.insert("active".into(), serde_json::to_value(active).map_err(|_| error(Rule::Schema, "cannot encode complete activation"))?); + let rank = envelope + .section_order + .iter() + .position(|id| *id == section.id) + .ok_or_else(|| error(Rule::MissingTarget, "live section has no complete rank"))?; + envelope.section_snapshots.insert(section.id.clone(), SectionSnapshot { data, index: rank, projected }); + } + for (id, snapshot) in &mut envelope.section_snapshots { + if let Some(rank) = envelope.section_order.iter().position(|known| known == id) { + snapshot.index = rank; + } + } + Ok(()) +} + +fn record_section_projections(envelope: &mut LayoutEnvelope) { + let layout = &envelope.layout; + for (id, snapshot) in &mut envelope.section_snapshots { + snapshot.projected = layout.sections.iter().find(|section| section.id == *id).cloned(); + } +} + +/// Stage live edits without losing dormant order, projected activation or opaque +/// fields. The caller publishes only after its guarded layout dispatch succeeds. +pub fn with_live_layout(envelope: &LayoutEnvelope, layout: Layout, registry: &PanelRegistry) -> PanelResult { + encode(envelope, registry)?; + validate(&layout, registry)?; + let mut next = envelope.clone(); + next.layout = layout; + refresh_section_memory(&mut next, None, &std::collections::BTreeSet::new())?; + record_section_projections(&mut next); + encode(&next, registry)?; + Ok(next) +} + +/// Iterative traversal also bounds caller-constructed JSON, which did not pass +/// through serde_json's parser/recursion limit. +pub fn bounded_json(value: &serde_json::Value) -> PanelResult<()> { + let mut stack = vec![(value, 0_usize)]; + let mut nodes = 0_usize; + let mut bytes = 0_usize; + while let Some((value, depth)) = stack.pop() { + nodes = nodes.saturating_add(1); + if nodes > 8192 || depth > 32 { + return Err(error(Rule::CollectionLimit, "JSON node/depth cap")); + } + match value { + serde_json::Value::String(s) => bytes = bytes.saturating_add(s.len()), + serde_json::Value::Array(values) => { + if values.len() > 8192 || stack.len().saturating_add(values.len()) > 8192 { + return Err(error(Rule::CollectionLimit, "JSON array cap")); + } + stack.extend(values.iter().map(|value| (value, depth + 1))); + } + serde_json::Value::Object(values) => { + if values.len() > 8192 || stack.len().saturating_add(values.len()) > 8192 { + return Err(error(Rule::CollectionLimit, "JSON object cap")); + } + for (key, value) in values { + bytes = bytes.saturating_add(key.len()); + stack.push((value, depth + 1)); + } + } + serde_json::Value::Number(n) if n.as_f64().is_some_and(|n| !n.is_finite()) => return Err(error(Rule::Bounds, "nonfinite JSON value")), + _ => {} + } + if bytes > MAX_ENVELOPE_BYTES { + return Err(error(Rule::CollectionLimit, "JSON byte cap")); + } + } + Ok(()) +} + +/// Decode bounded bytes, quarantine unknown kinds, and retry retained panels when +/// registered again. Corrupt/future input returns a validated safe preset plus notice. +pub fn decode(bytes: &[u8], registry: &PanelRegistry, fallback: &Layout) -> PanelResult { + validate(fallback, registry)?; + match decode_inner(bytes, registry, &fallback.workspace, true) { + Ok(envelope) => Ok(LoadOutcome { envelope, notice: None, rejected: None }), + Err(reason) => Ok(LoadOutcome { + envelope: LayoutEnvelope::new(fallback.clone()), + notice: Some(reason), + rejected: if bytes.len() <= MAX_ENVELOPE_BYTES { Some(bytes.to_vec()) } else { None }, + }), + } +} + +/// Validate an already-retained record exactly, without generating section order, +/// projections or quarantine/restoration metadata. Missing registrations do not +/// invalidate saved intent. Structure and every applicable known-kind constraint +/// are still validated, but this retained layout is NOT permission to commit it +/// to a live sink. Use `project_retained_record` to stage registry migration. +pub fn decode_retained_record(bytes: &[u8], registry: &PanelRegistry) -> PanelResult { + if bytes.len() > MAX_ENVELOPE_BYTES { + return Err(error(Rule::CollectionLimit, "panel envelope exceeds byte cap")); + } + let raw: serde_json::Value = serde_json::from_slice(bytes).map_err(|_| error(Rule::Schema, "invalid panel envelope JSON"))?; + bounded_json(&raw)?; + let envelope: LayoutEnvelope = serde_json::from_value(raw).map_err(|_| error(Rule::Schema, "invalid panel envelope shape"))?; + if envelope.format != ENVELOPE_FORMAT { + return Err(error(Rule::Schema, "unknown panel envelope format")); + } + if envelope.version != ENVELOPE_VERSION { + return Err(error(Rule::Version, "unknown panel envelope version")); + } + validate_retained_layout(&envelope.layout, registry)?; + validate_envelope_metadata(&envelope)?; + // The same canonical encodability budget as admission, without filling any + // metadata or requiring absent peers. The caller retains the ORIGINAL bytes. + encode_record(&envelope)?; + Ok(envelope) +} + +/// Read a retained record in its workspace without consuming a reappearance +/// obligation or materializing absent order/projection metadata. +pub fn decode_retained(bytes: &[u8], registry: &PanelRegistry, workspace: &WorkspaceId) -> PanelResult { + valid_id(&workspace.0)?; + let envelope = decode_retained_record(bytes, registry)?; + if envelope.layout.workspace != *workspace { + return Err(error(Rule::Schema, "panel envelope workspace mismatch")); + } + Ok(envelope) +} + +/// Stage a usable current-registry layout without consuming quarantined +/// reappearance obligations. Newly absent kinds move to the foundation's +/// lossless quarantine. Metadata expansion can fail at the existing caps; the +/// original record remains available for retry and no live state is published. +pub fn project_retained_record(bytes: &[u8], registry: &PanelRegistry, workspace: &WorkspaceId) -> PanelResult { + let envelope = decode_retained(bytes, registry, workspace)?; + if envelope.layout.instances.iter().any(|instance| registry.get(&instance.kind).is_err()) { + decode_inner(bytes, registry, workspace, false) + } else { + Ok(envelope) + } +} + +fn decode_inner(bytes: &[u8], registry: &PanelRegistry, workspace: &WorkspaceId, restore: bool) -> PanelResult { + if bytes.len() > MAX_ENVELOPE_BYTES { + return Err(error(Rule::CollectionLimit, "panel envelope exceeds byte cap")); + } + // serde_json's recursion limit remains enabled. Parsing starts only after the + // byte bound, so oversized arrays/strings cannot allocate without a bound. + let raw: serde_json::Value = serde_json::from_slice(bytes).map_err(|_| error(Rule::Schema, "invalid panel envelope JSON"))?; + bounded_json(&raw)?; + let mut envelope: LayoutEnvelope = serde_json::from_value(raw.clone()).map_err(|_| error(Rule::Schema, "invalid panel envelope shape"))?; + if envelope.version != ENVELOPE_VERSION || envelope.layout.version != LAYOUT_VERSION { + return Err(error(Rule::Version, "future or unsupported panel layout")); + } + if envelope.format != ENVELOPE_FORMAT || envelope.layout.workspace != *workspace { + return Err(error(Rule::Schema, "panel envelope format/workspace mismatch")); + } + if envelope.layout.instances.len() > MAX_INSTANCES + || envelope.layout.sections.len() > MAX_SECTIONS + || envelope.quarantine.len() > MAX_INSTANCES + || envelope.layout.sections.iter().any(|s| s.tabs.len() > MAX_TABS) + { + return Err(error(Rule::CollectionLimit, "panel collection limit")); + } + validate_retained_layout(&envelope.layout, registry)?; + validate_envelope_metadata(&envelope)?; + let unknown: Vec<_> = envelope.layout.instances.iter().filter(|p| registry.get(&p.kind).is_err()).cloned().collect(); + let capture: std::collections::BTreeSet<_> = envelope + .layout + .sections + .iter() + .filter(|section| unknown.iter().any(|p| section.tabs.contains(&p.id))) + .map(|section| section.id.clone()) + .collect(); + // Refresh from the saved live layout BEFORE newly unknown members are + // removed. A previous fully-restored snapshot is opaque metadata, not an + // authority that can overwrite intervening saved edits. + refresh_section_memory(&mut envelope, Some(&raw), &capture)?; + for instance in unknown { + let section_index = envelope.layout.sections.iter().position(|s| s.tabs.contains(&instance.id)); + let instance_data = raw + .get("layout") + .and_then(|l| l.get("instances")) + .and_then(|a| a.as_array()) + .and_then(|a| a.iter().find(|v| v.get("id").and_then(|s| s.as_str()) == Some(instance.id.0.as_str()))) + .cloned() + .ok_or_else(|| error(Rule::Schema, "unknown instance raw data missing"))?; + let section = if let Some(index) = section_index { + let id = envelope.layout.sections.get(index).ok_or_else(|| error(Rule::MissingTarget, "unknown section absent"))?.id.clone(); + Some(id) + } else { + None + }; + envelope.quarantine.push(QuarantinedPanel { instance: instance.id.clone(), kind: instance.kind, instance_data, section }); + envelope.layout.instances.retain(|p| p.id != instance.id); + } + let retained: std::collections::BTreeSet<_> = envelope.layout.instances.iter().map(|p| p.id.clone()).collect(); + for section in &mut envelope.layout.sections { + section.tabs.retain(|id| retained.contains(id)); + if !section.tabs.contains(§ion.active) + && let Some(first) = section.tabs.first() + { + section.active = first.clone(); + } + } + envelope.layout.sections.retain(|s| !s.tabs.is_empty()); + // Newly quarantining an active tab creates a fallback selection. That + // projection is produced by us, not an intervening user activation. + record_section_projections(&mut envelope); + validate_envelope(&envelope, registry)?; + if restore { + restore_quarantine(&mut envelope, registry)?; + } + // Success means the lossless transformed envelope is itself persistable, + // including its aggregate byte/node/depth budget. Otherwise retain recovery. + encode(&envelope, registry)?; + Ok(envelope) +} + +pub fn restore_quarantine(envelope: &mut LayoutEnvelope, registry: &PanelRegistry) -> PanelResult<()> { + restore_quarantine_with_availability(envelope, registry, &AvailabilityMap::new()) +} + +pub fn restore_quarantine_with_availability( + envelope: &mut LayoutEnvelope, + registry: &PanelRegistry, + availability: &AvailabilityMap, +) -> PanelResult<()> { + validate_envelope(envelope, registry)?; + if availability.len() > MAX_INSTANCES { + return Err(error(Rule::CollectionLimit, "reappearance availability cap")); + } + for (id, state) in availability { + valid_id(&id.0)?; + if matches!(state, Availability::Unavailable { reason } if reason.is_empty() || reason.len() > 256) { + return Err(error(Rule::Availability, "invalid reappearance availability reason")); + } + } + let mut working = envelope.clone(); + // Direct consumers may have edited the live layout since the last decode or + // restore. Merge those edits before using saved ranks/activation again. + refresh_section_memory(&mut working, None, &std::collections::BTreeSet::new())?; + // Build a candidate for each entry. An incompatible reappearance stays in + // quarantine instead of invalidating the known layout or erasing its wire data. + let mut remaining = Vec::new(); + for item in &envelope.quarantine { + if registry.get(&item.kind).is_err() || availability.get(&item.instance).is_some_and(|state| *state != Availability::Available) { + remaining.push(item.clone()); + continue; + } + let mut candidate = working.layout.clone(); + let instance: PanelInstance = + serde_json::from_value(item.instance_data.clone()).map_err(|_| error(Rule::Schema, "invalid quarantined instance"))?; + candidate.instances.push(instance.clone()); + if instance.requested_open { + let Some(section_id) = &item.section else { + remaining.push(item.clone()); + continue; + }; + let snapshot = working.section_snapshots.get(section_id).ok_or_else(|| error(Rule::MissingTarget, "shared snapshot missing"))?; + let mut saved: Section = serde_json::from_value(snapshot.data.clone()).map_err(|_| error(Rule::Schema, "invalid quarantined section"))?; + if let Some(section) = candidate.sections.iter_mut().find(|s| s.id == saved.id) { + let members: std::collections::BTreeSet<_> = section.tabs.iter().cloned().chain(std::iter::once(instance.id.clone())).collect(); + section.tabs = saved + .tabs + .iter() + .filter(|id| members.contains(*id)) + .cloned() + .chain(section.tabs.iter().filter(|id| !saved.tabs.contains(id)).cloned()) + .collect(); + if saved.active == instance.id { + section.active = saved.active.clone(); + } + } else { + saved.tabs = vec![instance.id.clone()]; + saved.active = instance.id.clone(); + candidate.sections.push(saved); + } + } + // Rank against the full saved order, not an index clamped into a partial + // list. Sorting also includes surviving sections with no snapshot. + candidate.sections.sort_by_key(|section| working.section_order.iter().position(|id| *id == section.id).unwrap_or(MAX_SECTIONS)); + if validate(&candidate, registry).is_ok() { + if working.retained_data.len() >= MAX_INSTANCES && !working.retained_data.contains_key(&item.instance) { + remaining.push(item.clone()); + continue; + } + working + .retained_data + .entry(item.instance.clone()) + .or_insert_with(|| serde_json::json!({"instance":item.instance_data,"section":item.section})); + working.layout = candidate; + } else { + remaining.push(item.clone()); + } + } + working.quarantine = remaining; + record_section_projections(&mut working); + encode(&working, registry)?; + *envelope = working; + Ok(()) +} + +/// Validate saved identities/ownership independently of optional peers, then use +/// the ordinary validator for known members. The temporary known-only view is +/// validation input only: it is never returned, encoded, or dispatched. +fn validate_retained_layout(layout: &Layout, registry: &PanelRegistry) -> PanelResult<()> { + validate_wire_structure(layout)?; + if layout.instances.iter().all(|instance| registry.get(&instance.kind).is_ok()) { + return validate(layout, registry); + } + let mut edges = std::collections::BTreeSet::new(); + for section in &layout.sections { + let zone = section.location.zone(); + let first = edges.insert(zone); + for id in §ion.tabs { + let instance = layout.instance(id)?; + if let Ok(spec) = registry.get(&instance.kind) { + // Filtering absent tabs/sections must not hide these constraints + // of a known member in the ORIGINAL full saved placement. + if section.tabs.len() > 1 && !spec.features.tabbable { + return Err(error(Rule::FeatureDisabled, "panel cannot join tabs")); + } + if spec.edge_rule == EdgeRule::PinOuter && matches!(zone, Zone::Left | Zone::Right) && !first { + return Err(error(Rule::PinOrder, "pinned section must be outermost")); + } + } + } + } + let mut known = layout.clone(); + known.instances.retain(|instance| registry.get(&instance.kind).is_ok()); + let ids: std::collections::BTreeSet<_> = known.instances.iter().map(|instance| instance.id.clone()).collect(); + for section in &mut known.sections { + section.tabs.retain(|id| ids.contains(id)); + if !section.tabs.contains(§ion.active) + && let Some(first) = section.tabs.first() + { + section.active = first.clone(); + } + } + known.sections.retain(|section| !section.tabs.is_empty()); + validate(&known, registry) +} + +fn validate_wire_structure(layout: &Layout) -> PanelResult<()> { + if layout.version != LAYOUT_VERSION { + return Err(error(Rule::Version, "unsupported layout version")); + } + valid_id(&layout.workspace.0)?; + if layout.instances.len() > MAX_INSTANCES || layout.sections.len() > MAX_SECTIONS { + return Err(error(Rule::CollectionLimit, "layout collection limit")); + } + let mut instances = std::collections::BTreeSet::new(); + let mut sections = std::collections::BTreeSet::new(); + let mut seen = std::collections::BTreeSet::new(); + let mut hosts = std::collections::BTreeSet::new(); + for instance in &layout.instances { + valid_id(&instance.id.0)?; + valid_id(&instance.kind.0)?; + valid_id(&instance.memory.section.0)?; + instance.memory.location.validate()?; + instance.memory.size.validate()?; + if instance.memory.tab_index >= MAX_TABS || instance.memory.section_index > MAX_SECTIONS { + return Err(error(Rule::Bounds, "invalid placement memory")); + } + if !instances.insert(&instance.id) { + return Err(error(Rule::DuplicateId, "duplicate unknown/known instance")); + } + } + for section in &layout.sections { + valid_id(§ion.id.0)?; + section.location.validate()?; + section.size.validate()?; + if !sections.insert(§ion.id) { + return Err(error(Rule::DuplicateId, "duplicate unknown/known section")); + } + if section.tabs.len() > MAX_TABS { + return Err(error(Rule::CollectionLimit, "section tab cap")); + } + if let SectionLocation::Window { host, .. } = §ion.location + && !hosts.insert(host) + { + return Err(error(Rule::DuplicateId, "native host reused")); + } + if section.tabs.is_empty() || !section.tabs.contains(§ion.active) { + return Err(error(Rule::ExactlyOnce, "invalid unknown/known active tab")); + } + for id in §ion.tabs { + if !instances.contains(id) || !seen.insert(id) { + return Err(error(Rule::ExactlyOnce, "unknown/known tab ownership invalid")); + } + } + } + for instance in &layout.instances { + if instance.requested_open != seen.contains(&instance.id) { + return Err(error(Rule::ExactlyOnce, "unknown/known open state invalid")); + } + } + Ok(()) +} + +/// JSON schema for the wire contract. Semantic constraints are enforced by decode +/// and the reducer; schema alone is never treated as a validation proof. +pub fn layout_action_schema() -> schemars::Schema { + schemars::schema_for!(LayoutAction) +} +pub fn layout_reply_schema() -> schemars::Schema { + schemars::schema_for!(LayoutReply) +} +pub fn layout_error_schema() -> schemars::Schema { + schemars::schema_for!(PanelError) +} +pub fn layout_envelope_schema() -> schemars::Schema { + schemars::schema_for!(LayoutEnvelope) +} + +pub fn decode_action(bytes: &[u8]) -> PanelResult { + if bytes.len() > MAX_ENVELOPE_BYTES { + return Err(error(Rule::CollectionLimit, "action byte cap")); + } + let value: serde_json::Value = serde_json::from_slice(bytes).map_err(|_| error(Rule::Schema, "invalid action JSON"))?; + bounded_json(&value)?; + let action: LayoutAction = serde_json::from_value(value).map_err(|_| error(Rule::Schema, "invalid action shape"))?; + if let LayoutAction::Apply { mutations, .. } = &action + && (mutations.is_empty() || mutations.len() > MAX_MUTATIONS) + { + return Err(error(Rule::CollectionLimit, "action mutation cap")); + } + Ok(action) +} diff --git a/crates/engine/src/panels/reducer.rs b/crates/engine/src/panels/reducer.rs new file mode 100644 index 000000000..5a8189162 --- /dev/null +++ b/crates/engine/src/panels/reducer.rs @@ -0,0 +1,732 @@ +use schemars::JsonSchema; +use serde::{Deserialize, Serialize}; + +use super::*; + +/// Joining an existing tab group and creating a split are deliberately distinct. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)] +#[serde(tag = "type", rename_all = "snake_case")] +pub enum Destination { + NewSection { section: SectionId, index: usize, location: SectionLocation, size: Size }, + JoinTab { section: SectionId, index: usize }, +} + +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)] +#[serde(tag = "type", rename_all = "snake_case")] +pub enum Mutation { + Open { + kind: PanelKind, + instance: InstanceId, + destination: Option, + }, + Close { + instance: InstanceId, + }, + /// Explicit owner cleanup, only after close. Hiding is never destruction. + Destroy { + instance: InstanceId, + }, + Move { + instance: InstanceId, + destination: Destination, + }, + Activate { + instance: InstanceId, + }, + Focus { + instance: InstanceId, + }, + Peek { + instance: InstanceId, + }, + DismissPeek, + Collapse { + section: SectionId, + collapsed: bool, + }, + SetSize { + section: SectionId, + size: Size, + }, + /// Both neighbours change together; their shared axis extent is conserved. + ResizePair { + first: SectionId, + second: SectionId, + first_size: Size, + second_size: Size, + }, + ResetPair { + first: SectionId, + second: SectionId, + }, + /// A native window's close button redocks its whole section. + NativeClose { + host: HostId, + }, +} + +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)] +#[serde(tag = "type", rename_all = "snake_case")] +pub enum LayoutAction { + Inspect, + Apply { + expected_revision: Option, + mutations: Vec, + }, + /// Apply a complete saved layout/preset, including a workspace change. + /// Omission and requested_open=false hide content without lifecycle intent. + Replace { + expected_revision: Option, + layout: Layout, + }, +} + +/// Stable targets for a later command adapter; none are registered with Session yet. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)] +#[serde(tag = "type", content = "id", rename_all = "snake_case")] +pub enum LayoutTarget { + Workspace(WorkspaceId), + Instance(InstanceId), + Section(SectionId), + NativeHost(HostId), +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)] +#[serde(tag = "type", rename_all = "snake_case")] +pub enum HostEffect { + Focus { instance: InstanceId }, + Peek { instance: InstanceId }, + DismissPeek, + CreateNative { host: HostId, section: SectionId }, + RebindNative { host: HostId, section: SectionId }, + ReleaseNative { host: HostId }, +} + +#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema)] +pub struct InteractionState { + pub focused: Option, + pub peek: Option, +} + +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)] +pub struct LayoutReply { + pub api_version: u32, + pub revision: u64, + pub layout: Layout, + pub interaction: InteractionState, + pub effects: Vec, + pub capabilities: HostCapabilities, + pub availability: AvailabilityMap, +} + +/// Same boundary for GUI and programmatic callers. No mutable Session reference. +pub trait ActionSink { + fn dispatch(&mut self, action: LayoutAction) -> PanelResult; + fn inspect(&self) -> LayoutReply; + /// Pure projection on the authoritative service. Adapters stage bounded + /// envelope/storage changes from this before guarded dispatch publishes. + fn project(&self, _action: LayoutAction) -> PanelResult { + Err(error(Rule::Capability, "layout sink cannot stage commands")) + } +} + +#[derive(Debug)] +pub struct LayoutService { + identity: std::sync::Arc<()>, + registry: PanelRegistry, + layout: Layout, + revision: u64, + availability: AvailabilityMap, + interaction: InteractionState, + capabilities: HostCapabilities, + identities: std::collections::BTreeMap, +} + +/// An optimistic, fully validated candidate. Fields stay private so it cannot be forged. +pub struct PreparedLayout { + service_identity: std::sync::Arc<()>, + base_revision: u64, + next: Layout, + interaction: InteractionState, + effects: Vec, + changed: bool, + availability: AvailabilityMap, + identities: std::collections::BTreeMap, +} + +impl PreparedLayout { + pub fn layout(&self) -> &Layout { + &self.next + } + pub fn effects(&self) -> &[HostEffect] { + &self.effects + } + /// Runtime availability is staged with the same atomic layout commit. + pub fn set_availability(&mut self, availability: AvailabilityMap) -> PanelResult<()> { + validate_availability(&availability)?; + self.changed |= self.availability != availability; + self.availability = availability; + Ok(()) + } +} + +impl LayoutService { + pub fn new(registry: PanelRegistry, layout: Layout, capabilities: HostCapabilities) -> PanelResult { + validate(&layout, ®istry)?; + if capabilities.max_native_hosts > MAX_SECTIONS { + return Err(error(Rule::CollectionLimit, "native capability exceeds section cap")); + } + // Restored native entries remain data even on web; resolve_geometry marks them + // unpresented. New native mutations still require a capable adapter. + Ok(Self { + identity: std::sync::Arc::new(()), + registry, + identities: layout.instances.iter().map(|p| (p.id.clone(), p.kind.clone())).collect(), + layout, + revision: 0, + availability: AvailabilityMap::new(), + interaction: InteractionState::default(), + capabilities, + }) + } + pub fn registry(&self) -> &PanelRegistry { + &self.registry + } + pub fn layout(&self) -> &Layout { + &self.layout + } + pub fn interaction(&self) -> &InteractionState { + &self.interaction + } + pub fn capabilities(&self) -> &HostCapabilities { + &self.capabilities + } + pub fn availability(&self, id: &InstanceId) -> Availability { + self.availability.get(id).cloned().unwrap_or(Availability::Available) + } + pub fn set_availability(&mut self, values: AvailabilityMap) -> PanelResult<()> { + validate_availability(&values)?; + if self.availability != values { + let revision = self.revision.checked_add(1).ok_or_else(|| error(Rule::Revision, "layout revision exhausted"))?; + self.availability = values; + self.revision = revision; + self.reconcile_interaction(); + } + Ok(()) + } + fn reconcile_interaction(&mut self) { + let layout = &self.layout; + let availability = &self.availability; + let visible = |id: &InstanceId| { + layout.instance(id).is_ok_and(|p| p.requested_open) && availability.get(id).is_none_or(|state| *state == Availability::Available) + }; + if self.interaction.focused.as_ref().is_some_and(|id| !visible(id)) { + self.interaction.focused = None; + } + if self.interaction.peek.as_ref().is_some_and(|id| !visible(id)) { + self.interaction.peek = None; + } + } + pub fn prepare(&self, action: LayoutAction) -> PanelResult { + let mut next = self.layout.clone(); + let mut interaction = self.interaction.clone(); + let mut effects = Vec::new(); + let mut availability = self.availability.clone(); + let mut destroyed = std::collections::BTreeSet::new(); + if let LayoutAction::Replace { expected_revision, layout } = &action { + if expected_revision.is_some_and(|r| r != self.revision) { + return Err(error(Rule::Revision, "stale layout revision")); + } + validate(layout, &self.registry)?; + next = layout.clone(); + availability.clear(); + interaction = InteractionState::default(); + } + if let LayoutAction::Apply { expected_revision, mutations } = action { + if expected_revision.is_some_and(|r| r != self.revision) { + return Err(error(Rule::Revision, "stale layout revision")); + } + if mutations.is_empty() || mutations.len() > MAX_MUTATIONS { + return Err(error(Rule::CollectionLimit, "transaction requires 1..64 mutations")); + } + validate_lifecycle_intents(&mutations)?; + for mutation in &mutations { + if let Mutation::Destroy { instance } = mutation { + destroyed.insert(instance.clone()); + } + } + for mutation in mutations { + apply(&mut next, &self.registry, &self.availability, &self.capabilities, &mut interaction, &mut effects, mutation)?; + // A bounded intermediate state cannot smuggle oversized collections into + // a later mutation. Semantic invariants are checked at atomic commit. + if next.instances.len() > MAX_INSTANCES || next.sections.len() > MAX_SECTIONS || next.sections.iter().any(|s| s.tabs.len() > MAX_TABS) + { + return Err(error(Rule::CollectionLimit, "transaction collection limit")); + } + } + validate(&next, &self.registry)?; + for before in &self.layout.instances { + if next.instances.iter().any(|after| after.id == before.id && after.kind != before.kind) { + return Err(error(Rule::DuplicateId, "transaction cannot reuse an instance for another kind")); + } + } + } + let mut identities = self.identities.clone(); + for id in destroyed { + identities.remove(&id); + } + for p in &next.instances { + if identities.get(&p.id).is_some_and(|kind| *kind != p.kind) { + return Err(error(Rule::DuplicateId, "instance identity cannot change kind across layouts/workspaces")); + } + identities.insert(p.id.clone(), p.kind.clone()); + } + if identities.len() > MAX_INSTANCES { + return Err(error(Rule::CollectionLimit, "retained instance identity cap")); + } + // Native effects describe the committed difference, never intermediate windows. + let old = native_hosts(&self.layout); + let new = native_hosts(&next); + for (host, section) in &new { + if !old.iter().any(|(h, _)| h == host) { + if !self.capabilities.native_windows || new.len() > self.capabilities.max_native_hosts { + return Err(error(Rule::Capability, "native hosts unavailable or at capacity")); + } + effects.push(HostEffect::CreateNative { host: host.clone(), section: section.clone() }); + } else if self.layout.workspace != next.workspace || old.iter().any(|(h, s)| h == host && s != section) { + if !self.capabilities.native_windows { + return Err(error(Rule::Capability, "cannot rebind unsupported native host")); + } + effects.push(HostEffect::RebindNative { host: host.clone(), section: section.clone() }); + } + } + for (host, _) in old { + if !new.iter().any(|(h, _)| *h == host) { + effects.push(HostEffect::ReleaseNative { host }); + } + } + if interaction.focused.as_ref().is_some_and(|id| !next.containing(id).is_ok_and(|s| !s.collapsed && s.active == *id)) { + interaction.focused = None; + } + if interaction + .peek + .as_ref() + .is_some_and(|id| !next.instance(id).is_ok_and(|p| p.requested_open) || !next.containing(id).is_ok_and(|s| s.collapsed)) + { + interaction.peek = None; + } + effects.retain(|effect| match effect { + HostEffect::Focus { instance } => interaction.focused.as_ref() == Some(instance), + HostEffect::Peek { instance } => interaction.peek.as_ref() == Some(instance), + _ => true, + }); + let changed = next != self.layout || interaction != self.interaction || availability != self.availability || !effects.is_empty(); + if changed && self.revision == u64::MAX { + return Err(error(Rule::Revision, "layout revision exhausted")); + } + Ok(PreparedLayout { + service_identity: self.identity.clone(), + base_revision: self.revision, + next, + interaction, + effects, + changed, + availability, + identities, + }) + } + pub fn commit(&mut self, prepared: PreparedLayout) -> PanelResult { + if !std::sync::Arc::ptr_eq(&prepared.service_identity, &self.identity) || prepared.base_revision != self.revision { + return Err(error(Rule::Revision, "candidate became stale")); + } + if prepared.changed { + self.revision = self.revision.checked_add(1).ok_or_else(|| error(Rule::Revision, "layout revision exhausted"))?; + } + self.layout = prepared.next; + self.interaction = prepared.interaction; + self.availability = prepared.availability; + self.identities = prepared.identities; + self.reconcile_interaction(); + let mut reply = self.inspect(); + reply.effects = prepared.effects; + Ok(reply) + } +} + +fn validate_availability(values: &AvailabilityMap) -> PanelResult<()> { + if values.len() > MAX_INSTANCES { + return Err(error(Rule::CollectionLimit, "availability map full")); + } + for (id, state) in values { + valid_id(&id.0)?; + if let Availability::Unavailable { reason } = state + && (reason.is_empty() || reason.len() > 256) + { + return Err(error(Rule::Availability, "availability reason must contain 1..256 bytes")); + } + } + Ok(()) +} + +/// Close/Destroy are explicit, irreversible content intents. Do not infer them +/// solely from net layout differences, or permit later mutations to erase them. +pub fn validate_lifecycle_intents(mutations: &[Mutation]) -> PanelResult<()> { + if mutations.len() > MAX_MUTATIONS { + return Err(error(Rule::CollectionLimit, "lifecycle intent batch cap")); + } + let mut counts = std::collections::BTreeMap::<&InstanceId, (usize, bool)>::new(); + for mutation in mutations { + let (id, terminal) = match mutation { + Mutation::Close { instance } | Mutation::Destroy { instance } => (instance, true), + Mutation::Open { instance, .. } + | Mutation::Move { instance, .. } + | Mutation::Activate { instance } + | Mutation::Focus { instance } + | Mutation::Peek { instance } => (instance, false), + _ => continue, + }; + let entry = counts.entry(id).or_default(); + entry.0 += 1; + entry.1 |= terminal; + if entry.1 && entry.0 > 1 { + return Err(error(Rule::Lifecycle, "Close/Destroy cannot share a batch with another operation on that instance")); + } + } + Ok(()) +} + +impl ActionSink for LayoutService { + fn project(&self, action: LayoutAction) -> PanelResult { + Ok(self.prepare(action)?.layout().clone()) + } + fn dispatch(&mut self, action: LayoutAction) -> PanelResult { + let prepared = self.prepare(action)?; + self.commit(prepared) + } + fn inspect(&self) -> LayoutReply { + LayoutReply { + api_version: PANEL_API_VERSION, + revision: self.revision, + layout: self.layout.clone(), + interaction: self.interaction.clone(), + effects: Vec::new(), + capabilities: self.capabilities.clone(), + availability: self.availability.clone(), + } + } +} + +fn native_hosts(layout: &Layout) -> Vec<(HostId, SectionId)> { + layout + .sections + .iter() + .filter_map(|s| match &s.location { + SectionLocation::Window { host, .. } => Some((host.clone(), s.id.clone())), + _ => None, + }) + .collect() +} + +fn available(map: &AvailabilityMap, id: &InstanceId) -> PanelResult<()> { + if let Some(state) = map.get(id) { + state.require()?; + } + Ok(()) +} + +fn section_mut<'a>(layout: &'a mut Layout, id: &SectionId) -> PanelResult<&'a mut Section> { + layout.sections.iter_mut().find(|s| s.id == *id).ok_or_else(|| error(Rule::MissingTarget, "section not found")) +} + +fn remember(layout: &mut Layout, id: &InstanceId) -> PanelResult<()> { + let section = layout.containing(id)?.clone(); + let section_index = layout.sections.iter().position(|s| s.id == section.id).ok_or_else(|| error(Rule::MissingTarget, "section not found"))?; + let tab_index = section.tabs.iter().position(|p| p == id).ok_or_else(|| error(Rule::MissingTarget, "tab not found"))?; + let p = layout.instances.iter_mut().find(|p| p.id == *id).ok_or_else(|| error(Rule::MissingTarget, "instance not found"))?; + p.memory = PlacementMemory { + section: section.id, + location: section.location, + section_index, + tab_index, + size: section.size, + collapsed: section.collapsed, + }; + Ok(()) +} + +fn detach(layout: &mut Layout, id: &InstanceId) { + for s in &mut layout.sections { + s.tabs.retain(|p| p != id); + if s.active == *id + && let Some(first) = s.tabs.first() + { + s.active = first.clone(); + } + } + layout.sections.retain(|s| !s.tabs.is_empty()); +} + +fn place(layout: &mut Layout, id: &InstanceId, destination: Destination) -> PanelResult<()> { + match destination { + Destination::NewSection { section, index, location, size } => { + valid_id(§ion.0)?; + location.validate()?; + size.validate()?; + if layout.sections.iter().any(|s| s.id == section) { + return Err(error(Rule::DuplicateId, "new-section identity already exists")); + } + if index > layout.sections.len() { + return Err(error(Rule::Bounds, "section insertion index out of bounds")); + } + layout.sections.insert(index, Section { id: section, location, tabs: vec![id.clone()], active: id.clone(), size, collapsed: false }); + } + Destination::JoinTab { section, index } => { + let s = section_mut(layout, §ion)?; + if index > s.tabs.len() { + return Err(error(Rule::Bounds, "tab insertion index out of bounds")); + } + s.tabs.insert(index, id.clone()); + // Joining never steals active tab or resizes the group. + } + } + Ok(()) +} + +fn reopen_destination(layout: &Layout, p: &PanelInstance) -> Destination { + if let Ok(s) = layout.section(&p.memory.section) { + Destination::JoinTab { section: s.id.clone(), index: p.memory.tab_index.min(s.tabs.len()) } + } else { + Destination::NewSection { + section: p.memory.section.clone(), + index: p.memory.section_index.min(layout.sections.len()), + location: p.memory.location.clone(), + size: p.memory.size, + } + } +} + +fn apply( + layout: &mut Layout, + registry: &PanelRegistry, + availability: &AvailabilityMap, + caps: &HostCapabilities, + interaction: &mut InteractionState, + effects: &mut Vec, + mutation: Mutation, +) -> PanelResult<()> { + match mutation { + Mutation::Open { kind, instance, destination } => { + valid_id(&instance.0)?; + registry.get(&kind)?; + available(availability, &instance)?; + if let Ok(existing) = layout.instance(&instance) { + if existing.kind != kind { + return Err(error(Rule::DuplicateId, "instance belongs to another kind")); + } + if existing.requested_open { + if destination.is_some() { + return Err(error(Rule::Placement, "use Move for an open instance")); + } + return Ok(()); + } + let p = existing.clone(); + let restore_collapsed = destination.is_none() && layout.section(&p.memory.section).is_err(); + let destination = destination.unwrap_or_else(|| reopen_destination(layout, &p)); + place(layout, &instance, destination)?; + if let Some(entry) = layout.instances.iter_mut().find(|p| p.id == instance) { + entry.requested_open = true; + } + if restore_collapsed && let Some(s) = layout.sections.iter_mut().find(|s| s.id == p.memory.section) { + s.collapsed = p.memory.collapsed; + } + } else { + let destination = destination.ok_or_else(|| error(Rule::Placement, "new instance requires explicit destination"))?; + place(layout, &instance, destination)?; + let s = layout.containing(&instance)?.clone(); + layout.instances.push(PanelInstance { + id: instance.clone(), + kind, + requested_open: true, + memory: PlacementMemory { + section: s.id, + location: s.location, + section_index: 0, + tab_index: 0, + size: s.size, + collapsed: s.collapsed, + }, + }); + } + } + Mutation::Close { instance } => { + let p = layout.instance(&instance)?; + if !registry.get(&p.kind)?.features.closable { + return Err(error(Rule::FeatureDisabled, "panel is not closable")); + } + if p.requested_open { + remember(layout, &instance)?; + detach(layout, &instance); + if let Some(p) = layout.instances.iter_mut().find(|p| p.id == instance) { + p.requested_open = false; + } + } + } + Mutation::Destroy { instance } => { + if layout.instance(&instance)?.requested_open { + return Err(error(Rule::Lifecycle, "close before owner destruction")); + } + layout.instances.retain(|p| p.id != instance); + } + Mutation::Move { instance, destination } => { + if !layout.instance(&instance)?.requested_open { + return Err(error(Rule::Placement, "cannot move a closed instance")); + } + let collapsed = layout.containing(&instance)?.collapsed; + remember(layout, &instance)?; + detach(layout, &instance); + let new_section = match &destination { + Destination::NewSection { section, .. } => Some(section.clone()), + _ => None, + }; + place(layout, &instance, destination)?; + if let Some(id) = new_section { + section_mut(layout, &id)?.collapsed = collapsed; + } + } + Mutation::Activate { instance } => { + available(availability, &instance)?; + let section = layout.containing(&instance)?.id.clone(); + section_mut(layout, §ion)?.active = instance; + } + Mutation::Focus { instance } => { + available(availability, &instance)?; + let p = layout.instance(&instance)?.clone(); + if !p.requested_open { + let destination = reopen_destination(layout, &p); + place(layout, &instance, destination)?; + if let Some(entry) = layout.instances.iter_mut().find(|p| p.id == instance) { + entry.requested_open = true; + } + } + let section = layout.containing(&instance)?.id.clone(); + let s = section_mut(layout, §ion)?; + s.active = instance.clone(); + s.collapsed = false; + interaction.peek = None; + interaction.focused = Some(instance.clone()); + effects.push(HostEffect::Focus { instance }); + } + Mutation::Peek { instance } => { + available(availability, &instance)?; + let s = layout.containing(&instance)?; + if !s.collapsed { + return Err(error(Rule::Placement, "peek requires a collapsed section")); + } + interaction.peek = Some(instance.clone()); + effects.push(HostEffect::Peek { instance }); + } + Mutation::DismissPeek => { + interaction.peek = None; + effects.push(HostEffect::DismissPeek); + } + Mutation::Collapse { section, collapsed } => { + section_mut(layout, §ion)?.collapsed = collapsed; + } + Mutation::SetSize { section, size } => { + size.validate()?; + section_mut(layout, §ion)?.size = size; + } + Mutation::ResizePair { first, second, first_size, second_size } => { + first_size.validate()?; + second_size.validate()?; + let (a, b, zone) = pair(layout, &first, &second)?; + let sum = |a: Size, b: Size| if zone == Zone::Bottom { a.width + b.width } else { a.height + b.height }; + if (sum(a.size, b.size) - sum(first_size, second_size)).abs() > 0.01 { + return Err(error(Rule::Bounds, "paired sash must conserve shared extent")); + } + if zone == Zone::Bottom && (first_size.height != a.size.height || second_size.height != b.size.height) + || zone != Zone::Bottom && (first_size.width != a.size.width || second_size.width != b.size.width) + { + return Err(error(Rule::Bounds, "paired sash changes only split axis")); + } + section_mut(layout, &first)?.size = first_size; + section_mut(layout, &second)?.size = second_size; + } + Mutation::ResetPair { first, second } => { + let (a, b, zone) = pair(layout, &first, &second)?; + let mut a_size = a.size; + let mut b_size = b.size; + let (a_min, a_max) = tab_bounds(layout, registry, a)?; + let (b_min, b_max) = tab_bounds(layout, registry, b)?; + let axis = |s: Size| if zone == Zone::Bottom { s.width } else { s.height }; + let extent = axis(a_size) + axis(b_size); + let lo = axis(a_min).max(extent - axis(b_max)); + let hi = axis(a_max).min(extent - axis(b_min)); + if lo > hi { + return Err(error(Rule::Bounds, "pair cannot satisfy defaults within bounds")); + } + let a_default = registry.get(&layout.instance(&a.active)?.kind)?.default_size; + let b_default = registry.get(&layout.instance(&b.active)?.kind)?.default_size; + let preferred = extent * axis(a_default) / (axis(a_default) + axis(b_default)); + let split = preferred.clamp(lo, hi); + if zone == Zone::Bottom { + a_size.width = split; + b_size.width = extent - split; + } else { + a_size.height = split; + b_size.height = extent - split; + } + section_mut(layout, &first)?.size = a_size; + section_mut(layout, &second)?.size = b_size; + } + Mutation::NativeClose { host } => { + valid_id(&host.0)?; + let index = layout + .sections + .iter() + .position(|s| matches!(&s.location, SectionLocation::Window { host: h, .. } if *h == host)) + .ok_or_else(|| error(Rule::MissingTarget, "native host not found"))?; + let mut section = layout.sections.remove(index); + let SectionLocation::Window { return_to, .. } = section.location else { + return Err(error(Rule::Placement, "not a native section")); + }; + if let Some(join) = &return_to.join + && let Some(target) = layout.sections.iter_mut().find(|s| s.id == join.section && s.location.zone() == return_to.zone) + { + if target.tabs.len().saturating_add(section.tabs.len()) > MAX_TABS { + return Err(error(Rule::CollectionLimit, "native return tab capacity")); + } + let index = join.index.min(target.tabs.len()); + drop(target.tabs.splice(index..index, section.tabs)); + return Ok(()); + } + section.location = SectionLocation::Dock { zone: return_to.zone }; + section.size = return_to.size; + section.collapsed = return_to.collapsed; + layout.sections.insert(return_to.index.min(layout.sections.len()), section); + } + } + let windows = native_hosts(layout); + // Retained unsupported windows can be closed/redocked without native capability. + if caps.native_windows && windows.len() > caps.max_native_hosts { + return Err(error(Rule::Capability, "native host limit")); + } + Ok(()) +} + +fn pair<'a>(layout: &'a Layout, first: &SectionId, second: &SectionId) -> PanelResult<(&'a Section, &'a Section, Zone)> { + if first == second { + return Err(error(Rule::Placement, "sash requires two distinct neighbours")); + } + let a = layout.section(first)?; + let b = layout.section(second)?; + let zone = a.location.zone(); + let edge: Vec<_> = layout.sections.iter().filter(|s| s.location.zone() == zone).collect(); + if !zone.docked() + || b.location.zone() != zone + || !edge.windows(2).any(|p| p.first().is_some_and(|s| s.id == *first) && p.get(1).is_some_and(|s| s.id == *second)) + { + return Err(error(Rule::Placement, "sash requires ordered neighbours in one dock")); + } + Ok((a, b, zone)) +} diff --git a/crates/engine/src/panels/tests.rs b/crates/engine/src/panels/tests.rs new file mode 100644 index 000000000..2db660b99 --- /dev/null +++ b/crates/engine/src/panels/tests.rs @@ -0,0 +1,2476 @@ +use super::*; + +fn id(value: &str) -> InstanceId { + InstanceId::new(value).unwrap() +} +fn section(value: &str) -> SectionId { + SectionId::new(value).unwrap() +} +fn size(width: f32, height: f32) -> Size { + Size { width, height } +} +fn rect(width: f32, height: f32) -> LogicalRect { + LogicalRect { origin: Point { x: 0.0, y: 0.0 }, size: size(width, height) } +} +fn open(service: &mut LayoutService, instance: &str, group: &str) { + let index = service.layout().sections.len(); + service.dispatch(transaction(vec![fixture_open("fixture.log", instance, group, Zone::Left, index).unwrap()])).unwrap(); +} +fn reject(service: &mut LayoutService, mutations: Vec, rule: Rule) { + let before = service.inspect(); + assert_eq!(service.dispatch(transaction(mutations)).unwrap_err().rule, rule); + assert_eq!(service.inspect(), before, "failed action must preserve layout/revision/interaction"); +} + +#[test] +fn registry_constraints_and_identifiers_are_bounded() { + let base = synthetic_registry().unwrap().specs().next().unwrap().clone(); + for bad in ["", "UPPER", "two words", &"a".repeat(MAX_ID_BYTES + 1)] { + assert_eq!(PanelKind::new(bad).unwrap_err().rule, Rule::Id); + } + for bad in [f32::NAN, f32::INFINITY, -1.0, 0.0, MAX_LOGICAL + 1.0] { + let mut spec = base.clone(); + spec.min_size.width = bad; + assert_eq!(PanelRegistry::default().register(spec).unwrap_err().rule, Rule::Bounds); + } + let mut spec = base.clone(); + spec.edge_rule = EdgeRule::PinOuter; + assert_eq!(PanelRegistry::default().register(spec).unwrap_err().rule, Rule::Placement); + let mut spec = base.clone(); + spec.allowed_zones.remove(&Zone::Floating); + assert_eq!(PanelRegistry::default().register(spec).unwrap_err().rule, Rule::Placement); + let mut registry = PanelRegistry::default(); + registry.register(base.clone()).unwrap(); + assert_eq!(registry.register(base).unwrap_err().rule, Rule::DuplicateId); +} + +#[test] +fn single_instance_includes_closed_memory_but_multi_instances_coexist() { + let mut service = fixture_service(false).unwrap(); + service.dispatch(transaction(vec![fixture_open("fixture.editor", "editor", "edit", Zone::Left, 0).unwrap()])).unwrap(); + service.dispatch(transaction(vec![Mutation::Close { instance: id("editor") }])).unwrap(); + reject(&mut service, vec![fixture_open("fixture.editor", "editor-two", "edit-two", Zone::Left, 0).unwrap()], Rule::ExactlyOnce); + open(&mut service, "log-one", "logs-one"); + open(&mut service, "log-two", "logs-two"); + validate(service.layout(), service.registry()).unwrap(); +} + +#[test] +fn duplicate_missing_and_closed_instances_cannot_enter_sections() { + let mut service = fixture_service(false).unwrap(); + open(&mut service, "one", "first"); + let mut broken = service.layout().clone(); + broken.sections.first_mut().unwrap().tabs.push(id("one")); + assert_eq!(validate(&broken, service.registry()).unwrap_err().rule, Rule::ExactlyOnce); + broken = service.layout().clone(); + broken.instances.first_mut().unwrap().requested_open = false; + assert_eq!(validate(&broken, service.registry()).unwrap_err().rule, Rule::ExactlyOnce); + broken = service.layout().clone(); + broken.sections.clear(); + assert_eq!(validate(&broken, service.registry()).unwrap_err().rule, Rule::ExactlyOnce); + broken = service.layout().clone(); + broken.sections.first_mut().unwrap().tabs.clear(); + assert_eq!(validate(&broken, service.registry()).unwrap_err().rule, Rule::CollectionLimit); +} + +#[test] +fn multi_field_failure_is_atomic_and_inspection_reads_committed_state() { + let mut service = fixture_service(false).unwrap(); + open(&mut service, "one", "first"); + reject( + &mut service, + vec![ + Mutation::SetSize { section: section("first"), size: size(400.0, 300.0) }, + Mutation::Move { instance: id("absent"), destination: Destination::JoinTab { section: section("first"), index: 0 } }, + ], + Rule::MissingTarget, + ); + let revision = service.inspect().revision; + assert_eq!( + service + .dispatch(LayoutAction::Apply { expected_revision: Some(revision + 1), mutations: vec![Mutation::Close { instance: id("one") }] }) + .unwrap_err() + .rule, + Rule::Revision + ); + let prepared = service.prepare(transaction(vec![Mutation::Close { instance: id("one") }])).unwrap(); + assert!(service.inspect().layout.instance(&id("one")).unwrap().requested_open); + service.dispatch(transaction(vec![Mutation::Focus { instance: id("one") }])).unwrap(); + assert_eq!(service.commit(prepared).unwrap_err().rule, Rule::Revision); +} + +#[test] +fn pin_outer_conflicts_include_shared_groups_and_follow_logical_side() { + let mut service = fixture_service(false).unwrap(); + service.dispatch(transaction(vec![fixture_open("fixture.pin", "pin-one", "pins", Zone::Left, 0).unwrap()])).unwrap(); + reject( + &mut service, + vec![Mutation::Open { + kind: PanelKind::new("fixture.pin").unwrap(), + instance: id("pin-two"), + destination: Some(Destination::JoinTab { section: section("pins"), index: 1 }), + }], + Rule::PinConflict, + ); + reject(&mut service, vec![fixture_open("fixture.pin", "pin-two", "pins-two", Zone::Left, 1).unwrap()], Rule::PinConflict); + service.dispatch(transaction(vec![fixture_open("fixture.pin", "pin-two", "pins-two", Zone::Right, 1).unwrap()])).unwrap(); + service + .dispatch(transaction(vec![Mutation::Move { + instance: id("pin-one"), + destination: Destination::NewSection { + section: section("free-pin"), + index: 1, + location: SectionLocation::Floating { origin: Point { x: 0.0, y: 0.0 } }, + size: size(280.0, 240.0), + }, + }])) + .unwrap(); + validate(service.layout(), service.registry()).unwrap(); +} + +#[test] +fn outermost_order_and_forbidden_bottom_are_declarative() { + let mut service = fixture_service(false).unwrap(); + open(&mut service, "one", "first"); + reject(&mut service, vec![fixture_open("fixture.pin", "pin", "pins", Zone::Left, 1).unwrap()], Rule::PinOrder); + reject(&mut service, vec![fixture_open("fixture.pin", "pin", "pins", Zone::Bottom, 1).unwrap()], Rule::Placement); +} + +#[test] +fn joins_intersect_two_dimensional_constraints_without_changing_active_tab() { + let base = synthetic_registry().unwrap().get(&PanelKind::new("fixture.log").unwrap()).unwrap().clone(); + let mut registry = PanelRegistry::default(); + registry.register(base.clone()).unwrap(); + let mut narrow = base.clone(); + narrow.kind = PanelKind::new("fixture.narrow").unwrap(); + narrow.max_size.width = 250.0; + narrow.default_size.width = 200.0; + let mut wide = base; + wide.kind = PanelKind::new("fixture.wide").unwrap(); + wide.min_size.width = 300.0; + wide.default_size.width = 400.0; + registry.register(narrow).unwrap(); + registry.register(wide).unwrap(); + let mut service = LayoutService::new(registry, Layout::empty(WorkspaceId::new("fixture").unwrap()), HostCapabilities::default()).unwrap(); + open(&mut service, "one", "first"); + service + .dispatch(transaction(vec![Mutation::Open { + kind: PanelKind::new("fixture.log").unwrap(), + instance: id("two"), + destination: Some(Destination::JoinTab { section: section("first"), index: 1 }), + }])) + .unwrap(); + assert_eq!(service.layout().section(§ion("first")).unwrap().active, id("one")); + // Empty intersection is rejected before testing the group's current size. + let narrow_open = Mutation::Open { + kind: PanelKind::new("fixture.narrow").unwrap(), + instance: id("narrow"), + destination: Some(Destination::NewSection { + section: section("narrow-section"), + index: 1, + location: SectionLocation::Dock { zone: Zone::Right }, + size: size(200.0, 240.0), + }), + }; + service.dispatch(transaction(vec![narrow_open])).unwrap(); + reject( + &mut service, + vec![Mutation::Open { + kind: PanelKind::new("fixture.wide").unwrap(), + instance: id("wide"), + destination: Some(Destination::JoinTab { section: section("narrow-section"), index: 1 }), + }], + Rule::IncompatibleTabs, + ); +} + +#[test] +fn tab_indices_and_new_section_targets_are_checked() { + let mut service = fixture_service(false).unwrap(); + open(&mut service, "one", "first"); + open(&mut service, "two", "second"); + reject( + &mut service, + vec![Mutation::Move { instance: id("two"), destination: Destination::JoinTab { section: section("first"), index: usize::MAX } }], + Rule::Bounds, + ); + reject(&mut service, vec![fixture_open("fixture.log", "three", "first", Zone::Left, 0).unwrap()], Rule::DuplicateId); + reject(&mut service, vec![fixture_open("fixture.log", "three", "third", Zone::Left, usize::MAX).unwrap()], Rule::Bounds); + service + .dispatch(transaction(vec![Mutation::Move { + instance: id("two"), + destination: Destination::JoinTab { section: section("first"), index: 1 }, + }])) + .unwrap(); + assert_eq!(service.layout().sections.len(), 1); + service.dispatch(transaction(vec![Mutation::Activate { instance: id("two") }])).unwrap(); + assert_eq!(service.layout().sections.first().unwrap().active, id("two")); +} + +#[test] +fn paired_sashes_conserve_axis_and_reset_both_neighbours() { + let mut service = fixture_service(false).unwrap(); + open(&mut service, "one", "first"); + open(&mut service, "two", "second"); + service + .dispatch(transaction(vec![Mutation::ResizePair { + first: section("first"), + second: section("second"), + first_size: size(280.0, 180.0), + second_size: size(280.0, 300.0), + }])) + .unwrap(); + reject( + &mut service, + vec![Mutation::ResizePair { + first: section("first"), + second: section("second"), + first_size: size(280.0, 200.0), + second_size: size(280.0, 300.0), + }], + Rule::Bounds, + ); + reject( + &mut service, + vec![Mutation::ResizePair { + first: section("first"), + second: section("first"), + first_size: size(280.0, 200.0), + second_size: size(280.0, 300.0), + }], + Rule::Placement, + ); + service.dispatch(transaction(vec![Mutation::ResetPair { first: section("first"), second: section("second") }])).unwrap(); + assert_eq!(service.layout().section(§ion("first")).unwrap().size.height, 240.0); + assert_eq!(service.layout().section(§ion("second")).unwrap().size.height, 240.0); +} + +#[test] +fn unavailable_requests_fail_but_saved_open_layout_stays_dormant() { + let mut service = fixture_service(false).unwrap(); + open(&mut service, "one", "first"); + let layout = service.layout().clone(); + service.set_availability([(id("one"), Availability::Unavailable { reason: "context absent".into() })].into()).unwrap(); + reject(&mut service, vec![Mutation::Focus { instance: id("one") }], Rule::Availability); + reject( + &mut service, + vec![Mutation::Open { kind: PanelKind::new("fixture.log").unwrap(), instance: id("one"), destination: None }], + Rule::Availability, + ); + assert_eq!(*service.layout(), layout); + let dormant = resolve_geometry(&service, rect(1000.0, 800.0), Direction::Ltr, 48.0).unwrap(); + assert!(dormant.panels.is_empty()); + assert_eq!(dormant.unpresented.first().unwrap().reason, UnpresentedReason::Unavailable); + service.set_availability(AvailabilityMap::new()).unwrap(); + assert_eq!(resolve_geometry(&service, rect(1000.0, 800.0), Direction::Ltr, 48.0).unwrap().panels.len(), 1); +} + +#[test] +fn closed_state_reopens_with_placement_size_and_collapse_memory() { + let mut service = fixture_service(false).unwrap(); + open(&mut service, "one", "first"); + service + .dispatch(transaction(vec![ + Mutation::SetSize { section: section("first"), size: size(350.0, 300.0) }, + Mutation::Collapse { section: section("first"), collapsed: true }, + Mutation::Close { instance: id("one") }, + ])) + .unwrap(); + assert!(service.layout().sections.is_empty()); + service + .dispatch(transaction(vec![Mutation::Open { kind: PanelKind::new("fixture.log").unwrap(), instance: id("one"), destination: None }])) + .unwrap(); + let restored = service.layout().section(§ion("first")).unwrap(); + assert_eq!(restored.size, size(350.0, 300.0)); + assert!(restored.collapsed); + service.dispatch(transaction(vec![Mutation::Focus { instance: id("one") }])).unwrap(); + assert!(!service.layout().section(§ion("first")).unwrap().collapsed); +} + +#[test] +fn peek_never_rewrites_saved_collapse_or_sizes_and_focus_restores_content() { + let mut service = fixture_service(false).unwrap(); + open(&mut service, "one", "first"); + service.dispatch(transaction(vec![Mutation::Collapse { section: section("first"), collapsed: true }])).unwrap(); + let layout = service.layout().clone(); + service.dispatch(transaction(vec![Mutation::Peek { instance: id("one") }])).unwrap(); + assert_eq!(*service.layout(), layout); + assert_eq!(resolve_geometry(&service, rect(1000.0, 800.0), Direction::Ltr, 48.0).unwrap().panels.len(), 1); + service.dispatch(transaction(vec![Mutation::DismissPeek])).unwrap(); + assert!(resolve_geometry(&service, rect(1000.0, 800.0), Direction::Ltr, 48.0).unwrap().panels.is_empty()); + service.dispatch(transaction(vec![Mutation::Focus { instance: id("one") }])).unwrap(); + service.dispatch(transaction(vec![Mutation::Close { instance: id("one") }])).unwrap(); + assert!(service.interaction().focused.is_none()); +} + +#[test] +fn overflow_is_transient_and_never_squeezes_or_rewrites_desired_dimensions() { + let mut service = fixture_service(false).unwrap(); + open(&mut service, "one", "first"); + let before = service.inspect(); + let small = resolve_geometry(&service, rect(80.0, 80.0), Direction::Ltr, 48.0).unwrap(); + assert!(small.panels.is_empty()); + assert_eq!(small.unpresented.first().unwrap().reason, UnpresentedReason::MinimumOverflow); + let large = resolve_geometry(&service, rect(1000.0, 800.0), Direction::Ltr, 48.0).unwrap(); + assert_eq!(large.panels.first().unwrap().outer.size, size(280.0, 240.0)); + assert_eq!(service.inspect(), before); +} + +#[test] +fn logical_rtl_flow_hysteresis_and_size_classes_use_usable_units() { + assert_eq!(Direction::Rtl.edge(Zone::Left).unwrap(), PhysicalEdge::Right); + for (width, expected) in [(239.0, SizeClass::Compact), (240.0, SizeClass::Regular), (480.0, SizeClass::Regular), (481.0, SizeClass::Wide)] { + assert_eq!(responsive(Zone::Floating, size(width, 600.0), None).unwrap().1, expected); + } + assert_eq!(responsive(Zone::Floating, size(105.0, 100.0), Some(Flow::Tall)).unwrap().0, Flow::Tall); + assert_eq!(responsive(Zone::Window, size(95.0, 100.0), Some(Flow::Wide)).unwrap().0, Flow::Wide); + assert_eq!(responsive(Zone::Window, size(89.0, 100.0), Some(Flow::Wide)).unwrap().0, Flow::Tall); + assert_eq!(responsive(Zone::Bottom, size(100.0, 400.0), None).unwrap().0, Flow::Wide); +} + +#[test] +fn pointer_regions_cannot_intercept_unpainted_viewport_space() { + let mut service = fixture_service(false).unwrap(); + open(&mut service, "one", "first"); + let mut panel = resolve_geometry(&service, rect(1000.0, 800.0), Direction::Ltr, 48.0).unwrap().panels.remove(0); + assert!(panel.consumes_pointer(Point { x: 20.0, y: 20.0 })); + assert!(!panel.consumes_pointer(Point { x: 500.0, y: 500.0 })); + panel.input.first_mut().unwrap().bounds = rect(1000.0, 800.0); + assert_eq!(panel.validate().unwrap_err().rule, Rule::Bounds); +} + +#[test] +fn native_capabilities_and_close_redock_are_atomic() { + let mut service = fixture_service(true).unwrap(); + open(&mut service, "one", "first"); + let native = Destination::NewSection { + section: section("native"), + index: 0, + location: SectionLocation::Window { + host: HostId::new("native-host").unwrap(), + origin: Point { x: 0.0, y: 0.0 }, + return_to: DockReturn { zone: Zone::Left, index: 0, size: size(280.0, 240.0), collapsed: false, join: None }, + }, + size: size(300.0, 250.0), + }; + let reply = service.dispatch(transaction(vec![Mutation::Move { instance: id("one"), destination: native.clone() }])).unwrap(); + assert!(reply.effects.iter().any(|e| matches!(e, HostEffect::CreateNative { .. }))); + let reply = service.dispatch(transaction(vec![Mutation::NativeClose { host: HostId::new("native-host").unwrap() }])).unwrap(); + assert_eq!(service.layout().containing(&id("one")).unwrap().location.zone(), Zone::Left); + assert!(reply.effects.iter().any(|e| matches!(e, HostEffect::ReleaseNative { .. }))); + let mut web = fixture_service(false).unwrap(); + open(&mut web, "one", "first"); + reject(&mut web, vec![Mutation::Move { instance: id("one"), destination: native }], Rule::Capability); +} + +#[test] +fn envelope_schema_roundtrip_and_version_fallback_preserve_original_input() { + let mut service = fixture_service(false).unwrap(); + open(&mut service, "one", "first"); + let envelope = LayoutEnvelope::new(service.layout().clone()); + let bytes = encode(&envelope, service.registry()).unwrap(); + assert_eq!(decode(&bytes, service.registry(), service.layout()).unwrap().envelope, envelope); + for schema in [layout_action_schema(), layout_reply_schema(), layout_envelope_schema()] { + assert!(serde_json::to_value(schema).unwrap().is_object()); + } + let mut future = envelope; + future.version += 1; + let raw = serde_json::to_vec(&future).unwrap(); + let loaded = decode(&raw, service.registry(), service.layout()).unwrap(); + assert_eq!(loaded.notice.unwrap().rule, Rule::Version); + assert_eq!(loaded.rejected.unwrap(), raw); + assert_eq!(loaded.envelope.layout, *service.layout()); + assert!(decode(b"broken", service.registry(), service.layout()).unwrap().notice.is_some()); +} + +#[test] +fn unknown_panels_are_quarantined_losslessly_and_reappear_when_registered() { + let mut known = fixture_service(false).unwrap(); + open(&mut known, "one", "first"); + let mut envelope = serde_json::to_value(LayoutEnvelope::new(known.layout().clone())).unwrap(); + envelope["layout"]["instances"][0]["kind"] = serde_json::json!("extension.panel"); + envelope["layout"]["instances"][0]["future_content"] = serde_json::json!({"keep":"conversation"}); + let bytes = serde_json::to_vec(&envelope).unwrap(); + let fallback = Layout::empty(known.layout().workspace.clone()); + let mut loaded = decode(&bytes, known.registry(), &fallback).unwrap().envelope; + assert!(loaded.layout.instances.is_empty()); + assert_eq!(loaded.quarantine.len(), 1); + assert_eq!(loaded.quarantine.first().unwrap().instance_data["future_content"]["keep"], "conversation"); + let mut registry = known.registry().clone(); + let mut spec = registry.get(&PanelKind::new("fixture.log").unwrap()).unwrap().clone(); + spec.kind = PanelKind::new("extension.panel").unwrap(); + registry.register(spec).unwrap(); + restore_quarantine(&mut loaded, ®istry).unwrap(); + assert!(loaded.quarantine.is_empty()); + assert_eq!(loaded.layout.instances.len(), 1); + assert_eq!(loaded.retained_data[&id("one")]["instance"]["future_content"]["keep"], "conversation"); + validate(&loaded.layout, ®istry).unwrap(); +} + +#[test] +fn persistence_failure_preserves_unrelated_preferences_and_old_layout() { + let mut persistence = FakePersistence::default(); + let service = fixture_service(false).unwrap(); + persistence.unrelated_preferences.insert("theme".into(), "raw authored intent".into()); + let bytes = encode(&LayoutEnvelope::new(service.layout().clone()), service.registry()).unwrap(); + persistence.save(&service.layout().workspace, &bytes).unwrap(); + persistence.fail_save = true; + assert!(persistence.save(&service.layout().workspace, b"replacement").is_err()); + assert_eq!(persistence.load(&service.layout().workspace).unwrap().unwrap(), bytes); + assert_eq!(persistence.unrelated_preferences.get("theme").unwrap(), "raw authored intent"); +} + +#[test] +fn collection_byte_and_depth_limits_reject_hostile_wire_values() { + let mut service = fixture_service(false).unwrap(); + reject(&mut service, Vec::new(), Rule::CollectionLimit); + reject(&mut service, vec![Mutation::DismissPeek; MAX_MUTATIONS + 1], Rule::CollectionLimit); + let oversized = vec![b' '; MAX_ENVELOPE_BYTES + 1]; + assert_eq!(decode_action(&oversized).unwrap_err().rule, Rule::CollectionLimit); + assert_eq!(decode(&oversized, service.registry(), service.layout()).unwrap().notice.unwrap().rule, Rule::CollectionLimit); + let mut nested = serde_json::Value::Null; + for _ in 0..34 { + nested = serde_json::json!([nested]); + } + assert_eq!(bounded_json(&nested).unwrap_err().rule, Rule::CollectionLimit); + let mut layout = service.layout().clone(); + open(&mut service, "one", "first"); + layout.instances = vec![service.layout().instances.first().unwrap().clone(); MAX_INSTANCES + 1]; + assert_eq!(validate(&layout, service.registry()).unwrap_err().rule, Rule::CollectionLimit); + layout = service.layout().clone(); + layout.sections = vec![layout.sections.first().unwrap().clone(); MAX_SECTIONS + 1]; + assert_eq!(validate(&layout, service.registry()).unwrap_err().rule, Rule::CollectionLimit); + layout = service.layout().clone(); + layout.sections.first_mut().unwrap().tabs = vec![id("one"); MAX_TABS + 1]; + assert_eq!(validate(&layout, service.registry()).unwrap_err().rule, Rule::CollectionLimit); +} + +#[test] +fn deterministic_hostile_action_sequences_preserve_all_invariants() { + let mut service = fixture_service(true).unwrap(); + let mut state = 0x3141_5926_u64; + for step in 0..1024 { + state = state.wrapping_mul(6364136223846793005).wrapping_add(1); + let target = id(&format!("instance-{}", state % 8)); + let group = section(&format!("section-{}", (state >> 8) % 8)); + let mutation = match (state >> 16) % 8 { + 0 => fixture_open("fixture.log", &target.0, &group.0, Zone::Left, 0).unwrap(), + 1 => Mutation::Close { instance: target }, + 2 => Mutation::Focus { instance: target }, + 3 => Mutation::SetSize { section: group, size: size(if step % 2 == 0 { f32::NAN } else { 280.0 }, 240.0) }, + 4 => Mutation::Collapse { section: group, collapsed: state.is_multiple_of(2) }, + 5 => Mutation::Move { instance: target, destination: Destination::JoinTab { section: group, index: (state % 40) as usize } }, + 6 => Mutation::Peek { instance: target }, + _ => Mutation::Destroy { instance: target }, + }; + let before = service.inspect(); + if service.dispatch(transaction(vec![mutation])).is_err() { + assert_eq!(service.inspect(), before); + } + validate(service.layout(), service.registry()).unwrap(); + } +} + +#[test] +fn layout_work_never_touches_document_dirty_revision_undo_geometry_or_tessellation() { + let mut session = crate::Session::default(); + session.execute("solid.box", &serde_json::json!({"length":10,"width":10,"height":10})).unwrap(); + session.mark_saved(); + let document = session.doc.clone(); + let model_state = session.model.state(); + let meshes: Vec<_> = model_state.bodies.iter().map(|b| b.cached_mesh()).collect(); + let revision = session.revision; + let undo = session.undo.len(); + let recomputed = session.model.recomputed; + let mut service = fixture_service(false).unwrap(); + open(&mut service, "one", "first"); + for width in [280.0, 350.0, 500.0] { + service.dispatch(transaction(vec![Mutation::SetSize { section: section("first"), size: size(width, 240.0) }])).unwrap(); + resolve_geometry(&service, rect(1000.0, 800.0), Direction::Ltr, 48.0).unwrap(); + } + assert!(!session.is_dirty()); + assert_eq!(session.revision, revision); + assert_eq!(session.undo.len(), undo); + assert_eq!(session.model.recomputed, recomputed); + assert!(std::sync::Arc::ptr_eq(&document, &session.doc)); + assert!(std::sync::Arc::ptr_eq(&model_state, &session.model.state())); + for (before, after) in meshes.iter().zip(session.model.state().bodies.iter().map(|b| b.cached_mesh())) { + match (before, after) { + (Some(a), Some(b)) => assert!(std::sync::Arc::ptr_eq(a, &b)), + (None, None) => {} + _ => panic!("layout touched tessellation cache"), + } + } +} + +#[test] +fn surface_precedence_and_truthful_contrast_fallback_have_wire_contracts() { + let registry = synthetic_registry().unwrap(); + let mut spec = registry.specs().next().unwrap().clone(); + assert_eq!(group_surface(Zone::Bottom, [&spec]), PanelSurface::Opaque); + spec.surface = PanelSurface::Translucent; + assert_eq!(group_surface(Zone::Bottom, [&spec]), PanelSurface::Translucent); + let mut opaque = spec.clone(); + opaque.surface = PanelSurface::Opaque; + assert_eq!(group_surface(Zone::Left, [&spec, &opaque]), PanelSurface::Opaque); + let outcome = ContrastOutcome::RetainReadableFallback { reason: ContrastFailure::UnreadableAtFullOpacity }; + let roundtrip: ContrastOutcome = serde_json::from_value(serde_json::to_value(&outcome).unwrap()).unwrap(); + assert_eq!(roundtrip, outcome); + assert!(ContrastOutcome::Readable { effective_background_alpha: 0.2 }.validate(0.3).is_err()); + assert!(ContrastOutcome::Readable { effective_background_alpha: f32::NAN }.validate(0.3).is_err()); + assert!(ContrastOutcome::Readable { effective_background_alpha: 0.8 }.validate(0.3).is_ok()); +} + +#[test] +fn versioned_fixture_and_action_schema_are_consumable_without_a_ui() { + let service = fixture_service(false).unwrap(); + let loaded = decode(FIXTURE_LAYOUT_V1, service.registry(), service.layout()).unwrap(); + assert!(loaded.notice.is_none()); + assert_eq!(loaded.envelope.layout.instances.len(), 1); + let mut live = LayoutService::new(service.registry().clone(), loaded.envelope.layout, HostCapabilities::default()).unwrap(); + let action = decode_action(br#"{"type":"apply","expected_revision":0,"mutations":[{"type":"focus","instance":"editor"}]}"#).unwrap(); + let sink: &mut dyn ActionSink = &mut live; + assert_eq!(sink.dispatch(action).unwrap().interaction.focused, Some(id("editor"))); + assert_eq!(serde_json::to_value(CompatibilityPreset::Classic).unwrap(), "classic"); +} + +#[test] +fn instance_section_registry_and_tab_limits_allow_the_boundary_then_reject() { + let mut service = fixture_service(false).unwrap(); + for index in 0..MAX_TABS { + let mutation = if index == 0 { + fixture_open("fixture.log", "log-0", "logs", Zone::Left, 0).unwrap() + } else { + Mutation::Open { + kind: PanelKind::new("fixture.log").unwrap(), + instance: id(&format!("log-{index}")), + destination: Some(Destination::JoinTab { section: section("logs"), index }), + } + }; + service.dispatch(transaction(vec![mutation])).unwrap(); + } + reject( + &mut service, + vec![Mutation::Open { + kind: PanelKind::new("fixture.log").unwrap(), + instance: id("excess"), + destination: Some(Destination::JoinTab { section: section("logs"), index: MAX_TABS }), + }], + Rule::CollectionLimit, + ); + let base = synthetic_registry().unwrap().specs().next().unwrap().clone(); + let mut registry = PanelRegistry::default(); + for i in 0..MAX_INSTANCES { + let mut spec = base.clone(); + spec.kind = PanelKind::new(format!("panel-{i}")).unwrap(); + registry.register(spec).unwrap(); + } + let mut excess = base; + excess.kind = PanelKind::new("excess").unwrap(); + assert_eq!(registry.register(excess).unwrap_err().rule, Rule::CollectionLimit); +} + +#[test] +fn feature_constraints_and_height_bounds_are_enforced_for_every_member() { + let mut spec = synthetic_registry().unwrap().get(&PanelKind::new("fixture.log").unwrap()).unwrap().clone(); + spec.features.closable = false; + spec.features.collapsible = false; + spec.features.tabbable = false; + spec.features.popout = false; + let mut registry = PanelRegistry::default(); + registry.register(spec).unwrap(); + let mut service = LayoutService::new(registry, Layout::empty(WorkspaceId::new("fixture").unwrap()), HostCapabilities::default()).unwrap(); + open(&mut service, "one", "first"); + reject(&mut service, vec![Mutation::Close { instance: id("one") }], Rule::FeatureDisabled); + reject(&mut service, vec![Mutation::Collapse { section: section("first"), collapsed: true }], Rule::FeatureDisabled); + reject(&mut service, vec![Mutation::SetSize { section: section("first"), size: size(280.0, 119.0) }], Rule::Bounds); + reject( + &mut service, + vec![Mutation::Open { + kind: PanelKind::new("fixture.log").unwrap(), + instance: id("two"), + destination: Some(Destination::JoinTab { section: section("first"), index: 1 }), + }], + Rule::FeatureDisabled, + ); +} + +#[test] +fn prepared_candidates_cannot_commit_to_a_different_live_service() { + let mut first = fixture_service(false).unwrap(); + let mut other = fixture_service(false).unwrap(); + let candidate = first.prepare(transaction(vec![fixture_open("fixture.log", "one", "first", Zone::Left, 0).unwrap()])).unwrap(); + let before = other.inspect(); + assert_eq!(other.commit(candidate).unwrap_err().rule, Rule::Revision); + assert_eq!(other.inspect(), before); + open(&mut first, "one", "first"); +} + +#[test] +fn native_close_returns_to_a_stable_tab_group_without_stealing_activation() { + let mut service = fixture_service(true).unwrap(); + open(&mut service, "one", "first"); + service + .dispatch(transaction(vec![Mutation::Open { + kind: PanelKind::new("fixture.log").unwrap(), + instance: id("two"), + destination: Some(Destination::JoinTab { section: section("first"), index: 1 }), + }])) + .unwrap(); + service + .dispatch(transaction(vec![Mutation::Move { + instance: id("two"), + destination: Destination::NewSection { + section: section("native"), + index: 1, + location: SectionLocation::Window { + host: HostId::new("native-host").unwrap(), + origin: Point { x: 0.0, y: 0.0 }, + return_to: DockReturn { + zone: Zone::Left, + index: 0, + size: size(280.0, 240.0), + collapsed: false, + join: Some(ReturnTab { section: section("first"), index: 1 }), + }, + }, + size: size(280.0, 240.0), + }, + }])) + .unwrap(); + service.dispatch(transaction(vec![Mutation::NativeClose { host: HostId::new("native-host").unwrap() }])).unwrap(); + let group = service.layout().section(§ion("first")).unwrap(); + assert_eq!(group.tabs, vec![id("one"), id("two")]); + assert_eq!(group.active, id("one")); + assert_eq!(service.layout().sections.len(), 1); +} + +#[test] +fn activation_preserves_collapse_and_does_not_request_focus_or_reopen() { + let mut service = fixture_service(false).unwrap(); + open(&mut service, "one", "first"); + service.dispatch(transaction(vec![Mutation::Collapse { section: section("first"), collapsed: true }])).unwrap(); + let reply = service.dispatch(transaction(vec![Mutation::Activate { instance: id("one") }])).unwrap(); + assert!(reply.effects.is_empty()); + assert!(reply.interaction.focused.is_none()); + assert!(reply.layout.sections.first().unwrap().collapsed); + service.dispatch(transaction(vec![Mutation::Close { instance: id("one") }])).unwrap(); + reject(&mut service, vec![Mutation::Activate { instance: id("one") }], Rule::MissingTarget); + service.set_availability([(id("future"), Availability::Unavailable { reason: "context missing".into() })].into()).unwrap(); + reject(&mut service, vec![fixture_open("fixture.log", "future", "future-section", Zone::Left, 0).unwrap()], Rule::Availability); +} + +#[test] +fn complete_layout_application_keeps_one_revision_and_validates_workspace_identities() { + let mut service = fixture_service(false).unwrap(); + open(&mut service, "one", "first"); + let saved = service.layout().clone(); + let revision = service.inspect().revision; + let away = Layout::empty(WorkspaceId::new("other-workspace").unwrap()); + let reply = service.dispatch(LayoutAction::Replace { expected_revision: Some(revision), layout: away.clone() }).unwrap(); + assert_eq!(reply.layout, away); + assert_eq!(reply.revision, revision + 1); + let before = service.inspect(); + assert_eq!( + service.dispatch(LayoutAction::Replace { expected_revision: Some(revision), layout: saved.clone() }).unwrap_err().rule, + Rule::Revision + ); + assert_eq!(service.inspect(), before); + let mut changed_kind = saved.clone(); + changed_kind.instances.first_mut().unwrap().kind = PanelKind::new("fixture.editor").unwrap(); + assert_eq!(service.dispatch(LayoutAction::Replace { expected_revision: None, layout: changed_kind }).unwrap_err().rule, Rule::DuplicateId); + let mut unknown = saved.clone(); + unknown.instances.first_mut().unwrap().kind = PanelKind::new("not.registered").unwrap(); + assert_eq!(service.dispatch(LayoutAction::Replace { expected_revision: None, layout: unknown }).unwrap_err().rule, Rule::MissingTarget); + assert_eq!(service.inspect(), before); + service.dispatch(LayoutAction::Replace { expected_revision: Some(before.revision), layout: saved.clone() }).unwrap(); + assert_eq!(service.layout(), &saved); +} + +#[test] +fn lifecycle_intents_are_rejected_before_intermediate_mutations() { + let mut service = fixture_service(false).unwrap(); + open(&mut service, "one", "first"); + open(&mut service, "two", "second"); + let reopen = Mutation::Open { kind: PanelKind::new("fixture.log").unwrap(), instance: id("one"), destination: None }; + for batch in [ + vec![Mutation::Close { instance: id("one") }, reopen.clone()], + vec![ + Mutation::Close { instance: id("one") }, + Mutation::Move { instance: id("one"), destination: Destination::JoinTab { section: section("second"), index: 0 } }, + reopen.clone(), + ], + vec![Mutation::Destroy { instance: id("one") }, reopen], + ] { + reject(&mut service, batch, Rule::Lifecycle); + } + service + .dispatch(transaction(vec![ + Mutation::Close { instance: id("one") }, + Mutation::SetSize { section: section("second"), size: size(300.0, 260.0) }, + ])) + .unwrap(); + assert!(!service.layout().instance(&id("one")).unwrap().requested_open); + assert_eq!(service.layout().section(§ion("second")).unwrap().size, size(300.0, 260.0)); +} + +fn future_group() -> serde_json::Value { + let mut service = fixture_service(false).unwrap(); + open(&mut service, "a", "group"); + for (index, name) in [(1, "b"), (2, "c")] { + service + .dispatch(transaction(vec![Mutation::Open { + kind: PanelKind::new("fixture.log").unwrap(), + instance: id(name), + destination: Some(Destination::JoinTab { section: section("group"), index }), + }])) + .unwrap(); + } + let mut raw = serde_json::to_value(LayoutEnvelope::new(service.layout().clone())).unwrap(); + for instance in raw["layout"]["instances"].as_array_mut().unwrap() { + let name = instance["id"].as_str().unwrap().to_owned(); + instance["kind"] = serde_json::json!(format!("extension.{name}")); + instance["future_draft"] = serde_json::json!(format!("draft-{name}")); + } + raw["layout"]["sections"][0]["tabs"] = serde_json::json!(["c", "b", "a"]); + raw["layout"]["sections"][0]["active"] = serde_json::json!("c"); + raw +} + +fn future_registry(names: &[&str]) -> PanelRegistry { + let mut registry = synthetic_registry().unwrap(); + let base = registry.get(&PanelKind::new("fixture.log").unwrap()).unwrap().clone(); + for name in names { + let mut spec = base.clone(); + spec.kind = PanelKind::new(format!("extension.{name}")).unwrap(); + registry.register(spec).unwrap(); + } + registry +} + +#[test] +fn shared_future_metadata_successfully_decodes_and_reencodes_without_duplication() { + let registry = future_registry(&["a"]); + let fallback = fixture_service(false).unwrap().layout().clone(); + let mut raw = future_group(); + raw["layout"]["sections"][0]["future_metadata"] = serde_json::json!(vec![serde_json::Value::Null; 5000]); + let bytes = serde_json::to_vec(&raw).unwrap(); + bounded_json(&raw).unwrap(); + let loaded = decode(&bytes, ®istry, &fallback).unwrap(); + assert!(loaded.notice.is_none()); + assert_eq!(loaded.envelope.quarantine.len(), 2); + assert_eq!(loaded.envelope.section_snapshots.len(), 1); + let encoded = encode(&loaded.envelope, ®istry).unwrap(); + let reopened = decode(&encoded, ®istry, &fallback).unwrap(); + assert!(reopened.notice.is_none()); + assert_eq!(reopened.envelope, loaded.envelope); + assert_eq!(reopened.envelope.section_snapshots[§ion("group")].data["future_metadata"].as_array().unwrap().len(), 5000); +} + +#[test] +fn all_unknown_tabs_restore_original_order_and_activation_across_registry_stages() { + let fallback = fixture_service(false).unwrap().layout().clone(); + let raw = future_group(); + let bytes = serde_json::to_vec(&raw).unwrap(); + let mut envelope = decode(&bytes, &future_registry(&[]), &fallback).unwrap().envelope; + assert!(envelope.layout.sections.is_empty()); + restore_quarantine(&mut envelope, &future_registry(&["a"])).unwrap(); + assert_eq!(envelope.layout.sections.first().unwrap().tabs, vec![id("a")]); + restore_quarantine(&mut envelope, &future_registry(&["a", "b"])).unwrap(); + assert_eq!(envelope.layout.sections.first().unwrap().tabs, vec![id("b"), id("a")]); + restore_quarantine(&mut envelope, &future_registry(&["a", "b", "c"])).unwrap(); + let group = envelope.layout.sections.first().unwrap(); + assert_eq!(group.tabs, vec![id("c"), id("b"), id("a")]); + assert_eq!(group.active, id("c")); + assert!(envelope.quarantine.is_empty()); + for name in ["a", "b", "c"] { + assert_eq!(envelope.retained_data[&id(name)]["instance"]["future_draft"], format!("draft-{name}")); + } + assert_eq!(envelope.section_snapshots[§ion("group")].data["active"], "c"); + encode(&envelope, &future_registry(&["a", "b", "c"])).unwrap(); +} + +#[test] +fn mixed_tab_reappearance_retains_unavailable_or_invalid_entries_and_future_fields() { + let fallback = fixture_service(false).unwrap().layout().clone(); + let raw = future_group(); + let mut envelope = decode(&serde_json::to_vec(&raw).unwrap(), &future_registry(&["a"]), &fallback).unwrap().envelope; + let mut registry = future_registry(&["a", "b"]); + let mut narrow = registry.get(&PanelKind::new("fixture.log").unwrap()).unwrap().clone(); + narrow.kind = PanelKind::new("extension.c").unwrap(); + narrow.default_size.width = 200.0; + narrow.max_size.width = 200.0; + registry.register(narrow).unwrap(); + let unavailable = [(id("b"), Availability::Unavailable { reason: "extension unavailable".into() })].into(); + restore_quarantine_with_availability(&mut envelope, ®istry, &unavailable).unwrap(); + assert_eq!(envelope.quarantine.len(), 2); + assert_eq!(envelope.layout.sections.first().unwrap().active, id("a")); + restore_quarantine(&mut envelope, &future_registry(&["a", "b", "c"])).unwrap(); + let group = envelope.layout.sections.first().unwrap(); + assert_eq!(group.tabs, vec![id("c"), id("b"), id("a")]); + assert_eq!(group.active, id("c")); + assert_eq!(envelope.retained_data[&id("b")]["instance"]["future_draft"], "draft-b"); +} + +#[test] +fn lossless_representation_over_budget_returns_recovery_instead_of_decode_success() { + let registry = future_registry(&[]); + let fallback = fixture_service(false).unwrap().layout().clone(); + let mut raw = future_group(); + raw["layout"]["sections"][0]["future_metadata"] = serde_json::json!(""); + let base = serde_json::to_vec(&raw).unwrap().len(); + raw["layout"]["sections"][0]["future_metadata"] = serde_json::json!("x".repeat(MAX_ENVELOPE_BYTES - base)); + let bytes = serde_json::to_vec(&raw).unwrap(); + assert_eq!(bytes.len(), MAX_ENVELOPE_BYTES); + let loaded = decode(&bytes, ®istry, &fallback).unwrap(); + assert_eq!(loaded.notice.unwrap().rule, Rule::CollectionLimit); + assert_eq!(loaded.rejected.unwrap(), bytes); + assert_eq!(loaded.envelope.layout, fallback); +} + +#[test] +fn restored_metadata_survives_unregister_register_and_known_survivor_activation() { + let fallback = fixture_service(false).unwrap().layout().clone(); + let raw = future_group(); + let all = future_registry(&["a", "b", "c"]); + let only_a = future_registry(&["a"]); + let mut envelope = decode(&serde_json::to_vec(&raw).unwrap(), &only_a, &fallback).unwrap().envelope; + restore_quarantine(&mut envelope, &all).unwrap(); + let bytes = encode(&envelope, &all).unwrap(); + let mut again = decode(&bytes, &only_a, &fallback).unwrap().envelope; + assert_eq!(again.quarantine.len(), 2); + restore_quarantine(&mut again, &all).unwrap(); + assert_eq!(again.layout.sections.first().unwrap().active, id("c")); + assert_eq!(again.retained_data[&id("c")]["instance"]["future_draft"], "draft-c"); + // A surviving known active tab is not displaced while some unrelated member + // reappears. The saved active member only reactivates when it itself returns. + let a_c = future_registry(&["a", "c"]); + let mut mixed = decode(&serde_json::to_vec(&raw).unwrap(), &a_c, &fallback).unwrap().envelope; + mixed.layout.sections.first_mut().unwrap().active = id("a"); + restore_quarantine(&mut mixed, &all).unwrap(); + assert_eq!(mixed.layout.sections.first().unwrap().active, id("a")); + assert_eq!(mixed.layout.sections.first().unwrap().tabs, vec![id("c"), id("b"), id("a")]); +} + +#[test] +fn complete_layout_wire_contract_checks_native_capacity_and_destroyed_identity_reuse() { + let mut service = fixture_service(false).unwrap(); + open(&mut service, "one", "first"); + let snapshot = service.layout().clone(); + let action = LayoutAction::Replace { expected_revision: Some(service.inspect().revision), layout: snapshot.clone() }; + let wire = serde_json::to_vec(&action).unwrap(); + assert_eq!(decode_action(&wire).unwrap(), action); + let mut native = snapshot.clone(); + native.sections.first_mut().unwrap().location = SectionLocation::Window { + host: HostId::new("native").unwrap(), + origin: Point { x: 0.0, y: 0.0 }, + return_to: DockReturn { zone: Zone::Left, index: 0, size: size(280.0, 240.0), collapsed: false, join: None }, + }; + let before = service.inspect(); + assert_eq!(service.dispatch(LayoutAction::Replace { expected_revision: None, layout: native }).unwrap_err().rule, Rule::Capability); + assert_eq!(service.inspect(), before); + service.dispatch(transaction(vec![Mutation::Close { instance: id("one") }])).unwrap(); + service.dispatch(transaction(vec![Mutation::Destroy { instance: id("one") }])).unwrap(); + let mut reused = snapshot; + reused.instances.first_mut().unwrap().kind = PanelKind::new("fixture.editor").unwrap(); + service.dispatch(LayoutAction::Replace { expected_revision: None, layout: reused }).unwrap(); + assert_eq!(service.layout().instance(&id("one")).unwrap().kind, PanelKind::new("fixture.editor").unwrap()); +} + +fn future_sections() -> serde_json::Value { + let mut service = fixture_service(false).unwrap(); + for (member, group) in [("a", "s0"), ("b", "s1"), ("c", "s2")] { + open(&mut service, member, group); + } + let mut raw = serde_json::to_value(LayoutEnvelope::new(service.layout().clone())).unwrap(); + let instances = raw["layout"]["instances"].as_array_mut().unwrap(); + for instance in instances.iter_mut() { + let name = instance["id"].as_str().unwrap().to_owned(); + instance["kind"] = serde_json::json!(format!("extension.{name}")); + instance["future_draft"] = serde_json::json!(format!("draft-{name}")); + } + instances.reverse(); // Exact regression: member processing order s2, s1, s0. + for group in raw["layout"]["sections"].as_array_mut().unwrap() { + let name = group["id"].as_str().unwrap().to_owned(); + group["future_surface"] = serde_json::json!({"keep":name}); + } + raw +} + +fn section_ids(envelope: &LayoutEnvelope) -> Vec { + envelope.layout.sections.iter().map(|section| section.id.clone()).collect() +} + +fn persistence_fallback() -> Layout { + fixture_service(false).unwrap().layout().clone() +} + +#[test] +fn whole_section_order_restores_from_reverse_instance_order_in_one_or_many_stages() { + let fallback = persistence_fallback(); + let raw = future_sections(); + let bytes = serde_json::to_vec(&raw).unwrap(); + let all = future_registry(&["a", "b", "c"]); + let loaded = decode(&bytes, &future_registry(&[]), &fallback).unwrap(); + assert!(loaded.notice.is_none()); + let original = loaded.envelope; + assert!(original.layout.sections.is_empty()); + assert_eq!(original.section_order, vec![section("s0"), section("s1"), section("s2")]); + let mut together = original.clone(); + restore_quarantine(&mut together, &all).unwrap(); + assert_eq!(section_ids(&together), vec![section("s0"), section("s1"), section("s2")]); + let mut staged = original; + for (registry, expected) in [ + (future_registry(&["c"]), vec![section("s2")]), + (future_registry(&["b", "c"]), vec![section("s1"), section("s2")]), + (all, vec![section("s0"), section("s1"), section("s2")]), + ] { + restore_quarantine(&mut staged, ®istry).unwrap(); + assert_eq!(section_ids(&staged), expected); + let saved = encode(&staged, ®istry).unwrap(); + let reopened = decode(&saved, ®istry, &fallback).unwrap(); + assert!(reopened.notice.is_none()); + staged = reopened.envelope; + } + assert!(staged.quarantine.is_empty()); + for (index, name) in ["s0", "s1", "s2"].into_iter().enumerate() { + let snapshot = &staged.section_snapshots[§ion(name)]; + assert_eq!(snapshot.index, index); + assert_eq!(snapshot.data["future_surface"]["keep"], name); + } +} + +fn command_destination(group: &str, index: usize, zone: &str) -> serde_json::Value { + serde_json::json!({"type":"new_section","section":group,"index":index,"location":{"type":"dock","zone":zone},"size":{"width":280,"height":240}}) +} +fn command_target(instance: &str) -> serde_json::Value { + serde_json::json!({"type":"instance","id":instance}) +} +fn command_ready_backend() -> commands::InMemoryPanelBackend { + let mut backend = fixture_command_backend().unwrap(); + backend + .execute("panel.open", &serde_json::json!({"kind":"fixture.log","instance":"one","destination":command_destination("s-one",0,"left")})) + .unwrap(); + backend + .execute("panel.open", &serde_json::json!({"kind":"fixture.log","instance":"two","destination":command_destination("s-two",1,"left")})) + .unwrap(); + backend +} +fn command_inputs() -> Vec<(&'static str, serde_json::Value)> { + use serde_json::json; + let selected = json!({"target":command_target("one")}); + let mut floating = command_destination("free", 1, "left"); + floating["location"] = json!({"type":"floating","origin":{"x":20,"y":30}}); + let mut native = floating.clone(); + native["location"] = json!({"type":"window","host":"native","origin":{"x":20,"y":30},"return_to":{"zone":"left","index":0,"size":{"width":280,"height":240},"collapsed":false}}); + vec![ + ("layout.apply", json!({"name":"Fixture default"})), + ("layout.get", json!({})), + ("layout.reset", json!({})), + ("layout.save", json!({"name":"Saved"})), + ("layout.workspace.select", json!({"workspace":"fixture.other"})), + ("panel.activate", selected.clone()), + ("panel.close", selected.clone()), + ("panel.collapse", json!({"target":command_target("one"),"collapsed":true})), + ("panel.dismiss", json!({})), + ("panel.float", json!({"target":command_target("one"),"destination":floating})), + ("panel.focus", selected.clone()), + ("panel.list", json!({})), + ("panel.move", json!({"target":command_target("one"),"destination":command_destination("moved",1,"right")})), + ("panel.native_close", json!({"target":{"type":"native_host","id":"native"}})), + ( + "panel.open", + json!({"kind":"fixture.application","instance":"application","destination":command_destination("application-section",2,"right")}), + ), + ("panel.peek", selected), + ("panel.popout", json!({"target":command_target("one"),"destination":native})), + ("panel.reset_pair", json!({"first":"s-one","second":"s-two"})), + ("panel.resize", json!({"target":command_target("one"),"size":{"width":300,"height":300}})), + ( + "panel.resize_pair", + json!({"first":"s-one","second":"s-two","first_size":{"width":280,"height":260},"second_size":{"width":280,"height":220}}), + ), + ] +} + +#[test] +fn every_panel_command_has_strict_input_output_contracts_and_hostile_field_rejection() { + use commands::LayoutCatalogue; + let inputs = command_inputs(); + assert_eq!(inputs.len(), commands::IDS.len()); + for (id, input) in inputs { + let spec = crate::find_command(id).unwrap(); + assert!(!spec.undoable && !spec.reads_model, "{id}"); + let contract = spec.contract.unwrap(); + assert!(contract.check(&input).is_empty(), "{id}: {input}"); + assert_eq!(contract.input_schema().as_value()["additionalProperties"], false, "{id}"); + let output = (spec.output.unwrap())(); + assert!(output.as_value().is_object(), "{id}"); + assert_eq!(output.as_value()["additionalProperties"], false, "{id}"); + let mut backend = command_ready_backend(); + let before = backend.service.inspect(); + let catalogue = backend.catalogue.state().clone(); + for junk in [serde_json::json!(false), serde_json::json!([]), serde_json::json!(["bad"]), serde_json::json!("bad"), { + let mut value = input.clone(); + value["unknown"] = serde_json::json!(true); + value + }] { + assert!(!contract.check(&junk).is_empty(), "{id}: {junk}"); + assert_eq!(commands::parse_command(id, &junk).unwrap_err().rule, Rule::Schema, "{id}"); + assert!(backend.execute(id, &junk).is_err(), "{id}"); + assert_eq!(backend.service.inspect(), before, "{id}"); + assert_eq!(backend.catalogue.state(), &catalogue, "{id}"); + } + for field in ["id", "instance", "kind", "first", "second", "workspace"] { + if input.get(field).is_some() { + let mut hostile = input.clone(); + hostile[field] = serde_json::json!("UPPER/invalid"); + assert!(commands::parse_command(id, &hostile).is_err(), "{id}/{field}"); + } + } + let mut oversized = input.clone(); + oversized["unknown"] = serde_json::json!("x".repeat(commands::MAX_COMMAND_BYTES + 1)); + assert_eq!(commands::parse_command(id, &oversized).unwrap_err().rule, Rule::CollectionLimit, "{id}"); + } +} + +#[test] +fn panel_command_success_replies_describe_committed_state_for_every_executable_operation() { + for (id, input) in command_inputs() { + let mut backend = command_ready_backend(); + if id == "panel.peek" { + backend.execute("panel.collapse", &serde_json::json!({"target":command_target("one"),"collapsed":true})).unwrap(); + } + let result = backend.execute(id, &input); + if matches!(id, "panel.popout" | "panel.native_close") { + assert!(result.is_err(), "{id}"); + continue; + } + let result = result.unwrap_or_else(|e| panic!("{id}: {e}")); + let reply: LayoutReply = serde_json::from_value(result.get("state").unwrap_or(&result).clone()).unwrap(); + let live = backend.service.inspect(); + assert_eq!(reply.layout, live.layout, "{id}"); + assert_eq!(reply.revision, live.revision, "{id}"); + assert_eq!(reply.interaction, live.interaction, "{id}"); + assert_eq!(reply.capabilities, live.capabilities, "{id}"); + assert_eq!(reply.availability, live.availability, "{id}"); + } +} + +#[test] +fn panel_commands_reject_nested_unknowns_sizes_indices_and_nonfinite_values_before_effects() { + let mut backend = command_ready_backend(); + for value in [ + serde_json::json!(0), + serde_json::json!(-1), + serde_json::json!(32769), + serde_json::json!(1e100), + serde_json::Value::Null, + serde_json::json!("NaN"), + ] { + let before = backend.service.inspect(); + assert!(backend.execute("panel.resize", &serde_json::json!({"target":command_target("one"),"size":{"width":value,"height":240}})).is_err()); + assert_eq!(backend.service.inspect(), before); + } + for path in ["target", "destination", "location", "size"] { + let mut input = serde_json::json!({"target":command_target("one"),"destination":command_destination("moved",0,"right")}); + match path { + "target" => input["target"]["unknown"] = true.into(), + "destination" => input["destination"]["unknown"] = true.into(), + "location" => input["destination"]["location"]["unknown"] = true.into(), + _ => input["destination"]["size"]["unknown"] = true.into(), + } + assert_eq!(commands::parse_command("panel.move", &input).unwrap_err().rule, Rule::Schema, "{path}"); + } + for index in [serde_json::json!(-1), serde_json::json!(65), serde_json::json!(1e100)] { + let mut dest = command_destination("moved", 0, "left"); + dest["index"] = index; + assert!(commands::parse_command("panel.move", &serde_json::json!({"target":command_target("one"),"destination":dest})).is_err()); + } + for hostile in [f32::NAN, f32::INFINITY, f32::NEG_INFINITY] { + let mutation = Mutation::SetSize { section: section("s-one"), size: size(hostile, 240.0) }; + assert!(backend.service.project(transaction(vec![mutation])).is_err()); + } +} + +#[test] +fn command_target_resolution_never_guesses_a_multi_instance_or_mismatched_target() { + let mut backend = command_ready_backend(); + assert_eq!(backend.execute("panel.focus", &serde_json::json!({"id":"fixture.log"})).unwrap_err().rule, Rule::ExactlyOnce); + backend.execute("panel.focus", &serde_json::json!({"id":"one"})).unwrap(); + backend + .execute( + "panel.open", + &serde_json::json!({"kind":"fixture.application","instance":"app","destination":command_destination("app-section",2,"right")}), + ) + .unwrap(); + backend.execute("panel.focus", &serde_json::json!({"id":"fixture.application"})).unwrap(); + for target in [serde_json::json!({"type":"workspace","id":"fixture.workspace"}), serde_json::json!({"type":"section","id":"s-one"})] { + assert_eq!(backend.execute("panel.focus", &serde_json::json!({"target":target})).unwrap_err().rule, Rule::Schema); + } + assert!(backend.execute("panel.focus", &serde_json::json!({"target":command_target("one"),"id":"one"})).is_err()); + backend.execute("panel.close", &serde_json::json!({"target":command_target("one")})).unwrap(); + assert_eq!(backend.execute("panel.activate", &serde_json::json!({"target":command_target("one")})).unwrap_err().rule, Rule::MissingTarget); + backend.execute("panel.focus", &serde_json::json!({"target":command_target("one")})).unwrap(); + backend.service.set_availability([(id("one"), Availability::Unavailable { reason: "fixture unavailable".into() })].into()).unwrap(); + for command in ["panel.focus", "panel.activate", "panel.peek"] { + assert_eq!(backend.execute(command, &serde_json::json!({"target":command_target("one")})).unwrap_err().rule, Rule::Availability); + } +} + +#[test] +fn command_storage_native_stale_and_lifecycle_failures_preserve_layout_and_catalogue() { + use commands::LayoutCatalogue; + let mut backend = command_ready_backend(); + let before = backend.service.inspect(); + let catalogue = backend.catalogue.state().clone(); + backend.catalogue.fail_stage = true; + assert_eq!(backend.execute("panel.close", &serde_json::json!({"target":command_target("one")})).unwrap_err().rule, Rule::Capability); + backend.catalogue.fail_stage = false; + assert_eq!( + backend.execute("panel.close", &serde_json::json!({"target":command_target("one"),"expected_revision":0})).unwrap_err().rule, + Rule::Revision + ); + let native = command_inputs().into_iter().find(|(id, _)| *id == "panel.popout").unwrap().1; + assert_eq!(backend.execute("panel.popout", &native).unwrap_err().rule, Rule::Capability); + let steps = vec![ + serde_json::json!({"command":"panel.close","params":{"target":command_target("one")}}), + serde_json::json!({"command":"panel.open","params":{"kind":"fixture.log","instance":"one"}}), + ]; + assert_eq!(backend.batch(&steps).unwrap_err().rule, Rule::Lifecycle); + assert_eq!(backend.service.inspect(), before); + assert_eq!(backend.catalogue.state(), &catalogue); + let invalid = vec![ + serde_json::json!({"command":"panel.collapse","params":{"target":command_target("one"),"collapsed":true}}), + serde_json::json!({"command":"panel.resize","params":{"target":command_target("two"),"size":{"width":1,"height":1}}}), + ]; + assert!(backend.batch(&invalid).is_err()); + assert_eq!(backend.service.inspect(), before); +} + +#[test] +fn command_presets_enforce_unicode_names_overwrite_builtins_and_user_count() { + let mut backend = fixture_command_backend().unwrap(); + for invalid in ["".into(), " ".into(), "x\n".into(), "x\u{0000}".into(), "🦀".repeat(65), " ".repeat(1025)] { + assert!(backend.execute("layout.save", &serde_json::json!({"name":invalid})).is_err()); + } + let name = "🦀".repeat(64); + assert_eq!(backend.execute("layout.save", &serde_json::json!({"name":format!(" {name} ")})).unwrap()["name"], name); + assert_eq!(backend.execute("layout.save", &serde_json::json!({"name":name})).unwrap_err().rule, Rule::DuplicateId); + assert_eq!(backend.execute("layout.save", &serde_json::json!({"name":name,"overwrite":true})).unwrap()["overwritten"], true); + assert_eq!(backend.execute("layout.save", &serde_json::json!({"name":"Fixture default","overwrite":true})).unwrap_err().rule, Rule::Capability); + for i in 1..commands::MAX_USER_PRESETS { + backend.execute("layout.save", &serde_json::json!({"name":format!("user-{i}")})).unwrap(); + } + assert_eq!(backend.execute("layout.save", &serde_json::json!({"name":"overflow"})).unwrap_err().rule, Rule::CollectionLimit); +} + +#[test] +fn command_apply_reset_and_workspace_roundtrip_never_select_implicitly() { + use serde_json::json; + let mut backend = command_ready_backend(); + let a = backend.service.layout().clone(); + backend.execute("layout.save", &json!({"name":"Saved"})).unwrap(); + backend.execute("layout.reset", &json!({})).unwrap(); + assert_eq!(backend.service.layout().workspace, a.workspace); + assert!(backend.service.layout().instances.is_empty()); + backend.execute("layout.apply", &json!({"name":"Saved"})).unwrap(); + assert_eq!(backend.service.layout(), &a); + let selected = backend.execute("layout.workspace.select", &json!({"workspace":"fixture.other"})).unwrap(); + assert_eq!(selected["source"], "default_preset"); + backend.execute("layout.apply", &json!({"name":"Saved"})).unwrap(); + assert_eq!(backend.service.layout().workspace.0, "fixture.other"); + backend.execute("panel.collapse", &json!({"target":command_target("one"),"collapsed":true})).unwrap(); + let b = backend.service.layout().clone(); + assert_eq!(backend.execute("layout.workspace.select", &json!({"workspace":"fixture.workspace"})).unwrap()["source"], "remembered"); + assert_eq!(backend.service.layout(), &a); + backend.execute("layout.workspace.select", &json!({"workspace":"fixture.other"})).unwrap(); + assert_eq!(backend.service.layout(), &b); + backend.execute("panel.peek", &json!({"target":command_target("one")})).unwrap(); + let before = backend.service.inspect(); + backend.catalogue.fail_stage = true; + assert_eq!(backend.execute("layout.workspace.select", &json!({"workspace":"fixture.other"})).unwrap()["source"], "unchanged"); + assert_eq!(backend.service.inspect(), before, "same workspace preserves revision/focus/peek even when storage is unavailable"); + backend.catalogue.fail_stage = false; + assert_eq!(backend.execute("layout.workspace.select", &json!({"workspace":"missing"})).unwrap_err().rule, Rule::MissingTarget); + let summaries = backend.execute("layout.get", &json!({})).unwrap(); + assert_eq!(summaries["workspaces"].as_array().unwrap().len(), 2); + backend.execute("layout.reset", &json!({})).unwrap(); + assert_eq!(backend.service.layout().workspace.0, "fixture.other"); + backend.execute("layout.apply", &json!({"name":"Saved"})).unwrap(); +} + +#[test] +fn command_save_apply_reset_preserve_full_unknown_envelopes_and_recovery() { + use commands::LayoutCatalogue; + let registry = synthetic_registry().unwrap(); + let fallback = persistence_fallback(); + let raw = future_sections(); + let envelope = decode(&serde_json::to_vec(&raw).unwrap(), ®istry, &fallback).unwrap().envelope; + let mut backend = fixture_command_backend().unwrap(); + backend.catalogue.remember(&envelope, Some(b"rejected future envelope"), ®istry).unwrap(); + backend.execute("layout.save", &serde_json::json!({"name":"Unknown"})).unwrap(); + backend.execute("layout.reset", &serde_json::json!({})).unwrap(); + backend.execute("layout.apply", &serde_json::json!({"name":"Unknown"})).unwrap(); + let stored = backend.catalogue.state().remembered(&fallback.workspace).unwrap(); + assert_eq!(stored.rejected(), Some(b"rejected future envelope".as_slice())); + let saved = stored.envelope(®istry, &fallback.workspace).unwrap(); + assert_eq!(saved.quarantine, envelope.quarantine); + assert_eq!(saved.section_order, envelope.section_order); + assert_eq!(saved.section_snapshots, envelope.section_snapshots); + let mut appeared = saved; + restore_quarantine(&mut appeared, &future_registry(&["a", "b", "c"])).unwrap(); + assert_eq!(section_ids(&appeared), vec![section("s0"), section("s1"), section("s2")]); + assert_eq!(appeared.retained_data[&id("a")]["instance"]["future_draft"], "draft-a"); +} + +#[test] +fn command_sidecar_collisions_and_aggregate_catalogue_growth_are_rejected_atomically() { + use commands::LayoutCatalogue; + let mut backend = fixture_command_backend().unwrap(); + let mut first = LayoutEnvelope::new(backend.service.layout().clone()); + first.retained_data.insert(id("future"), serde_json::json!({"draft":"first"})); + backend.catalogue.remember(&first, None, backend.service.registry()).unwrap(); + backend.execute("layout.save", &serde_json::json!({"name":"First"})).unwrap(); + let mut second = first.clone(); + second.retained_data.insert(id("future"), serde_json::json!({"draft":"second"})); + backend.catalogue.remember(&second, None, backend.service.registry()).unwrap(); + let before = backend.service.inspect(); + let catalogue = backend.catalogue.state().clone(); + assert_eq!(backend.execute("layout.apply", &serde_json::json!({"name":"First"})).unwrap_err().rule, Rule::DuplicateId); + assert_eq!(backend.service.inspect(), before); + assert_eq!(backend.catalogue.state(), &catalogue); + let mut large = first; + large.retained_data.insert(id("large"), serde_json::json!({"opaque":"x".repeat(200_000)})); + backend.catalogue.remember(&large, None, backend.service.registry()).unwrap(); + let mut rejected = false; + for i in 0..commands::MAX_USER_PRESETS { + let before = backend.catalogue.state().clone(); + if let Err(reason) = backend.execute("layout.save", &serde_json::json!({"name":format!("large-{i}")})) { + assert_eq!(reason.rule, Rule::CollectionLimit); + assert_eq!(backend.catalogue.state(), &before); + rejected = true; + break; + } + } + assert!(rejected, "aggregate bytes reject before count cap"); +} + +#[test] +fn session_only_panel_commands_report_capability_without_touching_document_or_model() { + let mut session = crate::Session::default(); + let doc = session.doc.clone(); + let model = session.model.state(); + let revision = session.revision; + let dirty = session.is_dirty(); + let undo = session.undo.len(); + let evaluations = session.evaluations; + for level in crate::schema::ParamCheck::ALL { + session.param_check = level; + for (id, input) in command_inputs() { + let reason = session.execute(id, &input).unwrap_err(); + assert!(matches!(reason, crate::EngineError::Panel(PanelError { rule: Rule::Capability, .. })), "{id}: {reason}"); + assert!(commands::structured_error(&reason.to_string()).is_some()); + } + } + assert!(std::sync::Arc::ptr_eq(&doc, &session.doc)); + assert!(std::sync::Arc::ptr_eq(&model, &session.model.state())); + assert_eq!(session.revision, revision); + assert_eq!(session.undo.len(), undo); + assert_eq!(session.is_dirty(), dirty); + assert_eq!(session.evaluations, evaluations); +} + +#[test] +fn all_mutating_panel_commands_reject_stale_revisions_before_catalogue_publication() { + use commands::LayoutCatalogue; + for (id, mut input) in command_inputs() { + if matches!(id, "panel.list" | "layout.get") { + continue; + } + let mut backend = command_ready_backend(); + let before = backend.service.inspect(); + let catalogue = backend.catalogue.state().clone(); + input["expected_revision"] = serde_json::json!(u64::MAX); + assert_eq!(backend.execute(id, &input).unwrap_err().rule, Rule::Revision, "{id}"); + assert_eq!(backend.service.inspect(), before, "{id}"); + assert_eq!(backend.catalogue.state(), &catalogue, "{id}"); + } +} + +#[test] +fn panel_command_pin_tab_intersections_and_paired_sashes_keep_foundation_rules() { + use serde_json::json; + let mut backend = command_ready_backend(); + backend + .execute("panel.open", &json!({"kind":"fixture.pin","instance":"pin","destination":command_destination("pin-section",0,"right")})) + .unwrap(); + let before = backend.service.inspect(); + assert_eq!( + backend + .execute("panel.open", &json!({"kind":"fixture.pin","instance":"pin-two","destination":command_destination("pin-two-section",1,"right")})) + .unwrap_err() + .rule, + Rule::PinConflict + ); + assert_eq!(backend.service.inspect(), before); + let bad_pair = json!({"first":"s-one","second":"s-two","first_size":{"width":281,"height":250},"second_size":{"width":280,"height":230}}); + assert_eq!(backend.execute("panel.resize_pair", &bad_pair).unwrap_err().rule, Rule::Bounds); + assert_eq!(backend.service.inspect(), before); + backend + .execute( + "panel.resize_pair", + &json!({"first":"s-one","second":"s-two","first_size":{"width":280,"height":260},"second_size":{"width":280,"height":220}}), + ) + .unwrap(); + let total: f32 = backend.service.layout().sections.iter().filter(|s| s.location.zone() == Zone::Left).map(|s| s.size.height).sum(); + assert_eq!(total, 480.0); + backend.execute("panel.reset_pair", &json!({"first":"s-one","second":"s-two"})).unwrap(); + assert_eq!(backend.service.layout().section(§ion("s-one")).unwrap().size.height, 240.0); + let mut registry = synthetic_registry().unwrap(); + let mut small = registry.get(&PanelKind::new("fixture.log").unwrap()).unwrap().clone(); + small.kind = PanelKind::new("fixture.small").unwrap(); + small.min_size = size(160.0, 120.0); + small.default_size = size(180.0, 140.0); + small.max_size = size(200.0, 180.0); + registry.register(small).unwrap(); + let mut large = registry.get(&PanelKind::new("fixture.log").unwrap()).unwrap().clone(); + large.kind = PanelKind::new("fixture.large").unwrap(); + large.min_size = size(400.0, 400.0); + large.default_size = size(450.0, 450.0); + large.max_size = size(500.0, 500.0); + registry.register(large).unwrap(); + let service = + LayoutService::new(registry.clone(), Layout::empty(WorkspaceId::new("fixture.workspace").unwrap()), HostCapabilities::default()).unwrap(); + let mut bounded = commands::InMemoryPanelBackend::new(service, fixture_command_catalogue(®istry).unwrap()); + bounded.execute("panel.open", &json!({"kind":"fixture.log","instance":"log","destination":command_destination("shared",0,"left")})).unwrap(); + let before = bounded.service.inspect(); + assert_eq!( + bounded + .execute("panel.open", &json!({"kind":"fixture.small","instance":"small","destination":{"type":"join_tab","section":"shared","index":1}})) + .unwrap_err() + .rule, + Rule::Bounds + ); + assert_eq!(bounded.service.inspect(), before); + bounded.execute("panel.resize", &json!({"target":command_target("log"),"size":{"width":180,"height":140}})).unwrap(); + bounded + .execute("panel.open", &json!({"kind":"fixture.small","instance":"small","destination":{"type":"join_tab","section":"shared","index":1}})) + .unwrap(); + let before = bounded.service.inspect(); + assert_eq!( + bounded + .execute("panel.open", &json!({"kind":"fixture.large","instance":"large","destination":{"type":"join_tab","section":"shared","index":2}})) + .unwrap_err() + .rule, + Rule::IncompatibleTabs + ); + assert_eq!(bounded.service.inspect(), before); +} + +#[test] +fn web_popout_explicitly_lowers_to_floating_while_desktop_requires_native_capability() { + let mut backend = command_ready_backend(); + let registry = backend.service.registry().clone(); + let input = command_inputs().into_iter().find(|(id, _)| *id == "panel.popout").unwrap().1; + let before = backend.service.inspect(); + assert_eq!(backend.execute("panel.popout", &input).unwrap_err().rule, Rule::Capability); + assert_eq!(backend.service.inspect(), before); + let result = commands::execute( + "panel.popout", + &input, + &mut commands::PanelCommandContext { sink: &mut backend.service, registry: ®istry, catalogue: &mut backend.catalogue, web: true }, + ) + .unwrap(); + assert_eq!(result["layout"]["sections"][1]["location"]["type"], "floating"); + assert!(result["effects"].as_array().unwrap().iter().all(|e| e["type"] != "create_native")); +} + +#[test] +fn catalogue_batch_stages_all_saves_and_replacements_once_and_rolls_back_failed_plans() { + use commands::LayoutCatalogue; + let mut backend = command_ready_backend(); + let before = backend.service.inspect(); + let result = backend + .batch(&[ + serde_json::json!({"command":"layout.save","params":{"name":"Batch saved"}}), + serde_json::json!({"command":"layout.reset"}), + serde_json::json!({"command":"layout.apply","params":{"name":"Batch saved"}}), + serde_json::json!({"command":"layout.get"}), + ]) + .unwrap(); + assert_eq!(result["completed"], 4); + assert_eq!(backend.service.layout(), &before.layout); + let before = backend.service.inspect(); + let catalogue = backend.catalogue.state().clone(); + assert!( + backend + .batch(&[ + serde_json::json!({"command":"layout.save","params":{"name":"Not saved"}}), + serde_json::json!({"command":"layout.workspace.select","params":{"workspace":"missing"}}), + ]) + .is_err() + ); + assert_eq!(backend.service.inspect(), before); + assert_eq!(backend.catalogue.state(), &catalogue); + let mixed = backend + .batch(&[ + serde_json::json!({"command":"panel.close","params":{"target":command_target("one")}}), + serde_json::json!({"command":"layout.reset"}), + ]) + .unwrap_err(); + assert_eq!(mixed.rule, Rule::Capability); + assert_eq!(backend.service.inspect(), before); + assert_eq!(backend.catalogue.state(), &catalogue); +} + +#[test] +fn catalogue_staging_cannot_publish_a_plan_after_an_external_revision_change() { + use commands::{CatalogueState, LayoutCatalogue, PreparedCatalogue}; + use std::cell::RefCell; + use std::rc::Rc; + struct SharedSink(Rc>); + impl ActionSink for SharedSink { + fn inspect(&self) -> LayoutReply { + self.0.borrow().inspect() + } + fn project(&self, action: LayoutAction) -> PanelResult { + self.0.borrow().project(action) + } + fn dispatch(&mut self, action: LayoutAction) -> PanelResult { + self.0.borrow_mut().dispatch(action) + } + } + struct RacingCatalogue { + catalogue: commands::InMemoryCatalogue, + service: Rc>, + published: bool, + } + impl LayoutCatalogue for RacingCatalogue { + fn state(&self) -> &CatalogueState { + self.catalogue.state() + } + fn prepare(&mut self, next: CatalogueState) -> PanelResult { + self.service.borrow_mut().set_availability([(id("one"), Availability::Unavailable { reason: "external update".into() })].into())?; + PreparedCatalogue::new(next) + } + fn publish(&mut self, prepared: PreparedCatalogue) { + self.published = true; + self.catalogue.publish(prepared); + } + } + let backend = command_ready_backend(); + let registry = backend.service.registry().clone(); + let shared = Rc::new(RefCell::new(backend.service)); + let mut sink = SharedSink(shared.clone()); + let mut catalogue = RacingCatalogue { catalogue: backend.catalogue, service: shared, published: false }; + let before = catalogue.state().clone(); + let reason = commands::execute( + "panel.close", + &serde_json::json!({"target":command_target("one")}), + &mut commands::PanelCommandContext { sink: &mut sink, registry: ®istry, catalogue: &mut catalogue, web: false }, + ) + .unwrap_err(); + assert_eq!(reason.rule, Rule::Revision); + assert!(!catalogue.published); + assert_eq!(catalogue.state(), &before); + assert!(sink.inspect().layout.instance(&id("one")).unwrap().requested_open); +} + +#[test] +fn catalogue_workspace_count_and_metadata_budgets_are_independent_and_atomic() { + use commands::LayoutCatalogue; + let registry = synthetic_registry().unwrap(); + let envelope = LayoutEnvelope::new(persistence_fallback()); + let mut catalogue = commands::InMemoryCatalogue::default(); + catalogue.register_builtin("Default", &envelope, ®istry).unwrap(); + for i in 0..commands::MAX_WORKSPACES { + catalogue + .register_workspace(commands::WorkspaceDescriptor { + id: WorkspaceId::new(format!("workspace-{i}")).unwrap(), + title_key: "ui.panel".into(), + default_preset: "Default".into(), + }) + .unwrap(); + } + let before = catalogue.state().clone(); + assert_eq!( + catalogue + .register_workspace(commands::WorkspaceDescriptor { + id: WorkspaceId::new("overflow").unwrap(), + title_key: "ui.panel".into(), + default_preset: "Default".into() + }) + .unwrap_err() + .rule, + Rule::CollectionLimit + ); + assert_eq!(catalogue.state(), &before); + let mut metadata = commands::InMemoryCatalogue::default(); + for i in 0..64 { + metadata.register_builtin(&format!("{}{:02}", "🦀".repeat(62), i), &envelope, ®istry).unwrap(); + } + let name = format!("{}00", "🦀".repeat(62)); + metadata + .register_workspace(commands::WorkspaceDescriptor { + id: WorkspaceId::new("first").unwrap(), + title_key: "ui.panel".into(), + default_preset: name.clone(), + }) + .unwrap(); + let before = metadata.state().clone(); + assert_eq!( + metadata + .register_workspace(commands::WorkspaceDescriptor { + id: WorkspaceId::new("second").unwrap(), + title_key: "ui.panel".into(), + default_preset: name + }) + .unwrap_err() + .rule, + Rule::CollectionLimit + ); + assert_eq!(metadata.state(), &before); +} + +#[test] +fn headless_cannot_claim_native_support_even_when_an_injected_service_sets_native_flags() { + let service = fixture_service(true).unwrap(); + let catalogue = fixture_command_catalogue(service.registry()).unwrap(); + let mut backend = commands::InMemoryPanelBackend::new(service, catalogue); + backend + .execute("panel.open", &serde_json::json!({"kind":"fixture.log","instance":"one","destination":command_destination("s-one",0,"left")})) + .unwrap(); + assert_eq!(backend.execute("panel.list", &serde_json::json!({})).unwrap()["state"]["capabilities"]["native_windows"], false); + let mut input = command_inputs().into_iter().find(|(id, _)| *id == "panel.popout").unwrap().1; + input["destination"]["index"] = serde_json::json!(0); + let before = backend.service.inspect(); + assert_eq!(backend.execute("panel.popout", &input).unwrap_err().rule, Rule::Capability); + assert_eq!(backend.service.inspect(), before); +} + +#[test] +fn registry_growth_save_and_live_mutation_keep_uncommitted_reappearance_retryable() { + use commands::LayoutCatalogue; + let absent = future_registry(&["a"]); + let grown = future_registry(&["a", "b", "c"]); + let fallback = persistence_fallback(); + let raw = future_group(); + let dormant = decode(&serde_json::to_vec(&raw).unwrap(), &absent, &fallback).unwrap().envelope; + let service = LayoutService::new(grown.clone(), dormant.layout.clone(), HostCapabilities::default()).unwrap(); + let mut catalogue = fixture_command_catalogue(&grown).unwrap(); + catalogue.remember(&dormant, Some(b"recovery"), &grown).unwrap(); + let snapshot = catalogue.state().export().unwrap(); + let catalogue = commands::InMemoryCatalogue::from_snapshot(&snapshot, &grown).unwrap(); + let hydrated = catalogue.state().remembered(&fallback.workspace).unwrap().envelope(&grown, &fallback.workspace).unwrap(); + assert_eq!(hydrated.quarantine, dormant.quarantine); + assert_eq!(hydrated.section_order, dormant.section_order); + assert_eq!(hydrated.section_snapshots, dormant.section_snapshots, "including materialized projected sections"); + let mut backend = commands::InMemoryPanelBackend::new(service, catalogue); + backend.execute("layout.save", &serde_json::json!({"name":"Registry grew"})).unwrap(); + backend + .execute( + "panel.open", + &serde_json::json!({"kind":"fixture.application","instance":"app","destination":command_destination("app-section",1,"right")}), + ) + .unwrap(); + backend.execute("panel.resize", &serde_json::json!({"target":command_target("app"),"size":{"width":300,"height":280}})).unwrap(); + let remembered = backend.catalogue.state().remembered(&fallback.workspace).unwrap(); + let retained = remembered.envelope(&grown, &fallback.workspace).unwrap(); + assert_eq!(retained.quarantine.len(), 2, "temporary decode is not a committed restore"); + assert_eq!(retained.section_snapshots[§ion("group")].data["active"], "c"); + assert_eq!(retained.section_snapshots[§ion("group")].data["tabs"], serde_json::json!(["c", "b", "a"])); + assert_eq!(retained.quarantine.iter().find(|q| q.instance == id("b")).unwrap().instance_data["future_draft"], "draft-b"); + assert_eq!(remembered.rejected(), Some(b"recovery".as_slice())); + let restored = decode(remembered.bytes(), &grown, &fallback).unwrap().envelope; + assert_eq!(restored.layout.section(§ion("group")).unwrap().active, id("c")); + assert_eq!(restored.layout.section(§ion("group")).unwrap().tabs, vec![id("c"), id("b"), id("a")]); + let before = backend.catalogue.state().clone(); + let live = backend.service.inspect(); + backend.catalogue.fail_stage = true; + assert!(backend.execute("layout.apply", &serde_json::json!({"name":"Registry grew"})).is_err()); + assert_eq!(backend.catalogue.state(), &before); + assert_eq!(backend.service.inspect(), live); + backend.catalogue.fail_stage = false; + backend.execute("layout.apply", &serde_json::json!({"name":"Registry grew"})).unwrap(); + assert_eq!(backend.service.layout().section(§ion("group")).unwrap().active, id("c")); + let committed = backend.catalogue.state().remembered(&fallback.workspace).unwrap().envelope(&grown, &fallback.workspace).unwrap(); + assert!(committed.quarantine.is_empty()); + assert_eq!(committed.retained_data[&id("b")]["instance"]["future_draft"], "draft-b"); +} + +#[test] +fn disabled_popout_rejects_native_and_web_before_lowering_while_float_remains_allowed() { + use commands::LayoutCatalogue; + for web in [false, true] { + let mut registry = synthetic_registry().unwrap(); + let mut spec = registry.get(&PanelKind::new("fixture.log").unwrap()).unwrap().clone(); + spec.kind = PanelKind::new("fixture.no-popout").unwrap(); + spec.features.popout = false; + registry.register(spec).unwrap(); + let mut service = LayoutService::new( + registry.clone(), + persistence_fallback(), + HostCapabilities { native_windows: true, max_native_hosts: 8, persistence: false }, + ) + .unwrap(); + service.dispatch(transaction(vec![fixture_open("fixture.no-popout", "one", "s-one", Zone::Left, 0).unwrap()])).unwrap(); + let mut catalogue = fixture_command_catalogue(®istry).unwrap(); + let before = service.inspect(); + let stored = catalogue.state().clone(); + let mut popout = command_inputs().into_iter().find(|(id, _)| *id == "panel.popout").unwrap().1; + popout["destination"]["index"] = serde_json::json!(0); + let reason = commands::execute( + "panel.popout", + &popout, + &mut commands::PanelCommandContext { sink: &mut service, registry: ®istry, catalogue: &mut catalogue, web }, + ) + .unwrap_err(); + assert_eq!(reason.rule, Rule::FeatureDisabled); + assert_eq!(service.inspect(), before); + assert_eq!(catalogue.state(), &stored); + popout["destination"]["location"] = serde_json::json!({"type":"floating","origin":{"x":20,"y":30}}); + commands::execute( + "panel.float", + &popout, + &mut commands::PanelCommandContext { sink: &mut service, registry: ®istry, catalogue: &mut catalogue, web }, + ) + .unwrap(); + assert_eq!(service.layout().containing(&id("one")).unwrap().location.zone(), Zone::Floating); + } +} + +// Deliberately uses only public consumer interfaces, as an independent storage +// crate would; user presets are never reconstructed by fake live commands. +mod catalogue_consumer { + use crate::panels::commands::{ + CatalogueState, InMemoryCatalogue, InMemoryPanelBackend, LayoutCatalogue, MAX_CATALOGUE_BYTES, MAX_CATALOGUE_SNAPSHOT_BYTES, + }; + use crate::panels::*; + + fn maximum_record(mut envelope: LayoutEnvelope, registry: &PanelRegistry, bytes: usize) -> LayoutEnvelope { + let padding = InstanceId::new("padding").unwrap(); + envelope.retained_data.insert(padding.clone(), serde_json::json!("")); + let overhead = encode(&envelope, registry).unwrap().len(); + let length = bytes.checked_sub(overhead).expect("test record has room for opaque padding"); + envelope.retained_data.insert(padding, serde_json::json!("x".repeat(length))); + assert_eq!(encode(&envelope, registry).unwrap().len(), bytes); + envelope + } + + fn unmaterialized_section_record(with_snapshot: bool) -> (PanelRegistry, LayoutEnvelope) { + let mut service = fixture_service(false).unwrap(); + service.dispatch(transaction(vec![fixture_open("fixture.log", "log", "logs", Zone::Left, 0).unwrap()])).unwrap(); + let registry = service.registry().clone(); + let mut envelope = LayoutEnvelope::new(service.layout().clone()); + envelope.section_order.clear(); // Encode-valid earlier-v1 intent, not missing content. + if with_snapshot { + let section = envelope.layout.sections.first().unwrap(); + let mut data = serde_json::to_value(section).unwrap(); + data["future_surface"] = serde_json::json!({"opaque":"preserve exactly"}); + envelope.section_snapshots.insert(section.id.clone(), SectionSnapshot { data, index: 0, projected: None }); + } + (registry, envelope) + } + + fn without_kind(registry: &PanelRegistry, missing: &str) -> PanelRegistry { + let mut absent = PanelRegistry::default(); + for spec in registry.specs().filter(|spec| spec.kind.0 != missing) { + absent.register(spec.clone()).unwrap(); + } + absent + } + + fn assert_same_placement(actual: &Layout, expected: &Layout) { + assert_eq!(actual.version, expected.version); + assert_eq!(actual.workspace, expected.workspace); + assert_eq!(actual.sections, expected.sections, "complete section order, tab order and activation"); + assert_eq!(actual.instances.len(), expected.instances.len()); + for instance in &expected.instances { + assert_eq!(actual.instance(&instance.id).unwrap(), instance); + } + } + + fn registered_extension_record() -> (PanelRegistry, LayoutEnvelope) { + let mut registry = synthetic_registry().unwrap(); + let mut extension = registry.get(&PanelKind::new("fixture.log").unwrap()).unwrap().clone(); + extension.kind = PanelKind::new("extension.a").unwrap(); + registry.register(extension).unwrap(); + let mut service = + LayoutService::new(registry.clone(), Layout::empty(WorkspaceId::new("fixture.workspace").unwrap()), HostCapabilities::default()).unwrap(); + service + .dispatch(transaction(vec![ + fixture_open("fixture.log", "ordinary", "group", Zone::Left, 0).unwrap(), + Mutation::Open { + kind: PanelKind::new("extension.a").unwrap(), + instance: InstanceId::new("extension").unwrap(), + destination: Some(Destination::JoinTab { section: SectionId::new("group").unwrap(), index: 0 }), + }, + fixture_open("fixture.application", "app", "app-section", Zone::Right, 1).unwrap(), + Mutation::Activate { instance: InstanceId::new("extension").unwrap() }, + ])) + .unwrap(); + let mut envelope = LayoutEnvelope::new(service.layout().clone()); + envelope.retained_data.insert(InstanceId::new("extension").unwrap(), serde_json::json!({"future_draft":{"text":"keep draft","cursor":7}})); + for (index, section) in envelope.layout.sections.iter().enumerate() { + let mut data = serde_json::to_value(section).unwrap(); + data["future_surface"] = serde_json::json!({"opaque":section.id.0}); + envelope.section_snapshots.insert(section.id.clone(), SectionSnapshot { data, index, projected: Some(section.clone()) }); + } + (registry, envelope) + } + + #[test] + fn registry_shrink_hydrates_exact_users_builtins_and_memories_then_stages_reappearance() { + let (registry, envelope) = registered_extension_record(); + let absent = without_kind(®istry, "extension.a"); + let mut catalogue = fixture_command_catalogue(®istry).unwrap(); + catalogue.register_builtin("Extension default", &envelope, ®istry).unwrap(); + catalogue + .register_workspace(commands::WorkspaceDescriptor { + id: WorkspaceId::new("extension.workspace").unwrap(), + title_key: "ui.panel".into(), + default_preset: "Extension default".into(), + }) + .unwrap(); + let mut source = InMemoryPanelBackend::new(fixture_service(false).unwrap(), catalogue); + source.execute("layout.save", &serde_json::json!({"name":"Ordinary user"})).unwrap(); + // Use the real extended registry/service when creating the saved user. + source.service = LayoutService::new(registry.clone(), envelope.layout.clone(), HostCapabilities::default()).unwrap(); + let rejected = [0, 255, 128, 0, 17]; + source.catalogue.remember(&envelope, Some(&rejected), ®istry).unwrap(); + source.execute("layout.save", &serde_json::json!({"name":"Extension user"})).unwrap(); + let snapshot = source.catalogue.state().export().unwrap(); + let hydrated = InMemoryCatalogue::from_snapshot(&snapshot, &absent).unwrap(); + assert_eq!(hydrated.state(), source.catalogue.state()); + assert_eq!(hydrated.state().export().unwrap(), snapshot); + assert_eq!(hydrated.state().user_presets().map(|(name, _)| name).collect::>(), vec!["Extension user", "Ordinary user"]); + let record = hydrated.state().preset("Extension user").unwrap(); + let exact = record.envelope(&absent, &envelope.layout.workspace).unwrap(); + assert_eq!(exact.layout, envelope.layout, "inspection keeps the original requested-open instance and activation"); + assert_eq!(exact.retained_data, envelope.retained_data); + assert_eq!(record.rejected(), Some(rejected.as_slice())); + let mut staged = record.project_envelope(&absent, &envelope.layout.workspace).unwrap(); + validate(&staged.layout, &absent).unwrap(); + assert!(staged.layout.instances.iter().all(|instance| instance.kind.0 != "extension.a")); + assert_eq!(staged.quarantine.len(), 1); + assert_eq!(staged.section_snapshots[&SectionId::new("group").unwrap()].data["active"], "extension"); + let dormant = staged.clone(); + let availability = [(InstanceId::new("extension").unwrap(), Availability::Unavailable { reason: "temporarily absent provider".into() })] + .into_iter() + .collect(); + restore_quarantine_with_availability(&mut staged, ®istry, &availability).unwrap(); + assert_eq!(staged, dormant, "a refused reappearance preserves retryable intent"); + restore_quarantine(&mut staged, ®istry).unwrap(); + assert_same_placement(&staged.layout, &envelope.layout); + assert_eq!(staged.section_order, envelope.section_order); + assert!(staged.quarantine.is_empty()); + assert_eq!(staged.retained_data[&InstanceId::new("extension").unwrap()], envelope.retained_data[&InstanceId::new("extension").unwrap()]); + assert_eq!(staged.section_snapshots[&SectionId::new("group").unwrap()].data["future_surface"]["opaque"], "group"); + let mut absent_backend = InMemoryPanelBackend::new( + LayoutService::new(absent.clone(), Layout::empty(envelope.layout.workspace.clone()), HostCapabilities::default()).unwrap(), + hydrated, + ); + absent_backend.execute("layout.apply", &serde_json::json!({"name":"Ordinary user"})).unwrap(); + absent_backend.execute("layout.workspace.select", &serde_json::json!({"workspace":"fixture.other"})).unwrap(); + absent_backend.execute("layout.reset", &serde_json::json!({})).unwrap(); + absent_backend.execute("layout.workspace.select", &serde_json::json!({"workspace":"extension.workspace"})).unwrap(); + assert!(absent_backend.service.layout().instances.iter().all(|instance| instance.kind.0 != "extension.a")); + let remembered = absent_backend + .catalogue + .state() + .remembered(&WorkspaceId::new("extension.workspace").unwrap()) + .unwrap() + .envelope(&absent, &WorkspaceId::new("extension.workspace").unwrap()) + .unwrap(); + assert_eq!(remembered.quarantine.len(), 1, "selecting a missing peer stages quarantine, never an unknown live instance"); + absent_backend.execute("layout.save", &serde_json::json!({"name":"Still dormant"})).unwrap(); + let after_shrink = absent_backend.catalogue.state().export().unwrap(); + let grown = InMemoryCatalogue::from_snapshot(&after_shrink, ®istry).unwrap(); + assert_eq!(grown.state().export().unwrap(), after_shrink); + assert_eq!(grown.state().preset("Extension user").unwrap().bytes(), source.catalogue.state().preset("Extension user").unwrap().bytes()); + assert_eq!(grown.state().preset("Extension user").unwrap().rejected(), Some(rejected.as_slice())); + let service = + LayoutService::new(registry.clone(), Layout::empty(WorkspaceId::new("recovery.workspace").unwrap()), HostCapabilities::default()) + .unwrap(); + let mut grown_backend = InMemoryPanelBackend::new(service, grown); + grown_backend.execute("layout.apply", &serde_json::json!({"name":"Still dormant"})).unwrap(); + let mut expected = envelope.layout; + expected.workspace = WorkspaceId::new("recovery.workspace").unwrap(); + assert_same_placement(grown_backend.service.layout(), &expected); + } + + #[test] + fn registry_shrink_maximum_records_remain_exact_and_projection_failure_is_retryable() { + for with_snapshot in [false, true] { + let (registry, envelope) = unmaterialized_section_record(with_snapshot); + let absent = without_kind(®istry, "fixture.log"); + let envelope = maximum_record(envelope, ®istry, MAX_ENVELOPE_BYTES); + let original = encode(&envelope, ®istry).unwrap(); + let rejected = [0, 255, 128, 0]; + let mut catalogue = InMemoryCatalogue::default(); + catalogue.register_builtin("Maximum", &envelope, ®istry).unwrap(); + let ordinary = LayoutEnvelope::new(Layout::empty(WorkspaceId::new("unrelated.workspace").unwrap())); + catalogue.register_builtin("Ordinary", &ordinary, ®istry).unwrap(); + catalogue.remember(&envelope, Some(&rejected), ®istry).unwrap(); + let snapshot = catalogue.state().export().unwrap(); + let hydrated = InMemoryCatalogue::from_snapshot(&snapshot, &absent).unwrap(); + assert_eq!(hydrated.state(), catalogue.state()); + assert_eq!(hydrated.state().export().unwrap(), snapshot); + let stored = hydrated.state().remembered(&envelope.layout.workspace).unwrap(); + assert_eq!(stored.bytes(), original.as_slice()); + assert_eq!(stored.rejected(), Some(rejected.as_slice())); + assert_eq!(stored.envelope(&absent, &envelope.layout.workspace).unwrap(), envelope); + if with_snapshot { + let projected = stored.project_envelope(&absent, &envelope.layout.workspace).unwrap(); + validate(&projected.layout, &absent).unwrap(); + assert_eq!(projected.quarantine.len(), 1); + assert_eq!(projected.section_snapshots[&SectionId::new("logs").unwrap()].data["active"], "log"); + } else { + // Capturing a previously absent snapshot needs additional bytes. + assert_eq!(stored.project_envelope(&absent, &envelope.layout.workspace).unwrap_err().rule, Rule::CollectionLimit); + } + let mut backend = + InMemoryPanelBackend::new(LayoutService::new(absent.clone(), ordinary.layout, HostCapabilities::default()).unwrap(), hydrated); + backend.execute("layout.apply", &serde_json::json!({"name":"Ordinary"})).unwrap(); + let before = backend.catalogue.state().clone(); + let live = backend.service.inspect(); + if with_snapshot { + // Existing snapshot storage frees enough space when its absent + // live section is quarantined; no cap is raised to permit it. + backend.execute("layout.apply", &serde_json::json!({"name":"Maximum"})).unwrap(); + assert!(backend.service.layout().instances.is_empty()); + let remembered = + backend.catalogue.state().remembered(&live.layout.workspace).unwrap().envelope(&absent, &live.layout.workspace).unwrap(); + assert_eq!(remembered.quarantine.len(), 1); + assert_eq!(remembered.retained_data, envelope.retained_data); + } else { + assert_eq!(backend.execute("layout.apply", &serde_json::json!({"name":"Maximum"})).unwrap_err().rule, Rule::CollectionLimit); + assert_eq!(backend.catalogue.state(), &before); + assert_eq!(backend.service.inspect(), live); + } + let grown = CatalogueState::hydrate(&snapshot, ®istry).unwrap(); + assert_eq!(grown.export().unwrap(), snapshot); + assert_eq!( + grown.preset("Maximum").unwrap().project_envelope(®istry, &envelope.layout.workspace).unwrap(), + envelope, + "returning registration needs no read-time metadata expansion" + ); + } + } + + #[test] + fn registry_shrink_and_growth_preserve_exact_aggregate_budget_and_recovery() { + let (registry, base) = unmaterialized_section_record(true); + let absent = without_kind(®istry, "fixture.log"); + let full = maximum_record(base.clone(), ®istry, MAX_ENVELOPE_BYTES); + let ordinary = + maximum_record(LayoutEnvelope::new(Layout::empty(WorkspaceId::new("ordinary.workspace").unwrap())), ®istry, MAX_ENVELOPE_BYTES); + let rejected = [255, 0, 128, 0, 1]; + let tail = maximum_record(base, ®istry, MAX_ENVELOPE_BYTES - rejected.len()); + let mut catalogue = InMemoryCatalogue::default(); + for index in 0..14 { + catalogue.register_builtin(&format!("Missing-{index}"), &full, ®istry).unwrap(); + } + catalogue.register_builtin("Ordinary", &ordinary, ®istry).unwrap(); + catalogue.remember(&tail, Some(&rejected), ®istry).unwrap(); + let snapshot = catalogue.state().export().unwrap(); + assert_eq!( + 14 * encode(&full, ®istry).unwrap().len() + + encode(&ordinary, ®istry).unwrap().len() + + encode(&tail, ®istry).unwrap().len() + + rejected.len(), + MAX_CATALOGUE_BYTES + ); + let absent_state = CatalogueState::hydrate(&snapshot, &absent).unwrap(); + assert_eq!(absent_state, catalogue.state().clone()); + assert_eq!(absent_state.export().unwrap(), snapshot); + assert_eq!(absent_state.preset("Ordinary").unwrap().project_envelope(&absent, &ordinary.layout.workspace).unwrap(), ordinary); + assert_eq!(absent_state.remembered(&tail.layout.workspace).unwrap().rejected(), Some(rejected.as_slice())); + let grown = CatalogueState::hydrate(&absent_state.export().unwrap(), ®istry).unwrap(); + assert_eq!(grown.export().unwrap(), snapshot); + assert_eq!(grown.preset("Missing-0").unwrap().envelope(®istry, &full.layout.workspace).unwrap(), full); + let mut hydrated = InMemoryCatalogue::from_snapshot(&snapshot, &absent).unwrap(); + let before = hydrated.state().clone(); + assert_eq!( + hydrated.register_builtin("Overflow", &LayoutEnvelope::new(Layout::empty(ordinary.layout.workspace)), &absent).unwrap_err().rule, + Rule::CollectionLimit + ); + assert_eq!(hydrated.state(), &before); + } + + #[test] + fn optional_peer_raw_future_fields_survive_exact_hydration_quarantine_and_reappearance() { + let (registry, mut envelope) = registered_extension_record(); + // A future writer may also carry opaque keys in the saved typed records. + // Keep a separate existing opaque sidecar to exercise both storage paths. + let draft = envelope.retained_data.remove(&InstanceId::new("extension").unwrap()).unwrap(); + envelope.retained_data.insert(InstanceId::new("unrelated-opaque").unwrap(), draft); + let mut raw = serde_json::to_value(&envelope).unwrap(); + raw["layout"]["instances"][1]["future_editor"] = serde_json::json!({"draft":"original raw draft","selection":[3,9]}); + raw["layout"]["sections"][0]["future_surface"] = serde_json::json!({"raw":"keep raw section intent"}); + let bytes = serde_json::to_vec(&raw).unwrap(); + let rejected = [0, 255, 128, 0]; + let saved = snapshot( + &[("Builtin", &bytes, None)], + &[("User", &bytes, Some(&rejected))], + &[("fixture.workspace", "ui.panel", "Builtin")], + &[("fixture.workspace", &bytes, Some(&rejected))], + ); + let original = CatalogueState::hydrate(&saved, ®istry).unwrap().export().unwrap(); + let absent = without_kind(®istry, "extension.a"); + let hydrated = CatalogueState::hydrate(&original, &absent).unwrap(); + assert_eq!(hydrated.export().unwrap(), original); + for record in + [hydrated.preset("Builtin").unwrap(), hydrated.preset("User").unwrap(), hydrated.remembered(&envelope.layout.workspace).unwrap()] + { + assert_eq!(record.bytes(), bytes.as_slice()); + let mut staged = record.project_envelope(&absent, &envelope.layout.workspace).unwrap(); + assert_eq!(staged.quarantine[0].instance_data["future_editor"], raw["layout"]["instances"][1]["future_editor"]); + assert_eq!(staged.section_snapshots[&SectionId::new("group").unwrap()].data["future_surface"]["raw"], "keep raw section intent"); + restore_quarantine(&mut staged, ®istry).unwrap(); + assert_same_placement(&staged.layout, &envelope.layout); + assert_eq!( + staged.retained_data[&InstanceId::new("extension").unwrap()]["instance"]["future_editor"], + raw["layout"]["instances"][1]["future_editor"] + ); + assert_eq!( + staged.retained_data[&InstanceId::new("unrelated-opaque").unwrap()], + envelope.retained_data[&InstanceId::new("unrelated-opaque").unwrap()] + ); + } + let grown = CatalogueState::hydrate(&hydrated.export().unwrap(), ®istry).unwrap(); + assert_eq!(grown.export().unwrap(), original); + assert_eq!(grown.preset("User").unwrap().rejected(), Some(rejected.as_slice())); + } + + #[test] + fn missing_peer_does_not_hide_corrupt_structure_or_known_member_constraints() { + let (registry, envelope) = registered_extension_record(); + let absent = without_kind(®istry, "extension.a"); + let valid = serde_json::to_value(&envelope).unwrap(); + let mut hostile = Vec::new(); + let mut value = valid.clone(); + value["layout"]["instances"][1]["memory"]["size"]["width"] = serde_json::json!(0); + hostile.push(value); + let mut value = valid.clone(); + value["layout"]["instances"][1]["memory"]["tab_index"] = serde_json::json!(MAX_TABS); + hostile.push(value); + let mut value = valid.clone(); + value["layout"]["sections"][0]["active"] = serde_json::json!("ghost"); + hostile.push(value); + let mut value = valid.clone(); + value["layout"]["instances"][1]["id"] = serde_json::json!("ordinary"); + hostile.push(value); + let mut value = valid.clone(); + value["layout"]["instances"][0]["memory"]["size"]["width"] = serde_json::json!(1); + hostile.push(value); + let mut value = valid.clone(); + value["layout"]["sections"][0]["size"]["width"] = serde_json::json!(1); + hostile.push(value); + let mut value = valid.clone(); + value["layout"]["instances"][0]["kind"] = serde_json::json!("fixture.application"); + hostile.push(value); // Repeats known single-instance kind. + let mut value = valid.clone(); + value["layout"]["sections"][0]["tabs"] = serde_json::json!(vec!["ordinary"; MAX_TABS + 1]); + hostile.push(value); + let mut value = valid.clone(); + value["layout"]["instances"][0]["requested_open"] = serde_json::json!(false); + value["layout"]["sections"][0]["tabs"] = serde_json::json!(["extension"]); + for section in value["layout"]["sections"].as_array_mut().unwrap() { + section["location"] = serde_json::json!({"type":"window","host":"same-host","origin":{"x":0,"y":0}, + "return_to":{"zone":"left","index":0,"size":{"width":280,"height":240},"collapsed":false}}); + } + hostile.push(value); // Duplicate native host, including an entirely absent-kind section. + let mut deep = serde_json::json!(null); + for _ in 0..34 { + deep = serde_json::json!({"future":deep}); + } + let mut value = valid.clone(); + value["retained_data"]["future"] = deep; + hostile.push(value); + for value in hostile { + let bytes = serde_json::to_vec(&value).unwrap(); + let snapshot = snapshot(&[], &[("Saved", &bytes, None)], &[], &[]); + assert!(CatalogueState::hydrate(&snapshot, &absent).is_err()); + assert!(project_retained_record(&bytes, &absent, &envelope.layout.workspace).is_err()); + } + // A known member's no-tab flag applies even when its only peer is absent. + let mut no_tabs = PanelRegistry::default(); + for spec in absent.specs() { + let mut spec = spec.clone(); + if spec.kind.0 == "fixture.log" { + spec.features.tabbable = false; + } + no_tabs.register(spec).unwrap(); + } + let bytes = encode(&envelope, ®istry).unwrap(); + assert_eq!(CatalogueState::hydrate(&snapshot(&[], &[("Saved", &bytes, None)], &[], &[]), &no_tabs).unwrap_err().rule, Rule::FeatureDisabled); + // An absent-only outer section still precedes a known pinned section. + let mut pin_service = + LayoutService::new(registry.clone(), Layout::empty(envelope.layout.workspace.clone()), HostCapabilities::default()).unwrap(); + pin_service + .dispatch(transaction(vec![ + fixture_open("fixture.pin", "pin", "pin-section", Zone::Left, 0).unwrap(), + fixture_open("extension.a", "missing", "missing-section", Zone::Right, 1).unwrap(), + ])) + .unwrap(); + let mut wire = serde_json::to_value(LayoutEnvelope::new(pin_service.layout().clone())).unwrap(); + wire["layout"]["sections"].as_array_mut().unwrap().reverse(); + wire["layout"]["sections"][0]["location"] = serde_json::json!({"type":"dock","zone":"left"}); + let bytes = serde_json::to_vec(&wire).unwrap(); + assert_eq!(CatalogueState::hydrate(&snapshot(&[], &[("Pinned", &bytes, None)], &[], &[]), &absent).unwrap_err().rule, Rule::PinOrder); + } + + #[test] + fn accepted_maximum_records_roundtrip_without_materializing_order_or_projection() { + for with_snapshot in [false, true] { + let (registry, envelope) = unmaterialized_section_record(with_snapshot); + let envelope = maximum_record(envelope, ®istry, MAX_ENVELOPE_BYTES); + let original = encode(&envelope, ®istry).unwrap(); + let rejected = [0, 255, 0, 127, 128, 42, 1]; + let mut catalogue = InMemoryCatalogue::default(); + catalogue.register_builtin("Maximum", &envelope, ®istry).unwrap(); + catalogue.remember(&envelope, Some(&rejected), ®istry).unwrap(); + let snapshot = catalogue.state().export().unwrap(); + let hydrated = InMemoryCatalogue::from_snapshot(&snapshot, ®istry).unwrap(); + assert_eq!(hydrated.state(), catalogue.state()); + assert_eq!(hydrated.state().export().unwrap(), snapshot, "same-registry hydration retains the original records byte for byte"); + for record in [hydrated.state().preset("Maximum").unwrap(), hydrated.state().remembered(&envelope.layout.workspace).unwrap()] { + assert_eq!(record.bytes(), original.as_slice()); + let loaded = record.envelope(®istry, &envelope.layout.workspace).unwrap(); + assert_eq!(loaded, envelope); + assert!(loaded.section_order.is_empty()); + assert!(loaded.section_snapshots.values().all(|snapshot| snapshot.projected.is_none())); + } + assert_eq!(hydrated.state().remembered(&envelope.layout.workspace).unwrap().rejected(), Some(rejected.as_slice())); + let mut oversized = envelope.clone(); + oversized.retained_data.insert( + InstanceId::new("padding").unwrap(), + serde_json::json!(format!("{}x", envelope.retained_data[&InstanceId::new("padding").unwrap()].as_str().unwrap())), + ); + let before = catalogue.state().clone(); + assert_eq!(catalogue.register_builtin("Oversized", &oversized, ®istry).unwrap_err().rule, Rule::CollectionLimit); + assert_eq!(catalogue.state(), &before); + let mut corrupt = snapshot; + corrupt.push(0); + assert_eq!(CatalogueState::hydrate(&corrupt, ®istry).unwrap_err().rule, Rule::Schema); + } + } + + #[test] + fn accepted_aggregate_limit_roundtrips_exact_records_and_rejected_binary_bytes() { + let (registry, base) = unmaterialized_section_record(true); + let full = maximum_record(base.clone(), ®istry, MAX_ENVELOPE_BYTES); + let full_bytes = encode(&full, ®istry).unwrap(); + let rejected = [0, 255, 0, 127, 128, 42, 1]; + let tail = maximum_record(base, ®istry, MAX_ENVELOPE_BYTES - rejected.len()); + let tail_bytes = encode(&tail, ®istry).unwrap(); + assert_eq!(15 * full_bytes.len() + tail_bytes.len() + rejected.len(), MAX_CATALOGUE_BYTES); + let mut catalogue = InMemoryCatalogue::default(); + for index in 0..15 { + catalogue.register_builtin(&format!("Maximum-{index}"), &full, ®istry).unwrap(); + } + catalogue.remember(&tail, Some(&rejected), ®istry).unwrap(); + let snapshot = catalogue.state().export().unwrap(); + let hydrated = CatalogueState::hydrate(&snapshot, ®istry).unwrap(); + assert_eq!(hydrated, catalogue.state().clone()); + assert_eq!(hydrated.export().unwrap(), snapshot, "no per-record expansion may silently exceed the aggregate cap"); + for index in 0..15 { + let record = hydrated.preset(&format!("Maximum-{index}")).unwrap(); + assert_eq!(record.bytes(), full_bytes.as_slice()); + assert_eq!(record.envelope(®istry, &full.layout.workspace).unwrap(), full); + } + let remembered = hydrated.remembered(&tail.layout.workspace).unwrap(); + assert_eq!(remembered.bytes(), tail_bytes.as_slice()); + assert_eq!(remembered.rejected(), Some(rejected.as_slice())); + let before = catalogue.state().clone(); + let empty = LayoutEnvelope::new(Layout::empty(full.layout.workspace.clone())); + assert_eq!(catalogue.register_builtin("One beyond aggregate budget", &empty, ®istry).unwrap_err().rule, Rule::CollectionLimit); + assert_eq!(catalogue.state(), &before); + } + + #[test] + fn maximum_retained_records_defer_live_refresh_and_reappearance_atomically() { + let mut service = fixture_service(false).unwrap(); + service.dispatch(transaction(vec![fixture_open("fixture.log", "future", "future-section", Zone::Left, 0).unwrap()])).unwrap(); + let mut raw = serde_json::to_value(LayoutEnvelope::new(service.layout().clone())).unwrap(); + raw["layout"]["instances"][0]["kind"] = serde_json::json!("extension.future"); + raw["layout"]["instances"][0]["future_draft"] = serde_json::json!("pending conversation"); + let absent = synthetic_registry().unwrap(); + let fallback = Layout::empty(service.layout().workspace.clone()); + let mut envelope = decode(&serde_json::to_vec(&raw).unwrap(), &absent, &fallback).unwrap().envelope; + envelope.section_order.clear(); + let mut grown = absent; + let mut spec = grown.get(&PanelKind::new("fixture.log").unwrap()).unwrap().clone(); + spec.kind = PanelKind::new("extension.future").unwrap(); + grown.register(spec).unwrap(); + let envelope = maximum_record(envelope, &grown, MAX_ENVELOPE_BYTES); + let rejected = [255, 0, 128, 0, 1]; + let mut catalogue = InMemoryCatalogue::default(); + catalogue.remember(&envelope, Some(&rejected), &grown).unwrap(); + let snapshot = catalogue.state().export().unwrap(); + let hydrated = CatalogueState::hydrate(&snapshot, &grown).unwrap(); + let loaded = hydrated.remembered(&fallback.workspace).unwrap().envelope(&grown, &fallback.workspace).unwrap(); + assert_eq!(loaded, envelope, "registered quarantine is not a read-time restoration"); + assert_eq!(loaded.quarantine.first().unwrap().instance_data["future_draft"], "pending conversation"); + assert_eq!(with_live_layout(&loaded, loaded.layout.clone(), &grown).unwrap_err().rule, Rule::CollectionLimit); + let mut candidate = loaded.clone(); + assert_eq!(restore_quarantine(&mut candidate, &grown).unwrap_err().rule, Rule::CollectionLimit); + assert_eq!(candidate, loaded, "failed materialization keeps all retryable intent and opaque records"); + assert_eq!(hydrated.export().unwrap(), snapshot); + assert_eq!(hydrated.remembered(&fallback.workspace).unwrap().rejected(), Some(rejected.as_slice())); + } + + #[test] + fn external_storage_roundtrip_restores_mutable_users_full_records_and_workspaces() { + let mut backend = fixture_command_backend().unwrap(); + backend.service.dispatch(transaction(vec![fixture_open("fixture.log", "log", "logs", Zone::Left, 0).unwrap()])).unwrap(); + let mut envelope = LayoutEnvelope::new(backend.service.layout().clone()); + envelope.retained_data.insert(InstanceId::new("opaque").unwrap(), serde_json::json!({"future":{"draft":"keep"}})); + backend.catalogue.remember(&envelope, Some(&[0, 255, 1, 0]), backend.service.registry()).unwrap(); + backend.execute("layout.save", &serde_json::json!({"name":"User saved"})).unwrap(); + let snapshot = backend.catalogue.state().export().unwrap(); + let users: Vec<_> = backend.catalogue.state().user_presets().map(|(name, _)| name).collect(); + assert_eq!(users, vec!["User saved"]); + // No executor is called while the independent consumer reconstructs state. + let registry = synthetic_registry().unwrap(); + let state = CatalogueState::hydrate(&snapshot, ®istry).unwrap(); + assert_eq!(state.summaries(), backend.catalogue.state().summaries()); + assert_eq!(state.user_presets().map(|(name, _)| name).collect::>(), users); + let saved = state.preset("User saved").unwrap(); + assert_eq!(saved.rejected(), Some([0, 255, 1, 0].as_slice())); + let restored = saved.envelope(®istry, &envelope.layout.workspace).unwrap(); + assert_eq!(restored.retained_data, envelope.retained_data); + assert_eq!(state.remembered(&envelope.layout.workspace).unwrap().rejected(), Some([0, 255, 1, 0].as_slice())); + let catalogue = InMemoryCatalogue::from_snapshot(&snapshot, ®istry).unwrap(); + assert_eq!(catalogue.state().user_count(), 1); + let mut reloaded = InMemoryPanelBackend::new(fixture_service(false).unwrap(), catalogue); + assert_eq!(reloaded.execute("layout.save", &serde_json::json!({"name":"User saved"})).unwrap_err().rule, Rule::DuplicateId); + reloaded.execute("layout.save", &serde_json::json!({"name":"User saved","overwrite":true})).unwrap(); + assert_eq!(reloaded.catalogue.state().user_count(), 1); + assert_eq!( + reloaded.execute("layout.save", &serde_json::json!({"name":"Fixture default","overwrite":true})).unwrap_err().rule, + Rule::Capability + ); + } + + type Entry<'a> = (&'a str, &'a [u8], Option<&'a [u8]>); + fn length(out: &mut Vec, count: usize) { + out.extend_from_slice(&(count as u32).to_le_bytes()); + } + fn bytes(out: &mut Vec, value: &[u8]) { + length(out, value.len()); + out.extend_from_slice(value); + } + fn entries(out: &mut Vec, records: &[Entry<'_>]) { + length(out, records.len()); + for (name, envelope, rejected) in records { + bytes(out, name.as_bytes()); + bytes(out, envelope); + match rejected { + Some(rejected) => { + out.push(1); + bytes(out, rejected); + } + None => out.push(0), + } + } + } + fn snapshot(builtins: &[Entry<'_>], users: &[Entry<'_>], workspaces: &[(&str, &str, &str)], remembered: &[Entry<'_>]) -> Vec { + let mut out = b"SCPCAT01".to_vec(); + entries(&mut out, builtins); + entries(&mut out, users); + length(&mut out, workspaces.len()); + for (id, title, default) in workspaces { + bytes(&mut out, id.as_bytes()); + bytes(&mut out, title.as_bytes()); + bytes(&mut out, default.as_bytes()); + } + entries(&mut out, remembered); + out + } + + #[test] + fn catalogue_hydration_rejects_duplicate_names_workspaces_and_corrupt_framing_before_publication() { + let registry = synthetic_registry().unwrap(); + let envelope = LayoutEnvelope::new(fixture_service(false).unwrap().layout().clone()); + let raw = encode(&envelope, ®istry).unwrap(); + let record = ("Saved", raw.as_slice(), None); + for duplicate in [ + snapshot(&[], &[record, record], &[], &[]), + snapshot(&[record], &[record], &[], &[]), + snapshot(&[record], &[], &[("a", "ui.panel", "Saved"), ("a", "ui.panel", "Saved")], &[]), + snapshot(&[], &[], &[], &[("fixture.workspace", raw.as_slice(), None), ("fixture.workspace", raw.as_slice(), None)]), + ] { + assert_eq!(CatalogueState::hydrate(&duplicate, ®istry).unwrap_err().rule, Rule::DuplicateId); + } + let valid = snapshot(&[], &[record], &[], &[]); + for size in [0, 7, 12, valid.len() - 1] { + assert!(CatalogueState::hydrate(&valid[..size], ®istry).is_err()); + } + let mut trailing = valid.clone(); + trailing.push(0); + assert!(CatalogueState::hydrate(&trailing, ®istry).is_err()); + let mut future = valid; + future[7] = b'2'; + assert_eq!(CatalogueState::hydrate(&future, ®istry).unwrap_err().rule, Rule::Version); + assert!(CatalogueState::hydrate(&snapshot(&[], &[("Saved", b"corrupt", None)], &[], &[]), ®istry).is_err()); + assert!(CatalogueState::hydrate(&snapshot(&[], &[], &[], &[("wrong-workspace", raw.as_slice(), None)]), ®istry).is_err()); + let live = fixture_command_backend().unwrap(); + let before = live.catalogue.state().clone(); + let layout = live.service.inspect(); + assert!(InMemoryCatalogue::from_snapshot(b"corrupt", ®istry).is_err()); + assert_eq!(live.catalogue.state(), &before); + assert_eq!(live.service.inspect(), layout); + } + + #[test] + fn catalogue_hydration_bounds_counts_strings_depth_nodes_recovery_and_total_bytes() { + let registry = synthetic_registry().unwrap(); + let envelope = LayoutEnvelope::new(fixture_service(false).unwrap().layout().clone()); + let raw = encode(&envelope, ®istry).unwrap(); + let mut count = b"SCPCAT01".to_vec(); + length(&mut count, 65); + assert_eq!(CatalogueState::hydrate(&count, ®istry).unwrap_err().rule, Rule::CollectionLimit); + for name in ["".to_string(), " not-normalised ".into(), "bad\n".into(), "x".repeat(257)] { + assert!(CatalogueState::hydrate(&snapshot(&[], &[(&name, &raw, None)], &[], &[]), ®istry).is_err()); + } + let rejected = vec![0; MAX_ENVELOPE_BYTES + 1]; + assert_eq!( + CatalogueState::hydrate(&snapshot(&[], &[("Saved", &raw, Some(&rejected))], &[], &[]), ®istry).unwrap_err().rule, + Rule::CollectionLimit + ); + let mut value = serde_json::to_value(&envelope).unwrap(); + let mut deep = serde_json::json!(null); + for _ in 0..34 { + deep = serde_json::json!({"future":deep}); + } + for hostile in [deep, serde_json::json!(vec![serde_json::Value::Null; 8193]), serde_json::json!("x".repeat(MAX_ENVELOPE_BYTES))] { + value["retained_data"]["future"] = hostile; + let hostile = serde_json::to_vec(&value).unwrap(); + assert!(CatalogueState::hydrate(&snapshot(&[], &[("Saved", &hostile, None)], &[], &[]), ®istry).is_err()); + } + assert_eq!(CatalogueState::hydrate(&vec![0; MAX_CATALOGUE_SNAPSHOT_BYTES + 1], ®istry).unwrap_err().rule, Rule::CollectionLimit); + } + + #[test] + fn catalogue_hydration_rejects_aggregate_payload_metadata_and_duplicate_envelope_identities() { + let registry = synthetic_registry().unwrap(); + let envelope = LayoutEnvelope::new(fixture_service(false).unwrap().layout().clone()); + let raw = encode(&envelope, ®istry).unwrap(); + let mut large = envelope.clone(); + large.retained_data.insert(InstanceId::new("future").unwrap(), serde_json::json!({"opaque":"x".repeat(200_000)})); + let large = encode(&large, ®istry).unwrap(); + let names: Vec<_> = (0..21).map(|i| format!("user-{i}")).collect(); + let users: Vec<_> = names.iter().map(|name| (name.as_str(), large.as_slice(), None)).collect(); + let oversized = snapshot(&[], &users, &[], &[]); + assert!(oversized.len() < MAX_CATALOGUE_SNAPSHOT_BYTES, "payload cap is independent of framing cap"); + assert_eq!(CatalogueState::hydrate(&oversized, ®istry).unwrap_err().rule, Rule::CollectionLimit); + let names: Vec<_> = (0..64).map(|i| format!("{}{:02}", "🦀".repeat(62), i)).collect(); + let builtins: Vec<_> = names.iter().map(|name| (name.as_str(), raw.as_slice(), None)).collect(); + let default = names.first().unwrap().as_str(); + let oversized = snapshot(&builtins, &[], &[("first", "ui.panel", default), ("second", "ui.panel", default)], &[]); + assert_eq!(CatalogueState::hydrate(&oversized, ®istry).unwrap_err().rule, Rule::CollectionLimit); + let mut service = fixture_service(false).unwrap(); + service.dispatch(transaction(vec![fixture_open("fixture.log", "same", "group", Zone::Left, 0).unwrap()])).unwrap(); + let mut duplicate = serde_json::to_value(LayoutEnvelope::new(service.layout().clone())).unwrap(); + let repeated = duplicate["layout"]["instances"][0].clone(); + duplicate["layout"]["instances"].as_array_mut().unwrap().push(repeated); + let duplicate = serde_json::to_vec(&duplicate).unwrap(); + assert!(CatalogueState::hydrate(&snapshot(&[], &[("Saved", &duplicate, None)], &[], &[]), ®istry).is_err()); + } +} + +#[test] +fn whole_section_ranks_include_known_survivors_and_preserve_intervening_live_order() { + let fallback = persistence_fallback(); + let raw = future_sections(); + let bytes = serde_json::to_vec(&raw).unwrap(); + let all = future_registry(&["a", "b", "c"]); + let mut mixed = decode(&bytes, &future_registry(&["b"]), &fallback).unwrap().envelope; + assert_eq!(section_ids(&mixed), vec![section("s1")]); + assert!(!mixed.section_snapshots.contains_key(§ion("s1"))); + restore_quarantine(&mut mixed, &future_registry(&["b", "c"])).unwrap(); + assert_eq!(section_ids(&mixed), vec![section("s1"), section("s2")]); + restore_quarantine(&mut mixed, &all).unwrap(); + assert_eq!(section_ids(&mixed), vec![section("s0"), section("s1"), section("s2")]); + let a_c = future_registry(&["a", "c"]); + let mut edited = decode(&bytes, &a_c, &fallback).unwrap().envelope; + edited.layout.sections.reverse(); // Visible saved user order is now s2, s0. + let reloaded = decode(&encode(&edited, &a_c).unwrap(), &a_c, &fallback).unwrap(); + assert!(reloaded.notice.is_none()); + edited = reloaded.envelope; + assert_eq!(edited.section_order, vec![section("s2"), section("s1"), section("s0")]); + restore_quarantine(&mut edited, &all).unwrap(); + assert_eq!(section_ids(&edited), vec![section("s2"), section("s1"), section("s0")]); +} + +#[test] +fn new_visible_sections_anchor_to_live_neighbours_while_old_sections_are_dormant() { + let fallback = persistence_fallback(); + let b = future_registry(&["b"]); + let all = future_registry(&["a", "b", "c"]); + let mut envelope = decode(&serde_json::to_vec(&future_sections()).unwrap(), &b, &fallback).unwrap().envelope; + let mut live = LayoutService::new(b, envelope.layout.clone(), HostCapabilities::default()).unwrap(); + live.dispatch(transaction(vec![fixture_open("fixture.log", "new", "new-section", Zone::Right, 0).unwrap()])).unwrap(); + envelope.layout = live.layout().clone(); + restore_quarantine(&mut envelope, &all).unwrap(); + assert_eq!(section_ids(&envelope), vec![section("s0"), section("new-section"), section("s1"), section("s2")]); + assert!(envelope.quarantine.is_empty()); + encode(&envelope, &all).unwrap(); +} + +#[test] +fn a_new_whole_section_episode_uses_the_latest_saved_complete_section_order() { + let fallback = persistence_fallback(); + let all = future_registry(&["a", "b", "c"]); + let none = future_registry(&[]); + let mut envelope = decode(&serde_json::to_vec(&future_sections()).unwrap(), &none, &fallback).unwrap().envelope; + restore_quarantine(&mut envelope, &all).unwrap(); + envelope.layout.sections.rotate_right(1); + assert_eq!(section_ids(&envelope), vec![section("s2"), section("s0"), section("s1")]); + let reloaded = decode(&encode(&envelope, &all).unwrap(), &none, &fallback).unwrap(); + assert!(reloaded.notice.is_none()); + envelope = reloaded.envelope; + assert_eq!(envelope.section_order, vec![section("s2"), section("s0"), section("s1")]); + restore_quarantine(&mut envelope, &all).unwrap(); + assert_eq!(section_ids(&envelope), vec![section("s2"), section("s0"), section("s1")]); + assert_eq!(envelope.section_snapshots[§ion("s0")].data["future_surface"]["keep"], "s0"); +} + +fn future_pair(active: &str) -> serde_json::Value { + let mut raw = future_group(); + raw["layout"]["instances"].as_array_mut().unwrap().retain(|instance| instance["id"] != "c"); + raw["layout"]["sections"][0]["tabs"] = serde_json::json!(["a", "b"]); + raw["layout"]["sections"][0]["active"] = serde_json::json!(active); + raw["layout"]["sections"][0]["future_metadata"] = serde_json::json!({"keep":"opaque section data"}); + raw +} + +#[test] +fn a_new_quarantine_episode_refreshes_saved_tab_order_activation_and_outer_semantics() { + let fallback = persistence_fallback(); + let a = future_registry(&["a"]); + let all = future_registry(&["a", "b"]); + for initial_active in ["a", "b"] { + let mut envelope = decode(&serde_json::to_vec(&future_pair(initial_active)).unwrap(), &a, &fallback).unwrap().envelope; + restore_quarantine(&mut envelope, &all).unwrap(); + let group = envelope.layout.sections.first_mut().unwrap(); + group.tabs = vec![id("b"), id("a")]; + group.active = id("b"); + group.size = size(400.0, 300.0); + group.collapsed = true; + group.location = SectionLocation::Dock { zone: Zone::Right }; + let mut saved: serde_json::Value = serde_json::from_slice(&encode(&envelope, &all).unwrap()).unwrap(); + saved["layout"]["sections"][0]["new_future_field"] = serde_json::json!("latest opaque intent"); + let loaded = decode(&serde_json::to_vec(&saved).unwrap(), &a, &fallback).unwrap(); + assert!(loaded.notice.is_none()); + envelope = loaded.envelope; + let memory = &envelope.section_snapshots[§ion("group")]; + assert_eq!(memory.data["tabs"], serde_json::json!(["b", "a"])); + assert_eq!(memory.data["active"], "b"); + assert_eq!(envelope.layout.sections.first().unwrap().active, id("a")); // Generated fallback, not a user edit. + let loaded = decode(&encode(&envelope, &a).unwrap(), &a, &fallback).unwrap(); + assert!(loaded.notice.is_none()); + envelope = loaded.envelope; + restore_quarantine(&mut envelope, &all).unwrap(); + let group = envelope.layout.sections.first().unwrap(); + assert_eq!(group.tabs, vec![id("b"), id("a")]); + assert_eq!(group.active, id("b")); + assert_eq!(group.size, size(400.0, 300.0)); + assert!(group.collapsed); + assert_eq!(group.location.zone(), Zone::Right); + let memory = &envelope.section_snapshots[§ion("group")]; + assert_eq!(memory.data["future_metadata"]["keep"], "opaque section data"); + assert_eq!(memory.data["new_future_field"], "latest opaque intent"); + assert_eq!(envelope.retained_data[&id("b")]["instance"]["future_draft"], "draft-b"); + encode(&envelope, &all).unwrap(); + } +} + +#[test] +fn mixed_partial_episodes_keep_dormant_members_and_latest_visible_user_choices() { + let fallback = persistence_fallback(); + let a = future_registry(&["a"]); + let a_b = future_registry(&["a", "b"]); + let all = future_registry(&["a", "b", "c"]); + let mut raw = future_group(); + raw["layout"]["sections"][0]["tabs"] = serde_json::json!(["a", "b", "c"]); + raw["layout"]["sections"][0]["future_metadata"] = serde_json::json!({"opaque":true}); + let mut envelope = decode(&serde_json::to_vec(&raw).unwrap(), &a_b, &fallback).unwrap().envelope; + assert_eq!(envelope.layout.sections.first().unwrap().tabs, vec![id("a"), id("b")]); + assert_eq!(envelope.layout.sections.first().unwrap().active, id("a")); + let group = envelope.layout.sections.first_mut().unwrap(); + group.tabs.reverse(); + group.active = id("b"); + let saved = encode(&envelope, &a_b).unwrap(); + let loaded = decode(&saved, &a, &fallback).unwrap(); + assert!(loaded.notice.is_none()); + envelope = loaded.envelope; + assert_eq!(envelope.quarantine.len(), 2); + assert_eq!(envelope.section_snapshots[§ion("group")].data["tabs"], serde_json::json!(["b", "a", "c"])); + assert_eq!(envelope.section_snapshots[§ion("group")].data["active"], "b"); + restore_quarantine(&mut envelope, &a_b).unwrap(); + assert_eq!(envelope.quarantine.len(), 1); + assert_eq!(envelope.layout.sections.first().unwrap().tabs, vec![id("b"), id("a")]); + assert_eq!(envelope.layout.sections.first().unwrap().active, id("b")); + let mut unchanged = envelope.clone(); + restore_quarantine(&mut unchanged, &all).unwrap(); + assert_eq!(unchanged.layout.sections.first().unwrap().tabs, vec![id("b"), id("a"), id("c")]); + assert_eq!(unchanged.layout.sections.first().unwrap().active, id("b")); + // A direct live edit between restoration stages is authoritative too. + let group = envelope.layout.sections.first_mut().unwrap(); + group.tabs.reverse(); + group.active = id("a"); + restore_quarantine(&mut envelope, &all).unwrap(); + assert_eq!(envelope.layout.sections.first().unwrap().tabs, vec![id("a"), id("b"), id("c")]); + assert_eq!(envelope.layout.sections.first().unwrap().active, id("a")); + assert_eq!(envelope.section_snapshots[§ion("group")].data["future_metadata"]["opaque"], true); + encode(&envelope, &all).unwrap(); +} + +#[test] +fn unchanged_partial_save_does_not_replace_pending_activation_with_a_fallback() { + let fallback = persistence_fallback(); + let a_b = future_registry(&["a", "b"]); + let all = future_registry(&["a", "b", "c"]); + let mut raw = future_group(); + raw["layout"]["sections"][0]["tabs"] = serde_json::json!(["a", "b", "c"]); + let mut envelope = decode(&serde_json::to_vec(&raw).unwrap(), &a_b, &fallback).unwrap().envelope; + for _ in 0..2 { + let loaded = decode(&encode(&envelope, &a_b).unwrap(), &a_b, &fallback).unwrap(); + assert!(loaded.notice.is_none()); + envelope = loaded.envelope; + } + assert_eq!(envelope.section_snapshots[§ion("group")].data["active"], "c"); + restore_quarantine(&mut envelope, &all).unwrap(); + assert_eq!(envelope.layout.sections.first().unwrap().active, id("c")); +} + +#[test] +fn earlier_v1_rank_metadata_and_new_order_projection_bounds_are_supported() { + let fallback = persistence_fallback(); + let none = future_registry(&[]); + let all = future_registry(&["a", "b", "c"]); + let envelope = decode(&serde_json::to_vec(&future_sections()).unwrap(), &none, &fallback).unwrap().envelope; + let mut earlier = serde_json::to_value(&envelope).unwrap(); + earlier.as_object_mut().unwrap().remove("section_order"); + for snapshot in earlier["section_snapshots"].as_object_mut().unwrap().values_mut() { + snapshot.as_object_mut().unwrap().remove("projected"); + } + let loaded = decode(&serde_json::to_vec(&earlier).unwrap(), &none, &fallback).unwrap(); + assert!(loaded.notice.is_none()); + let mut restored = loaded.envelope; + restore_quarantine(&mut restored, &all).unwrap(); + assert_eq!(section_ids(&restored), vec![section("s0"), section("s1"), section("s2")]); + let mut duplicate = envelope.clone(); + duplicate.section_order = vec![section("s0"), section("s0")]; + assert_eq!(encode(&duplicate, &none).unwrap_err().rule, Rule::DuplicateId); + let mut excessive = envelope; + excessive.section_order = (0..=MAX_SECTIONS).map(|index| section(&format!("s-{index}"))).collect(); + assert_eq!(encode(&excessive, &none).unwrap_err().rule, Rule::CollectionLimit); + let snapshot = restored.section_snapshots.get_mut(§ion("s0")).unwrap(); + snapshot.projected.as_mut().unwrap().tabs = vec![id("a"); MAX_TABS + 1]; + assert_eq!(encode(&restored, &all).unwrap_err().rule, Rule::CollectionLimit); +} diff --git a/crates/engine/src/schema/mod.rs b/crates/engine/src/schema/mod.rs index 9913457d1..655e62acb 100644 --- a/crates/engine/src/schema/mod.rs +++ b/crates/engine/src/schema/mod.rs @@ -68,6 +68,7 @@ pub mod joints; pub mod libraries; pub mod mass_properties; pub mod motion; +pub mod panels; pub mod print_face; pub mod render; pub mod render_lights; diff --git a/crates/engine/src/schema/panels.rs b/crates/engine/src/schema/panels.rs new file mode 100644 index 000000000..9adf2f5d4 --- /dev/null +++ b/crates/engine/src/schema/panels.rs @@ -0,0 +1,298 @@ +//! Strict external application-layout contracts. These are command parameters, +//! not another persistent layout model. +use schemars::JsonSchema; +use serde::{Deserialize, Serialize}; + +use crate::panels::*; + +/// Discovery and ParamCheck use the exact parser the injected executor uses. +pub struct CommandContract

{ + id: &'static str, + typed: super::TypedContract

, +} +impl

CommandContract

{ + pub const fn new(id: &'static str) -> Self { + Self { id, typed: super::TypedContract::new() } + } +} +impl super::Contract for CommandContract

{ + fn input_schema(&self) -> schemars::Schema { + super::Contract::input_schema(&self.typed) + } + fn allowed_keys(&self) -> std::sync::Arc> { + super::Contract::allowed_keys(&self.typed) + } + fn check(&self, params: &serde_json::Value) -> Vec { + match crate::panels::commands::parse_command(self.id, params) { + Ok(_) => Vec::new(), + Err(reason) => { + // Keep the shared parser's bounds ahead of deserialization, but + // retain ordinary contract paths and unknown-key suggestions. + if reason.rule == Rule::Schema { + let issues = super::Contract::check(&self.typed, params); + if !issues.is_empty() { + return issues; + } + } + vec![super::Issue { path: String::new(), message: reason.to_string(), suggestion: None }] + } + } + } +} + +#[derive(Clone, Debug, Deserialize, JsonSchema)] +#[serde(tag = "type", content = "id", rename_all = "snake_case", deny_unknown_fields)] +pub enum Target { + Workspace(WorkspaceId), + Instance(InstanceId), + Section(SectionId), + NativeHost(HostId), +} +impl From for LayoutTarget { + fn from(value: Target) -> Self { + match value { + Target::Workspace(id) => Self::Workspace(id), + Target::Instance(id) => Self::Instance(id), + Target::Section(id) => Self::Section(id), + Target::NativeHost(id) => Self::NativeHost(id), + } + } +} + +#[derive(Clone, Copy, Debug, Deserialize, JsonSchema)] +#[serde(deny_unknown_fields)] +pub struct OuterSize { + pub width: f32, + pub height: f32, +} +impl From for Size { + fn from(value: OuterSize) -> Self { + Self { width: value.width, height: value.height } + } +} +#[derive(Clone, Copy, Debug, Deserialize, JsonSchema)] +#[serde(deny_unknown_fields)] +pub struct Origin { + pub x: f32, + pub y: f32, +} +impl From for Point { + fn from(value: Origin) -> Self { + Self { x: value.x, y: value.y } + } +} +#[derive(Clone, Debug, Deserialize, JsonSchema)] +#[serde(deny_unknown_fields)] +pub struct ReturnJoin { + pub section: SectionId, + pub index: usize, +} +#[derive(Clone, Debug, Deserialize, JsonSchema)] +#[serde(deny_unknown_fields)] +pub struct ReturnTo { + pub zone: Zone, + pub index: usize, + pub size: OuterSize, + pub collapsed: bool, + #[serde(default)] + pub join: Option, +} +impl From for DockReturn { + fn from(value: ReturnTo) -> Self { + Self { + zone: value.zone, + index: value.index, + size: value.size.into(), + collapsed: value.collapsed, + join: value.join.map(|join| ReturnTab { section: join.section, index: join.index }), + } + } +} +#[derive(Clone, Debug, Deserialize, JsonSchema)] +#[serde(tag = "type", rename_all = "snake_case", deny_unknown_fields)] +pub enum Location { + Dock { zone: Zone }, + Floating { origin: Origin }, + Window { host: HostId, origin: Origin, return_to: ReturnTo }, +} +impl From for SectionLocation { + fn from(value: Location) -> Self { + match value { + Location::Dock { zone } => Self::Dock { zone }, + Location::Floating { origin } => Self::Floating { origin: origin.into() }, + Location::Window { host, origin, return_to } => Self::Window { host, origin: origin.into(), return_to: return_to.into() }, + } + } +} +#[derive(Clone, Debug, Deserialize, JsonSchema)] +#[serde(tag = "type", rename_all = "snake_case", deny_unknown_fields)] +pub enum Placement { + NewSection { section: SectionId, index: usize, location: Location, size: OuterSize }, + JoinTab { section: SectionId, index: usize }, +} +impl From for Destination { + fn from(value: Placement) -> Self { + match value { + Placement::NewSection { section, index, location, size } => { + Self::NewSection { section, index, location: location.into(), size: size.into() } + } + Placement::JoinTab { section, index } => Self::JoinTab { section, index }, + } + } +} + +#[derive(Debug, Deserialize, JsonSchema)] +#[serde(deny_unknown_fields)] +pub struct Empty {} +#[derive(Debug, Deserialize, JsonSchema)] +#[serde(deny_unknown_fields)] +pub struct Open { + pub kind: PanelKind, + pub instance: InstanceId, + pub destination: Option, + pub expected_revision: Option, +} +#[derive(Debug, Deserialize, JsonSchema)] +#[serde(deny_unknown_fields)] +pub struct Select { + pub target: Option, + /// Compatibility selector: exact instance, or a single-instance canonical kind. + pub id: Option, + pub expected_revision: Option, +} +#[derive(Debug, Deserialize, JsonSchema)] +#[serde(deny_unknown_fields)] +pub struct Move { + pub target: Option, + pub id: Option, + pub destination: Placement, + pub expected_revision: Option, +} +#[derive(Debug, Deserialize, JsonSchema)] +#[serde(deny_unknown_fields)] +pub struct Resize { + pub target: Option, + pub id: Option, + pub size: OuterSize, + pub expected_revision: Option, +} +#[derive(Debug, Deserialize, JsonSchema)] +#[serde(deny_unknown_fields)] +pub struct Collapse { + pub target: Option, + pub id: Option, + pub collapsed: bool, + pub expected_revision: Option, +} +#[derive(Debug, Deserialize, JsonSchema)] +#[serde(deny_unknown_fields)] +pub struct Revision { + pub expected_revision: Option, +} +#[derive(Debug, Deserialize, JsonSchema)] +#[serde(deny_unknown_fields)] +pub struct ResizePair { + pub first: SectionId, + pub second: SectionId, + pub first_size: OuterSize, + pub second_size: OuterSize, + pub expected_revision: Option, +} +#[derive(Debug, Deserialize, JsonSchema)] +#[serde(deny_unknown_fields)] +pub struct ResetPair { + pub first: SectionId, + pub second: SectionId, + pub expected_revision: Option, +} +#[derive(Debug, Deserialize, JsonSchema)] +#[serde(deny_unknown_fields)] +pub struct Save { + pub name: String, + #[serde(default)] + pub overwrite: bool, + pub expected_revision: Option, +} +#[derive(Debug, Deserialize, JsonSchema)] +#[serde(deny_unknown_fields)] +pub struct Apply { + pub name: String, + pub expected_revision: Option, +} +#[derive(Debug, Deserialize, JsonSchema)] +#[serde(deny_unknown_fields)] +pub struct WorkspaceSelect { + pub workspace: WorkspaceId, + pub expected_revision: Option, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, JsonSchema)] +#[serde(deny_unknown_fields)] +pub struct WorkspaceSummary { + pub id: WorkspaceId, + pub title_key: String, + pub default_preset: String, + pub has_remembered_layout: bool, +} +#[derive(Debug, Serialize, JsonSchema)] +#[serde(deny_unknown_fields)] +pub struct GetReply { + pub state: LayoutReply, + pub workspaces: Vec, +} +#[derive(Debug, Serialize, JsonSchema)] +#[serde(deny_unknown_fields)] +pub struct ListReply { + pub state: LayoutReply, + pub kinds: Vec, +} +#[derive(Debug, Serialize, JsonSchema)] +#[serde(deny_unknown_fields)] +pub struct SaveReply { + pub name: String, + pub overwritten: bool, + pub state: LayoutReply, +} +#[derive(Debug, Serialize, JsonSchema)] +#[serde(rename_all = "snake_case")] +pub enum WorkspaceSource { + Remembered, + DefaultPreset, + Unchanged, +} +#[derive(Debug, Serialize, JsonSchema)] +#[serde(deny_unknown_fields)] +pub struct WorkspaceReply { + pub previous_workspace: WorkspaceId, + pub source: WorkspaceSource, + pub state: LayoutReply, +} + +/// Successful wire replies have no extensible object fields. Maps (availability) +/// remain maps. Persistence schemas intentionally retain their own opaque fields. +pub fn strict_output() -> schemars::Schema { + let mut schema = super::output_schema_for::(); + fn seal(value: &mut serde_json::Value) { + match value { + serde_json::Value::Object(object) => { + if object.contains_key("properties") { + object.insert("additionalProperties".into(), false.into()); + } + for value in object.values_mut() { + seal(value); + } + } + serde_json::Value::Array(values) => values.iter_mut().for_each(seal), + _ => {} + } + } + if let Some(object) = schema.as_object_mut() { + if object.contains_key("properties") { + object.insert("additionalProperties".into(), false.into()); + } + for value in object.values_mut() { + seal(value); + } + } + schema +} diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 4eb70dce2..f86234e98 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -1182,7 +1182,7 @@ fn only_own_ids_name_commands() { fn unknown_commands_suggest_the_closest_ids() { let mut s = Session::default(); let mut msg = |id: &str| s.execute(id, &serde_json::json!({})).unwrap_err().to_string(); - assert_eq!(msg("file.open"), "unknown command `file.open` (did you mean `doc.open`?)"); + assert_eq!(msg("file.open"), "unknown command `file.open` (did you mean `doc.open` or `panel.open`?)"); assert!(msg("solid.extrud").starts_with("unknown command `solid.extrud` (did you mean `solid.extrude`"), "{}", msg("solid.extrud")); assert!(msg("Extrude").contains("`solid.extrude`"), "{}", msg("Extrude")); assert_eq!(msg("FusionFilletEdgesCommand"), "unknown command `FusionFilletEdgesCommand`"); diff --git a/crates/mcp/src/backend.rs b/crates/mcp/src/backend.rs index dde907c35..d84e36183 100644 --- a/crates/mcp/src/backend.rs +++ b/crates/mcp/src/backend.rs @@ -7,6 +7,8 @@ use std::time::{Duration, Instant}; use serde_json::{Value, json}; use solidcraft_engine::Session; use solidcraft_engine::control_pending; +use solidcraft_engine::panels::ActionSink; +use solidcraft_engine::panels::commands::LayoutCatalogue; use solidcraft_engine::render::StandardView; use solidcraft_engine::schema::ParamCheck; use solidcraft_engine::view::Guides; @@ -559,6 +561,11 @@ impl Remote { /// `strict` refuses a call that breaks its command's contract without sending it, and `warn` /// sends it and adds the issues to the app's reply. fn execute_checked(&mut self, params: Value) -> Result { + if let Some(id) = step_command(¶ms).filter(|id| solidcraft_engine::panels::commands::is_command(id)) { + let empty = json!({}); + solidcraft_engine::panels::commands::parse_command(id, params.get("params").filter(|p| !p.is_null()).unwrap_or(&empty)) + .map_err(solidcraft_engine::panels::commands::error_text)?; + } if self.app_checks() { let params = self.at_level(params); let reply = self.call_once("engine.execute", params, true); @@ -616,6 +623,7 @@ impl Backend for Remote { "control.pending" => self.pending_status(), "engine.execute" if self.param_check != ParamCheck::Off => self.execute_checked(params), "engine.batch" if self.param_check != ParamCheck::Off => self.batch_checked(params), + "engine.script" if self.param_check != ParamCheck::Off => self.call_once(method, self.at_level(params), true), _ => self.call_once(method, params, true), } } @@ -644,6 +652,8 @@ pub struct Headless { pub session: Session, /// Orientation for renders; the camera is refitted to the model every time. pub view: StandardView, + /// Application layout persists across calls, outside Session/document undo. + pub panels: solidcraft_engine::panels::PanelResult, } impl Default for Headless { @@ -662,16 +672,77 @@ impl Headless { } Err(e) => session.log.push(format!("image host unavailable: {e}")), } - Headless { session, view: StandardView::Iso } + Headless { session, view: StandardView::Iso, panels: solidcraft_engine::panels::commands::InMemoryPanelBackend::empty() } } + pub fn with_panels(mut self, panels: solidcraft_engine::panels::commands::InMemoryPanelBackend) -> Self { + self.panels = Ok(panels); + self + } + fn execute_command(&mut self, id: &str, params: &Value) -> Result { + use solidcraft_engine::panels::commands; + if commands::is_command(id) { + self.panels.as_mut().map_err(|reason| commands::error_text(reason.clone()))?.execute(id, params).map_err(commands::error_text) + } else { + self.session.execute(id, params).map_err(|e| e.to_string()) + } + } + fn panel_sequence(&mut self, method: &str, p: &Value, steps: &[Value]) -> Result { + use solidcraft_engine::panels::{Rule, commands, error}; + if steps.len() > 100_000 { + return Err("script too long".into()); + } + if method == "engine.batch" + && let Some(refusal) = solidcraft_engine::batch_preflight::check(steps, self.session.param_check, &[]) + { + return Ok(refusal.reply(steps.len())); + } + let panels = steps.iter().filter(|step| step_command(step).is_some_and(commands::is_command)).count(); + if method == "engine.batch" && p.get("rollback").and_then(Value::as_bool).unwrap_or(true) { + if panels != steps.len() { + return Err(commands::error_text(error( + Rule::Capability, + "atomic mixed document/layout batches are unavailable; use rollback:false or separate transactions", + ))); + } + return self.panels.as_mut().map_err(|reason| commands::error_text(reason.clone()))?.batch(steps).map_err(commands::error_text); + } + let mut results = Vec::new(); + for (i, step) in steps.iter().enumerate() { + let empty = json!({}); + let params = step.get("params").filter(|p| !p.is_null()).unwrap_or(&empty); + let result = step_command(step).ok_or_else(|| "missing command".to_string()).and_then(|id| self.execute_command(id, params)); + match result { + Ok(result) => results.push(result), + Err(error) if method == "engine.batch" => return Ok(commands::sequential_failure(i, step_command(step), error, results)), + Err(error) => return Err(error), + } + } + if method == "engine.batch" { Ok(json!({"completed":results.len(),"results":results,"undone":0})) } else { Ok(json!(results)) } + } +} + +fn step_command(step: &Value) -> Option<&str> { + step.get("command").or_else(|| step.get("id")).and_then(Value::as_str) } fn dim(p: &Value, k: &str, default: f64) -> u32 { p.get(k).and_then(Value::as_f64).filter(|x| x.is_finite()).unwrap_or(default).clamp(16.0, 4096.0) as u32 } -impl Backend for Headless { - fn call(&mut self, method: &str, p: Value) -> Result { +impl Headless { + fn call_at_current_level(&mut self, method: &str, p: Value) -> Result { + if matches!(method, "engine.execute" | "command") && step_command(&p).is_some_and(solidcraft_engine::panels::commands::is_command) { + let empty = json!({}); + return self.execute_command(step_command(&p).unwrap_or_default(), p.get("params").filter(|p| !p.is_null()).unwrap_or(&empty)); + } + if matches!(method, "engine.script" | "engine.batch") + && let Some(steps) = p + .as_array() + .or_else(|| p.get("commands").and_then(Value::as_array)) + .filter(|steps| steps.iter().any(|step| step_command(step).is_some_and(solidcraft_engine::panels::commands::is_command))) + { + return self.panel_sequence(method, &p, steps); + } let s = &mut self.session; let str_p = |k: &str| p.get(k).and_then(Value::as_str); match method { @@ -738,6 +809,19 @@ impl Backend for Headless { other => Err(format!("unknown method `{other}`")), } } +} +impl Backend for Headless { + fn call(&mut self, method: &str, p: Value) -> Result { + let own = self.session.param_check; + if matches!(method, "engine.execute" | "command" | "engine.batch" | "engine.script") + && let Some(value) = p.get("param_check") + { + self.session.param_check = value.as_str().and_then(ParamCheck::parse).ok_or("`param_check` must be off, warn or strict")?; + } + let reply = self.call_at_current_level(method, p); + self.session.param_check = own; + reply + } fn has_ui(&self) -> bool { false } @@ -773,7 +857,10 @@ impl Auto { /// Switch to the app when the session is still empty and one is running. fn look_for_app(&mut self) { - let empty = self.headless.as_ref().is_some_and(|h| h.session.doc.features.is_empty()); + let empty = self.headless.as_ref().is_some_and(|h| { + h.session.doc.features.is_empty() + && h.panels.as_ref().is_ok_and(|panels| panels.service.inspect().revision == 0 && panels.catalogue.state().user_count() == 0) + }); if !empty { return; } diff --git a/crates/mcp/src/tests.rs b/crates/mcp/src/tests.rs index 86832a329..a5df10c95 100644 --- a/crates/mcp/src/tests.rs +++ b/crates/mcp/src/tests.rs @@ -10,6 +10,315 @@ fn server() -> Server { Server::new(Box::new(Headless::default())) } +fn panel_headless() -> Headless { + Headless::new(solidcraft_engine::Session::default()).with_panels(solidcraft_engine::panels::fixture_command_backend().unwrap()) +} +fn panel_mcp_steps() -> Vec { + vec![ + json!({"command":"panel.open","params":{"kind":"fixture.log","instance":"log","destination":{"type":"new_section","section":"logs","index":0, + "location":{"type":"dock","zone":"left"},"size":{"width":280,"height":240}}}}), + json!({"command":"panel.collapse","params":{"target":{"type":"instance","id":"log"},"collapsed":true}}), + ] +} +#[test] +fn headless_panel_single_batch_and_script_keep_one_backend_and_never_change_the_session() { + use crate::Backend; + let mut one = panel_headless(); + let mut batch = panel_headless(); + let mut script = panel_headless(); + let doc = one.session.doc.clone(); + let model = one.session.model.state(); + let before = (one.session.document_id.clone(), one.session.revision, one.session.undo.len(), one.session.is_dirty(), one.session.camera); + for step in panel_mcp_steps() { + one.call("engine.execute", step).unwrap(); + } + batch.call("engine.batch", json!({"commands":panel_mcp_steps()})).unwrap(); + script.call("engine.script", json!({"commands":panel_mcp_steps()})).unwrap(); + let state = one.call("engine.execute", json!({"command":"layout.get"})).unwrap(); + assert_eq!(batch.call("engine.execute", json!({"command":"layout.get"})).unwrap()["state"]["layout"], state["state"]["layout"]); + assert_eq!(script.call("engine.execute", json!({"command":"layout.get"})).unwrap()["state"]["layout"], state["state"]["layout"]); + assert_eq!(state["state"]["capabilities"]["native_windows"], false); + assert_eq!((one.session.document_id.clone(), one.session.revision, one.session.undo.len(), one.session.is_dirty(), one.session.camera), before); + assert!(std::sync::Arc::ptr_eq(&doc, &one.session.doc)); + assert!(std::sync::Arc::ptr_eq(&model, &one.session.model.state())); + one.call("engine.script", json!({"commands":[{"command":"layout.save","params":{"name":"MCP saved"}},{"command":"layout.reset"}]})).unwrap(); + one.call("engine.execute", json!({"command":"layout.apply","params":{"name":"MCP saved"}})).unwrap(); + assert_eq!(one.call("engine.execute", json!({"command":"layout.get"})).unwrap()["state"]["layout"], state["state"]["layout"]); +} +#[test] +fn mcp_panel_tools_publish_structured_errors_and_committed_state_through_shared_backend() { + let mut s = Server::new(Box::new(panel_headless())); + let input = panel_mcp_steps()[0].clone(); + let result = tool(&mut s, "execute", input); + assert_eq!(result["layout"]["instances"][0]["id"], "log"); + let result = tool( + &mut s, + "batch", + json!({"commands":[ + {"command":"panel.collapse","params":{"target":{"type":"instance","id":"log"},"collapsed":true}}, + {"command":"panel.peek","params":{"target":{"type":"instance","id":"log"}}}]}), + ); + assert_eq!(result["completed"], 2); + let result = raw_tool(&mut s, "execute", json!({"command":"panel.focus","params":{"id":"fixture.log"}})); + assert_eq!(result["result"]["isError"], true); + assert_eq!(result["result"]["structuredContent"]["panel_error"]["rule"], "exactly_once"); + let result = raw_tool(&mut s, "execute", json!({"command":"layout.get","params":{"unknown":true}})); + assert_eq!(result["result"]["structuredContent"]["panel_error"]["rule"], "schema"); +} +#[test] +fn headless_catalogue_atomic_batch_failure_keeps_presets_and_layout_and_session_only_is_truthful() { + use crate::Backend; + use solidcraft_engine::panels::{ActionSink, commands::LayoutCatalogue}; + let mut h = panel_headless(); + let state = h.panels.as_ref().unwrap().service.inspect(); + let catalogue = h.panels.as_ref().unwrap().catalogue.state().clone(); + let error = h + .call( + "engine.batch", + json!({"commands":[ + {"command":"layout.save","params":{"name":"Not committed"}}, + {"command":"layout.workspace.select","params":{"workspace":"not-registered"}}]}), + ) + .unwrap_err(); + assert_eq!(solidcraft_engine::panels::commands::structured_error(&error).unwrap()["rule"], "missing_target"); + assert_eq!(h.panels.as_ref().unwrap().service.inspect(), state); + assert_eq!(h.panels.as_ref().unwrap().catalogue.state(), &catalogue); + let mut plain = Headless::default(); + let got = plain.call("engine.execute", json!({"command":"panel.list"})).unwrap(); + assert!(got["kinds"].as_array().unwrap().is_empty()); + assert_eq!(got["state"]["capabilities"]["native_windows"], false); + assert!(plain.call("engine.execute", json!({"command":"layout.reset"})).is_err()); + assert!(solidcraft_engine::Session::default().run_script(&json!({"commands":[{"command":"layout.get"}]})).is_err()); +} + +#[test] +fn auto_backend_keeps_headless_layout_work_even_without_document_features() { + use crate::Backend; + use std::cell::Cell; + use std::rc::Rc; + let mut headless = panel_headless(); + headless.call("engine.execute", json!({"command":"layout.save","params":{"name":"Owned headless layout"}})).unwrap(); + let discoveries = Rc::new(Cell::new(0)); + let seen = discoveries.clone(); + let mut auto = crate::Auto::new( + headless, + Box::new(move || { + seen.set(seen.get() + 1); + None + }), + None, + ); + assert_eq!(auto.call("engine.execute", json!({"command":"layout.get"})).unwrap()["state"]["layout"]["workspace"], "fixture.workspace"); + assert_eq!(discoveries.get(), 0, "owned layout must not be discarded while probing for an app"); +} + +#[test] +fn remote_panel_single_batch_and_script_forward_to_one_authoritative_backend() { + use crate::Backend; + let authoritative = std::sync::Arc::new(std::sync::Mutex::new(solidcraft_engine::panels::fixture_command_backend().unwrap())); + let state = authoritative.clone(); + // This is an authored local transport fixture, never run during implementation. + let (addr, seen) = scripted_app(move |request| { + let mut backend = state.lock().unwrap(); + let params = &request["params"]; + let result = match request["method"].as_str() { + Some("engine.execute") => backend.execute(params["command"].as_str().unwrap(), params.get("params").unwrap_or(&json!({}))), + Some("engine.batch") => backend.batch(params["commands"].as_array().unwrap()), + Some("engine.script") => { + let mut replies = Vec::new(); + for step in params["commands"].as_array().unwrap() { + replies.push(backend.execute(step["command"].as_str().unwrap(), step.get("params").unwrap_or(&json!({}))).unwrap()); + } + Ok(json!(replies)) + } + _ => return json!({"ok":false,"error":"unknown method"}), + }; + match result { + Ok(result) => json!({"ok":true,"result":result}), + Err(reason) => json!({"ok":false,"error":solidcraft_engine::panels::commands::error_text(reason)}), + } + }); + let mut remote = crate::Remote::connect_with_token(&addr, Some("0123456789abcdef0123456789abcdef")).unwrap(); + remote.call("engine.execute", panel_mcp_steps()[0].clone()).unwrap(); + remote + .call( + "engine.batch", + json!({"commands":[panel_mcp_steps()[1].clone(),{"command":"panel.peek","params":{"target":{"type":"instance","id":"log"}}}]}), + ) + .unwrap(); + authoritative.lock().unwrap().execute("panel.collapse", &json!({"target":{"type":"instance","id":"log"},"collapsed":false})).unwrap(); + assert_eq!( + remote.call("engine.execute", json!({"command":"layout.get"})).unwrap()["state"]["layout"]["sections"][0]["collapsed"], + false, + "remote reads external live changes" + ); + remote + .call("engine.script", json!({"commands":[{"command":"layout.save","params":{"name":"Remote saved"}},{"command":"layout.reset"}]})) + .unwrap(); + assert!(remote.call("engine.execute", json!({"command":"layout.get"})).unwrap()["state"]["layout"]["instances"].as_array().unwrap().is_empty()); + let seen = seen.lock().unwrap(); + assert!(seen.1.iter().any(|method| method == "engine.batch")); + assert!(seen.1.iter().any(|method| method == "engine.script")); +} + +#[test] +fn headless_null_params_match_all_panel_routes_and_normal_document_sequences() { + use crate::Backend; + let mut headless = panel_headless(); + let expected = headless.call("engine.execute", json!({"command":"panel.list","params":null})).unwrap(); + for (method, rollback) in [("engine.batch", true), ("engine.batch", false), ("engine.script", false)] { + let reply = headless + .call( + method, + json!({"rollback":rollback,"commands":[ + {"command":"panel.list","params":null},{"command":"layout.get","params":null}, + ]}), + ) + .unwrap(); + let results = if method == "engine.script" { &reply } else { &reply["results"] }; + assert_eq!(results[0], expected); + assert_eq!(results[1]["state"], expected["state"]); + } + for method in ["engine.batch", "engine.script"] { + let previous = headless.session.document_id.clone(); + let reply = headless + .call( + method, + json!({"rollback":false,"commands":[ + {"command":"file.new","params":null},{"command":"panel.list","params":null},{"command":"parameters.list","params":null}, + ]}), + ) + .unwrap(); + assert!(reply.get("failed").is_none(), "{reply}"); + assert_ne!(headless.session.document_id, previous); + } +} + +struct LayoutFallbackBackend { + headless: Headless, + calls: Vec<(String, String)>, +} +impl LayoutFallbackBackend { + fn new() -> Self { + Self { headless: panel_headless(), calls: Vec::new() } + } +} +impl crate::Backend for LayoutFallbackBackend { + fn call(&mut self, method: &str, params: Value) -> Result { + self.calls.push((method.into(), params.get("command").and_then(Value::as_str).unwrap_or_default().into())); + if method == "engine.batch" { + return Err("engine.batch unavailable: fixture has no atomic endpoint".into()); + } + crate::Backend::call(&mut self.headless, method, params) + } + fn has_ui(&self) -> bool { + false + } + fn in_process(&self) -> bool { + true + } + fn describe(&self) -> String { + "synthetic layout fallback boundary".into() + } +} +fn fallback_tool_reply(backend: &mut LayoutFallbackBackend, args: Value) -> (Value, Value) { + let tool = crate::tools::call_tool(backend, "batch", &args); + let body = serde_json::from_str(tool["content"][0]["text"].as_str().unwrap()).unwrap(); + (tool, body) +} + +#[test] +fn atomic_tool_layout_batches_never_emulate_an_unavailable_backend_with_document_undo() { + use solidcraft_engine::panels::{ActionSink, commands::LayoutCatalogue}; + let open = panel_mcp_steps()[0].clone(); + for steps in [ + json!([open.clone()]), + json!([open.clone(),{"command":"parameters.change","params":{"name":"broken","expression":"("}}]), + json!([{"command":"execute","params":{"command":"panel.open","params":open["params"]}}]), + ] { + let mut backend = LayoutFallbackBackend::new(); + let before = backend.headless.panels.as_ref().unwrap().service.inspect(); + let catalogue = backend.headless.panels.as_ref().unwrap().catalogue.state().clone(); + let document = backend.headless.session.doc.clone(); + let model = backend.headless.session.model.state(); + let session = (backend.headless.session.revision, backend.headless.session.undo.len(), backend.headless.session.is_dirty()); + let (tool, body) = fallback_tool_reply(&mut backend, json!({"commands":steps})); + assert_eq!(tool["isError"], true); + assert_eq!(tool["structuredContent"]["panel_error"]["rule"], "capability"); + assert_eq!(body["completed"], 0); + assert_eq!(body["applied"], json!([])); + assert_eq!(body["rolled_back"], false); + assert_eq!(backend.calls, vec![("engine.batch".into(), String::new())], "no checkpoint, inspection or single layout call"); + assert_eq!(backend.headless.panels.as_ref().unwrap().service.inspect(), before); + assert_eq!(backend.headless.panels.as_ref().unwrap().catalogue.state(), &catalogue); + assert!(std::sync::Arc::ptr_eq(&document, &backend.headless.session.doc)); + assert!(std::sync::Arc::ptr_eq(&model, &backend.headless.session.model.state())); + assert_eq!((backend.headless.session.revision, backend.headless.session.undo.len(), backend.headless.session.is_dirty()), session); + } +} + +#[test] +fn oversized_atomic_tool_layout_batch_refuses_before_any_backend_or_checkpoint_call() { + use solidcraft_engine::panels::{ActionSink, commands::LayoutCatalogue}; + let mut backend = LayoutFallbackBackend::new(); + let before = backend.headless.panels.as_ref().unwrap().service.inspect(); + let catalogue = backend.headless.panels.as_ref().unwrap().catalogue.state().clone(); + let document = backend.headless.session.doc.clone(); + let model = backend.headless.session.model.state(); + let args = json!({"commands":[panel_mcp_steps()[0],{"command":"parameters.change","params":{"name":"broken","expression":"x".repeat(solidcraft_engine::MAX_LINE-32768)}}]}); + assert!(args.to_string().len() < solidcraft_engine::MAX_LINE, "fixture fits the incoming line but exceeds the outgoing margin"); + let (tool, body) = fallback_tool_reply(&mut backend, args); + assert_eq!(tool["isError"], true); + assert_eq!(tool["structuredContent"]["panel_error"]["rule"], "collection_limit"); + assert_eq!(body["completed"], 0); + assert_eq!(body["applied"], json!([])); + assert!(backend.calls.is_empty()); + assert_eq!(backend.headless.panels.as_ref().unwrap().service.inspect(), before); + assert_eq!(backend.headless.panels.as_ref().unwrap().catalogue.state(), &catalogue); + assert!(std::sync::Arc::ptr_eq(&document, &backend.headless.session.doc)); + assert!(std::sync::Arc::ptr_eq(&model, &backend.headless.session.model.state())); +} + +#[test] +fn sequential_tool_layout_fallback_truthfully_retains_completed_changes_without_checkpointing() { + use solidcraft_engine::panels::{ActionSink, InstanceId, commands::LayoutCatalogue}; + let mut backend = LayoutFallbackBackend::new(); + let (_, body) = fallback_tool_reply( + &mut backend, + json!({"rollback":false,"commands":[ + panel_mcp_steps()[0],{"command":"parameters.change","params":{"name":"broken","expression":"("}}, + ]}), + ); + assert_eq!(body["ok"], false); + assert_eq!(body["completed"], 1); + assert_eq!(body["applied"], json!([0])); + assert_eq!(body["rolled_back"], false); + assert_eq!(body["undone"], 0); + let panels = backend.headless.panels.as_ref().unwrap(); + assert!(panels.service.layout().instance(&InstanceId::new("log").unwrap()).unwrap().requested_open); + assert_eq!(panels.service.inspect().revision, 1); + assert!(panels.catalogue.state().remembered(&panels.service.layout().workspace).is_some()); + assert!(!backend.calls.iter().any(|(_, command)| command == "edit.checkpoint" || command == "edit.restore_checkpoint")); + assert_eq!(backend.calls.iter().filter(|(_, command)| command == "panel.open").count(), 1); +} + +#[test] +fn document_only_atomic_tool_fallback_keeps_existing_checkpoint_rollback_behavior() { + let mut backend = LayoutFallbackBackend::new(); + let (_, body) = fallback_tool_reply( + &mut backend, + json!({"commands":[ + {"command":"parameters.change","params":{"name":"temporary","expression":1}}, + {"command":"parameters.change","params":{"name":"broken","expression":"("}}, + ]}), + ); + assert_eq!(body["rolled_back"], true, "{body}"); + assert_eq!(body["applied"], json!([])); + assert!(backend.headless.session.doc.param("temporary").is_none()); + assert!(backend.calls.iter().any(|(_, command)| command == "edit.checkpoint")); + assert!(backend.calls.iter().any(|(_, command)| command == "edit.restore_checkpoint")); +} + /// Screenshots are drawn on the GPU by the renderer the host installs (`solidcraft-cli mcp`); the /// tests install the same one. `false`, with the reason printed, on a machine without a GPU /// adapter: the screenshots are then left out of the test. diff --git a/crates/mcp/src/tools.rs b/crates/mcp/src/tools.rs index 10edfe085..08e4ac47f 100644 --- a/crates/mcp/src/tools.rs +++ b/crates/mcp/src/tools.rs @@ -514,6 +514,13 @@ fn text_result(v: &Value, is_error: bool) -> Value { let mut r = json!({"content": [{"type": "text", "text": text}]}); if is_error { r["isError"] = json!(true); + if let Some(reason) = v + .as_str() + .and_then(solidcraft_engine::panels::commands::structured_error) + .or_else(|| v.get("failed").and_then(|failed| failed.get("panel_error")).cloned()) + { + r["structuredContent"] = json!({"panel_error":reason}); + } } r } @@ -1161,12 +1168,36 @@ fn batch(b: &mut dyn Backend, a: &Map) -> Value { } } +fn layout_step(step: &Value) -> bool { + let command = step.get("command").or_else(|| step.get("id")).and_then(Value::as_str).unwrap_or_default(); + let command = if command == "execute" { + step.get("params").and_then(|params| params.get("command")).and_then(Value::as_str).unwrap_or_default() + } else { + command + }; + command.split('.').next().is_some_and(|area| area.eq_ignore_ascii_case("panel") || area.eq_ignore_ascii_case("layout")) +} + +fn atomic_layout_refusal(count: usize, rule: solidcraft_engine::panels::Rule, detail: &str) -> (Value, bool) { + use solidcraft_engine::panels::{commands, error}; + let mut reply = commands::sequential_failure(0, None, commands::error_text(error(rule, detail)), Vec::new()); + reply["ok"] = json!(false); + reply["applied"] = json!([]); + reply["not_run"] = if count <= MAX_BATCH { json!((0..count).collect::>()) } else { json!([]) }; + reply["not_run_count"] = json!(count); + reply["note"] = json!("nothing was run: atomic application layout requires the authoritative backend transaction"); + (reply, true) +} + /// The batch itself: its reply and whether it failed. fn batch_run(b: &mut dyn Backend, a: &Map) -> (Value, bool) { let Some(steps) = a.get("commands").and_then(Value::as_array) else { return (json!("`commands` must be an array of {command, params}"), true); }; if steps.len() > MAX_BATCH { + if a.get("rollback").and_then(Value::as_bool).unwrap_or(true) && steps.iter().any(layout_step) { + return atomic_layout_refusal(steps.len(), solidcraft_engine::panels::Rule::CollectionLimit, "atomic layout batch step count cap"); + } return (json!(format!("batch too long ({} steps, at most {MAX_BATCH})", steps.len())), true); } let rollback = a.get("rollback").and_then(Value::as_bool).unwrap_or(true); @@ -1217,6 +1248,7 @@ fn batch_run(b: &mut dyn Backend, a: &Map) -> (Value, bool) { } } let steps = &mapped; + let atomic_layout = rollback && steps.iter().any(layout_step); // A step the batch would refuse at its turn refuses it now, before anything runs (#5853). // Only where the commands run in this process: a running app may be another version, with // commands this one lacks, and checks the batch against its own registry when it gets it. @@ -1251,7 +1283,8 @@ fn batch_run(b: &mut dyn Backend, a: &Map) -> (Value, bool) { o.insert("timings".into(), Value::Bool(true)); o.insert("profile".into(), Value::Bool(profile)); } - if params.to_string().len() + 64 * 1024 <= solidcraft_engine::MAX_LINE { + let fits_transport = params.to_string().len().saturating_add(64 * 1024) <= solidcraft_engine::MAX_LINE; + if fits_transport { match b.call("engine.batch", params) { Ok(mut r) => { if let Some(failed) = r.get_mut("failed") @@ -1266,6 +1299,7 @@ fn batch_run(b: &mut dyn Backend, a: &Map) -> (Value, bool) { } // Older apps and the headless session, or the app wants the steps one by one. Err(e) if e.starts_with("unknown method") || e.starts_with("engine.batch unavailable") => {} + Err(e) if solidcraft_engine::panels::commands::structured_error(&e).is_some() => return (Value::String(e), true), // Never sent: no app to send it to. Or sent and still running (it was not cancelled): // the `pending` tool gets its result. Err(e) if e.starts_with(crate::backend::NOT_RUNNING) || e.starts_with(STILL_RUNNING) => { @@ -1278,6 +1312,20 @@ fn batch_run(b: &mut dyn Backend, a: &Map) -> (Value, bool) { } } } + // Application layout is outside document checkpoints. Neither an unavailable + // batch endpoint nor an oversized transport request authorizes a sequential + // emulation of an atomic layout/mixed transaction. + if atomic_layout { + return atomic_layout_refusal( + steps.len(), + if fits_transport { solidcraft_engine::panels::Rule::Capability } else { solidcraft_engine::panels::Rule::CollectionLimit }, + if fits_transport { + "authoritative atomic layout batch capability is unavailable" + } else { + "atomic layout batch exceeds transport size cap" + }, + ); + } let start = if rollback { Undo::begin(b) } else { Undo::None }; let mut results = Vec::with_capacity(steps.len()); let mut rows = Vec::new(); diff --git a/crates/ui-egui/src/agent_cursor.rs b/crates/ui-egui/src/agent_cursor.rs index bf49fe740..09590e21f 100644 --- a/crates/ui-egui/src/agent_cursor.rs +++ b/crates/ui-egui/src/agent_cursor.rs @@ -272,6 +272,9 @@ fn batch_targets(steps: &[Value]) -> Vec<(Pos2, &'static str)> { /// The places a command's parameters pick, in the world: [x, y, z] points (faces, edges, /// vertices, positions), active-sketch [x, y] points, and a new sketch's plane. pub fn picks(app: &SolveApp, command: &str, params: &Value) -> Vec { + if solidcraft_engine::panels::commands::is_command(command) { + return Vec::new(); + } let id = solidcraft_engine::find_command(command).map_or(command, |c| c.id); let mut out = Vec::new(); if id == "sketch.create" diff --git a/crates/ui-egui/src/command_help.rs b/crates/ui-egui/src/command_help.rs index 3b20b3465..f3b7c67e4 100644 --- a/crates/ui-egui/src/command_help.rs +++ b/crates/ui-egui/src/command_help.rs @@ -91,6 +91,11 @@ pub const DOCUMENTED: &[&str] = &[ "joint.reach", "joint.rigid_group", "joint.screw", + "layout.apply", + "layout.get", + "layout.reset", + "layout.save", + "layout.workspace.select", "library.apply", "library.export", "library.inspect", @@ -101,6 +106,21 @@ pub const DOCUMENTED: &[&str] = &[ "motion.trace", "occurrence.ground", "occurrence.move", + "panel.activate", + "panel.close", + "panel.collapse", + "panel.dismiss", + "panel.float", + "panel.focus", + "panel.list", + "panel.move", + "panel.native_close", + "panel.open", + "panel.peek", + "panel.popout", + "panel.reset_pair", + "panel.resize", + "panel.resize_pair", "parameters.change", "parameters.export", "parameters.graph", diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs index 6208cd199..45edee7e8 100644 --- a/crates/ui-egui/src/control.rs +++ b/crates/ui-egui/src/control.rs @@ -176,7 +176,12 @@ fn ok(v: Value) -> Outcome { Outcome::Done(json!({"ok": true, "result": v})) } fn err(e: impl std::fmt::Display) -> Outcome { - Outcome::Done(json!({"ok": false, "error": e.to_string()})) + let text = e.to_string(); + let mut reply = json!({"ok": false, "error": text}); + if let Some(reason) = solidcraft_engine::panels::commands::structured_error(&text) { + reply["panel_error"] = reason; + } + Outcome::Done(reply) } fn wrap(r: Result) -> Outcome { match r { @@ -266,6 +271,10 @@ fn key_from(name: &str) -> Option { /// Run one command as `engine.execute` does: through `app.run`, then the first-body fit and the /// camera the command asked for. fn execute(app: &mut SolveApp, id: &str, params: Value) -> Result { + if solidcraft_engine::panels::commands::is_command(id) { + // No first-body meshing, camera-follow or fit tail for application layout. + return app.run(id, params); + } // User bindings live in the UI. A bridged agent needs the same key the menus show, // including null for a cleared binding; the standalone engine keeps its defaults. if id == "engine.commands" { @@ -379,6 +388,38 @@ fn batch(app: &mut SolveApp, p: &Value) -> Outcome { let Some(steps) = p.get("commands").and_then(Value::as_array).filter(|s| s.len() <= MAX_BATCH) else { return err(format!("engine.batch: commands must be an array of at most {MAX_BATCH} steps")); }; + let panels = steps.iter().filter(|step| command(step).is_some_and(solidcraft_engine::panels::commands::is_command)).count(); + if panels > 0 { + if let Some(why) = batch_refusal(steps) { + return err(why); + } + if let Some(refusal) = solidcraft_engine::batch_preflight::check(steps, app.session.param_check, &["view.pick"]) { + return ok(refusal.reply(steps.len())); + } + let rollback = p.get("rollback").and_then(Value::as_bool).unwrap_or(true); + if rollback { + if panels != steps.len() { + return err(solidcraft_engine::panels::commands::error_text(solidcraft_engine::panels::error( + solidcraft_engine::panels::Rule::Capability, + "atomic mixed document/layout batches are unavailable; use rollback:false or separate transactions", + ))); + } + return wrap(app.run_panel_batch(steps).map_err(solidcraft_engine::panels::commands::error_text)); + } + // Explicit sequential mode has per-command atomicity and no document + // checkpoint; previous application changes are truthfully retained. + let mut results = Vec::new(); + for (i, step) in steps.iter().enumerate() { + let result = command(step) + .ok_or_else(|| "missing command".to_string()) + .and_then(|id| execute(app, id, step.get("params").cloned().filter(|p| !p.is_null()).unwrap_or(json!({})))); + match result { + Ok(result) => results.push(result), + Err(error) => return ok(solidcraft_engine::panels::commands::sequential_failure(i, command(step), error, results)), + } + } + return ok(json!({"completed":results.len(),"results":results,"undone":0})); + } // (With the agent cursor shown, the pointer has already acted out a short summary of the // batch: `agent_cursor::intercept`.) if let Some(why) = batch_refusal(steps) { @@ -684,6 +725,30 @@ fn dispatch(app: &mut SolveApp, ctx: &egui::Context, method: &str, p: &Value) -> if let Some(c) = steps.and_then(|steps| steps.iter().find_map(switches_design)) { return err(format!("engine.script unavailable: {c} switches to another design (send it on its own)")); } + if let Some(steps) = + steps.filter(|steps| steps.iter().any(|step| command(step).is_some_and(solidcraft_engine::panels::commands::is_command))) + { + if steps.len() > 100_000 { + return err("script too long"); + } + let mut results = Vec::new(); + for (i, step) in steps.iter().enumerate() { + let result = command(step) + .ok_or_else(|| "missing command".to_string()) + .and_then(|id| execute(app, id, step.get("params").cloned().filter(|p| !p.is_null()).unwrap_or(json!({})))); + match result { + Ok(result) => results.push(result), + Err(error) => { + let mut reply = json!({"ok":false,"error":error,"step":i + 1}); + if let Some(reason) = solidcraft_engine::panels::commands::structured_error(&error) { + reply["panel_error"] = reason; + } + return Outcome::Done(reply); + } + } + } + return ok(json!(results)); + } let mut replaced = false; let r = app .session @@ -1466,6 +1531,166 @@ pub(crate) fn write_screenshot(image: &egui::ColorImage, path: &str) -> Result<( #[cfg(test)] mod tests { + fn panel_command_app() -> crate::SolveApp { + use crate::panel_runtime::*; + let h = PanelMountHarness::new(false).unwrap(); + let catalogue = solidcraft_engine::panels::fixture_command_catalogue(h.runtime.layout().registry()).unwrap(); + let mut app = crate::SolveApp::new(solidcraft_engine::Session::default(), Default::default()); + app.enable_panel_runtime(h.runtime, Box::::default()).unwrap(); + app.panel_runtime_mut().unwrap().set_command_adapters(Box::new(catalogue), Box::new(FakeNativeAdapter::new(false))).unwrap(); + app + } + fn panel_control(app: &mut crate::SolveApp, method: &str, params: serde_json::Value) -> serde_json::Value { + let (request, _) = super::ControlRequest::new(method, params); + match super::handle(app, &egui::Context::default(), &request) { + super::Outcome::Done(reply) => reply, + _ => panic!("unexpected screenshot"), + } + } + fn panel_steps() -> Vec { + vec![ + json!({"command":"panel.open","params":{"kind":"fixture.log","instance":"log","destination":{"type":"new_section","section":"logs","index":0, + "location":{"type":"dock","zone":"left"},"size":{"width":280,"height":240}}}}), + json!({"command":"panel.collapse","params":{"target":{"type":"instance","id":"log"},"collapsed":true}}), + ] + } + #[test] + fn panel_control_single_atomic_batch_and_script_share_live_runtime_without_geometry_or_camera_work() { + use solidcraft_engine::panels::ActionSink; + let mut single = panel_command_app(); + let mut batch = panel_command_app(); + let mut script = panel_command_app(); + // A one-body design with a deliberately different camera exercises the + // old first-body-fit condition, rather than making it vacuously false. + for app in [&mut single, &mut batch, &mut script] { + app.run("solid.box", json!({"length":10,"width":10,"height":10})).unwrap(); + app.cam.distance *= 1.5; + app.session.mark_saved(); + } + let doc = single.session.doc.clone(); + let model = single.session.model.state(); + let camera = single.cam; + let meshes: Vec<_> = model.bodies.iter().map(|body| body.cached_mesh()).collect(); + let invariant = (single.session.document_id.clone(), single.session.revision, single.session.undo.len(), single.session.is_dirty()); + for step in panel_steps() { + assert_eq!(panel_control(&mut single, "engine.execute", step)["ok"], true); + } + assert_eq!(panel_control(&mut batch, "engine.batch", json!({"commands":panel_steps(),"param_check":"strict"}))["ok"], true); + assert_eq!(panel_control(&mut script, "engine.script", json!({"commands":panel_steps(),"param_check":"strict"}))["ok"], true); + let live = single.panel_runtime().unwrap().layout().inspect(); + assert_eq!(batch.panel_runtime().unwrap().layout().layout(), &live.layout); + assert_eq!(script.panel_runtime().unwrap().layout().layout(), &live.layout); + assert_eq!(panel_control(&mut single, "engine.execute", json!({"command":"layout.get"}))["result"]["state"]["revision"], live.revision); + assert!(crate::agent_cursor::picks(&single, "panel.open", &panel_steps()[0]["params"]).is_empty()); + assert_eq!(single.cam, camera); + assert_eq!((single.session.document_id.clone(), single.session.revision, single.session.undo.len(), single.session.is_dirty()), invariant); + assert!(std::sync::Arc::ptr_eq(&doc, &single.session.doc)); + assert!(std::sync::Arc::ptr_eq(&model, &single.session.model.state())); + for (old, new) in meshes.iter().zip(single.session.model.state().bodies.iter().map(|body| body.cached_mesh())) { + match (old, new) { + (Some(a), Some(b)) => assert!(std::sync::Arc::ptr_eq(a, &b)), + (None, None) => {} + _ => panic!("layout changed tessellation cache"), + } + } + } + #[test] + fn panel_control_reports_structured_missing_capability_unknown_fields_and_lifecycle_batch_errors() { + use solidcraft_engine::panels::ActionSink; + let mut disabled = crate::SolveApp::new(solidcraft_engine::Session::default(), Default::default()); + let reply = panel_control(&mut disabled, "engine.execute", json!({"command":"layout.get"})); + assert_eq!(reply["ok"], false); + assert_eq!(reply["panel_error"]["rule"], "capability"); + let mut app = panel_command_app(); + for check in ["off", "warn", "strict"] { + let reply = panel_control(&mut app, "engine.execute", json!({"command":"panel.list","params":{"unknown":true},"param_check":check})); + assert_eq!(reply["ok"], false); + assert_eq!(reply["panel_error"]["rule"], "schema"); + assert_eq!(reply["param_check"], check); + } + panel_control(&mut app, "engine.execute", panel_steps()[0].clone()); + let before = app.panel_runtime().unwrap().layout().inspect(); + let reply = panel_control( + &mut app, + "engine.batch", + json!({"commands":[ + {"command":"panel.close","params":{"target":{"type":"instance","id":"log"}}}, + {"command":"panel.open","params":{"kind":"fixture.log","instance":"log"}}]}), + ); + assert_eq!(reply["ok"], false); + assert_eq!(reply["panel_error"]["rule"], "lifecycle"); + assert_eq!(app.panel_runtime().unwrap().layout().inspect(), before); + } + #[test] + fn panel_control_catalogue_batches_and_scripts_retain_memory_and_refuse_unsupported_atomic_domains() { + let mut app = panel_command_app(); + panel_control(&mut app, "engine.execute", panel_steps()[0].clone()); + let reply = panel_control( + &mut app, + "engine.batch", + json!({"commands":[ + {"command":"layout.save","params":{"name":"Control saved"}}, + {"command":"layout.reset"}, {"command":"layout.apply","params":{"name":"Control saved"}}, {"command":"layout.get"}]}), + ); + assert_eq!(reply["ok"], true, "{reply}"); + assert_eq!(reply["result"]["completed"], 4); + assert_eq!(reply["result"]["results"][3]["state"]["layout"]["instances"][0]["id"], "log"); + let mixed = json!({"commands":[{"command":"layout.get"},{"command":"file.new"}]}); + let before = app.session.document_id.clone(); + let reply = panel_control(&mut app, "engine.batch", mixed); + assert_eq!(reply["panel_error"]["rule"], "capability"); + assert_eq!(app.session.document_id, before); + let reply = panel_control( + &mut app, + "engine.script", + json!({"commands":[ + {"command":"layout.workspace.select","params":{"workspace":"fixture.other"}}, + {"command":"layout.apply","params":{"name":"Control saved"}}, {"command":"layout.get"}]}), + ); + assert_eq!(reply["ok"], true, "{reply}"); + assert_eq!(reply["result"][2]["state"]["layout"]["workspace"], "fixture.other"); + } + + #[test] + fn null_panel_params_match_single_atomic_sequential_and_script_routes() { + let mut app = panel_command_app(); + let expected = app.run("panel.list", json!({})).unwrap(); + assert_eq!(app.run("panel.list", serde_json::Value::Null).unwrap(), expected); + let single = panel_control(&mut app, "engine.execute", json!({"command":"panel.list","params":null})); + assert_eq!(single["result"], expected); + for (method, rollback) in [("engine.batch", true), ("engine.batch", false), ("engine.script", false)] { + let reply = panel_control( + &mut app, + method, + json!({"rollback":rollback,"commands":[ + {"command":"panel.list","params":null},{"command":"layout.get","params":null}, + ]}), + ); + assert_eq!(reply["ok"], true, "{method}: {reply}"); + let results = if method == "engine.script" { &reply["result"] } else { &reply["result"]["results"] }; + assert_eq!(results[0], expected, "{method}"); + assert_eq!(results[1]["state"], expected["state"]); + } + } + + #[test] + fn null_normal_document_params_remain_accepted_in_panel_containing_sequences() { + for method in ["engine.batch", "engine.script"] { + let mut app = panel_command_app(); + let previous = app.session.document_id.clone(); + let reply = panel_control( + &mut app, + method, + json!({"rollback":false,"commands":[ + {"command":"file.new","params":null},{"command":"panel.list","params":null},{"command":"parameters.list","params":null}, + ]}), + ); + assert_eq!(reply["ok"], true, "{reply}"); + assert!(reply["result"].get("failed").is_none(), "{reply}"); + assert_ne!(app.session.document_id, previous); + assert_eq!(app.panel_runtime().unwrap().environment().document.as_ref().unwrap().0, app.session.document_id); + } + } #[test] fn blur_control_validates_before_mutation_and_reports_no_gpu() { let mut h = crate::scenario::Harness::new(); diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index cf021e91c..f534ca6dd 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -194,6 +194,7 @@ pub mod network_prompt; pub mod op_auto; pub mod open_elsewhere; pub(crate) mod open_meshing; +pub mod panel_runtime; pub mod params_dialog; pub mod personal_sheet_rules; pub(crate) mod pick_index; @@ -509,6 +510,8 @@ pub(crate) enum EscapeOwner { } pub struct SolveApp { + /// Common panel foundation, internal opt-in; stays on the app across document tabs. + pub(crate) panel_runtime: Option, pub blur: blur::State, pub(crate) viewport_status: ui_kit::StatusPresentation, pub(crate) viewport_status_fixture: viewport_status_fixture::Fixture, @@ -784,6 +787,7 @@ impl SolveApp { #[cfg(not(target_arch = "wasm32"))] solidcraft_engine::slicer_files::clean_old(); let mut app = SolveApp { + panel_runtime: None, viewport_status: Default::default(), blur: Default::default(), viewport_status_fixture: Default::default(), @@ -1159,6 +1163,9 @@ impl SolveApp { /// Run a command programmatically (JSON parameters, no dialogs). pub fn run(&mut self, id: &str, params: Value) -> Result { + if solidcraft_engine::panels::commands::is_command(id) { + return self.run_panel_command(id, ¶ms).map_err(solidcraft_engine::panels::commands::error_text); + } if self.file_load.busy() || self.file_picker.is_some() || self.saving.is_some() { return Err("a file operation is in progress".into()); } @@ -1550,6 +1557,12 @@ impl SolveApp { } fn start_with_variant_memory(&mut self, id: &str, remember_variant: bool, opener: Option, section_edit: bool) { + if solidcraft_engine::panels::commands::is_command(id) { + if let Err(why) = self.run(id, json!({})) { + self.set_status(why, true); + } + return; + } self.tree.clear_folder_pick(); if id == "timeline.play" { if let Err(why) = self.run(id, json!({})) { @@ -2794,6 +2807,7 @@ impl SolveApp { /// Per-frame logic before layout. pub fn logic(&mut self, ctx: &egui::Context) { + panel_runtime::tick_app(self); // Sleep/wake often skips frames without a device-lost signal; refresh egui GPU textures // when the frame clock jumps so the chrome is not stuck blank (#8749). let frame_time = ctx.input(|i| i.time); diff --git a/crates/ui-egui/src/panel_runtime/app.rs b/crates/ui-egui/src/panel_runtime/app.rs new file mode 100644 index 000000000..af9a0ca33 --- /dev/null +++ b/crates/ui-egui/src/panel_runtime/app.rs @@ -0,0 +1,211 @@ +use solidcraft_engine::Session; +use solidcraft_engine::panels::*; + +use super::*; + +/// Later content adapters supply their own services. The app integration exposes +/// only an immutable Session during refresh; a layout tick cannot run a document +/// command. Explicit content commands stay on the separate supplied sink. +pub trait AppPanelServices { + fn refresh_read_only(&mut self, session: &Session) -> PanelResult<()>; + fn services(&mut self) -> ContentServices<'_>; +} + +pub struct AppPanelRuntime { + runtime: PanelRuntime, + services: Box, + last_error: Option, + catalogue: Box, + native: Box, + adapters_set: bool, +} +impl AppPanelRuntime { + pub fn new(runtime: PanelRuntime, services: Box) -> Self { + Self { + runtime, + services, + last_error: None, + catalogue: Box::::default(), + native: Box::new(UnavailableNative), + adapters_set: false, + } + } + pub fn last_error(&self) -> Option<&PanelError> { + self.last_error.as_ref() + } + pub fn runtime(&self) -> &PanelRuntime { + &self.runtime + } + /// Internal capability injection. Production preferences/native realization + /// remain peer work. Installation is once-only and precedes native hosts. + pub fn set_command_adapters(&mut self, catalogue: Box, native: Box) -> PanelResult<()> { + if self.adapters_set { + return Err(error(Rule::Lifecycle, "application panel adapters are already installed")); + } + if self.runtime.layout().layout().sections.iter().any(|s| matches!(&s.location, SectionLocation::Window { .. })) { + return Err(error(Rule::Lifecycle, "cannot replace adapters with live native hosts")); + } + self.catalogue = catalogue; + self.native = native; + self.adapters_set = true; + Ok(()) + } + /// Actual application boundaries refresh the current document/model context + /// even when no frame tick ran between two sequential programmatic steps. + fn refresh_context(&mut self, session: &Session) -> PanelResult<()> { + self.services.refresh_read_only(session)?; + let mut environment = self.runtime.environment().clone(); + environment.document = Some(DocumentId::new(session.document_id.clone())?); + let services = self.services.services(); + self.runtime.set_environment(environment, services.local)?; + self.runtime.refresh_context(services.models, services.local) + } + pub fn command(&mut self, session: &Session, id: &str, params: &serde_json::Value) -> PanelResult { + self.refresh_context(session)?; + let registry = self.runtime.layout().registry().clone(); + let mut services = self.services.services(); + let mut sink = RuntimeActionSink { runtime: &mut self.runtime, native: self.native.as_mut(), services: &mut services }; + commands::execute( + id, + params, + &mut commands::PanelCommandContext { + sink: &mut sink, + registry: ®istry, + catalogue: self.catalogue.as_mut(), + web: cfg!(target_arch = "wasm32"), + }, + ) + } + pub fn command_batch(&mut self, session: &Session, steps: &[serde_json::Value]) -> PanelResult { + // Unsupported intent mixtures refuse before even context lifecycle or + // availability publication; supported calls then read current context. + commands::preflight_batch(steps, &self.runtime.layout().layout().workspace)?; + self.refresh_context(session)?; + let registry = self.runtime.layout().registry().clone(); + let mut services = self.services.services(); + let mut sink = RuntimeActionSink { runtime: &mut self.runtime, native: self.native.as_mut(), services: &mut services }; + commands::execute_batch( + steps, + &mut commands::PanelCommandContext { + sink: &mut sink, + registry: ®istry, + catalogue: self.catalogue.as_mut(), + web: cfg!(target_arch = "wasm32"), + }, + ) + } + /// All forwarding borrows the exact provider injected at enablement. + fn with_services(&mut self, use_services: impl FnOnce(&mut PanelRuntime, &mut ContentServices<'_>) -> PanelResult) -> PanelResult { + let mut services = self.services.services(); + use_services(&mut self.runtime, &mut services) + } + pub fn dispatch(&mut self, session: &Session, action: LayoutAction) -> PanelResult { + self.refresh_context(session)?; + let mut services = self.services.services(); + RuntimeActionSink { runtime: &mut self.runtime, native: self.native.as_mut(), services: &mut services }.dispatch(action) + } + pub fn mount(&mut self, resolved: &ResolvedLayout, host: &mut dyn PanelHost) -> PanelResult<()> { + self.with_services(|runtime, services| runtime.mount(resolved, host, services)) + } + pub fn content_action(&mut self, session: &Session, instance: &InstanceId, action: &ControlId) -> PanelResult<()> { + self.refresh_context(session)?; + self.with_services(|runtime, services| runtime.content_action(instance, action, services)) + } + pub fn tick(&mut self, session: &Session) -> PanelResult<()> { + let refresh = self.services.refresh_read_only(session); + let mut environment = self.runtime.environment().clone(); + environment.document = Some(DocumentId::new(session.document_id.clone())?); + let mut services = self.services.services(); + self.runtime.set_environment(environment, services.local)?; + let update = self.runtime.update(&mut services); + refresh.and(update) + } + /// Explicit teardown preflights all owners before any controller is destroyed. + pub fn shutdown(&mut self) -> PanelResult<()> { + if self.runtime.layout().layout().sections.iter().any(|section| matches!(§ion.location, SectionLocation::Window { .. })) { + return Err(error(Rule::Lifecycle, "redock native panels before disabling their application adapter")); + } + let services = self.services.services(); + self.runtime.shutdown(services.local) + } +} + +impl crate::SolveApp { + pub fn run_panel_command(&mut self, id: &str, params: &serde_json::Value) -> PanelResult { + // Parse even without a runtime: hostile/unknown fields never become a + // misleading capability success or reach the document command path. + match self.panel_runtime.as_mut() { + Some(integration) => integration.command(&self.session, id, params), + None => { + commands::parse_command(id, params)?; + Err(error(Rule::Capability, "application panel runtime is not enabled")) + } + } + } + pub fn run_panel_batch(&mut self, steps: &[serde_json::Value]) -> PanelResult { + self.panel_runtime + .as_mut() + .ok_or_else(|| error(Rule::Capability, "application panel runtime is not enabled"))? + .command_batch(&self.session, steps) + } + /// Internal opt-in only: no preference, control method, command or default change. + pub fn enable_panel_runtime(&mut self, runtime: PanelRuntime, services: Box) -> PanelResult<()> { + if self.panel_runtime.is_some() { + return Err(error(Rule::Lifecycle, "panel runtime already enabled")); + } + let mut integration = AppPanelRuntime::new(runtime, services); + integration.tick(&self.session)?; + self.panel_runtime = Some(integration); + Ok(()) + } + pub fn panel_runtime(&self) -> Option<&PanelRuntime> { + self.panel_runtime.as_ref().map(|integration| &integration.runtime) + } + pub fn panel_runtime_mut(&mut self) -> Option<&mut AppPanelRuntime> { + self.panel_runtime.as_mut() + } + pub fn dispatch_panel_layout(&mut self, action: LayoutAction) -> PanelResult { + self.panel_runtime.as_mut().ok_or_else(|| error(Rule::Lifecycle, "panel runtime disabled"))?.dispatch(&self.session, action) + } + pub fn mount_panels(&mut self, resolved: &ResolvedLayout, host: &mut dyn PanelHost) -> PanelResult<()> { + self.panel_runtime.as_mut().ok_or_else(|| error(Rule::Lifecycle, "panel runtime disabled"))?.mount(resolved, host) + } + pub fn panel_content_action(&mut self, instance: &InstanceId, action: &ControlId) -> PanelResult<()> { + self.panel_runtime.as_mut().ok_or_else(|| error(Rule::Lifecycle, "panel runtime disabled"))?.content_action(&self.session, instance, action) + } + pub fn tick_panel_runtime(&mut self) -> PanelResult<()> { + self.panel_runtime.as_mut().ok_or_else(|| error(Rule::Lifecycle, "panel runtime disabled"))?.tick(&self.session) + } + pub fn disable_panel_runtime(&mut self) -> PanelResult<()> { + if let Some(integration) = &mut self.panel_runtime { + integration.shutdown()?; + } + self.panel_runtime = None; + Ok(()) + } +} + +/// No platform window is claimed without an injected native implementation. +struct UnavailableNative; +impl NativeHostAdapter for UnavailableNative { + fn capabilities(&self) -> HostCapabilities { + HostCapabilities::default() + } + fn prepare(&self, effects: &[HostEffect]) -> PanelResult<()> { + if effects + .iter() + .any(|effect| matches!(effect, HostEffect::CreateNative { .. } | HostEffect::RebindNative { .. } | HostEffect::ReleaseNative { .. })) + { + return Err(error(Rule::Capability, "native adapter not injected")); + } + Ok(()) + } + fn commit(&mut self, _effects: &[HostEffect]) {} +} + +pub(crate) fn tick_app(app: &mut crate::SolveApp) { + if let Some(integration) = &mut app.panel_runtime { + // Errors remain inspectable without inventing untranslated production UI. + integration.last_error = integration.tick(&app.session).err(); + } +} diff --git a/crates/ui-egui/src/panel_runtime/fixtures.rs b/crates/ui-egui/src/panel_runtime/fixtures.rs new file mode 100644 index 000000000..d7cdc9775 --- /dev/null +++ b/crates/ui-egui/src/panel_runtime/fixtures.rs @@ -0,0 +1,571 @@ +//! Shared executable mount/editor/native fixtures. These are synthetic specimens, +//! not production panel migrations, UI commands or evidence of visual correctness. +use std::cell::RefCell; +use std::collections::{BTreeMap, VecDeque}; +use std::rc::Rc; + +use solidcraft_engine::panels::*; + +use super::*; + +#[derive(Clone, Debug, Default)] +pub struct FixtureState { + pub updates: u64, + pub renders: u64, + pub cancels: u64, + pub reopens: u64, + pub applies: u64, + pub finishes: u64, + pub reparents: u64, + pub destroys: u64, + pub transaction_live: bool, + pub reject_cancel: bool, + pub reject_reopen: bool, + pub fail_update: bool, + pub invalid_availability: bool, + pub last_state: Option, + pub draft: String, + pub last_clip: Option, +} + +#[derive(Clone, Default)] +pub struct FixtureProbe { + states: Rc>>>>, +} +impl FixtureProbe { + pub fn state(&self, key: &ControllerKey) -> PanelResult { + let states = self.states.try_borrow().map_err(|_| error(Rule::Lifecycle, "fixture probe borrowed"))?; + let state = states.get(key).ok_or_else(|| error(Rule::MissingTarget, "fixture controller missing"))?; + let value = state.try_borrow().map_err(|_| error(Rule::Lifecycle, "fixture state borrowed"))?.clone(); + Ok(value) + } + pub fn edit(&self, key: &ControllerKey, edit: impl FnOnce(&mut FixtureState)) -> PanelResult<()> { + let states = self.states.try_borrow().map_err(|_| error(Rule::Lifecycle, "fixture probe borrowed"))?; + let state = states.get(key).ok_or_else(|| error(Rule::MissingTarget, "fixture controller missing"))?; + let mut value = state.try_borrow_mut().map_err(|_| error(Rule::Lifecycle, "fixture state borrowed"))?; + edit(&mut value); + if value.draft.len() > 4096 { + value.draft = value.draft.chars().take(1024).collect(); + } + Ok(()) + } + fn publish(&self, key: ControllerKey, state: Rc>) -> PanelResult<()> { + let mut states = self.states.try_borrow_mut().map_err(|_| error(Rule::Lifecycle, "fixture probe borrowed"))?; + if states.len() >= MAX_RETAINED_CONTROLLERS && !states.contains_key(&key) { + return Err(error(Rule::CollectionLimit, "fixture state cap")); + } + states.insert(key, state); + Ok(()) + } +} + +struct FixtureController { + state: Rc>, + editor: bool, + instance: InstanceId, + probe: FixtureProbe, + key: ControllerKey, +} + +impl PanelController for FixtureController { + fn availability(&self, owner: &ContentOwner, models: &dyn PanelModels) -> Availability { + if self.state.try_borrow().is_ok_and(|state| state.invalid_availability) { + return Availability::Unavailable { reason: String::new() }; + } + if self.editor { + match models.read(owner, "fixture.editable") { + Ok(serde_json::Value::Bool(true)) => Availability::Available, + _ => Availability::Unavailable { reason: "synthetic editor requires editable document context".into() }, + } + } else { + Availability::Available + } + } + fn update(&mut self, _owner: &ContentOwner, _services: &mut ContentServices<'_>) -> PanelResult<()> { + self.probe.publish(self.key.clone(), self.state.clone())?; + let mut state = self.state.try_borrow_mut().map_err(|_| error(Rule::Lifecycle, "fixture state borrowed"))?; + state.updates = state.updates.saturating_add(1); + if state.fail_update { + return Err(error(Rule::Lifecycle, "synthetic service update failed")); + } + Ok(()) + } + fn presentation(&self) -> PanelPresentation { + let summary = self.state.try_borrow().ok().map(|s| (s.updates, s.transaction_live)); + PanelPresentation { + title: format!("Specimen {}", self.instance.0), + icon: "panel".into(), + status: summary.map(|(updates, live)| format!("updates={updates}; transaction={live}")), + attention: self.editor, + actions: if self.editor { + ["apply", "cancel", "finish"] + .into_iter() + .map(|id| RuntimeAction { id: ControlId(id.into()), label: id.into(), enabled: true, disabled_reason: None }) + .collect() + } else { + Vec::new() + }, + } + } + fn prepare_lifecycle(&self, event: &LifecycleEvent) -> PanelResult<()> { + let state = self.state.try_borrow_mut().map_err(|_| error(Rule::Lifecycle, "fixture state borrowed"))?; + if self.editor && state.transaction_live && state.reject_cancel && matches!(event, LifecycleEvent::Close | LifecycleEvent::DestroyOwner) { + return Err(error(Rule::Lifecycle, "synthetic editor cannot safely cancel")); + } + if state.reject_reopen && matches!(event, LifecycleEvent::Reopen) { + return Err(error(Rule::Lifecycle, "synthetic controller cannot safely reopen")); + } + Ok(()) + } + fn lifecycle(&mut self, event: &LifecycleEvent) { + // Publishing diagnostics happens after commit, never in a staged factory. + let _ = self.probe.publish(self.key.clone(), self.state.clone()); + // This fixture's preflight prohibits concurrent borrows. An adapter must + // make commit infallible; it must not defer fallible work into this hook. + if let Ok(mut state) = self.state.try_borrow_mut() { + match event { + LifecycleEvent::Close => { + if self.editor && state.transaction_live { + state.cancels = state.cancels.saturating_add(1); + state.transaction_live = false; + } + } + LifecycleEvent::Reopen => { + state.reopens = state.reopens.saturating_add(1); + if self.editor { + state.transaction_live = true; + } + } + LifecycleEvent::Reparent => state.reparents = state.reparents.saturating_add(1), + LifecycleEvent::DestroyOwner => { + if self.editor && state.transaction_live { + state.cancels = state.cancels.saturating_add(1); + state.transaction_live = false; + } + state.destroys = state.destroys.saturating_add(1); + state.last_state = Some(ControllerState { destroyed: true, ..ControllerState::default() }); + } + LifecycleEvent::State(value) => state.last_state = Some(value.clone()), + } + } + } + fn render(&mut self, slot: ContentSlot, ui: &mut egui::Ui, _context: &PanelContext, _services: &mut ContentServices<'_>) -> PanelResult<()> { + if slot == ContentSlot::Body { + let mut state = self.state.try_borrow_mut().map_err(|_| error(Rule::Lifecycle, "fixture state borrowed"))?; + state.renders = state.renders.saturating_add(1); + state.last_clip = Some(ui.clip_rect()); + } + Ok(()) + } + fn action(&mut self, owner: &ContentOwner, action: &ControlId, services: &mut ContentServices<'_>) -> PanelResult<()> { + if !self.editor { + return Err(error(Rule::MissingTarget, "log has no editor actions")); + } + let mut state = self.state.try_borrow_mut().map_err(|_| error(Rule::Lifecycle, "fixture state borrowed"))?; + match action.0.as_str() { + "apply" => { + // Only this explicit content command reaches the model sink. + services.commands.execute(owner, "fixture.apply", serde_json::json!({"draft":state.draft}))?; + state.applies = state.applies.saturating_add(1); + } + "cancel" => { + if state.reject_cancel { + return Err(error(Rule::Lifecycle, "synthetic cancel rejected")); + } + state.cancels = state.cancels.saturating_add(1); + state.transaction_live = false; + } + "finish" => { + services.commands.execute(owner, "fixture.finish", serde_json::json!({"draft":state.draft}))?; + state.finishes = state.finishes.saturating_add(1); + state.transaction_live = false; + } + _ => return Err(error(Rule::MissingTarget, "unknown synthetic action")), + } + Ok(()) + } +} + +pub fn bind_synthetic_controllers(runtime: &mut PanelRuntime, probe: &FixtureProbe) -> PanelResult<()> { + for (kind, editor, ownership) in [ + ("fixture.application", false, Ownership::Application), + ("fixture.editor", true, Ownership::Document), + ("fixture.log", false, Ownership::Workspace), + ("fixture.pin", false, Ownership::Workspace), + ] { + runtime.register(PanelKind::new(kind)?, fixture_controller_binding(probe, editor, ownership))?; + } + Ok(()) +} + +/// Bind the same synthetic lifecycle to another registered kind/ownership policy. +/// This lets capacity fixtures exercise several document editors without adding +/// production registrations or changing the pure layout registry. +pub fn fixture_controller_binding(probe: &FixtureProbe, editor: bool, ownership: Ownership) -> ControllerBinding { + let probe = probe.clone(); + ControllerBinding { + ownership, + create: Box::new(move |instance, owner| { + let key = ControllerKey { instance: instance.id.clone(), owner: owner.clone() }; + Ok(Box::new(FixtureController { + state: Rc::new(RefCell::new(FixtureState { transaction_live: editor && instance.requested_open, ..FixtureState::default() })), + editor, + instance: instance.id.clone(), + probe: probe.clone(), + key, + })) + }), + } +} + +#[derive(Default)] +pub struct FakeModels { + pub editable: bool, +} + +/// Synthetic app provider for command/control fixtures, with the same retained +/// model/command/local-service bindings as PanelMountHarness. +#[derive(Default)] +pub struct FakeAppPanelServices { + pub models: FakeModels, + pub commands: FakeContentCommands, + pub local: FakeLocalServices, +} +impl AppPanelServices for FakeAppPanelServices { + fn refresh_read_only(&mut self, _session: &solidcraft_engine::Session) -> PanelResult<()> { + Ok(()) + } + fn services(&mut self) -> ContentServices<'_> { + ContentServices { models: &self.models, commands: &mut self.commands, local: &mut self.local } + } +} +impl PanelModels for FakeModels { + fn read(&self, _owner: &ContentOwner, key: &str) -> PanelResult { + match key { + "fixture.editable" => Ok(serde_json::Value::Bool(self.editable)), + _ => Err(error(Rule::MissingTarget, "unknown synthetic model read")), + } + } +} + +#[derive(Default)] +pub struct FakeContentCommands { + pub calls: u64, + pub fail: bool, +} +impl ContentCommandSink for FakeContentCommands { + fn execute(&mut self, _owner: &ContentOwner, command: &str, input: serde_json::Value) -> PanelResult { + valid_id(command)?; + bounded_json(&input)?; + if serde_json::to_vec(&input).map_err(|_| error(Rule::Schema, "invalid synthetic command"))?.len() > MAX_ENVELOPE_BYTES { + return Err(error(Rule::CollectionLimit, "synthetic command cap")); + } + if self.fail { + return Err(error(Rule::Lifecycle, "synthetic content command failed")); + } + self.calls = self.calls.saturating_add(1); + Ok(serde_json::Value::Null) + } +} + +#[derive(Default)] +pub struct FakeLocalServices { + pub scopes: BTreeMap, + pub keyboard: BTreeMap, + pub requests: VecDeque<(LocalScope, LocalRequest)>, + pub releases: u64, +} +impl FakeLocalServices { + pub fn bind(&mut self, instance: InstanceId, scope: LocalScope) -> PanelResult<()> { + valid_id(&instance.0)?; + scope.validate()?; + if self.scopes.len() >= MAX_INSTANCES && !self.scopes.contains_key(&instance) { + return Err(error(Rule::CollectionLimit, "local scope cap")); + } + if let Some(old) = self.scopes.get(&instance).cloned() { + if old == scope { + return Ok(()); + } + self.release(&old, &instance); + } + self.scopes.insert(instance, scope); + Ok(()) + } +} +impl PanelLocalServices for FakeLocalServices { + fn request(&mut self, scope: &LocalScope, request: LocalRequest) -> PanelResult<()> { + scope.validate()?; + request.validate()?; + if self.scopes.get(request.instance()) != Some(scope) { + return Err(error(Rule::Placement, "cross-document or cross-viewport service request")); + } + match &request { + LocalRequest::KeyboardOwner { instance, control } => { + if self.keyboard.get(scope).is_some_and(|(owner, _)| owner != instance) { + return Err(error(Rule::Lifecycle, "keyboard owned by another panel")); + } + self.keyboard.insert(scope.clone(), (instance.clone(), control.clone())); + } + LocalRequest::ReleaseKeyboard { instance } => { + if self.keyboard.get(scope).is_some_and(|(owner, _)| owner == instance) { + self.keyboard.remove(scope); + } + } + LocalRequest::ClearOverlays { instance } => { + self.requests.retain(|(at, req)| at != scope || req.instance() != instance || !matches!(req, LocalRequest::Overlay { .. })) + } + _ => {} + } + if self.requests.len() >= MAX_INSTANCES { + self.requests.pop_front(); + } + self.requests.push_back((scope.clone(), request)); + Ok(()) + } + fn release(&mut self, scope: &LocalScope, instance: &InstanceId) { + if self.keyboard.get(scope).is_some_and(|(owner, _)| owner == instance) { + self.keyboard.remove(scope); + } + self.requests.retain(|(at, request)| at != scope || request.instance() != instance); + if self.scopes.get(instance) == Some(scope) { + self.scopes.remove(instance); + } + self.releases = self.releases.saturating_add(1); + } +} + +pub struct FakeNativeAdapter { + pub capabilities: HostCapabilities, + pub hosts: BTreeMap, + pub fail_prepare: bool, + pub commits: u64, +} +impl FakeNativeAdapter { + pub fn new(native: bool) -> Self { + Self { + capabilities: HostCapabilities { native_windows: native, persistence: true, max_native_hosts: if native { 8 } else { 0 } }, + hosts: BTreeMap::new(), + fail_prepare: false, + commits: 0, + } + } +} +impl NativeHostAdapter for FakeNativeAdapter { + fn capabilities(&self) -> HostCapabilities { + self.capabilities.clone() + } + fn prepare(&self, effects: &[HostEffect]) -> PanelResult<()> { + if self.fail_prepare { + return Err(error(Rule::Capability, "synthetic native preparation failure")); + } + if effects.len() > MAX_MUTATIONS * 3 { + return Err(error(Rule::CollectionLimit, "native effect cap")); + } + let mut hosts = self.hosts.clone(); + for effect in effects { + match effect { + HostEffect::CreateNative { host, section } => { + if !self.capabilities.native_windows { + return Err(error(Rule::Capability, "native windows unsupported")); + } + if hosts.insert(host.clone(), section.clone()).is_some() { + return Err(error(Rule::DuplicateId, "native host already exists")); + } + } + HostEffect::RebindNative { host, section } => { + if !self.capabilities.native_windows { + return Err(error(Rule::Capability, "native rebind unsupported")); + } + if !hosts.contains_key(host) { + return Err(error(Rule::MissingTarget, "native rebind host absent")); + } + hosts.insert(host.clone(), section.clone()); + } + HostEffect::ReleaseNative { host } => { + hosts.remove(host); + } + _ => {} + } + } + if hosts.len() > self.capabilities.max_native_hosts { + return Err(error(Rule::Capability, "native host capacity")); + } + Ok(()) + } + fn commit(&mut self, effects: &[HostEffect]) { + for effect in effects { + match effect { + HostEffect::CreateNative { host, section } | HostEffect::RebindNative { host, section } => { + self.hosts.insert(host.clone(), section.clone()); + } + HostEffect::ReleaseNative { host } => { + self.hosts.remove(host); + } + _ => {} + } + } + self.commits = self.commits.saturating_add(1); + } +} + +#[derive(Clone, Debug)] +pub struct MountRecord { + pub geometry: ResolvedPanel, + pub presentation: PanelPresentation, + pub context: PanelContext, +} + +#[derive(Default)] +pub struct FakePanelHost { + pub mounts: VecDeque, + pub slot_calls: u64, + pub context: egui::Context, +} +impl PanelHost for FakePanelHost { + fn mount( + &mut self, + geometry: &ResolvedPanel, + presentation: &PanelPresentation, + context: &PanelContext, + content: &mut dyn PanelController, + services: &mut ContentServices<'_>, + ) -> PanelResult<()> { + geometry.validate()?; + presentation.validate()?; + context.validate()?; + let mut failure = None; + let ctx = self.context.clone(); + let _output = ctx.run_ui(egui::RawInput::default(), |root_ui| { + crate::ui_kit::Container::new(root_ui.ctx(), crate::ui_kit::Surface::Viewport).central().show(root_ui, |ui| { + for slot in [ContentSlot::Header, ContentSlot::Body, ContentSlot::Footer] { + if failure.is_some() { + break; + } + if let Err(reason) = content.render(slot, ui, context, services) { + failure = Some(reason); + } + self.slot_calls = self.slot_calls.saturating_add(1); + } + }); + }); + if let Some(reason) = failure { + return Err(reason); + } + if self.mounts.len() >= MAX_INSTANCES { + self.mounts.pop_front(); + } + self.mounts.push_back(MountRecord { geometry: geometry.clone(), presentation: presentation.clone(), context: context.clone() }); + Ok(()) + } +} + +/// Reusable harness uses actual reducer, controller, host and services interfaces. +pub struct PanelMountHarness { + pub runtime: PanelRuntime, + pub probe: FixtureProbe, + pub models: FakeModels, + pub commands: FakeContentCommands, + pub local: FakeLocalServices, + pub native: FakeNativeAdapter, + pub host: FakePanelHost, + pub persistence: FakePersistence, + pub catalogue: commands::InMemoryCatalogue, +} +impl PanelMountHarness { + pub fn command(&mut self, id: &str, params: &serde_json::Value) -> PanelResult { + let registry = self.runtime.layout().registry().clone(); + let mut services = ContentServices { models: &self.models, commands: &mut self.commands, local: &mut self.local }; + let mut sink = RuntimeActionSink { runtime: &mut self.runtime, native: &mut self.native, services: &mut services }; + commands::execute( + id, + params, + &mut commands::PanelCommandContext { sink: &mut sink, registry: ®istry, catalogue: &mut self.catalogue, web: false }, + ) + } + pub fn command_batch(&mut self, steps: &[serde_json::Value]) -> PanelResult { + let registry = self.runtime.layout().registry().clone(); + let mut services = ContentServices { models: &self.models, commands: &mut self.commands, local: &mut self.local }; + let mut sink = RuntimeActionSink { runtime: &mut self.runtime, native: &mut self.native, services: &mut services }; + commands::execute_batch( + steps, + &mut commands::PanelCommandContext { sink: &mut sink, registry: ®istry, catalogue: &mut self.catalogue, web: false }, + ) + } + pub fn apply_layout(&mut self, layout: Layout, expected_revision: Option) -> PanelResult { + self.runtime.dispatch( + LayoutAction::Replace { expected_revision, layout }, + &mut self.native, + &mut ContentServices { models: &self.models, commands: &mut self.commands, local: &mut self.local }, + ) + } + pub fn new(native: bool) -> PanelResult { + Self::configured(native, true) + } + pub fn without_content(native: bool) -> PanelResult { + Self::configured(native, false) + } + fn configured(native: bool, bind: bool) -> PanelResult { + let layout = fixture_service(native)?; + let catalogue = fixture_command_catalogue(layout.registry())?; + let environment = RuntimeEnvironment { + workspace: layout.layout().workspace.clone(), + document: Some(DocumentId::new("fixture.document")?), + window: HostId::new("fixture.window")?, + viewport: ViewportId::new("fixture.viewport")?, + direction: Direction::Ltr, + motion: Motion::Reduced, + }; + let mut runtime = PanelRuntime::new(layout, environment)?; + let probe = FixtureProbe::default(); + if bind { + bind_synthetic_controllers(&mut runtime, &probe)?; + } + Ok(Self { + runtime, + probe, + models: FakeModels { editable: true }, + commands: FakeContentCommands::default(), + local: FakeLocalServices::default(), + native: FakeNativeAdapter::new(native), + host: FakePanelHost::default(), + persistence: FakePersistence::default(), + catalogue, + }) + } + pub fn dispatch(&mut self, mutations: Vec) -> PanelResult { + self.runtime.dispatch( + transaction(mutations), + &mut self.native, + &mut ContentServices { models: &self.models, commands: &mut self.commands, local: &mut self.local }, + ) + } + pub fn tick(&mut self) -> PanelResult<()> { + self.runtime.update(&mut ContentServices { models: &self.models, commands: &mut self.commands, local: &mut self.local }) + } + pub fn mount(&mut self, capacity: LogicalRect) -> PanelResult { + self.tick()?; + let environment = self.runtime.environment().clone(); + let resolved = resolve_geometry(self.runtime.layout(), capacity, environment.direction, 48.0)?; + for panel in &resolved.panels { + let viewport = match &self.runtime.layout().layout().section(&panel.section)?.location { + SectionLocation::Window { host, .. } => ViewportId::new(host.0.clone())?, + _ => environment.viewport.clone(), + }; + self.local.bind( + panel.instance.clone(), + LocalScope { workspace: environment.workspace.clone(), document: environment.document.clone(), viewport }, + )?; + } + self.runtime.mount( + &resolved, + &mut self.host, + &mut ContentServices { models: &self.models, commands: &mut self.commands, local: &mut self.local }, + )?; + Ok(resolved) + } + pub fn save(&mut self) -> PanelResult<()> { + let layout = self.runtime.layout().layout(); + let bytes = encode(&LayoutEnvelope::new(layout.clone()), self.runtime.layout().registry())?; + self.persistence.save(&layout.workspace, &bytes) + } +} diff --git a/crates/ui-egui/src/panel_runtime/host.rs b/crates/ui-egui/src/panel_runtime/host.rs new file mode 100644 index 000000000..928321cff --- /dev/null +++ b/crates/ui-egui/src/panel_runtime/host.rs @@ -0,0 +1,316 @@ +use solidcraft_engine::panels::*; + +/// Content receives this value separately from state/model/command services. All +/// geometry is already in logical units; do not multiply it by egui UI scale. +#[derive(Clone, Debug, PartialEq)] +pub struct PanelContext { + pub instance: InstanceId, + pub owner: super::ContentOwner, + pub workspace: WorkspaceId, + pub document: Option, + pub viewport: ViewportId, + pub native_host: Option, + pub outer: LogicalRect, + pub usable_body: LogicalRect, + pub flow: Flow, + pub size_class: SizeClass, + pub focused: bool, + pub direction: Direction, + pub motion: Motion, +} +impl PanelContext { + pub fn validate(&self) -> PanelResult<()> { + valid_id(&self.instance.0)?; + self.owner.validate()?; + LocalScope { workspace: self.workspace.clone(), document: self.document.clone(), viewport: self.viewport.clone() }.validate()?; + self.outer.validate()?; + self.usable_body.validate()?; + if !self.outer.contains_rect(self.usable_body) { + return Err(error(Rule::Bounds, "presentation body outside host")); + } + if let Some(host) = &self.native_host { + valid_id(&host.0)?; + if self.viewport.0 != host.0 { + return Err(error(Rule::Placement, "native presentation has wrong local viewport")); + } + } + if let super::ContentOwner::Document(document) = &self.owner + && self.document.as_ref() != Some(document) + { + return Err(error(Rule::Placement, "presentation document differs from content owner")); + } + if let super::ContentOwner::Workspace(workspace) = &self.owner + && self.workspace != *workspace + { + return Err(error(Rule::Placement, "presentation workspace differs from content owner")); + } + Ok(()) + } +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Motion { + Reduced, + Animated, +} +impl Motion { + /// Reparent/focus must not wait for animation completion, including at zero duration. + pub fn duration_ms(self, requested: u16) -> u16 { + if self == Self::Reduced { 0 } else { requested.min(500) } + } +} + +#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)] +pub struct LocalScope { + pub workspace: WorkspaceId, + pub document: Option, + pub viewport: ViewportId, +} +impl LocalScope { + pub fn validate(&self) -> PanelResult<()> { + valid_id(&self.workspace.0)?; + valid_id(&self.viewport.0)?; + if let Some(id) = &self.document { + valid_id(&id.0)?; + } + Ok(()) + } +} + +#[derive(Clone, Debug, PartialEq)] +pub enum LocalRequest { + KeyboardOwner { instance: InstanceId, control: ControlId }, + ReleaseKeyboard { instance: InstanceId }, + Focus { instance: InstanceId, control: ControlId }, + FileDrop { instance: InstanceId, name: String, bytes: Vec }, + PointerDrop { instance: InstanceId, at: Point, payload: String }, + Overlay { instance: InstanceId, region: InputRegion }, + ClearOverlays { instance: InstanceId }, + Clipboard { instance: InstanceId, text: String }, + Pick { instance: InstanceId, at: Point }, +} +impl LocalRequest { + pub fn instance(&self) -> &InstanceId { + match self { + Self::KeyboardOwner { instance, .. } + | Self::ReleaseKeyboard { instance } + | Self::Focus { instance, .. } + | Self::FileDrop { instance, .. } + | Self::PointerDrop { instance, .. } + | Self::Overlay { instance, .. } + | Self::ClearOverlays { instance } + | Self::Clipboard { instance, .. } + | Self::Pick { instance, .. } => instance, + } + } + pub fn validate(&self) -> PanelResult<()> { + valid_id(&self.instance().0)?; + match self { + Self::KeyboardOwner { control, .. } | Self::Focus { control, .. } => valid_id(&control.0)?, + Self::FileDrop { name, bytes, .. } => { + if name.is_empty() || name.len() > 256 || bytes.len() > MAX_ENVELOPE_BYTES { + return Err(error(Rule::CollectionLimit, "file drop bound")); + } + } + Self::PointerDrop { at, payload, .. } => { + at.validate()?; + if payload.len() > 4096 { + return Err(error(Rule::CollectionLimit, "pointer drop payload bound")); + } + } + Self::Overlay { region, .. } => { + valid_id(®ion.control.0)?; + region.bounds.validate()?; + if region.accessible_name.is_empty() || region.accessible_name.len() > 256 { + return Err(error(Rule::Bounds, "overlay semantic name bound")); + } + } + Self::Clipboard { text, .. } if text.len() > MAX_ENVELOPE_BYTES => return Err(error(Rule::CollectionLimit, "clipboard bound")), + Self::Pick { at, .. } => at.validate()?, + _ => {} + } + Ok(()) + } +} + +/// Services must reject cross-document/viewport delivery. A native redock drops +/// host-local focus/overlays but retains the content controller and its owner. +pub trait PanelLocalServices { + fn request(&mut self, scope: &LocalScope, request: LocalRequest) -> PanelResult<()>; + fn release(&mut self, scope: &LocalScope, instance: &InstanceId); +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct RuntimeAction { + pub id: ControlId, + pub label: String, + pub enabled: bool, + pub disabled_reason: Option, +} +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct PanelPresentation { + /// Already localised by content; fixtures use specimen text only. + pub title: String, + pub icon: String, + pub status: Option, + pub attention: bool, + pub actions: Vec, +} +impl PanelPresentation { + pub fn validate(&self) -> PanelResult<()> { + if self.title.is_empty() || self.title.len() > 256 || self.status.as_ref().is_some_and(|s| s.len() > 1024) || self.actions.len() > MAX_TABS { + return Err(error(Rule::CollectionLimit, "presentation bound")); + } + valid_id(&self.icon)?; + let mut ids = std::collections::BTreeSet::new(); + for action in &self.actions { + valid_id(&action.id.0)?; + if !ids.insert(&action.id) { + return Err(error(Rule::DuplicateId, "duplicate content action")); + } + if action.label.is_empty() + || action.label.len() > 256 + || action.disabled_reason.as_ref().is_some_and(|r| r.is_empty() || r.len() > 256) + || !action.enabled && action.disabled_reason.is_none() + { + return Err(error(Rule::Bounds, "content action label/reason bound")); + } + } + Ok(()) + } +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum ContentSlot { + Header, + Body, + Footer, +} + +/// Shared host adapter seam. Geometry is resolved by the host; content chooses +/// its own scrolling within slots. The egui adapter below owns one kit Container. +pub trait PanelHost { + fn mount( + &mut self, + geometry: &ResolvedPanel, + presentation: &PanelPresentation, + context: &PanelContext, + content: &mut dyn PanelController, + services: &mut ContentServices<'_>, + ) -> PanelResult<()>; +} + +/// Two-phase host effects. `prepare` is side-effect-free and fallible; `commit` +/// cannot fail. Native adapters must stage resources before acknowledging prepare +/// and retain/restorable resources until the layout transaction commits. +pub trait NativeHostAdapter { + fn capabilities(&self) -> HostCapabilities; + fn prepare(&self, effects: &[HostEffect]) -> PanelResult<()>; + fn commit(&mut self, effects: &[HostEffect]); +} + +/// Existing ui_kit is the outer boundary. This adapter paints into host-provided +/// space; it does not invent windows, docking gestures or a second camera path. +pub struct EguiPanelHost<'a> { + pub ui: &'a mut egui::Ui, +} + +impl PanelHost for EguiPanelHost<'_> { + fn mount( + &mut self, + geometry: &ResolvedPanel, + presentation: &PanelPresentation, + context: &PanelContext, + content: &mut dyn PanelController, + services: &mut ContentServices<'_>, + ) -> PanelResult<()> { + geometry.validate()?; + presentation.validate()?; + context.validate()?; + if geometry.instance != context.instance || geometry.outer != context.outer || geometry.body != context.usable_body { + return Err(error(Rule::Placement, "host geometry differs from presentation context")); + } + // This reference adapter draws/interacts with one full rectangular card. + // Rich sparse/translucent regions belong to the surface host adapter. + if geometry.painted.len() != 1 + || geometry.painted.first() != Some(&geometry.outer) + || geometry.input.len() != 1 + || !geometry.input.first().is_some_and(|region| region.role == InputRole::Surface && region.bounds == geometry.outer) + { + return Err(error(Rule::Capability, "reference egui host requires one full painted/input surface")); + } + let rect = |r: LogicalRect| egui::Rect::from_min_size(egui::pos2(r.origin.x, r.origin.y), egui::vec2(r.size.width, r.size.height)); + let outer = rect(geometry.outer); + let body = rect(geometry.body); + let parent_clip = self.ui.clip_rect().intersect(outer); + let container = crate::ui_kit::Container::new(self.ui.ctx(), crate::ui_kit::Surface::Panel); + let frame = container.frame(self.ui.ctx(), crate::theme::Tokens::get().dialog_body, crate::frame::Side::Left).inner_margin(0); + let mut failure = None; + self.ui.scope_builder( + egui::UiBuilder::new().id_salt(("panel_runtime", &geometry.instance.0, &context.owner, &context.viewport.0)).max_rect(outer), + |ui| { + ui.set_clip_rect(ui.clip_rect().intersect(parent_clip)); + container.show_frame(ui, frame, outer, |ui| { + // Slots have explicit bounds. No mandatory ScrollArea around content. + let header = egui::Rect::from_min_max(outer.min, egui::pos2(outer.right(), body.top())); + let footer = egui::Rect::from_min_max(egui::pos2(outer.left(), body.bottom()), outer.max); + for (slot, bounds) in [(ContentSlot::Header, header), (ContentSlot::Body, body), (ContentSlot::Footer, footer)] { + if failure.is_some() { + break; + } + ui.scope_builder(egui::UiBuilder::new().id_salt(slot as u8).max_rect(bounds), |ui| { + ui.set_clip_rect(ui.clip_rect().intersect(bounds)); + if slot == ContentSlot::Header { + // Dynamic title/status have semantic metadata; content owns + // additional controls and returns requests through services. + let tokens = crate::theme::Tokens::get(); + let ink = if presentation.attention { tokens.form_primary } else { tokens.form_ink }; + let mut response = ui.label(egui::RichText::new(&presentation.title).color(ink)); + if let Some(status) = &presentation.status { + response = response.on_hover_text(status); + } + response.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Label, true, &presentation.title)); + } + if slot == ContentSlot::Footer && !presentation.actions.is_empty() { + egui::ScrollArea::horizontal().id_salt("panel_actions").show(ui, |ui| { + ui.horizontal(|ui| { + for action in &presentation.actions { + let response = ui + .push_id(&action.id.0, |ui| { + ui.add_enabled_ui(action.enabled, |ui| { + crate::ui_kit::button(ui, action.label.as_str(), crate::ui_kit::Button::Small) + }) + .inner + }) + .inner; + let clicked = response.clicked(); + if let Some(reason) = &action.disabled_reason { + response.on_disabled_hover_text(reason); + } + if clicked + && failure.is_none() + && let Err(reason) = content.action(&context.owner, &action.id, services) + { + failure = Some(reason); + } + } + }); + }); + } + if let Err(reason) = content.render(slot, ui, context, services) { + failure = Some(reason); + } + }); + } + ui.set_min_size(outer.size()); + }); + }, + ); + if let Some(reason) = failure { + return Err(reason); + } + Ok(()) + } +} + +use super::{ContentServices, PanelController}; diff --git a/crates/ui-egui/src/panel_runtime/mod.rs b/crates/ui-egui/src/panel_runtime/mod.rs new file mode 100644 index 000000000..7293ab066 --- /dev/null +++ b/crates/ui-egui/src/panel_runtime/mod.rs @@ -0,0 +1,14 @@ +//! Opt-in common panel runtime. No production registrations, gestures or preferences. +//! Model/commands, controller state, presentation and layout have separate owners. +mod app; +mod fixtures; +mod host; +mod runtime; + +pub use app::*; +pub use fixtures::*; +pub use host::*; +pub use runtime::*; + +#[cfg(test)] +mod tests; diff --git a/crates/ui-egui/src/panel_runtime/runtime.rs b/crates/ui-egui/src/panel_runtime/runtime.rs new file mode 100644 index 000000000..403caf10f --- /dev/null +++ b/crates/ui-egui/src/panel_runtime/runtime.rs @@ -0,0 +1,799 @@ +use std::collections::{BTreeMap, BTreeSet}; + +use solidcraft_engine::panels::*; + +use super::*; + +/// Retention spans every open document, independently of the active layout. +pub const MAX_RETAINED_DOCUMENT_OWNERS: usize = crate::documents::MAX_OPEN; +/// Application, workspace and window owners share a separate bounded budget. +pub const MAX_RETAINED_OTHER_OWNERS: usize = MAX_INSTANCES; +/// Total retained owners; also bounds the separate destroyed-owner tombstone set. +pub const MAX_RETAINED_OWNERS: usize = MAX_RETAINED_DOCUMENT_OWNERS + MAX_RETAINED_OTHER_OWNERS; +/// Each owner can retain a full layout's controllers, including hidden ones. +pub const MAX_RETAINED_CONTROLLERS_PER_OWNER: usize = MAX_INSTANCES; +/// Layout instance limits remain unchanged; retention never evicts live content. +pub const MAX_RETAINED_CONTROLLERS: usize = MAX_RETAINED_OWNERS * MAX_RETAINED_CONTROLLERS_PER_OWNER; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Ownership { + Application, + Workspace, + Document, + Window, +} + +/// Window ownership is explicit content ownership, independent of native placement. +/// Redocking does not turn a document editor into a new window-owned controller. +#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub enum ContentOwner { + Application, + Workspace(WorkspaceId), + Document(DocumentId), + Window(HostId), +} +impl ContentOwner { + pub fn validate(&self) -> PanelResult<()> { + match self { + Self::Application => Ok(()), + Self::Workspace(id) => valid_id(&id.0), + Self::Document(id) => valid_id(&id.0), + Self::Window(id) => valid_id(&id.0), + } + } +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct RuntimeEnvironment { + pub workspace: WorkspaceId, + pub document: Option, + pub window: HostId, + pub viewport: ViewportId, + pub direction: Direction, + pub motion: Motion, +} +impl RuntimeEnvironment { + pub fn validate(&self) -> PanelResult<()> { + valid_id(&self.workspace.0)?; + valid_id(&self.window.0)?; + valid_id(&self.viewport.0)?; + if let Some(doc) = &self.document { + valid_id(&doc.0)?; + } + Ok(()) + } + fn owner(&self, policy: Ownership) -> PanelResult { + Ok(match policy { + Ownership::Application => ContentOwner::Application, + Ownership::Workspace => ContentOwner::Workspace(self.workspace.clone()), + Ownership::Document => { + ContentOwner::Document(self.document.clone().ok_or_else(|| error(Rule::Availability, "document-bound panel needs a document"))?) + } + Ownership::Window => ContentOwner::Window(self.window.clone()), + }) + } +} + +/// Content model access is owner-scoped and read-only. Layout code never receives +/// a Session. Consumers may implement richer views behind the same trait. +pub trait PanelModels { + fn read(&self, owner: &ContentOwner, key: &str) -> PanelResult; +} + +/// Explicit content commands have their own typed owner. They are separate from +/// layout actions and are never implicitly sent when a panel is hidden/reparented. +pub trait ContentCommandSink { + fn execute(&mut self, owner: &ContentOwner, command: &str, input: serde_json::Value) -> PanelResult; +} + +pub struct ContentServices<'a> { + pub models: &'a dyn PanelModels, + pub commands: &'a mut dyn ContentCommandSink, + pub local: &'a mut dyn PanelLocalServices, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct ControllerState { + pub requested_open: bool, + pub available: Availability, + pub presented: bool, + pub activated: bool, + pub destroyed: bool, +} +impl Default for ControllerState { + fn default() -> Self { + Self { requested_open: false, available: Availability::Available, presented: false, activated: false, destroyed: false } + } +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum LifecycleEvent { + State(ControllerState), + /// Only explicit close calls this; deactivation never cancels a transaction. + Close, + Reopen, + Reparent, + DestroyOwner, +} + +pub trait PanelController { + /// Availability may depend on document/tool context, independent of visibility. + fn availability(&self, owner: &ContentOwner, models: &dyn PanelModels) -> Availability; + /// Runs for retained controllers, including hidden, closed and inactive documents. + fn update(&mut self, owner: &ContentOwner, services: &mut ContentServices<'_>) -> PanelResult<()>; + fn presentation(&self) -> PanelPresentation; + /// MUST be side-effect-free. Failure rejects the whole layout transaction. + /// Validate cancellation and reserve anything fallible before committing. + /// State notifications are observational and cannot veto a layout change. + fn prepare_lifecycle(&self, event: &LifecycleEvent) -> PanelResult<()>; + /// Infallible application of an already prepared lifecycle transition. + fn lifecycle(&mut self, event: &LifecycleEvent); + fn render(&mut self, slot: ContentSlot, ui: &mut egui::Ui, context: &PanelContext, services: &mut ContentServices<'_>) -> PanelResult<()>; + /// Apply/Finish/Cancel/Stop stay explicit content actions, never layout mutations. + fn action(&mut self, owner: &ContentOwner, action: &ControlId, services: &mut ContentServices<'_>) -> PanelResult<()>; +} + +pub struct ControllerBinding { + pub ownership: Ownership, + /// Staging may be discarded on failure; do not publish external side effects. + pub create: Box PanelResult>>, +} + +#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)] +pub struct ControllerKey { + pub instance: InstanceId, + pub owner: ContentOwner, +} + +struct RetainedController { + controller: Box, + /// A controller created closed, or explicitly closed after creation, needs + /// Reopen before reuse. Snapshot hiding never sets this lifecycle flag. + needs_reopen: bool, + state: ControllerState, + scope: LocalScope, + section: Option, + native_host: Option, + flow: Option, + availability: Availability, +} + +/// Layout stays on the app, controllers on their content owners, host services on +/// their local scopes. None of these values enter document serialization or undo. +pub struct PanelRuntime { + layout: LayoutService, + bindings: BTreeMap, + controllers: BTreeMap, + environment: RuntimeEnvironment, + destroyed_owners: BTreeSet, + destroyed: bool, + update_errors: Vec, +} + +#[derive(Clone, Debug)] +pub struct RuntimeUpdateError { + pub controller: Option, + pub error: PanelError, +} + +/// A scoped live action sink for host and future command routing. It includes the +/// runtime lifecycle guard rather than exposing a mutable bare LayoutService. +pub struct RuntimeActionSink<'a, 'services> { + pub runtime: &'a mut PanelRuntime, + pub native: &'a mut dyn NativeHostAdapter, + pub services: &'a mut ContentServices<'services>, +} +impl ActionSink for RuntimeActionSink<'_, '_> { + fn project(&self, action: LayoutAction) -> PanelResult { + self.runtime.layout.project(action) + } + fn dispatch(&mut self, action: LayoutAction) -> PanelResult { + let mut reply = self.runtime.dispatch(action, self.native, self.services)?; + let native = self.native.capabilities(); + reply.capabilities.native_windows &= native.native_windows; + reply.capabilities.max_native_hosts = reply.capabilities.max_native_hosts.min(native.max_native_hosts); + Ok(reply) + } + fn inspect(&self) -> LayoutReply { + let mut reply = self.runtime.layout.inspect(); + let native = self.native.capabilities(); + reply.capabilities.native_windows &= native.native_windows; + reply.capabilities.max_native_hosts = reply.capabilities.max_native_hosts.min(native.max_native_hosts); + reply + } +} + +impl PanelRuntime { + pub fn new(layout: LayoutService, environment: RuntimeEnvironment) -> PanelResult { + environment.validate()?; + if layout.layout().workspace != environment.workspace { + return Err(error(Rule::Placement, "runtime workspace differs from layout service")); + } + Ok(Self { + layout, + bindings: BTreeMap::new(), + controllers: BTreeMap::new(), + environment, + destroyed_owners: BTreeSet::new(), + destroyed: false, + update_errors: Vec::new(), + }) + } + pub fn register(&mut self, kind: PanelKind, binding: ControllerBinding) -> PanelResult<()> { + self.require_live()?; + self.layout.registry().get(&kind)?; + if self.bindings.contains_key(&kind) { + return Err(error(Rule::DuplicateId, "controller binding already registered")); + } + if self.bindings.len() >= MAX_INSTANCES { + return Err(error(Rule::CollectionLimit, "binding cap")); + } + self.bindings.insert(kind, binding); + Ok(()) + } + pub fn layout(&self) -> &LayoutService { + &self.layout + } + pub fn environment(&self) -> &RuntimeEnvironment { + &self.environment + } + pub fn controller_count(&self) -> usize { + self.controllers.len() + } + pub fn update_errors(&self) -> &[RuntimeUpdateError] { + &self.update_errors + } + fn require_live(&self) -> PanelResult<()> { + if self.destroyed { + return Err(error(Rule::Lifecycle, "runtime destroyed")); + } + Ok(()) + } + pub fn state(&self, key: &ControllerKey) -> Option<&ControllerState> { + self.controllers.get(key).map(|c| &c.state) + } + pub fn presentation(&self, key: &ControllerKey) -> PanelResult { + let value = self.controllers.get(key).ok_or_else(|| error(Rule::MissingTarget, "controller not retained"))?.controller.presentation(); + value.validate()?; + Ok(value) + } + fn key(&self, instance: &PanelInstance) -> PanelResult { + self.key_in(instance, &self.environment) + } + fn key_in(&self, instance: &PanelInstance, environment: &RuntimeEnvironment) -> PanelResult { + let binding = self.bindings.get(&instance.kind).ok_or_else(|| error(Rule::Availability, "no content binding available"))?; + let owner = environment.owner(binding.ownership)?; + if self.destroyed_owners.contains(&owner) { + return Err(error(Rule::Availability, "content owner destroyed")); + } + Ok(ControllerKey { instance: instance.id.clone(), owner }) + } + fn scope(&self) -> LocalScope { + LocalScope { + workspace: self.environment.workspace.clone(), + document: self.environment.document.clone(), + viewport: self.environment.viewport.clone(), + } + } + + /// Changes active context without dropping editors/conversations of inactive + /// documents. Their independent service updates keep running under their owner. + pub fn set_environment(&mut self, environment: RuntimeEnvironment, local: &mut dyn PanelLocalServices) -> PanelResult<()> { + self.require_live()?; + environment.validate()?; + if environment.workspace != self.layout.layout().workspace { + return Err(error(Rule::Placement, "apply the saved workspace layout through LayoutAction::Replace")); + } + if self.environment == environment { + return Ok(()); + } + // Capacity/factory refusal must leave the active owner and local input + // untouched, just like a refused layout replacement. + let staged = self.stage_controllers(self.layout.layout(), &environment)?; + let mut events = Vec::new(); + for (key, retained) in &self.controllers { + let mut state = retained.state.clone(); + state.presented = false; + state.activated = false; + events.push((key.clone(), state)); + } + for (key, state) in events { + if let Some(retained) = self.controllers.get_mut(&key) { + local.release(&retained.scope, &key.instance); + retained.controller.lifecycle(&LifecycleEvent::State(state.clone())); + retained.state = state; + } + } + self.environment = environment; + self.controllers.extend(staged); + Ok(()) + } + + fn stage_controllers(&self, layout: &Layout, environment: &RuntimeEnvironment) -> PanelResult> { + let mut staged = BTreeMap::new(); + let mut owner_counts = BTreeMap::::new(); + for key in self.controllers.keys() { + *owner_counts.entry(key.owner.clone()).or_default() += 1; + } + let mut document_owners = owner_counts.keys().filter(|owner| matches!(owner, ContentOwner::Document(_))).count(); + let mut other_owners = owner_counts.len() - document_owners; + for p in &layout.instances { + let key = match self.key_in(p, environment) { + Ok(key) => key, + Err(_) => continue, + }; + if self.controllers.contains_key(&key) || staged.contains_key(&key) { + continue; + } + if self.controllers.len() + staged.len() >= MAX_RETAINED_CONTROLLERS { + return Err(error(Rule::CollectionLimit, "retained controller cap")); + } + if !owner_counts.contains_key(&key.owner) { + if matches!(&key.owner, ContentOwner::Document(_)) { + if document_owners >= MAX_RETAINED_DOCUMENT_OWNERS { + return Err(error(Rule::CollectionLimit, "retained document owner cap")); + } + document_owners += 1; + } else { + if other_owners >= MAX_RETAINED_OTHER_OWNERS { + return Err(error(Rule::CollectionLimit, "retained application/workspace/window owner cap")); + } + other_owners += 1; + } + } + let count = owner_counts.entry(key.owner.clone()).or_default(); + if *count >= MAX_RETAINED_CONTROLLERS_PER_OWNER { + return Err(error(Rule::CollectionLimit, "retained controller cap for content owner")); + } + *count += 1; + let binding = self.bindings.get(&p.kind).ok_or_else(|| error(Rule::Availability, "binding disappeared"))?; + let controller = (binding.create)(p, &key.owner)?; + staged.insert( + key, + RetainedController { + controller, + needs_reopen: !p.requested_open, + state: ControllerState::default(), + scope: LocalScope { + workspace: environment.workspace.clone(), + document: environment.document.clone(), + viewport: environment.viewport.clone(), + }, + section: None, + native_host: None, + flow: None, + availability: Availability::Available, + }, + ); + } + Ok(staged) + } + + /// Refresh command/query availability from the current read-only provider. + /// This does not tick content, evaluate models or invent presentation geometry. + /// A failed retained service stays failed until a real update recovers it. + pub fn refresh_context(&mut self, models: &dyn PanelModels, local: &mut dyn PanelLocalServices) -> PanelResult<()> { + self.require_live()?; + let staged = self.stage_controllers(self.layout.layout(), &self.environment)?; + let mut availability = AvailabilityMap::new(); + for instance in &self.layout.layout().instances { + let state = match self.key(instance) { + Ok(key) => match self.controllers.get(&key).or_else(|| staged.get(&key)) { + Some(retained) => { + let state = retained.controller.availability(&key.owner, models); + if matches!(&state,Availability::Unavailable { reason } if reason.is_empty() || reason.len() > 256) { + return Err(error(Rule::Availability, "controller availability reason bound")); + } + if self.update_errors.iter().any(|failure| failure.controller.as_ref() == Some(&key)) { + retained.availability.clone() + } else { + state + } + } + None => Availability::Unavailable { reason: "content controller unavailable".into() }, + }, + Err(reason) => Availability::Unavailable { reason: reason.detail }, + }; + availability.insert(instance.id.clone(), state); + } + self.layout.set_availability(availability.clone())?; + self.controllers.extend(staged); + for instance in &self.layout.layout().instances { + if let Ok(key) = self.key(instance) + && let Some(retained) = self.controllers.get_mut(&key) + && let Some(state) = availability.get(&instance.id) + { + retained.availability = state.clone(); + } + } + self.sync_states(None, local); + Ok(()) + } + + /// Independent tick: all retained services, then current-owner availability. + /// No geometry or painting is required for this method. + pub fn update(&mut self, services: &mut ContentServices<'_>) -> PanelResult<()> { + if self.destroyed { + return Err(error(Rule::Lifecycle, "runtime destroyed")); + } + self.update_errors.clear(); + match self.stage_controllers(self.layout.layout(), &self.environment) { + Ok(staged) => self.controllers.extend(staged), + Err(reason) => self.update_errors.push(RuntimeUpdateError { controller: None, error: error(reason.rule, reason.detail) }), + } + for (key, retained) in &mut self.controllers { + let update = retained.controller.update(&key.owner, services); + let availability = retained.controller.availability(&key.owner, services.models); + let invalid = matches!(&availability, Availability::Unavailable { reason } if reason.is_empty() || reason.len() > 256); + let failed = update.is_err() || invalid; + if let Err(reason) = update { + self.update_errors.push(RuntimeUpdateError { controller: Some(key.clone()), error: error(reason.rule, reason.detail) }); + } + if invalid { + self.update_errors.push(RuntimeUpdateError { + controller: Some(key.clone()), + error: error(Rule::Availability, "controller availability reason bound"), + }); + } + if failed { + retained.availability = Availability::Unavailable { + reason: if invalid { "invalid availability report".into() } else { "content service update failed".into() }, + }; + } else { + retained.availability = availability; + } + } + let mut availability = AvailabilityMap::new(); + for p in &self.layout.layout().instances { + let state = match self.key(p) { + Ok(key) => self + .controllers + .get(&key) + .map(|c| c.availability.clone()) + .unwrap_or(Availability::Unavailable { reason: "content controller unavailable".into() }), + Err(reason) => Availability::Unavailable { reason: reason.detail }, + }; + availability.insert(p.id.clone(), state); + } + if let Err(reason) = self.layout.set_availability(availability) { + self.update_errors.push(RuntimeUpdateError { controller: None, error: reason }); + } + self.sync_states(None, services.local); + // At most two errors per retained controller, plus staging/reconciliation. + if self.update_errors.is_empty() { + Ok(()) + } else { + Err(error(Rule::Lifecycle, format!("{} panel service failures; inspect update_errors", self.update_errors.len()))) + } + } + + /// Lifecycle preflight and native preflight happen before layout commit. A + /// failed close/cancel leaves layout, interaction, controllers and host intact. + pub fn dispatch( + &mut self, + action: LayoutAction, + native: &mut dyn NativeHostAdapter, + services: &mut ContentServices<'_>, + ) -> PanelResult { + if action == LayoutAction::Inspect { + return Ok(self.layout.inspect()); + } + if self.destroyed { + return Err(error(Rule::Lifecycle, "runtime destroyed")); + } + let requests: Vec<_> = match &action { + LayoutAction::Apply { mutations, .. } => mutations + .iter() + .filter_map(|m| match m { + Mutation::Open { instance, .. } + | Mutation::Focus { instance } + | Mutation::Activate { instance } + | Mutation::Peek { instance } => Some(instance.clone()), + _ => None, + }) + .collect(), + LayoutAction::Inspect | LayoutAction::Replace { .. } => Vec::new(), + }; + let replacement = matches!(&action, LayoutAction::Replace { .. }); + let mut explicit_close = BTreeSet::new(); + let mut explicit_destroy = BTreeSet::new(); + let mut explicit_open = BTreeSet::new(); + if let LayoutAction::Apply { mutations, .. } = &action { + for mutation in mutations { + match mutation { + Mutation::Close { instance } => { + explicit_close.insert(instance.clone()); + } + Mutation::Destroy { instance } => { + explicit_destroy.insert(instance.clone()); + } + Mutation::Open { instance, .. } | Mutation::Focus { instance } => { + explicit_open.insert(instance.clone()); + } + _ => {} + } + } + } + let mut prepared = self.layout.prepare(action)?; + let mut environment = self.environment.clone(); + environment.workspace = prepared.layout().workspace.clone(); + let capabilities = native.capabilities(); + if capabilities.max_native_hosts > MAX_SECTIONS { + return Err(error(Rule::Capability, "native adapter reports invalid capacity")); + } + if prepared.effects().iter().any(|e| matches!(e, HostEffect::CreateNative { .. })) && !capabilities.native_windows { + return Err(error(Rule::Capability, "native adapter is unavailable")); + } + let staged = self.stage_controllers(prepared.layout(), &environment)?; + let mut availability = AvailabilityMap::new(); + for instance in &prepared.layout().instances { + let state = match self.key_in(instance, &environment) { + Ok(key) => match self.controllers.get(&key).or_else(|| staged.get(&key)) { + Some(retained) => { + let state = retained.controller.availability(&key.owner, services.models); + if matches!(&state, Availability::Unavailable { reason } if reason.is_empty() || reason.len() > 256) { + return Err(error(Rule::Availability, "controller availability reason bound")); + } + // A failed retained service cannot become healthy solely by moving it. + if self.update_errors.iter().any(|e| e.controller.as_ref() == Some(&key)) { retained.availability.clone() } else { state } + } + None => Availability::Unavailable { reason: "content controller unavailable".into() }, + }, + Err(reason) => Availability::Unavailable { reason: reason.detail }, + }; + availability.insert(instance.id.clone(), state); + } + prepared.set_availability(availability.clone())?; + for id in requests { + if let Ok(instance) = prepared.layout().instance(&id) + && let Some(state) = availability.get(&instance.id) + { + state.require()?; + } + } + let mut events: Vec<(ControllerKey, LifecycleEvent)> = Vec::new(); + for (key, retained) in self.controllers.iter().chain(staged.iter()) { + let before = self.layout.layout().instances.iter().find(|p| p.id == key.instance); + let after = prepared.layout().instances.iter().find(|p| p.id == key.instance); + let affected = !matches!(&key.owner, ContentOwner::Workspace(workspace) if *workspace != self.environment.workspace); + if explicit_destroy.contains(&key.instance) { + retained.controller.prepare_lifecycle(&LifecycleEvent::DestroyOwner)?; + events.push((key.clone(), LifecycleEvent::DestroyOwner)); + } else if affected && explicit_close.contains(&key.instance) { + retained.controller.prepare_lifecycle(&LifecycleEvent::Close)?; + events.push((key.clone(), LifecycleEvent::Close)); + } else if !matches!(&key.owner, ContentOwner::Workspace(workspace) if *workspace != environment.workspace) + && (replacement || explicit_open.contains(&key.instance)) + && retained.needs_reopen + && after.is_some_and(|p| p.requested_open) + { + retained.controller.prepare_lifecycle(&LifecycleEvent::Reopen)?; + events.push((key.clone(), LifecycleEvent::Reopen)); + } + let old = self.layout.layout().containing(&key.instance).ok().map(|s| (&s.id, &s.location)); + let new = prepared.layout().containing(&key.instance).ok().map(|s| (&s.id, &s.location)); + let same_controller = after.is_some_and(|p| self.key_in(p, &environment).is_ok_and(|k| k == *key)) + && before.is_some_and(|p| self.key(p).is_ok_and(|k| k == *key)); + if same_controller + && (old != new || self.environment.workspace != environment.workspace) + && before.is_some_and(|p| p.requested_open) + && after.is_some_and(|p| p.requested_open) + { + retained.controller.prepare_lifecycle(&LifecycleEvent::Reparent)?; + events.push((key.clone(), LifecycleEvent::Reparent)); + } + } + // Effects are available from the same candidate, before irreversible work. + native.prepare(prepared.effects())?; + let reply = self.layout.commit(prepared)?; + self.controllers.extend(staged); + if replacement { + for (key, retained) in &self.controllers { + services.local.release(&retained.scope, &key.instance); + } + } + self.environment = environment; + let current_keys: BTreeSet<_> = self.layout.layout().instances.iter().filter_map(|p| self.key(p).ok()).collect(); + for (key, retained) in &mut self.controllers { + if current_keys.contains(key) + && let Some(state) = availability.get(&key.instance) + { + retained.availability = state.clone(); + } + } + for (key, event) in events { + if let Some(retained) = self.controllers.get_mut(&key) { + if matches!(event, LifecycleEvent::Close | LifecycleEvent::Reparent | LifecycleEvent::DestroyOwner) { + services.local.release(&retained.scope, &key.instance); + } + retained.controller.lifecycle(&event); + match event { + LifecycleEvent::Close => retained.needs_reopen = true, + LifecycleEvent::Reopen => retained.needs_reopen = false, + _ => {} + } + } + if event == LifecycleEvent::DestroyOwner { + self.controllers.remove(&key); + } + } + native.commit(&reply.effects); + // Presentation will be reconciled by mount/update; layout changes do not + // force content drawing or touch model revisions/undo/tessellation. + self.sync_states(None, services.local); + Ok(reply) + } + + fn sync_states(&mut self, resolved: Option<&ResolvedLayout>, local: &mut dyn PanelLocalServices) { + let active_keys: BTreeSet<_> = self.layout.layout().instances.iter().filter_map(|p| self.key(p).ok()).collect(); + let scope = self.scope(); + let mut pending = Vec::new(); + for (key, retained) in &self.controllers { + let instance = self.layout.layout().instance(&key.instance).ok(); + let current = active_keys.contains(key); + let available = retained.availability.clone(); + let requested_open = current && instance.is_some_and(|p| p.requested_open); + let section = if current { self.layout.layout().containing(&key.instance).ok() } else { None }; + let section_id = section.map(|s| s.id.clone()); + let host = section.and_then(|s| match &s.location { + SectionLocation::Window { host, .. } => Some(host.clone()), + _ => None, + }); + let peek = &self.layout.interaction().peek; + let selected = section.is_some_and(|s| (!s.collapsed && s.active == key.instance) || peek.as_ref() == Some(&key.instance)); + let geometry_presented = match resolved { + Some(r) => r.panels.iter().any(|p| p.instance == key.instance), + None => retained.state.presented && retained.section == section_id && retained.native_host == host && selected, + }; + let presented = current && requested_open && available == Availability::Available && geometry_presented; + let activated = presented && selected; + let state = ControllerState { requested_open, available, presented, activated, destroyed: false }; + pending.push((key.clone(), state, section_id, host, current)); + } + for (key, state, section, host, current) in pending { + if let Some(retained) = self.controllers.get_mut(&key) { + let mut target_scope = scope.clone(); + if let Some(host) = &host { + target_scope.viewport = ViewportId(host.0.clone()); + } + if retained.state.presented && !state.presented || current && (retained.scope != target_scope || retained.native_host != host) { + local.release(&retained.scope, &key.instance); + } + if state != retained.state { + retained.controller.lifecycle(&LifecycleEvent::State(state.clone())); + } + retained.state = state; + retained.section = section; + retained.native_host = host; + if current { + retained.scope = target_scope; + } + } + } + } + + pub fn mount(&mut self, resolved: &ResolvedLayout, host: &mut dyn PanelHost, services: &mut ContentServices<'_>) -> PanelResult<()> { + self.require_live()?; + resolved.validate()?; + for record in &resolved.unpresented { + self.layout.layout().section(&record.section)?; + } + let mut ids = BTreeSet::new(); + for geometry in &resolved.panels { + geometry.validate()?; + if !ids.insert(&geometry.instance) { + return Err(error(Rule::ExactlyOnce, "panel mounted twice")); + } + let section = self.layout.layout().containing(&geometry.instance)?; + if section.id != geometry.section + || section.location.zone() != geometry.zone + || !self.layout.layout().instance(&geometry.instance)?.requested_open + { + return Err(error(Rule::Placement, "resolved host differs from live layout")); + } + let peek = self.layout.interaction().peek.as_ref() == Some(&geometry.instance); + if section.active != geometry.instance && !peek || section.collapsed && !peek { + return Err(error(Rule::Placement, "cannot mount inactive or collapsed tab content")); + } + let (min, max) = tab_bounds(self.layout.layout(), self.layout.registry(), section)?; + if !geometry.outer.size.within(min, max) { + return Err(error(Rule::Bounds, "host violates tab outer bounds")); + } + if self.layout.availability(&geometry.instance) != Availability::Available { + return Err(error(Rule::Availability, "cannot mount unavailable content")); + } + let key = self.key(self.layout.layout().instance(&geometry.instance)?)?; + self.controllers.get(&key).ok_or_else(|| error(Rule::Availability, "content controller unavailable"))?.availability.require()?; + } + self.sync_states(Some(resolved), services.local); + let interaction = self.layout.interaction().clone(); + for geometry in &resolved.panels { + let instance = self.layout.layout().instance(&geometry.instance)?; + let key = self.key(instance)?; + let retained = self.controllers.get_mut(&key).ok_or_else(|| error(Rule::MissingTarget, "call update before mount"))?; + let (flow, size_class) = responsive(geometry.zone, geometry.body.size, retained.flow)?; + let context = PanelContext { + instance: geometry.instance.clone(), + owner: key.owner.clone(), + workspace: self.environment.workspace.clone(), + document: self.environment.document.clone(), + viewport: retained.scope.viewport.clone(), + native_host: retained.native_host.clone(), + outer: geometry.outer, + usable_body: geometry.body, + flow, + size_class, + focused: interaction.focused.as_ref() == Some(&geometry.instance), + direction: self.environment.direction, + motion: self.environment.motion, + }; + let presentation = retained.controller.presentation(); + presentation.validate()?; + host.mount(geometry, &presentation, &context, retained.controller.as_mut(), services)?; + retained.flow = Some(flow); + } + Ok(()) + } + + pub fn content_action(&mut self, instance: &InstanceId, action: &ControlId, services: &mut ContentServices<'_>) -> PanelResult<()> { + self.require_live()?; + valid_id(&action.0)?; + self.layout.availability(instance).require()?; + let key = self.key(self.layout.layout().instance(instance)?)?; + let retained = self.controllers.get_mut(&key).ok_or_else(|| error(Rule::MissingTarget, "controller not retained"))?; + retained.availability.require()?; + let presentation = retained.controller.presentation(); + presentation.validate()?; + let command = + presentation.actions.iter().find(|a| a.id == *action).ok_or_else(|| error(Rule::MissingTarget, "content action not advertised"))?; + if !command.enabled { + return Err(error(Rule::Availability, command.disabled_reason.as_deref().unwrap_or("content action unavailable"))); + } + retained.controller.action(&key.owner, action, services) + } + + pub fn destroy_owner(&mut self, owner: &ContentOwner, local: &mut dyn PanelLocalServices) -> PanelResult<()> { + self.require_live()?; + owner.validate()?; + if self.destroyed_owners.len() >= MAX_RETAINED_OWNERS && !self.destroyed_owners.contains(owner) { + return Err(error(Rule::CollectionLimit, "destroyed owner cap")); + } + for (key, retained) in &self.controllers { + if key.owner == *owner { + retained.controller.prepare_lifecycle(&LifecycleEvent::DestroyOwner)?; + } + } + self.controllers.retain(|key, retained| { + if key.owner != *owner { + return true; + } + local.release(&retained.scope, &key.instance); + retained.controller.lifecycle(&LifecycleEvent::DestroyOwner); + false + }); + self.destroyed_owners.insert(owner.clone()); + Ok(()) + } + + /// Explicitly rebind a previously destroyed owner; it receives fresh content + /// controllers on update, never a silent resurrection during hidden ticks. + pub fn revive_owner(&mut self, owner: &ContentOwner) -> PanelResult<()> { + self.require_live()?; + owner.validate()?; + self.destroyed_owners.remove(owner); + Ok(()) + } + + pub fn shutdown(&mut self, local: &mut dyn PanelLocalServices) -> PanelResult<()> { + for retained in self.controllers.values() { + retained.controller.prepare_lifecycle(&LifecycleEvent::DestroyOwner)?; + } + for (key, retained) in &mut self.controllers { + local.release(&retained.scope, &key.instance); + retained.controller.lifecycle(&LifecycleEvent::DestroyOwner); + } + self.controllers.clear(); + self.destroyed = true; + Ok(()) + } +} diff --git a/crates/ui-egui/src/panel_runtime/tests.rs b/crates/ui-egui/src/panel_runtime/tests.rs new file mode 100644 index 000000000..ccee0ee4a --- /dev/null +++ b/crates/ui-egui/src/panel_runtime/tests.rs @@ -0,0 +1,1691 @@ +use solidcraft_engine::panels::*; + +use super::*; + +fn id(value: &str) -> InstanceId { + InstanceId::new(value).unwrap() +} +fn section(value: &str) -> SectionId { + SectionId::new(value).unwrap() +} +fn capacity() -> LogicalRect { + LogicalRect { origin: Point { x: 0.0, y: 0.0 }, size: Size { width: 1400.0, height: 1000.0 } } +} +fn editor_key(h: &PanelMountHarness) -> ControllerKey { + ControllerKey { instance: id("editor"), owner: ContentOwner::Document(h.runtime.environment().document.clone().unwrap()) } +} +fn open_editor(h: &mut PanelMountHarness) { + h.dispatch(vec![fixture_open("fixture.editor", "editor", "editor-section", Zone::Left, 0).unwrap()]).unwrap(); +} +fn move_editor(zone: Zone) -> Mutation { + Mutation::Move { + instance: id("editor"), + destination: Destination::NewSection { + section: section("editor-moved"), + index: 0, + location: if zone == Zone::Floating { + SectionLocation::Floating { origin: Point { x: 50.0, y: 50.0 } } + } else { + SectionLocation::Dock { zone } + }, + size: Size { width: 300.0, height: 280.0 }, + }, + } +} + +#[test] +fn mount_harness_uses_real_controller_slots_and_usable_presentation_context() { + let mut h = PanelMountHarness::new(false).unwrap(); + open_editor(&mut h); + let resolved = h.mount(capacity()).unwrap(); + assert_eq!(resolved.panels.len(), 1); + assert!(h.host.slot_calls >= 3); + assert_eq!(h.host.slot_calls % 3, 0); + let record = h.host.mounts.back().unwrap(); + assert_eq!(record.context.usable_body.size.height, 192.0); + assert_eq!(record.context.flow, Flow::Tall); + assert_eq!(record.presentation.actions.len(), 3); + assert!(h.probe.state(&editor_key(&h)).unwrap().renders >= 1); + assert!(h.runtime.state(&editor_key(&h)).unwrap().presented); +} + +#[test] +fn hiding_tabbing_collapsing_and_reparenting_retain_editor_transaction() { + let mut h = PanelMountHarness::new(false).unwrap(); + open_editor(&mut h); + h.mount(capacity()).unwrap(); + let key = editor_key(&h); + h.probe.edit(&key, |s| s.draft = "retained draft".into()).unwrap(); + h.dispatch(vec![ + Mutation::Open { + kind: PanelKind::new("fixture.log").unwrap(), + instance: id("log"), + destination: Some(Destination::JoinTab { section: section("editor-section"), index: 1 }), + }, + Mutation::Activate { instance: id("log") }, + ]) + .unwrap(); + h.mount(capacity()).unwrap(); + assert!(!h.runtime.state(&key).unwrap().presented); + let updates = h.probe.state(&key).unwrap().updates; + h.dispatch(vec![Mutation::Collapse { section: section("editor-section"), collapsed: true }]).unwrap(); + h.tick().unwrap(); + h.dispatch(vec![move_editor(Zone::Floating)]).unwrap(); + h.tick().unwrap(); + let state = h.probe.state(&key).unwrap(); + assert!(state.transaction_live); + assert_eq!(state.draft, "retained draft"); + assert_eq!((state.cancels, state.applies, state.finishes), (0, 0, 0)); + assert!(state.updates > updates); + assert_eq!(h.commands.calls, 0); + assert_eq!(state.reparents, 1); +} + +#[test] +fn explicit_close_cancel_preflight_failure_preserves_whole_transaction() { + let mut h = PanelMountHarness::new(false).unwrap(); + open_editor(&mut h); + h.mount(capacity()).unwrap(); + let key = editor_key(&h); + h.probe.edit(&key, |s| s.reject_cancel = true).unwrap(); + let before = h.runtime.layout().inspect(); + let count = h.runtime.controller_count(); + let commits = h.native.commits; + let result = h.dispatch(vec![ + Mutation::SetSize { section: section("editor-section"), size: Size { width: 400.0, height: 300.0 } }, + Mutation::Close { instance: id("editor") }, + ]); + assert_eq!(result.unwrap_err().rule, Rule::Lifecycle); + assert_eq!(h.runtime.layout().inspect(), before); + assert_eq!(h.runtime.controller_count(), count); + assert_eq!(h.native.commits, commits); + assert!(h.probe.state(&key).unwrap().transaction_live); + assert_eq!(h.probe.state(&key).unwrap().cancels, 0); + h.probe.edit(&key, |s| s.reject_cancel = false).unwrap(); + h.dispatch(vec![Mutation::Close { instance: id("editor") }]).unwrap(); + assert_eq!(h.probe.state(&key).unwrap().cancels, 1); + assert!(!h.probe.state(&key).unwrap().transaction_live); + h.dispatch(vec![Mutation::Close { instance: id("editor") }]).unwrap(); + assert_eq!(h.probe.state(&key).unwrap().cancels, 1); + h.dispatch(vec![Mutation::Open { kind: PanelKind::new("fixture.editor").unwrap(), instance: id("editor"), destination: None }]).unwrap(); + assert!(h.probe.state(&key).unwrap().transaction_live); +} + +#[test] +fn saved_open_layout_reopens_an_explicitly_closed_editor_before_mount() { + let mut h = PanelMountHarness::new(false).unwrap(); + open_editor(&mut h); + h.mount(capacity()).unwrap(); + let saved = h.runtime.layout().layout().clone(); + let key = editor_key(&h); + h.probe.edit(&key, |s| s.draft = "closed editor draft".into()).unwrap(); + h.dispatch(vec![Mutation::Close { instance: id("editor") }]).unwrap(); + assert!(!h.probe.state(&key).unwrap().transaction_live); + assert_eq!(h.probe.state(&key).unwrap().cancels, 1); + h.apply_layout(saved.clone(), None).unwrap(); + assert!(h.probe.state(&key).unwrap().transaction_live); + assert_eq!(h.probe.state(&key).unwrap().reopens, 1); + h.mount(capacity()).unwrap(); + assert!(h.runtime.state(&key).unwrap().presented); + assert_eq!(h.runtime.controller_count(), 1); + assert_eq!(h.probe.state(&key).unwrap().draft, "closed editor draft"); + // Committed Reopen clears the lifecycle flag; repeated snapshots cannot reset it. + h.probe.edit(&key, |s| s.reject_reopen = true).unwrap(); + h.apply_layout(saved, None).unwrap(); + assert_eq!(h.probe.state(&key).unwrap().reopens, 1); +} + +#[test] +fn snapshot_closed_entries_hide_live_drafts_but_start_initially_dormant_editors_on_open() { + let mut h = PanelMountHarness::new(false).unwrap(); + open_editor(&mut h); + h.mount(capacity()).unwrap(); + let saved = h.runtime.layout().layout().clone(); + let key = editor_key(&h); + h.probe + .edit(&key, |s| { + s.draft = "hidden live draft".into(); + s.reject_reopen = true; + }) + .unwrap(); + let mut hidden = saved.clone(); + hidden.sections.clear(); + hidden.instances.first_mut().unwrap().requested_open = false; + h.apply_layout(hidden.clone(), None).unwrap(); + h.tick().unwrap(); + assert!(!h.runtime.state(&key).unwrap().requested_open); + assert!(h.probe.state(&key).unwrap().transaction_live); + h.apply_layout(saved.clone(), None).unwrap(); + h.mount(capacity()).unwrap(); + assert_eq!(h.probe.state(&key).unwrap().reopens, 0); + assert_eq!(h.probe.state(&key).unwrap().cancels, 0); + assert_eq!(h.probe.state(&key).unwrap().draft, "hidden live draft"); + + let mut dormant = PanelMountHarness::new(false).unwrap(); + dormant.apply_layout(hidden, None).unwrap(); + dormant.tick().unwrap(); + let dormant_key = editor_key(&dormant); + assert!(!dormant.probe.state(&dormant_key).unwrap().transaction_live); + dormant.apply_layout(saved, None).unwrap(); + dormant.mount(capacity()).unwrap(); + assert!(dormant.probe.state(&dormant_key).unwrap().transaction_live); + assert_eq!(dormant.probe.state(&dormant_key).unwrap().reopens, 1); +} + +#[test] +fn snapshot_reopen_refusal_is_atomic_across_retained_documents_and_workspace_switches() { + let mut h = PanelMountHarness::new(true).unwrap(); + open_editor(&mut h); + h.dispatch(vec![ + fixture_open("fixture.application", "application", "application-section", Zone::Right, 1).unwrap(), + fixture_open("fixture.log", "log", "log-section", Zone::Bottom, 2).unwrap(), + ]) + .unwrap(); + h.tick().unwrap(); + let first = editor_key(&h); + let mut next = h.runtime.environment().clone(); + next.document = Some(DocumentId::new("second-document").unwrap()); + h.runtime.set_environment(next, &mut h.local).unwrap(); + h.mount(capacity()).unwrap(); + let second = editor_key(&h); + h.probe.edit(&first, |s| s.draft = "first canceled draft".into()).unwrap(); + h.probe.edit(&second, |s| s.draft = "second canceled draft".into()).unwrap(); + let mut saved = h.runtime.layout().layout().clone(); + saved.workspace = WorkspaceId::new("reopened-workspace").unwrap(); + h.dispatch(vec![Mutation::Close { instance: id("editor") }]).unwrap(); + h.mount(capacity()).unwrap(); + for key in [&first, &second] { + assert!(!h.probe.state(key).unwrap().transaction_live); + assert_eq!(h.probe.state(key).unwrap().cancels, 1); + } + let scope = h.local.scopes[&id("application")].clone(); + h.local.request(&scope, LocalRequest::KeyboardOwner { instance: id("application"), control: ControlId::new("draft").unwrap() }).unwrap(); + let before = h.runtime.layout().inspect(); + let environment = h.runtime.environment().clone(); + let count = h.runtime.controller_count(); + let keyboard = h.local.keyboard.clone(); + let scopes = h.local.scopes.clone(); + let releases = h.local.releases; + let commits = h.native.commits; + let hosts = h.native.hosts.clone(); + h.probe.edit(&second, |s| s.reject_reopen = true).unwrap(); + assert_eq!(h.apply_layout(saved.clone(), None).unwrap_err().rule, Rule::Lifecycle); + h.probe.edit(&second, |s| s.reject_reopen = false).unwrap(); + h.native.fail_prepare = true; + assert_eq!(h.apply_layout(saved.clone(), None).unwrap_err().rule, Rule::Capability); + assert_eq!(h.runtime.layout().inspect(), before); + assert_eq!(h.runtime.environment(), &environment); + assert_eq!(h.runtime.controller_count(), count); + assert_eq!(h.local.keyboard, keyboard); + assert_eq!(h.local.scopes, scopes); + assert_eq!(h.local.releases, releases); + assert_eq!(h.native.commits, commits); + assert_eq!(h.native.hosts, hosts); + for key in [&first, &second] { + assert_eq!(h.probe.state(key).unwrap().reopens, 0); + assert!(!h.probe.state(key).unwrap().transaction_live); + } + h.native.fail_prepare = false; + h.apply_layout(saved, None).unwrap(); + h.mount(capacity()).unwrap(); + assert_eq!(h.runtime.controller_count(), count + 1, "only the destination workspace log is new"); + for (key, draft) in [(&first, "first canceled draft"), (&second, "second canceled draft")] { + let state = h.probe.state(key).unwrap(); + assert!(state.transaction_live); + assert_eq!(state.reopens, 1); + assert_eq!(state.cancels, 1); + assert_eq!(state.draft, draft); + } +} + +#[test] +fn snapshot_reopen_targets_the_destination_workspace_owner() { + let mut h = PanelMountHarness::new(false).unwrap(); + h.dispatch(vec![fixture_open("fixture.log", "log", "log-section", Zone::Left, 0).unwrap()]).unwrap(); + let first_layout = h.runtime.layout().layout().clone(); + let first = ControllerKey { instance: id("log"), owner: ContentOwner::Workspace(first_layout.workspace.clone()) }; + h.dispatch(vec![Mutation::Close { instance: id("log") }]).unwrap(); + let mut second_layout = first_layout.clone(); + second_layout.workspace = WorkspaceId::new("second-workspace").unwrap(); + h.apply_layout(second_layout.clone(), None).unwrap(); + let second = ControllerKey { instance: id("log"), owner: ContentOwner::Workspace(second_layout.workspace.clone()) }; + h.dispatch(vec![Mutation::Close { instance: id("log") }]).unwrap(); + h.apply_layout(first_layout, None).unwrap(); + assert_eq!(h.probe.state(&first).unwrap().reopens, 1); + assert_eq!(h.probe.state(&second).unwrap().reopens, 0); + h.apply_layout(second_layout, None).unwrap(); + assert_eq!(h.probe.state(&first).unwrap().reopens, 1); + assert_eq!(h.probe.state(&second).unwrap().reopens, 1); +} + +#[test] +fn contextual_unavailability_retains_dormant_editor_and_background_updates() { + let mut h = PanelMountHarness::new(false).unwrap(); + open_editor(&mut h); + h.mount(capacity()).unwrap(); + let key = editor_key(&h); + let before = h.runtime.layout().layout().clone(); + h.models.editable = false; + h.tick().unwrap(); + assert_eq!(h.runtime.layout().layout(), &before); + assert!(matches!(h.runtime.state(&key).unwrap().available, Availability::Unavailable { .. })); + assert!(!h.runtime.state(&key).unwrap().presented); + assert_eq!(h.dispatch(vec![Mutation::Focus { instance: id("editor") }]).unwrap_err().rule, Rule::Availability); + let updates = h.probe.state(&key).unwrap().updates; + h.tick().unwrap(); + assert!(h.probe.state(&key).unwrap().updates > updates); + h.models.editable = true; + h.mount(capacity()).unwrap(); + assert!(h.runtime.state(&key).unwrap().presented); + assert!(h.probe.state(&key).unwrap().transaction_live); + assert_eq!(h.probe.state(&key).unwrap().cancels, 0); +} + +#[test] +fn unavailable_new_editor_does_not_commit_layout_or_controller() { + let mut h = PanelMountHarness::new(false).unwrap(); + h.models.editable = false; + let before = h.runtime.layout().inspect(); + assert_eq!( + h.dispatch(vec![fixture_open("fixture.editor", "editor", "editor-section", Zone::Left, 0).unwrap()]).unwrap_err().rule, + Rule::Availability + ); + assert_eq!(h.runtime.layout().inspect(), before); + assert_eq!(h.runtime.controller_count(), 0); +} + +#[test] +fn document_switch_retains_independent_editors_and_does_not_duplicate_layout() { + let mut h = PanelMountHarness::new(false).unwrap(); + open_editor(&mut h); + h.mount(capacity()).unwrap(); + let first_key = editor_key(&h); + h.probe.edit(&first_key, |s| s.draft = "document one draft".into()).unwrap(); + let original = h.runtime.environment().clone(); + let layout = h.runtime.layout().layout().clone(); + let mut next = original.clone(); + next.document = Some(DocumentId::new("another-document").unwrap()); + h.runtime.set_environment(next, &mut h.local).unwrap(); + h.tick().unwrap(); + assert_eq!(h.runtime.controller_count(), 2); + assert_eq!(h.runtime.layout().layout(), &layout); + let second_key = editor_key(&h); + h.probe.edit(&second_key, |s| s.draft = "document two draft".into()).unwrap(); + let updates = h.probe.state(&first_key).unwrap().updates; + h.tick().unwrap(); + assert!(h.probe.state(&first_key).unwrap().updates > updates); + h.runtime.set_environment(original, &mut h.local).unwrap(); + h.mount(capacity()).unwrap(); + assert_eq!(h.runtime.controller_count(), 2); + assert_eq!(h.probe.state(&first_key).unwrap().draft, "document one draft"); + assert_eq!(h.probe.state(&second_key).unwrap().draft, "document two draft"); + assert_eq!(h.probe.state(&first_key).unwrap().cancels, 0); +} + +fn document_editor_harness() -> PanelMountHarness { + let mut h = PanelMountHarness::without_content(false).unwrap(); + for (kind, editor, ownership) in [ + ("fixture.application", false, Ownership::Application), + ("fixture.log", true, Ownership::Document), + ("fixture.pin", false, Ownership::Workspace), + ] { + h.runtime.register(PanelKind::new(kind).unwrap(), fixture_controller_binding(&h.probe, editor, ownership)).unwrap(); + } + h +} + +#[test] +fn all_open_documents_retain_four_editors_plus_application_and_workspace_services() { + let mut h = document_editor_harness(); + h.dispatch(vec![ + fixture_open("fixture.application", "application", "application-section", Zone::Right, 0).unwrap(), + fixture_open("fixture.pin", "workspace", "workspace-section", Zone::Left, 1).unwrap(), + fixture_open("fixture.log", "document-0", "document-section-0", Zone::Floating, 2).unwrap(), + fixture_open("fixture.log", "document-1", "document-section-1", Zone::Floating, 3).unwrap(), + fixture_open("fixture.log", "document-2", "document-section-2", Zone::Floating, 4).unwrap(), + fixture_open("fixture.log", "document-3", "document-section-3", Zone::Floating, 5).unwrap(), + ]) + .unwrap(); + let saved = h.runtime.layout().layout().clone(); + let original = h.runtime.environment().clone(); + let app_key = ControllerKey { instance: id("application"), owner: ContentOwner::Application }; + let workspace_key = ControllerKey { instance: id("workspace"), owner: ContentOwner::Workspace(saved.workspace.clone()) }; + let mut editor_keys = Vec::new(); + assert_eq!(MAX_RETAINED_DOCUMENT_OWNERS, crate::documents::MAX_OPEN); + for document in 0..crate::documents::MAX_OPEN { + let mut environment = original.clone(); + environment.document = Some(DocumentId::new(format!("retained-document-{document}")).unwrap()); + // The initial fixture owner counts toward the same 32-document budget. + if document == 0 { + environment = original.clone(); + } + h.runtime.set_environment(environment, &mut h.local).unwrap(); + h.tick().unwrap(); + for panel in 0..4 { + let key = ControllerKey { + instance: id(&format!("document-{panel}")), + owner: ContentOwner::Document(h.runtime.environment().document.clone().unwrap()), + }; + h.probe + .edit(&key, |s| { + s.draft = format!("document {document}, panel {panel}"); + s.reject_cancel = true; + s.reject_reopen = true; + }) + .unwrap(); + editor_keys.push(key); + } + } + assert_eq!(h.runtime.controller_count(), crate::documents::MAX_OPEN * 4 + 2); + assert!(h.runtime.controller_count() > MAX_INSTANCES); + assert_eq!(h.runtime.layout().layout(), &saved); + h.apply_layout(Layout::empty(saved.workspace.clone()), None).unwrap(); + let keys: Vec<_> = editor_keys.iter().cloned().chain([app_key, workspace_key]).collect(); + let updates: Vec<_> = keys.iter().map(|key| h.probe.state(key).unwrap().updates).collect(); + for _ in 0..3 { + h.tick().unwrap(); + } + for (key, before) in keys.iter().zip(updates) { + assert_eq!(h.probe.state(key).unwrap().updates, before + 3); + assert!(!h.runtime.state(key).unwrap().presented); + } + h.apply_layout(saved.clone(), None).unwrap(); + h.runtime.set_environment(original, &mut h.local).unwrap(); + h.mount(capacity()).unwrap(); + for (index, key) in editor_keys.iter().enumerate() { + let state = h.probe.state(key).unwrap(); + assert_eq!(state.draft, format!("document {}, panel {}", index / 4, index % 4)); + assert!(state.transaction_live); + assert_eq!((state.cancels, state.reopens, state.destroys), (0, 0, 0)); + } + assert_eq!(h.runtime.controller_count(), crate::documents::MAX_OPEN * 4 + 2); + assert_eq!(h.commands.calls, 0); +} + +#[test] +fn retained_document_owner_capacity_refusal_preserves_environment_layout_and_local_input() { + let mut h = document_editor_harness(); + h.dispatch(vec![fixture_open("fixture.log", "editor", "editor-section", Zone::Left, 0).unwrap()]).unwrap(); + let original = h.runtime.environment().clone(); + for document in 1..MAX_RETAINED_DOCUMENT_OWNERS { + let mut environment = original.clone(); + environment.document = Some(DocumentId::new(format!("document-{document}")).unwrap()); + h.runtime.set_environment(environment, &mut h.local).unwrap(); + } + h.mount(capacity()).unwrap(); + let key = editor_key(&h); + h.probe.edit(&key, |s| s.draft = "at document capacity".into()).unwrap(); + let scope = h.local.scopes[&id("editor")].clone(); + h.local.request(&scope, LocalRequest::KeyboardOwner { instance: id("editor"), control: ControlId::new("draft").unwrap() }).unwrap(); + let before = h.runtime.layout().inspect(); + let environment = h.runtime.environment().clone(); + let count = h.runtime.controller_count(); + let keyboard = h.local.keyboard.clone(); + let scopes = h.local.scopes.clone(); + let releases = h.local.releases; + let commits = h.native.commits; + let mut excess = environment.clone(); + excess.document = Some(DocumentId::new("excess-document").unwrap()); + assert_eq!(h.runtime.set_environment(excess, &mut h.local).unwrap_err().rule, Rule::CollectionLimit); + assert_eq!(h.runtime.environment(), &environment); + assert_eq!(h.runtime.layout().inspect(), before); + assert_eq!(h.runtime.controller_count(), count); + assert_eq!(h.local.keyboard, keyboard); + assert_eq!(h.local.scopes, scopes); + assert_eq!(h.local.releases, releases); + assert_eq!(h.native.commits, commits); + h.tick().unwrap(); + assert!(h.runtime.update_errors().is_empty()); + assert_eq!(h.probe.state(&key).unwrap().draft, "at document capacity"); + assert!(h.probe.state(&key).unwrap().transaction_live); + // Returning to a retained open owner succeeds at capacity, without eviction. + h.runtime.set_environment(original, &mut h.local).unwrap(); + h.tick().unwrap(); + assert_eq!(h.runtime.controller_count(), MAX_RETAINED_DOCUMENT_OWNERS); +} + +#[test] +fn retained_workspace_owner_capacity_refusal_is_an_atomic_snapshot_failure() { + let mut h = PanelMountHarness::new(false).unwrap(); + h.dispatch(vec![ + fixture_open("fixture.application", "application", "application-section", Zone::Left, 0).unwrap(), + fixture_open("fixture.log", "log", "log-section", Zone::Right, 1).unwrap(), + ]) + .unwrap(); + let saved = h.runtime.layout().layout().clone(); + // The application consumes one non-document owner; workspaces share the rest. + for workspace in 1..MAX_RETAINED_OTHER_OWNERS - 1 { + let mut layout = saved.clone(); + layout.workspace = WorkspaceId::new(format!("retained-workspace-{workspace}")).unwrap(); + h.apply_layout(layout, None).unwrap(); + } + h.mount(capacity()).unwrap(); + assert_eq!(h.runtime.controller_count(), MAX_RETAINED_OTHER_OWNERS); + let scope = h.local.scopes[&id("application")].clone(); + h.local.request(&scope, LocalRequest::KeyboardOwner { instance: id("application"), control: ControlId::new("draft").unwrap() }).unwrap(); + let before = h.runtime.layout().inspect(); + let environment = h.runtime.environment().clone(); + let keyboard = h.local.keyboard.clone(); + let scopes = h.local.scopes.clone(); + let releases = h.local.releases; + let commits = h.native.commits; + let mut excess = saved.clone(); + excess.workspace = WorkspaceId::new("excess-workspace").unwrap(); + assert_eq!(h.apply_layout(excess, None).unwrap_err().rule, Rule::CollectionLimit); + assert_eq!(h.runtime.layout().inspect(), before); + assert_eq!(h.runtime.environment(), &environment); + assert_eq!(h.runtime.controller_count(), MAX_RETAINED_OTHER_OWNERS); + assert_eq!(h.local.keyboard, keyboard); + assert_eq!(h.local.scopes, scopes); + assert_eq!(h.local.releases, releases); + assert_eq!(h.native.commits, commits); + h.apply_layout(saved, None).unwrap(); + h.tick().unwrap(); + assert_eq!(h.runtime.controller_count(), MAX_RETAINED_OTHER_OWNERS); +} + +#[test] +fn retained_controller_capacity_per_owner_does_not_increase_the_layout_instance_limit() { + let mut h = document_editor_harness(); + let mutations: Vec<_> = (0..MAX_INSTANCES) + .map(|index| { + let group = index / MAX_TABS; + let instance = id(&format!("editor-{index}")); + let section_id = section(&format!("editors-{group}")); + if index % MAX_TABS == 0 { + fixture_open("fixture.log", &instance.0, §ion_id.0, Zone::Left, group).unwrap() + } else { + Mutation::Open { + kind: PanelKind::new("fixture.log").unwrap(), + instance, + destination: Some(Destination::JoinTab { section: section_id, index: index % MAX_TABS }), + } + } + }) + .collect(); + for batch in mutations.chunks(MAX_MUTATIONS) { + h.dispatch(batch.to_vec()).unwrap(); + } + h.mount(capacity()).unwrap(); + assert_eq!(h.runtime.controller_count(), MAX_INSTANCES); + let first = ControllerKey { instance: id("editor-0"), owner: ContentOwner::Document(h.runtime.environment().document.clone().unwrap()) }; + h.probe.edit(&first, |s| s.draft = "full owner draft".into()).unwrap(); + let before = h.runtime.layout().inspect(); + let commits = h.native.commits; + let releases = h.local.releases; + // One visible layout instance still cannot introduce a 129th retained + // identity/controller alongside this owner's hidden drafts. The engine's + // identity cap and runtime's per-owner bound stay aligned. + let mut source = fixture_service(false).unwrap(); + source.dispatch(transaction(vec![fixture_open("fixture.log", "excess-editor", "excess-section", Zone::Left, 0).unwrap()])).unwrap(); + assert_eq!(h.apply_layout(source.layout().clone(), None).unwrap_err().rule, Rule::CollectionLimit); + assert_eq!(h.runtime.layout().inspect(), before); + assert_eq!(h.runtime.controller_count(), MAX_INSTANCES); + assert_eq!(h.native.commits, commits); + assert_eq!(h.local.releases, releases); + assert_eq!(h.probe.state(&first).unwrap().draft, "full owner draft"); + assert!(h.probe.state(&first).unwrap().transaction_live); + assert_eq!(h.probe.state(&first).unwrap().destroys, 0); + assert_eq!( + h.dispatch(vec![fixture_open("fixture.log", "excess-editor", "excess-section", Zone::Left, 4).unwrap()]).unwrap_err().rule, + Rule::CollectionLimit + ); + h.apply_layout(before.layout, None).unwrap(); + h.tick().unwrap(); + assert_eq!(h.runtime.controller_count(), MAX_INSTANCES); +} + +#[test] +fn multi_instance_controllers_have_independent_identity_and_service_lifetimes() { + let mut h = PanelMountHarness::new(false).unwrap(); + h.dispatch(vec![ + fixture_open("fixture.log", "log-one", "logs-one", Zone::Left, 0).unwrap(), + fixture_open("fixture.log", "log-two", "logs-two", Zone::Right, 1).unwrap(), + ]) + .unwrap(); + h.mount(capacity()).unwrap(); + assert_eq!(h.runtime.controller_count(), 2); + let first = ControllerKey { instance: id("log-one"), owner: ContentOwner::Workspace(h.runtime.environment().workspace.clone()) }; + let second = ControllerKey { instance: id("log-two"), owner: first.owner.clone() }; + h.dispatch(vec![Mutation::Close { instance: id("log-one") }]).unwrap(); + h.tick().unwrap(); + assert!(!h.runtime.state(&first).unwrap().requested_open); + assert!(h.runtime.state(&second).unwrap().requested_open); + assert!(h.probe.state(&first).unwrap().updates > 0); + h.dispatch(vec![Mutation::Destroy { instance: id("log-one") }]).unwrap(); + assert_eq!(h.runtime.controller_count(), 1); + assert_eq!(h.probe.state(&first).unwrap().destroys, 1); +} + +#[test] +fn native_preflight_failure_and_close_redock_preserve_controller_identity() { + let mut h = PanelMountHarness::new(true).unwrap(); + open_editor(&mut h); + h.mount(capacity()).unwrap(); + let key = editor_key(&h); + let before = h.runtime.layout().inspect(); + let mutation = Mutation::Move { + instance: id("editor"), + destination: Destination::NewSection { + section: section("native-editor"), + index: 0, + location: SectionLocation::Window { + host: HostId::new("native-host").unwrap(), + origin: Point { x: 0.0, y: 0.0 }, + return_to: DockReturn { zone: Zone::Left, index: 0, size: Size { width: 280.0, height: 240.0 }, collapsed: false, join: None }, + }, + size: Size { width: 400.0, height: 300.0 }, + }, + }; + h.native.fail_prepare = true; + assert_eq!(h.dispatch(vec![mutation.clone()]).unwrap_err().rule, Rule::Capability); + assert_eq!(h.runtime.layout().inspect(), before); + assert!(h.native.hosts.is_empty()); + assert_eq!(h.probe.state(&key).unwrap().reparents, 0); + h.native.fail_prepare = false; + h.dispatch(vec![mutation]).unwrap(); + assert_eq!(h.native.hosts.len(), 1); + h.dispatch(vec![Mutation::NativeClose { host: HostId::new("native-host").unwrap() }]).unwrap(); + assert!(h.native.hosts.is_empty()); + assert_eq!(h.runtime.controller_count(), 1); + let state = h.probe.state(&key).unwrap(); + assert!(state.transaction_live); + assert_eq!(state.cancels, 0); + assert_eq!(state.reparents, 2); +} + +#[test] +fn content_apply_finish_and_cancel_are_separate_from_layout_actions() { + let mut h = PanelMountHarness::new(false).unwrap(); + open_editor(&mut h); + h.tick().unwrap(); + let key = editor_key(&h); + h.commands.fail = true; + assert!( + h.runtime + .content_action( + &id("editor"), + &ControlId::new("apply").unwrap(), + &mut ContentServices { models: &h.models, commands: &mut h.commands, local: &mut h.local } + ) + .is_err() + ); + assert_eq!(h.probe.state(&key).unwrap().applies, 0); + h.commands.fail = false; + h.runtime + .content_action( + &id("editor"), + &ControlId::new("apply").unwrap(), + &mut ContentServices { models: &h.models, commands: &mut h.commands, local: &mut h.local }, + ) + .unwrap(); + assert_eq!(h.commands.calls, 1); + assert!(h.probe.state(&key).unwrap().transaction_live); + h.runtime + .content_action( + &id("editor"), + &ControlId::new("finish").unwrap(), + &mut ContentServices { models: &h.models, commands: &mut h.commands, local: &mut h.local }, + ) + .unwrap(); + assert_eq!(h.commands.calls, 2); + assert!(!h.probe.state(&key).unwrap().transaction_live); + assert!(h.runtime.layout().layout().instance(&id("editor")).unwrap().requested_open); +} + +#[test] +fn local_keyboard_drops_overlays_clipboard_and_picking_reject_wrong_scope() { + let mut local = FakeLocalServices::default(); + let scope = LocalScope { + workspace: WorkspaceId::new("workspace").unwrap(), + document: Some(DocumentId::new("document").unwrap()), + viewport: ViewportId::new("viewport").unwrap(), + }; + local.bind(id("one"), scope.clone()).unwrap(); + local.bind(id("two"), scope.clone()).unwrap(); + let keyboard = LocalRequest::KeyboardOwner { instance: id("one"), control: ControlId::new("editor").unwrap() }; + local.request(&scope, keyboard).unwrap(); + assert_eq!( + local.request(&scope, LocalRequest::KeyboardOwner { instance: id("two"), control: ControlId::new("editor").unwrap() }).unwrap_err().rule, + Rule::Lifecycle + ); + let mut other = scope.clone(); + other.viewport = ViewportId::new("other").unwrap(); + let requests = [ + LocalRequest::FileDrop { instance: id("one"), name: "part.sc".into(), bytes: vec![0; 10] }, + LocalRequest::PointerDrop { instance: id("one"), at: Point { x: 1.0, y: 2.0 }, payload: "fixture".into() }, + LocalRequest::Overlay { + instance: id("one"), + region: InputRegion { + control: ControlId::new("overlay").unwrap(), + role: InputRole::Overlay, + bounds: capacity(), + keyboard_focusable: true, + accessible_name: "Specimen".into(), + }, + }, + LocalRequest::Clipboard { instance: id("one"), text: "fixture".into() }, + LocalRequest::Pick { instance: id("one"), at: Point { x: 5.0, y: 5.0 } }, + ]; + for request in requests { + assert_eq!(local.request(&other, request.clone()).unwrap_err().rule, Rule::Placement); + let mut wrong_document = scope.clone(); + wrong_document.document = Some(DocumentId::new("wrong-document").unwrap()); + assert_eq!(local.request(&wrong_document, request.clone()).unwrap_err().rule, Rule::Placement); + local.request(&scope, request).unwrap(); + } + local.release(&scope, &id("one")); + assert!(local.keyboard.is_empty()); + assert!(local.requests.is_empty()); +} + +#[test] +fn reparent_releases_host_local_state_and_retains_transaction() { + let mut h = PanelMountHarness::new(false).unwrap(); + open_editor(&mut h); + h.mount(capacity()).unwrap(); + let scope = h.local.scopes.get(&id("editor")).unwrap().clone(); + h.local.request(&scope, LocalRequest::KeyboardOwner { instance: id("editor"), control: ControlId::new("draft").unwrap() }).unwrap(); + h.dispatch(vec![move_editor(Zone::Right)]).unwrap(); + assert!(h.local.keyboard.is_empty()); + assert!(!h.local.scopes.contains_key(&id("editor"))); + assert!(h.probe.state(&editor_key(&h)).unwrap().transaction_live); +} + +#[test] +fn reduced_motion_rtl_and_hidden_updates_are_independent_of_paint() { + let mut h = PanelMountHarness::new(false).unwrap(); + open_editor(&mut h); + let mut environment = h.runtime.environment().clone(); + environment.direction = Direction::Rtl; + h.runtime.set_environment(environment, &mut h.local).unwrap(); + let resolved = h.mount(capacity()).unwrap(); + assert!(resolved.panels.first().unwrap().outer.origin.x > 0.0); + let context = &h.host.mounts.back().unwrap().context; + assert_eq!(context.direction, Direction::Rtl); + assert_eq!(context.motion.duration_ms(250), 0); + assert_eq!(Motion::Animated.duration_ms(600), 500); + let renders = h.probe.state(&editor_key(&h)).unwrap().renders; + h.dispatch(vec![Mutation::Collapse { section: section("editor-section"), collapsed: true }]).unwrap(); + for _ in 0..5 { + h.tick().unwrap(); + } + assert_eq!(h.probe.state(&editor_key(&h)).unwrap().renders, renders); + assert!(h.probe.state(&editor_key(&h)).unwrap().updates >= 6); +} + +#[test] +fn mount_rejects_duplicate_inactive_or_invalid_regions() { + let mut h = PanelMountHarness::new(false).unwrap(); + open_editor(&mut h); + h.tick().unwrap(); + let mut resolved = resolve_geometry(h.runtime.layout(), capacity(), Direction::Ltr, 48.0).unwrap(); + resolved.panels.push(resolved.panels.first().unwrap().clone()); + assert_eq!( + h.runtime + .mount(&resolved, &mut h.host, &mut ContentServices { models: &h.models, commands: &mut h.commands, local: &mut h.local }) + .unwrap_err() + .rule, + Rule::ExactlyOnce + ); + assert_eq!(h.host.slot_calls, 0); + resolved.panels.pop(); + resolved.panels.first_mut().unwrap().body.size.height = f32::INFINITY; + assert_eq!( + h.runtime + .mount(&resolved, &mut h.host, &mut ContentServices { models: &h.models, commands: &mut h.commands, local: &mut h.local }) + .unwrap_err() + .rule, + Rule::Bounds + ); +} + +#[test] +fn shutdown_is_atomic_and_explicit_owner_destruction_does_not_reset_layout() { + let mut h = PanelMountHarness::new(false).unwrap(); + open_editor(&mut h); + h.tick().unwrap(); + let key = editor_key(&h); + let layout = h.runtime.layout().layout().clone(); + h.probe.edit(&key, |s| s.reject_cancel = true).unwrap(); + assert_eq!(h.runtime.shutdown(&mut h.local).unwrap_err().rule, Rule::Lifecycle); + assert_eq!(h.runtime.controller_count(), 1); + assert_eq!(h.probe.state(&key).unwrap().destroys, 0); + h.probe.edit(&key, |s| s.reject_cancel = false).unwrap(); + h.runtime.destroy_owner(&key.owner, &mut h.local).unwrap(); + assert_eq!(h.runtime.controller_count(), 0); + assert_eq!(h.probe.state(&key).unwrap().destroys, 1); + assert_eq!(h.runtime.layout().layout(), &layout); + h.tick().unwrap(); + assert_eq!(h.runtime.controller_count(), 0, "destroyed owners cannot silently return"); + h.runtime.revive_owner(&key.owner).unwrap(); + h.tick().unwrap(); + assert_eq!(h.runtime.controller_count(), 1); +} + +#[test] +fn runtime_action_sink_and_native_service_scopes_use_the_shared_interfaces() { + let mut h = PanelMountHarness::new(true).unwrap(); + { + let mut services = ContentServices { models: &h.models, commands: &mut h.commands, local: &mut h.local }; + let mut adapter = RuntimeActionSink { runtime: &mut h.runtime, native: &mut h.native, services: &mut services }; + let sink: &mut dyn ActionSink = &mut adapter; + sink.dispatch(transaction(vec![fixture_open("fixture.log", "one", "first", Zone::Left, 0).unwrap()])).unwrap(); + assert_eq!(sink.inspect().layout.instances.len(), 1); + } + h.dispatch(vec![Mutation::Move { + instance: id("one"), + destination: Destination::NewSection { + section: section("native"), + index: 0, + location: SectionLocation::Window { + host: HostId::new("native-viewport").unwrap(), + origin: Point { x: 0.0, y: 0.0 }, + return_to: DockReturn { zone: Zone::Left, index: 0, size: Size { width: 280.0, height: 240.0 }, collapsed: false, join: None }, + }, + size: Size { width: 280.0, height: 240.0 }, + }, + }]) + .unwrap(); + h.mount(capacity()).unwrap(); + assert_eq!(h.host.mounts.back().unwrap().context.viewport, ViewportId::new("native-viewport").unwrap()); + let scope = h.local.scopes.get(&id("one")).unwrap().clone(); + assert_eq!(scope.viewport, ViewportId::new("native-viewport").unwrap()); + let mut root = scope.clone(); + root.viewport = h.runtime.environment().viewport.clone(); + assert_eq!(h.local.request(&root, LocalRequest::Clipboard { instance: id("one"), text: "fixture".into() }).unwrap_err().rule, Rule::Placement); +} + +#[test] +fn egui_host_uses_logical_bounds_at_two_hundred_percent_scale() { + let mut h = PanelMountHarness::new(false).unwrap(); + open_editor(&mut h); + h.tick().unwrap(); + h.dispatch(vec![Mutation::SetSize { section: section("editor-section"), size: Size { width: 160.0, height: 120.0 } }]).unwrap(); + let resolved = resolve_geometry(h.runtime.layout(), capacity(), Direction::Ltr, 48.0).unwrap(); + let ctx = egui::Context::default(); + ctx.set_pixels_per_point(2.0); + let mut failure = None; + let _output = ctx.run_ui(egui::RawInput::default(), |root_ui| { + crate::ui_kit::Container::new(root_ui.ctx(), crate::ui_kit::Surface::Viewport).central().show(root_ui, |ui| { + let mut host = EguiPanelHost { ui }; + if let Err(reason) = + h.runtime.mount(&resolved, &mut host, &mut ContentServices { models: &h.models, commands: &mut h.commands, local: &mut h.local }) + { + failure = Some(reason); + } + }); + }); + assert!(failure.is_none(), "{failure:?}"); + assert_eq!(resolved.panels.first().unwrap().outer.size, Size { width: 160.0, height: 120.0 }); + assert!(h.probe.state(&editor_key(&h)).unwrap().renders >= 1); +} + +struct AppFixtureServices { + models: FakeModels, + commands: FakeContentCommands, + local: FakeLocalServices, + refreshed: u64, +} +impl AppPanelServices for AppFixtureServices { + fn refresh_read_only(&mut self, _session: &solidcraft_engine::Session) -> PanelResult<()> { + self.refreshed += 1; + Ok(()) + } + fn services(&mut self) -> ContentServices<'_> { + ContentServices { models: &self.models, commands: &mut self.commands, local: &mut self.local } + } +} + +#[test] +fn solve_app_integration_is_opt_in_and_cannot_dirty_or_mutate_document() { + let mut app = crate::SolveApp::new(solidcraft_engine::Session::default(), Default::default()); + assert!(app.panel_runtime().is_none()); + let doc = app.session.doc.clone(); + let model = app.session.model.state(); + let revision = app.session.revision; + let undo = app.session.undo.len(); + let dirty = app.session.is_dirty(); + let recomputed = app.session.model.recomputed; + let mut h = PanelMountHarness::new(false).unwrap(); + open_editor(&mut h); + app.enable_panel_runtime( + h.runtime, + Box::new(AppFixtureServices { + models: FakeModels { editable: true }, + commands: FakeContentCommands::default(), + local: FakeLocalServices::default(), + refreshed: 0, + }), + ) + .unwrap(); + super::app::tick_app(&mut app); + assert_eq!(app.panel_runtime().unwrap().controller_count(), 2, "the synthetic and real document retain separate controller owners"); + assert!(std::sync::Arc::ptr_eq(&doc, &app.session.doc)); + assert!(std::sync::Arc::ptr_eq(&model, &app.session.model.state())); + assert_eq!(app.session.revision, revision); + assert_eq!(app.session.undo.len(), undo); + assert_eq!(app.session.is_dirty(), dirty); + assert_eq!(app.session.model.recomputed, recomputed); + app.disable_panel_runtime().unwrap(); + assert!(app.panel_runtime().is_none()); +} + +#[test] +fn saved_layout_hiding_and_workspace_switches_retain_all_content_owners() { + let mut h = PanelMountHarness::new(false).unwrap(); + open_editor(&mut h); + h.dispatch(vec![ + fixture_open("fixture.application", "application", "application-section", Zone::Right, 1).unwrap(), + fixture_open("fixture.log", "log", "log-section", Zone::Bottom, 2).unwrap(), + ]) + .unwrap(); + h.mount(capacity()).unwrap(); + let saved = h.runtime.layout().layout().clone(); + let key = editor_key(&h); + let app_key = ControllerKey { instance: id("application"), owner: ContentOwner::Application }; + let log_key = ControllerKey { instance: id("log"), owner: ContentOwner::Workspace(saved.workspace.clone()) }; + for (key, draft) in [(&key, "active editor draft"), (&app_key, "application conversation"), (&log_key, "workspace conversation")] { + h.probe.edit(key, |s| s.draft = draft.into()).unwrap(); + } + h.probe + .edit(&key, |s| { + s.reject_cancel = true; + s.reject_reopen = true; + }) + .unwrap(); + let updates = h.probe.state(&key).unwrap().updates; + let hidden = Layout::empty(saved.workspace.clone()); + h.apply_layout(hidden, None).unwrap(); + let resolved = h.mount(capacity()).unwrap(); + assert!(resolved.panels.is_empty()); + assert!(resolved.rails.is_empty()); + assert!(!h.runtime.state(&key).unwrap().presented); + assert!(h.probe.state(&key).unwrap().transaction_live); + assert!(h.probe.state(&key).unwrap().updates > updates); + assert_eq!(h.probe.state(&key).unwrap().cancels, 0); + let mut other = saved.clone(); + other.workspace = WorkspaceId::new("workspace-two").unwrap(); + h.apply_layout(other.clone(), None).unwrap(); + h.tick().unwrap(); + let other_log = ControllerKey { instance: id("log"), owner: ContentOwner::Workspace(other.workspace.clone()) }; + assert_eq!(h.runtime.controller_count(), 4); + assert!(h.runtime.state(&other_log).is_some()); + assert!(!h.runtime.state(&log_key).unwrap().presented); + let hidden_updates = h.probe.state(&log_key).unwrap().updates; + h.tick().unwrap(); + assert!(h.probe.state(&log_key).unwrap().updates > hidden_updates); + h.probe.edit(&other_log, |s| s.draft = "other workspace draft".into()).unwrap(); + h.apply_layout(saved.clone(), None).unwrap(); + h.mount(capacity()).unwrap(); + assert_eq!(h.runtime.layout().layout(), &saved); + assert_eq!(h.runtime.environment().workspace, saved.workspace); + assert_eq!(h.runtime.controller_count(), 4); + assert!(h.runtime.state(&key).unwrap().presented); + for (key, draft) in [ + (&key, "active editor draft"), + (&app_key, "application conversation"), + (&log_key, "workspace conversation"), + (&other_log, "other workspace draft"), + ] { + assert_eq!(h.probe.state(key).unwrap().draft, draft); + } + assert_eq!((h.probe.state(&key).unwrap().cancels, h.commands.calls), (0, 0)); + assert_eq!(h.probe.state(&key).unwrap().reopens, 0); +} + +#[test] +fn failed_layout_application_preserves_environment_controllers_native_and_local_state() { + let mut h = PanelMountHarness::new(true).unwrap(); + open_editor(&mut h); + h.mount(capacity()).unwrap(); + let scope = h.local.scopes[&id("editor")].clone(); + h.local.request(&scope, LocalRequest::KeyboardOwner { instance: id("editor"), control: ControlId::new("draft").unwrap() }).unwrap(); + let before = h.runtime.layout().inspect(); + let environment = h.runtime.environment().clone(); + let controllers = h.runtime.controller_count(); + let keyboard = h.local.keyboard.clone(); + let scopes = h.local.scopes.clone(); + let releases = h.local.releases; + let commits = h.native.commits; + let mut other = before.layout.clone(); + other.workspace = WorkspaceId::new("other-workspace").unwrap(); + h.native.fail_prepare = true; + assert_eq!(h.apply_layout(other.clone(), Some(before.revision)).unwrap_err().rule, Rule::Capability); + assert_eq!(h.runtime.layout().inspect(), before); + assert_eq!(h.runtime.environment(), &environment); + assert_eq!(h.runtime.controller_count(), controllers); + assert_eq!(h.local.keyboard, keyboard); + assert_eq!(h.local.scopes, scopes); + assert_eq!(h.local.releases, releases); + assert_eq!(h.native.commits, commits); + h.native.fail_prepare = false; + assert_eq!(h.apply_layout(other.clone(), Some(before.revision + 1)).unwrap_err().rule, Rule::Revision); + other.instances.first_mut().unwrap().kind = PanelKind::new("fixture.log").unwrap(); + assert_eq!(h.apply_layout(other, None).unwrap_err().rule, Rule::DuplicateId); + assert_eq!(h.runtime.layout().inspect(), before); + assert_eq!(h.local.keyboard, keyboard); +} + +#[test] +fn snapshot_application_keeps_missing_bindings_and_unavailable_content_dormant() { + let mut source = PanelMountHarness::new(false).unwrap(); + open_editor(&mut source); + let saved = source.runtime.layout().layout().clone(); + let mut h = PanelMountHarness::without_content(false).unwrap(); + h.apply_layout(saved.clone(), None).unwrap(); + assert!(matches!(h.runtime.layout().availability(&id("editor")), Availability::Unavailable { .. })); + assert_eq!(h.runtime.controller_count(), 0); + assert_eq!(h.runtime.layout().layout(), &saved); + assert_eq!(h.dispatch(vec![Mutation::Focus { instance: id("editor") }]).unwrap_err().rule, Rule::Availability); + let mut contextual = PanelMountHarness::new(false).unwrap(); + contextual.models.editable = false; + contextual.apply_layout(saved.clone(), None).unwrap(); + contextual.tick().unwrap(); + assert_eq!(contextual.runtime.layout().layout(), &saved); + assert!(!contextual.runtime.state(&editor_key(&contextual)).unwrap().presented); + contextual.models.editable = true; + contextual.mount(capacity()).unwrap(); + assert!(contextual.runtime.state(&editor_key(&contextual)).unwrap().presented); +} + +#[test] +fn explicit_lifecycle_intents_cannot_be_erased_by_a_batch() { + let mut h = PanelMountHarness::new(true).unwrap(); + open_editor(&mut h); + h.mount(capacity()).unwrap(); + let key = editor_key(&h); + h.probe.edit(&key, |s| s.reject_cancel = true).unwrap(); + let scope = h.local.scopes[&id("editor")].clone(); + h.local.request(&scope, LocalRequest::KeyboardOwner { instance: id("editor"), control: ControlId::new("draft").unwrap() }).unwrap(); + let reopen = Mutation::Open { kind: PanelKind::new("fixture.editor").unwrap(), instance: id("editor"), destination: None }; + let before = h.runtime.layout().inspect(); + let keyboard = h.local.keyboard.clone(); + let scopes = h.local.scopes.clone(); + let releases = h.local.releases; + let commits = h.native.commits; + for batch in [ + vec![Mutation::Close { instance: id("editor") }, reopen.clone()], + vec![Mutation::Close { instance: id("editor") }, move_editor(Zone::Right), reopen.clone()], + vec![Mutation::Destroy { instance: id("editor") }, reopen], + ] { + assert_eq!(h.dispatch(batch).unwrap_err().rule, Rule::Lifecycle); + assert_eq!(h.runtime.layout().inspect(), before); + assert_eq!(h.local.keyboard, keyboard); + assert_eq!(h.local.scopes, scopes); + assert_eq!(h.local.releases, releases); + assert_eq!(h.native.commits, commits); + assert!(h.probe.state(&key).unwrap().transaction_live); + assert_eq!(h.probe.state(&key).unwrap().cancels, 0); + } + h.dispatch(vec![ + Mutation::SetSize { section: section("editor-section"), size: Size { width: 300.0, height: 260.0 } }, + fixture_open("fixture.log", "independent", "independent-section", Zone::Right, 1).unwrap(), + ]) + .unwrap(); + assert_eq!(h.runtime.controller_count(), 2); + // Noncanceling snapshot hiding is distinct from an explicit Close, including + // when the saved entry is already marked closed. + let mut hidden = h.runtime.layout().layout().clone(); + hidden.sections.retain(|s| s.id != section("editor-section")); + hidden.instances.iter_mut().find(|p| p.id == id("editor")).unwrap().requested_open = false; + h.apply_layout(hidden, None).unwrap(); + assert_eq!(h.dispatch(vec![Mutation::Close { instance: id("editor") }]).unwrap_err().rule, Rule::Lifecycle); +} + +#[test] +fn service_errors_do_not_starve_later_hidden_controllers_or_leave_stale_input() { + let mut h = PanelMountHarness::new(false).unwrap(); + open_editor(&mut h); + h.dispatch(vec![fixture_open("fixture.log", "zz-log", "log-section", Zone::Right, 1).unwrap()]).unwrap(); + h.mount(capacity()).unwrap(); + let editor = editor_key(&h); + let log = ControllerKey { instance: id("zz-log"), owner: ContentOwner::Workspace(h.runtime.environment().workspace.clone()) }; + let mut layout = h.runtime.layout().layout().clone(); + layout.sections.retain(|s| s.id != section("log-section")); + layout.instances.retain(|p| p.id != id("zz-log")); + h.apply_layout(layout, None).unwrap(); + h.mount(capacity()).unwrap(); + let scope = h.local.scopes[&id("editor")].clone(); + h.local.request(&scope, LocalRequest::KeyboardOwner { instance: id("editor"), control: ControlId::new("draft").unwrap() }).unwrap(); + h.probe.edit(&editor, |s| s.fail_update = true).unwrap(); + let updates = h.probe.state(&log).unwrap().updates; + for _ in 0..4 { + assert!(h.tick().is_err()); + assert_eq!(h.runtime.update_errors().len(), 1); + assert_eq!(h.runtime.update_errors().first().unwrap().controller.as_ref(), Some(&editor)); + } + assert_eq!(h.probe.state(&log).unwrap().updates, updates + 4); + assert!(!h.runtime.state(&log).unwrap().presented); + assert!(!h.runtime.state(&editor).unwrap().presented); + assert!(h.local.keyboard.is_empty()); + assert!(matches!(h.runtime.layout().availability(&id("editor")), Availability::Unavailable { .. })); + h.probe + .edit(&editor, |s| { + s.fail_update = false; + s.invalid_availability = true; + }) + .unwrap(); + assert!(h.tick().is_err()); + assert_eq!(h.runtime.update_errors().first().unwrap().error.rule, Rule::Availability); + assert_eq!(h.probe.state(&log).unwrap().updates, updates + 5); + h.probe.edit(&editor, |s| s.invalid_availability = false).unwrap(); + h.tick().unwrap(); + assert!(h.runtime.update_errors().is_empty()); + h.mount(capacity()).unwrap(); + assert!(h.runtime.state(&editor).unwrap().presented); +} + +#[test] +fn snapshot_native_transitions_stage_effects_without_canceling_editors() { + let mut h = PanelMountHarness::new(true).unwrap(); + open_editor(&mut h); + h.tick().unwrap(); + let key = editor_key(&h); + h.probe.edit(&key, |s| s.reject_cancel = true).unwrap(); + let mut native_layout = h.runtime.layout().layout().clone(); + native_layout.sections.first_mut().unwrap().location = SectionLocation::Window { + host: HostId::new("snapshot-host").unwrap(), + origin: Point { x: 0.0, y: 0.0 }, + return_to: DockReturn { zone: Zone::Left, index: 0, size: Size { width: 280.0, height: 240.0 }, collapsed: false, join: None }, + }; + let reply = h.apply_layout(native_layout.clone(), None).unwrap(); + assert!(reply.effects.iter().any(|e| matches!(e, HostEffect::CreateNative { .. }))); + assert_eq!(h.native.hosts.len(), 1); + let away = Layout::empty(WorkspaceId::new("away").unwrap()); + let before = h.runtime.layout().inspect(); + let hosts = h.native.hosts.clone(); + h.native.fail_prepare = true; + assert_eq!(h.apply_layout(away.clone(), None).unwrap_err().rule, Rule::Capability); + assert_eq!(h.runtime.layout().inspect(), before); + assert_eq!(h.native.hosts, hosts); + h.native.fail_prepare = false; + let reply = h.apply_layout(away, None).unwrap(); + assert!(reply.effects.iter().any(|e| matches!(e, HostEffect::ReleaseNative { .. }))); + assert!(h.native.hosts.is_empty()); + h.apply_layout(native_layout, None).unwrap(); + assert_eq!(h.native.hosts.len(), 1); + assert_eq!(h.runtime.controller_count(), 1); + assert!(h.probe.state(&key).unwrap().transaction_live); + assert_eq!(h.probe.state(&key).unwrap().cancels, 0); +} + +#[test] +fn egui_reference_host_rejects_sparse_or_no_input_geometry_before_widget_work() { + for mode in 0..3 { + let mut h = PanelMountHarness::new(false).unwrap(); + open_editor(&mut h); + h.tick().unwrap(); + let mut resolved = resolve_geometry(h.runtime.layout(), capacity(), Direction::Ltr, 48.0).unwrap(); + let geometry = resolved.panels.first_mut().unwrap(); + let island = LogicalRect { origin: geometry.outer.origin, size: Size { width: 20.0, height: 20.0 } }; + match mode { + 0 => geometry.input.clear(), + 1 => { + geometry.painted = vec![island]; + geometry.input.clear(); + } + _ => geometry.input.first_mut().unwrap().bounds = island, + } + resolved.validate().unwrap(); + let ctx = egui::Context::default(); + let mut failure = None; + let _output = ctx.run_ui(egui::RawInput::default(), |root_ui| { + crate::ui_kit::Container::new(root_ui.ctx(), crate::ui_kit::Surface::Viewport).central().show(root_ui, |ui| { + let before = ui.min_rect(); + let mut host = EguiPanelHost { ui }; + failure = h + .runtime + .mount(&resolved, &mut host, &mut ContentServices { models: &h.models, commands: &mut h.commands, local: &mut h.local }) + .err(); + assert_eq!(host.ui.min_rect(), before); + }); + }); + assert_eq!(failure.unwrap().rule, Rule::Capability); + assert_eq!(h.probe.state(&editor_key(&h)).unwrap().renders, 0); + } +} + +#[test] +fn normal_egui_mount_preserves_the_parent_clip() { + let mut h = PanelMountHarness::new(false).unwrap(); + open_editor(&mut h); + h.tick().unwrap(); + let resolved = resolve_geometry(h.runtime.layout(), capacity(), Direction::Ltr, 48.0).unwrap(); + let ctx = egui::Context::default(); + let parent = egui::Rect::from_min_max(egui::pos2(30.0, 40.0), egui::pos2(150.0, 160.0)); + let mut failure = None; + let _output = ctx.run_ui(egui::RawInput::default(), |root_ui| { + crate::ui_kit::Container::new(root_ui.ctx(), crate::ui_kit::Surface::Viewport).central().show(root_ui, |ui| { + ui.set_clip_rect(ui.clip_rect().intersect(parent)); + let mut host = EguiPanelHost { ui }; + failure = h + .runtime + .mount(&resolved, &mut host, &mut ContentServices { models: &h.models, commands: &mut h.commands, local: &mut h.local }) + .err(); + }); + }); + assert!(failure.is_none(), "{failure:?}"); + let clip = h.probe.state(&editor_key(&h)).unwrap().last_clip.unwrap(); + assert!(parent.contains_rect(clip)); + assert!(h.probe.state(&editor_key(&h)).unwrap().renders >= 1); +} + +#[derive(Default)] +struct ForwardingTrace { + service_borrows: usize, + refreshes: usize, + content_calls: u64, +} +struct ForwardingAppServices { + models: FakeModels, + commands: FakeContentCommands, + local: FakeLocalServices, + trace: std::rc::Rc>, +} + +fn panel_command_editor() -> serde_json::Value { + serde_json::json!({"kind":"fixture.editor","instance":"editor","destination":{"type":"new_section","section":"editor-section","index":0, + "location":{"type":"dock","zone":"left"},"size":{"width":280,"height":240}}}) +} +fn panel_command_editor_target() -> serde_json::Value { + serde_json::json!({"type":"instance","id":"editor"}) +} +fn panel_command_native_move() -> serde_json::Value { + serde_json::json!({"target":panel_command_editor_target(),"destination":{"type":"new_section","section":"native","index":0, + "location":{"type":"window","host":"native-host","origin":{"x":10,"y":20},"return_to":{"zone":"left","index":0,"size":{"width":280,"height":240},"collapsed":false}}, + "size":{"width":280,"height":240}}}) +} + +#[test] +fn panel_commands_use_runtime_guards_and_keep_every_authoritative_state_on_preflight_failure() { + use commands::LayoutCatalogue; + let mut h = PanelMountHarness::new(true).unwrap(); + h.command("panel.open", &panel_command_editor()).unwrap(); + h.mount(capacity()).unwrap(); + let key = editor_key(&h); + h.probe + .edit(&key, |state| { + state.draft = "unsaved command draft".into(); + state.reject_cancel = true; + }) + .unwrap(); + let before = h.runtime.layout().inspect(); + let catalogue = h.catalogue.state().clone(); + let controllers = h.runtime.controller_count(); + let local_keyboard = h.local.keyboard.clone(); + let local_scopes = h.local.scopes.clone(); + let releases = h.local.releases; + let requests = h.local.requests.len(); + let hosts = h.native.hosts.clone(); + assert_eq!(h.command("panel.close", &serde_json::json!({"target":panel_command_editor_target()})).unwrap_err().rule, Rule::Lifecycle); + h.native.fail_prepare = true; + assert_eq!(h.command("panel.popout", &panel_command_native_move()).unwrap_err().rule, Rule::Capability); + h.native.fail_prepare = false; + h.catalogue.fail_stage = true; + assert_eq!( + h.command("panel.collapse", &serde_json::json!({"target":panel_command_editor_target(),"collapsed":true})).unwrap_err().rule, + Rule::Capability + ); + h.catalogue.fail_stage = false; + let steps = vec![ + serde_json::json!({"command":"panel.close","params":{"target":panel_command_editor_target()}}), + serde_json::json!({"command":"panel.open","params":{"kind":"fixture.editor","instance":"editor"}}), + ]; + assert_eq!(h.command_batch(&steps).unwrap_err().rule, Rule::Lifecycle); + assert_eq!(h.runtime.layout().inspect(), before); + assert_eq!(h.catalogue.state(), &catalogue); + assert_eq!(h.runtime.controller_count(), controllers); + assert_eq!(h.local.keyboard, local_keyboard); + assert_eq!(h.native.hosts, hosts); + assert_eq!(h.local.scopes, local_scopes); + assert_eq!(h.local.releases, releases); + assert_eq!(h.local.requests.len(), requests); + let editor = h.probe.state(&key).unwrap(); + assert_eq!(editor.draft, "unsaved command draft"); + assert!(editor.transaction_live); + assert_eq!(editor.cancels, 0); +} + +#[test] +fn panel_commands_replace_layouts_and_workspaces_on_retained_runtime_with_live_hidden_services() { + let mut h = PanelMountHarness::new(false).unwrap(); + h.command("panel.open", &panel_command_editor()).unwrap(); + h.tick().unwrap(); + let key = editor_key(&h); + h.probe + .edit(&key, |s| { + s.draft = "retained across commands".into(); + s.reject_cancel = true; + }) + .unwrap(); + h.command("layout.save", &serde_json::json!({"name":"Draft layout"})).unwrap(); + let updates = h.probe.state(&key).unwrap().updates; + h.command("layout.reset", &serde_json::json!({})).unwrap(); + h.tick().unwrap(); + assert!(h.probe.state(&key).unwrap().updates > updates); + h.command("layout.apply", &serde_json::json!({"name":"Draft layout"})).unwrap(); + h.command("layout.workspace.select", &serde_json::json!({"workspace":"fixture.other"})).unwrap(); + let updates = h.probe.state(&key).unwrap().updates; + h.tick().unwrap(); + assert!(h.probe.state(&key).unwrap().updates > updates); + h.command("layout.workspace.select", &serde_json::json!({"workspace":"fixture.workspace"})).unwrap(); + h.tick().unwrap(); + assert_eq!(h.runtime.controller_count(), 1); + let state = h.probe.state(&key).unwrap(); + assert_eq!(state.draft, "retained across commands"); + assert!(state.transaction_live); + assert_eq!(state.cancels, 0); + assert_eq!(h.commands.calls, 0, "layout never runs content/model commands"); +} + +#[test] +fn panel_workspace_commands_reuse_each_workspaces_controller_and_background_draft() { + let mut h = PanelMountHarness::new(false).unwrap(); + let mut input = panel_command_editor(); + input["kind"] = serde_json::json!("fixture.log"); + input["instance"] = serde_json::json!("log"); + h.command("panel.open", &input).unwrap(); + h.tick().unwrap(); + let a = ControllerKey { instance: id("log"), owner: ContentOwner::Workspace(WorkspaceId::new("fixture.workspace").unwrap()) }; + h.probe.edit(&a, |s| s.draft = "workspace A draft".into()).unwrap(); + h.command("layout.save", &serde_json::json!({"name":"Shared instances"})).unwrap(); + h.command("layout.workspace.select", &serde_json::json!({"workspace":"fixture.other"})).unwrap(); + h.command("layout.apply", &serde_json::json!({"name":"Shared instances"})).unwrap(); + h.tick().unwrap(); + let b = ControllerKey { instance: id("log"), owner: ContentOwner::Workspace(WorkspaceId::new("fixture.other").unwrap()) }; + h.probe.edit(&b, |s| s.draft = "workspace B draft".into()).unwrap(); + let updates = h.probe.state(&a).unwrap().updates; + h.tick().unwrap(); + assert!(h.probe.state(&a).unwrap().updates > updates); + h.command("layout.workspace.select", &serde_json::json!({"workspace":"fixture.workspace"})).unwrap(); + h.tick().unwrap(); + assert_eq!(h.probe.state(&a).unwrap().draft, "workspace A draft"); + assert_eq!(h.probe.state(&b).unwrap().draft, "workspace B draft"); + assert_eq!(h.runtime.controller_count(), 2); + h.command("layout.workspace.select", &serde_json::json!({"workspace":"fixture.other"})).unwrap(); + h.tick().unwrap(); + assert_eq!(h.probe.state(&b).unwrap().draft, "workspace B draft"); + assert_eq!(h.runtime.controller_count(), 2); +} + +#[test] +fn panel_native_close_command_redocks_without_cancelling_or_replacing_editor() { + let mut h = PanelMountHarness::new(true).unwrap(); + h.command("panel.open", &panel_command_editor()).unwrap(); + h.tick().unwrap(); + let key = editor_key(&h); + h.probe + .edit(&key, |s| { + s.reject_cancel = true; + s.draft = "native draft".into(); + }) + .unwrap(); + h.command("panel.popout", &panel_command_native_move()).unwrap(); + assert_eq!(h.native.hosts.len(), 1); + let reply = h.command("panel.native_close", &serde_json::json!({"target":{"type":"native_host","id":"native-host"}})).unwrap(); + assert!(h.native.hosts.is_empty()); + assert_eq!(reply["layout"]["sections"][0]["location"]["type"], "dock"); + assert_eq!(h.probe.state(&key).unwrap().draft, "native draft"); + assert_eq!(h.probe.state(&key).unwrap().cancels, 0); + assert_eq!(h.runtime.controller_count(), 1); +} + +#[test] +fn solve_app_panel_commands_use_injected_services_without_document_camera_or_cache_changes() { + let PanelMountHarness { runtime, probe, .. } = PanelMountHarness::new(false).unwrap(); + let trace = std::rc::Rc::new(std::cell::RefCell::new(ForwardingTrace::default())); + let mut app = crate::SolveApp::new(solidcraft_engine::Session::default(), Default::default()); + let revision = app.session.revision; + let doc = app.session.doc.clone(); + let model = app.session.model.state(); + let undo = app.session.undo.len(); + let dirty = app.session.is_dirty(); + let camera = app.cam; + app.enable_panel_runtime( + runtime, + Box::new(ForwardingAppServices { + models: FakeModels { editable: true }, + commands: Default::default(), + local: Default::default(), + trace: trace.clone(), + }), + ) + .unwrap(); + let catalogue = fixture_command_catalogue(app.panel_runtime().unwrap().layout().registry()).unwrap(); + app.panel_runtime_mut().unwrap().set_command_adapters(Box::new(catalogue), Box::new(FakeNativeAdapter::new(false))).unwrap(); + app.run("panel.open", panel_command_editor()).unwrap(); + let key = ControllerKey { instance: id("editor"), owner: ContentOwner::Document(DocumentId::new(app.session.document_id.clone()).unwrap()) }; + probe.edit(&key, |s| s.draft = "app command draft".into()).unwrap(); + app.run("layout.save", serde_json::json!({"name":"App saved"})).unwrap(); + app.run("layout.reset", serde_json::json!({})).unwrap(); + app.tick_panel_runtime().unwrap(); + app.run("layout.apply", serde_json::json!({"name":"App saved"})).unwrap(); + assert_eq!(app.run("panel.list", serde_json::json!({})).unwrap()["state"]["layout"]["instances"][0]["id"], "editor"); + assert_eq!(probe.state(&key).unwrap().draft, "app command draft"); + assert_eq!(probe.state(&key).unwrap().cancels, 0); + assert!(trace.borrow().service_borrows >= 6); + assert_eq!(app.session.revision, revision); + assert_eq!(app.session.undo.len(), undo); + assert_eq!(app.session.is_dirty(), dirty); + assert_eq!(app.cam, camera); + assert!(std::sync::Arc::ptr_eq(&doc, &app.session.doc)); + assert!(std::sync::Arc::ptr_eq(&model, &app.session.model.state())); +} +impl AppPanelServices for ForwardingAppServices { + fn refresh_read_only(&mut self, _session: &solidcraft_engine::Session) -> PanelResult<()> { + let mut trace = self.trace.try_borrow_mut().map_err(|_| error(Rule::Lifecycle, "trace borrowed"))?; + trace.refreshes += 1; + trace.content_calls = self.commands.calls; + Ok(()) + } + fn services(&mut self) -> ContentServices<'_> { + if let Ok(mut trace) = self.trace.try_borrow_mut() { + trace.service_borrows += 1; + } + ContentServices { models: &self.models, commands: &mut self.commands, local: &mut self.local } + } +} + +#[test] +fn solve_app_forwards_dispatch_mount_content_switch_and_ticks_to_its_injected_provider() { + let PanelMountHarness { runtime, probe, .. } = PanelMountHarness::new(false).unwrap(); + let trace = std::rc::Rc::new(std::cell::RefCell::new(ForwardingTrace::default())); + let mut app = crate::SolveApp::new(solidcraft_engine::Session::default(), Default::default()); + let revision = app.session.revision; + let doc = app.session.doc.clone(); + let model = app.session.model.state(); + let undo = app.session.undo.len(); + let dirty = app.session.is_dirty(); + app.enable_panel_runtime( + runtime, + Box::new(ForwardingAppServices { + models: FakeModels { editable: true }, + commands: FakeContentCommands::default(), + local: FakeLocalServices::default(), + trace: trace.clone(), + }), + ) + .unwrap(); + app.dispatch_panel_layout(transaction(vec![ + fixture_open("fixture.editor", "editor", "editor-section", Zone::Left, 0).unwrap(), + fixture_open("fixture.log", "log", "log-section", Zone::Right, 1).unwrap(), + ])) + .unwrap(); + app.tick_panel_runtime().unwrap(); + let key = ControllerKey { instance: id("editor"), owner: ContentOwner::Document(DocumentId::new(app.session.document_id.clone()).unwrap()) }; + probe.edit(&key, |state| state.draft = "draft through app".into()).unwrap(); + let saved = app.panel_runtime().unwrap().layout().layout().clone(); + let resolved = resolve_geometry(app.panel_runtime().unwrap().layout(), capacity(), Direction::Ltr, 48.0).unwrap(); + let mut host = FakePanelHost::default(); + app.mount_panels(&resolved, &mut host).unwrap(); + assert!(!host.mounts.is_empty()); + app.panel_content_action(&id("editor"), &ControlId::new("apply").unwrap()).unwrap(); + assert_eq!(probe.state(&key).unwrap().applies, 1); + let mut other = saved.clone(); + other.workspace = WorkspaceId::new("app-workspace-two").unwrap(); + app.dispatch_panel_layout(LayoutAction::Replace { + expected_revision: Some(app.panel_runtime().unwrap().layout().inspect().revision), + layout: other.clone(), + }) + .unwrap(); + app.tick_panel_runtime().unwrap(); + assert_eq!(app.panel_runtime().unwrap().controller_count(), 3); + app.dispatch_panel_layout(LayoutAction::Replace { expected_revision: None, layout: Layout::empty(other.workspace) }).unwrap(); + let updates = probe.state(&key).unwrap().updates; + app.tick_panel_runtime().unwrap(); + assert!(probe.state(&key).unwrap().updates > updates); + app.dispatch_panel_layout(LayoutAction::Replace { expected_revision: None, layout: saved.clone() }).unwrap(); + app.tick_panel_runtime().unwrap(); + assert_eq!(probe.state(&key).unwrap().draft, "draft through app"); + assert!(probe.state(&key).unwrap().transaction_live); + assert_eq!(probe.state(&key).unwrap().cancels, 0); + assert_eq!(app.panel_runtime().unwrap().layout().layout(), &saved); + let trace = trace.borrow(); + assert_eq!(trace.content_calls, 1); + assert!(trace.service_borrows >= 10); + assert!(trace.refreshes >= 4); + assert_eq!(app.session.revision, revision); + assert_eq!(app.session.undo.len(), undo); + assert_eq!(app.session.is_dirty(), dirty); + assert!(std::sync::Arc::ptr_eq(&doc, &app.session.doc)); + assert!(std::sync::Arc::ptr_eq(&model, &app.session.model.state())); +} + +#[derive(Clone, Default)] +struct CurrentContextModels(std::rc::Rc>>); +impl PanelModels for CurrentContextModels { + fn read(&self, owner: &ContentOwner, key: &str) -> PanelResult { + let ContentOwner::Document(document) = owner else { + return Err(error(Rule::Availability, "fixture needs document owner")); + }; + if key != "fixture.editable" { + return Err(error(Rule::MissingTarget, "unknown fixture read")); + } + Ok(serde_json::json!(self.0.borrow().get(document).copied().unwrap_or(false))) + } +} +struct CurrentContextServices { + models: CurrentContextModels, + commands: FakeContentCommands, + local: FakeLocalServices, + refreshes: std::rc::Rc>>, +} +impl AppPanelServices for CurrentContextServices { + fn refresh_read_only(&mut self, session: &solidcraft_engine::Session) -> PanelResult<()> { + let editable = session.doc.param("fixture_editable").is_some_and(|param| param.expr.trim() == "1"); + self.models.0.borrow_mut().insert(DocumentId::new(session.document_id.clone())?, editable); + self.refreshes.borrow_mut().push((session.document_id.clone(), session.doc.name.clone())); + Ok(()) + } + fn services(&mut self) -> ContentServices<'_> { + ContentServices { models: &self.models, commands: &mut self.commands, local: &mut self.local } + } +} +fn current_context_app() -> (crate::SolveApp, FixtureProbe) { + let PanelMountHarness { runtime, probe, .. } = PanelMountHarness::new(false).unwrap(); + let mut session = solidcraft_engine::Session::default(); + session.execute("file.new", &serde_json::json!({"name":"Same name"})).unwrap(); + session.document_id = "context-a".into(); + session.execute("parameters.change", &serde_json::json!({"name":"fixture_editable","expression":1,"unit":""})).unwrap(); + let mut app = crate::SolveApp::new(session, Default::default()); + app.enable_panel_runtime( + runtime, + Box::new(CurrentContextServices { + models: CurrentContextModels::default(), + commands: Default::default(), + local: Default::default(), + refreshes: Default::default(), + }), + ) + .unwrap(); + (app, probe) +} +fn context_control(app: &mut crate::SolveApp, method: &str, params: serde_json::Value) -> serde_json::Value { + let (request, _) = crate::control::ControlRequest::new(method, params); + match crate::control::handle(app, &egui::Context::default(), &request) { + crate::control::Outcome::Done(value) => value, + _ => panic!("unexpected screenshot"), + } +} + +#[test] +fn application_command_query_and_failure_refresh_same_named_document_before_any_tick() { + let (mut app, probe) = current_context_app(); + app.run("panel.open", panel_command_editor()).unwrap(); + let a = ControllerKey { instance: id("editor"), owner: ContentOwner::Document(DocumentId::new("context-a").unwrap()) }; + probe.edit(&a, |state| state.draft = "document A draft".into()).unwrap(); + let mut b = solidcraft_engine::Session::default(); + b.execute("file.new", &serde_json::json!({"name":"Same name"})).unwrap(); + b.document_id = "context-b".into(); + app.session.replace_design(b); + let document = app.session.doc.clone(); + let model = app.session.model.state(); + let camera = app.cam; + let before = (app.session.revision, app.session.undo.len(), app.session.is_dirty()); + let query = app.run("panel.list", serde_json::json!({})).unwrap(); + assert_eq!(query["state"]["availability"]["editor"]["state"], "unavailable"); + let failure = app.run("panel.focus", serde_json::json!({"target":panel_command_editor_target()})).unwrap_err(); + assert_eq!(commands::structured_error(&failure).unwrap()["rule"], "availability"); + assert_eq!(app.panel_runtime().unwrap().environment().document, Some(DocumentId::new("context-b").unwrap())); + assert_eq!(probe.state(&a).unwrap().draft, "document A draft"); + assert_eq!(probe.state(&a).unwrap().cancels, 0); + assert_eq!((app.session.revision, app.session.undo.len(), app.session.is_dirty()), before); + assert!(std::sync::Arc::ptr_eq(&document, &app.session.doc)); + assert!(std::sync::Arc::ptr_eq(&model, &app.session.model.state())); + assert_eq!(app.cam, camera); +} + +#[test] +fn application_atomic_boundary_refreshes_same_document_context_for_query_and_mutation() { + let (mut app, _) = current_context_app(); + app.run("panel.open", panel_command_editor()).unwrap(); + app.run("parameters.change", serde_json::json!({"name":"fixture_editable","expression":0})).unwrap(); + let query = app.run_panel_batch(&[serde_json::json!({"command":"panel.list","params":null})]).unwrap(); + assert_eq!(query["results"][0]["state"]["availability"]["editor"]["state"], "unavailable"); + let revision = app.session.revision; + let model = app.session.model.state(); + assert_eq!( + app.run_panel_batch(&[serde_json::json!({"command":"panel.focus","params":{"target":panel_command_editor_target()}})]).unwrap_err().rule, + Rule::Availability + ); + assert_eq!(app.session.revision, revision); + assert!(std::sync::Arc::ptr_eq(&model, &app.session.model.state())); + app.run("parameters.change", serde_json::json!({"name":"fixture_editable","expression":1})).unwrap(); + let result = app + .run_panel_batch(&[ + serde_json::json!({"command":"panel.focus","params":{"target":panel_command_editor_target()}}), + serde_json::json!({"command":"panel.list"}), + ]) + .unwrap(); + assert_eq!(result["results"][1]["state"]["availability"]["editor"]["state"], "available"); +} + +#[test] +fn unsupported_atomic_intent_mixtures_refuse_before_context_or_controller_publication() { + let (mut app, probe) = current_context_app(); + app.run("panel.open", panel_command_editor()).unwrap(); + let key = ControllerKey { instance: id("editor"), owner: ContentOwner::Document(DocumentId::new("context-a").unwrap()) }; + let before = app.panel_runtime().unwrap().layout().inspect(); + let controllers = app.panel_runtime().unwrap().controller_count(); + let retained = probe.state(&key).unwrap(); + let mut next = solidcraft_engine::Session::default(); + next.document_id = "context-b".into(); + app.session.replace_design(next); + for commands in [ + serde_json::json!([{ "command":"panel.close","params":{"target":panel_command_editor_target()} },{"command":"layout.reset"}]), + serde_json::json!([{"command":"layout.reset"},{ "command":"panel.close","params":{"target":panel_command_editor_target()} }]), + ] { + assert_eq!(app.run_panel_batch(commands.as_array().unwrap()).unwrap_err().rule, Rule::Capability); + assert_eq!(app.panel_runtime().unwrap().layout().inspect(), before); + assert_eq!(app.panel_runtime().unwrap().controller_count(), controllers); + assert_eq!(app.panel_runtime().unwrap().environment().document, Some(DocumentId::new("context-a").unwrap())); + assert_eq!(probe.state(&key).unwrap().last_state, retained.last_state); + assert_eq!(probe.state(&key).unwrap().cancels, retained.cancels); + } +} + +#[test] +fn sequential_application_routes_refresh_after_file_new_and_same_document_model_changes() { + for method in ["engine.script", "engine.batch"] { + let (mut app, probe) = current_context_app(); + app.run("panel.open", panel_command_editor()).unwrap(); + let a = ControllerKey { instance: id("editor"), owner: ContentOwner::Document(DocumentId::new("context-a").unwrap()) }; + probe.edit(&a, |state| state.draft = "same instance, outgoing owner".into()).unwrap(); + let reply = context_control( + &mut app, + method, + serde_json::json!({"rollback":false,"commands":[ + {"command":"file.new","params":{"name":"Same name"}}, + {"command":"panel.open","params":{"kind":"fixture.editor","instance":"editor"}}, + ]}), + ); + let reason = if method == "engine.batch" { &reply["result"]["failed"]["panel_error"] } else { &reply["panel_error"] }; + assert_eq!(reason["rule"], "availability", "{reply}"); + assert_ne!(app.session.document_id, "context-a"); + assert_eq!(app.session.doc.name, "Same name"); + assert_eq!(app.panel_runtime().unwrap().environment().document.as_ref().unwrap().0, app.session.document_id); + assert_eq!(probe.state(&a).unwrap().draft, "same instance, outgoing owner"); + assert_eq!(probe.state(&a).unwrap().cancels, 0); + let success = context_control( + &mut app, + method, + serde_json::json!({"rollback":false,"commands":[ + {"command":"parameters.change","params":{"name":"fixture_editable","expression":1,"unit":""}}, + {"command":"panel.focus","params":{"target":panel_command_editor_target()}}, + ]}), + ); + assert_eq!(success["ok"], true, "{success}"); + assert!(success["result"].get("failed").is_none(), "{success}"); + let failure = context_control( + &mut app, + method, + serde_json::json!({"rollback":false,"commands":[ + {"command":"parameters.change","params":{"name":"fixture_editable","expression":0}}, + {"command":"panel.focus","params":{"target":panel_command_editor_target()}}, + ]}), + ); + let reason = if method == "engine.batch" { &failure["result"]["failed"]["panel_error"] } else { &failure["panel_error"] }; + assert_eq!(reason["rule"], "availability", "{failure}"); + } +} + +#[derive(Clone)] +struct SharedCommandNative(std::rc::Rc>); +impl NativeHostAdapter for SharedCommandNative { + fn capabilities(&self) -> HostCapabilities { + self.0.borrow().capabilities() + } + fn prepare(&self, effects: &[HostEffect]) -> PanelResult<()> { + self.0.borrow().prepare(effects) + } + fn commit(&mut self, effects: &[HostEffect]) { + self.0.borrow_mut().commit(effects); + } +} + +#[test] +fn solve_app_gui_and_command_routes_share_native_owner_and_refuse_adapter_hot_swap() { + let PanelMountHarness { runtime, probe, .. } = PanelMountHarness::new(true).unwrap(); + let catalogue = fixture_command_catalogue(runtime.layout().registry()).unwrap(); + let native = std::rc::Rc::new(std::cell::RefCell::new(FakeNativeAdapter::new(true))); + let mut app = crate::SolveApp::new(solidcraft_engine::Session::default(), Default::default()); + app.enable_panel_runtime(runtime, Box::new(FakeAppPanelServices { models: FakeModels { editable: true }, ..Default::default() })).unwrap(); + app.panel_runtime_mut().unwrap().set_command_adapters(Box::new(catalogue), Box::new(SharedCommandNative(native.clone()))).unwrap(); + app.run("panel.open", panel_command_editor()).unwrap(); + let key = ControllerKey { instance: id("editor"), owner: ContentOwner::Document(DocumentId::new(app.session.document_id.clone()).unwrap()) }; + probe + .edit(&key, |state| { + state.draft = "native draft".into(); + state.reject_cancel = true; + }) + .unwrap(); + let destination: Destination = serde_json::from_value(panel_command_native_move()["destination"].clone()).unwrap(); + app.dispatch_panel_layout(transaction(vec![Mutation::Move { instance: id("editor"), destination }])).unwrap(); + assert_eq!(native.borrow().hosts.len(), 1); + assert!( + app.panel_runtime_mut() + .unwrap() + .set_command_adapters(Box::::default(), Box::new(FakeNativeAdapter::new(true))) + .is_err() + ); + assert!(app.disable_panel_runtime().is_err()); + assert_eq!(native.borrow().hosts.len(), 1); + app.run("panel.native_close", serde_json::json!({"target":{"type":"native_host","id":"native-host"}})).unwrap(); + assert!(native.borrow().hosts.is_empty(), "command redocks the GUI-created host through its actual owner"); + app.run("panel.popout", panel_command_native_move()).unwrap(); + native.borrow_mut().fail_prepare = true; + let before = app.panel_runtime().unwrap().layout().inspect(); + let hosts = native.borrow().hosts.clone(); + assert_eq!( + app.dispatch_panel_layout(transaction(vec![Mutation::NativeClose { host: HostId::new("native-host").unwrap() }])).unwrap_err().rule, + Rule::Capability + ); + assert_eq!(app.panel_runtime().unwrap().layout().inspect(), before); + assert_eq!(native.borrow().hosts, hosts); + native.borrow_mut().fail_prepare = false; + app.dispatch_panel_layout(transaction(vec![Mutation::NativeClose { host: HostId::new("native-host").unwrap() }])).unwrap(); + assert!(native.borrow().hosts.is_empty(), "GUI redocks the command-created host through the same owner"); + assert_eq!(probe.state(&key).unwrap().draft, "native draft"); + assert_eq!(probe.state(&key).unwrap().cancels, 0); +} diff --git a/docs/control-protocol.md b/docs/control-protocol.md index b3e95e8e0..32b2c4e69 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -1,5 +1,212 @@ # Control protocol +The [universal panel foundation](panel-foundation.md) supplies typed layout actions +and retained runtime guards. The application-layout commands below are registered +engine commands reached through `engine.execute`, `engine.batch`, `engine.script` +and MCP's existing `execute`/`batch` tools. They require an injected application +backend; enabling the internal panel runtime remains an explicit integration step. +Current product defaults and the production shell are unchanged. + +### Application panel and layout commands + +Every command has input and output schemas through ordinary command discovery. +Inputs are strict at every parameter-check level: unknown fields, including nested +placement fields, are errors. As with other engine calls, omitted/null parameters +mean an empty object. IDs use the foundation's bounded lowercase ID domains; +dimensions are finite positive outer logical units, at most 32768. Requests are +bounded to 16384 encoded bytes before cloning or deserialising. No command opens a +dialog, edits the document, changes dirty/undo/revision, evaluates or tessellates a +model, fits a body, follows a camera request or selects a ribbon/tool/document tab. +Layout revision is independent of document revision. + +Canonical existing targets are typed: `{"target":{"type":"instance","id":"log"}}`. +`section`, `workspace` and `native_host` are the other foundation target types; +each command accepts only the domains listed below. A legacy `id` may replace +`target`, but both together are rejected. It first resolves an exact instance ID. +A kind ID resolves only when its registration is single-instance and exactly one +canonical instance exists, including retained closed state. Multi-instance kinds +are rejected even when only one instance currently exists. No first-match guessing +or implicit instance creation occurs. `panel.open` instead requires separate `kind` +and `instance` fields. + +All mutations accept optional `expected_revision:u64`. A stale revision produces +the foundation `revision` rule and leaves the command's layout and catalogue +unchanged. Successful mutations return the committed `LayoutReply` (layout, +revision, interaction, effects, capabilities and availability), never an echoed +placement request. `layout` includes all retained instances with `requested_open`, +ordered sections and their active tabs. Missing availability entries mean available. +Query replies contain no new host effects. + +| Command | Parameters and behaviour | +|---|---| +| `panel.list` | `{}` → `{state:LayoutReply,kinds:[PanelSpec]}` from the live sink and registry. | +| `panel.open` | `{kind,instance,destination?,expected_revision?}`. New instances require a destination; closed instances can reuse remembered placement. | +| `panel.close` | `{target:instance,expected_revision?}`. Explicit guarded close retains placement and can refuse cancellation. | +| `panel.move` | `{target:instance,destination,expected_revision?}`. Existing open instances only. | +| `panel.resize` | `{target:section|instance,size:{width,height},expected_revision?}`. Instance must have an open section; all tab bounds intersect. | +| `panel.collapse` | `{target:section|instance,collapsed:bool,expected_revision?}`. Keeps requested dimensions. | +| `panel.float` | Same as move, requiring a `new_section` with `floating` location. | +| `panel.popout` | Same as move, requiring a `new_section` with `window` location and return destination. Desktop/headless without native capability refuse; web explicitly lowers to `floating`. | +| `panel.focus` | `{target:instance,expected_revision?}`. Reopens retained closed state, activates, expands and requests focus. | +| `panel.activate` | `{target:instance,expected_revision?}`. Activates an open tab without expanding or requesting focus. | +| `panel.peek` | `{target:instance,expected_revision?}`. Temporary presentation of a collapsed tab, without persistence changes to size/collapse. | +| `panel.dismiss` | `{expected_revision?}`. Dismisses transient peek. | +| `panel.resize_pair` | `{first:SectionId,second:SectionId,first_size:{width,height},second_size:{width,height},expected_revision?}`. Adjacent sections of one dock; conserves split-axis extent and cross-axis dimensions. | +| `panel.reset_pair` | `{first,second,expected_revision?}`. Resets adjacent sections to the registered default ratio within intersected bounds. | +| `panel.native_close` | `{target:{type:"native_host",id:HostId},expected_revision?}`. Native window close redocks its whole section; it does not explicitly close/cancel content. | +| `layout.save` | `{name,overwrite?:false,expected_revision?}` → `{name,overwritten,state}`. Saves the complete current envelope in the injected catalogue. | +| `layout.apply` | `{name,expected_revision?}`. Applies a named preset to the **current** workspace, rebinding its known layout workspace ID. | +| `layout.reset` | `{expected_revision?}`. Applies the selected workspace's registered immutable default. User presets and other workspace histories remain. Missing defaults return a capability error. | +| `layout.get` | `{}` → `{state,workspaces:[{id,title_key,default_preset,has_remembered_layout}]}`. Selection is only `state.layout.workspace`. | +| `layout.workspace.select` | `{workspace:WorkspaceId,expected_revision?}` → `{previous_workspace,source:"remembered"|"default_preset"|"unchanged",state}`. Registered descriptors only; no implicit creation. | + +Destinations are distinct foundation operations, not aliases: + +```json +{"type":"new_section","section":"logs","index":0,"location":{"type":"dock","zone":"left"},"size":{"width":280,"height":240}} +{"type":"join_tab","section":"logs","index":1} +``` + +New-section indices address the global section order after detachment; join indices +address the destination's tab list after detachment. Joining keeps the destination's +activation, collapse and dimensions. Locations are `dock` (left/right/bottom), +`floating` (`origin:{x,y}`), or `window` (`host`, `origin`, `return_to`). Native +`return_to` contains `{zone,index,size,collapsed,join?:{section,index}}`; it never +recursively contains another native host. Pins and placement/size intersections +retain the foundation's structured refusal rules. + +Preset names trim surrounding whitespace, require 1..64 Unicode scalar values and +reject controls anywhere in the supplied name. Raw input is capped at 1024 UTF-8 +bytes before trimming; the trimmed name is at most 256 bytes. Names are case-sensitive. +There are at most 64 user presets. Collisions reject unless `overwrite:true` is +explicit; built-ins are immutable. No production kinds, preset contents or workspace +descriptors are invented. Headless starts with an empty registry/catalogue and an +internal current-layout identity, not a registered product workspace. Fixtures and +peer integrations can inject synthetic or real registrations. Missing capabilities +return errors rather than guessed defaults or disk/native success. + +Workspace selection stages the outgoing full envelope, destination and selected +workspace together, then uses one guarded `Replace` on the retained runtime. +Same-workspace selection is a true no-op, preserving revision, focus, peek and +effects even if storage staging is unavailable. Applying/resetting a preset never +selects a workspace. Replacements hide omitted content without implicit Close or +Cancel; retained editors, conversations and hidden services survive A→B→A. + +Catalogue preparation uses encoded full `LayoutEnvelope` records and explicit +aggregate caps: 64 registered workspaces, 64 built-ins, 64 remembered envelopes, +64 user presets, 16384 metadata bytes, and 4194304 aggregate envelope/recovery bytes. +Each envelope/rejected recovery buffer remains at most 262144 bytes and obeys the +foundation node/depth/collection caps. Quarantine, retained data, shared section +snapshots including projected sections, complete section order and bounded rejected +recovery intent survive save/apply/reset. Conflicting opaque identities, snapshots, +retained data or recovery intent reject atomically. Restoration uses the foundation +decoder and reappearance logic. Storage preparation finishes before live dispatch; +catalogue publication is infallible after successful native/controller guards. +Revision changes during staging reject the staged catalogue. No fallible storage +write after live commit is treated as an atomic success. The shipped catalogue is +in-memory; production preference durability and migrations remain peer work. + +Atomic layout batches contain 1..64 commands, using the same parser/executor and +one final guarded Apply or Replace plus one catalogue publication. Queries and +saves may accompany mutations; save/apply/reset/workspace sequences can stage +together. Replies describe the **final committed** state, not hypothetical +intermediate live states. Every `expected_revision` in an atomic batch refers to +the initial live revision. Explicit Close/Open conflicts remain `lifecycle` errors. +Atomic batches cannot combine a snapshot replacement with explicit panel mutations, +or mix document commands with application layout; they return `capability` before +publishing anything. This preserves the foundation's explicit lifecycle intents. +Use `rollback:false` for sequential per-command transactions across these domains; +failures report `rolled_back:false`, `undone:0` and completed results. Scripts use +the same injected backend sequentially and stop at the first failure. A Session-only +executor (including ordinary CLI design scripts without an injected backend) +returns a structured missing-capability error for layout commands. + +The GUI route uses the enabled runtime's actual content-service provider and an +injected `NativeHostAdapter`, never a reconstructed LayoutService. Headless MCP +owns one persistent application backend distinct from Session; Remote forwards to +the app and keeps no mirrored layout. Auto mode does not discard headless layout +work when an app appears. Foundation errors retain `{rule,detail}` with bounded +details: control replies add `panel_error` alongside the existing error string; +MCP tool errors add `structuredContent.panel_error`. The error string also encodes +that object, preserving identity through older string-only backend boundaries. +Rust integrations implement `ActionSink::project(LayoutAction)` as a pure +projection on the authoritative service. Its default returns `capability` so an +older inspect/dispatch-only sink cannot accidentally publish unstaged commands. +`LayoutService` and `RuntimeActionSink` provide it using the foundation's own +preparation path. `with_live_layout` refreshes the envelope's shared section memory +and projections without discarding opaque fields, then encodes against the same +foundation limits before publication. + +Storage consumers can enumerate `CatalogueState::user_presets()` read-only and +round-trip a complete validated catalogue with `export()` and +`CatalogueState::hydrate(bytes,registry)` or `InMemoryCatalogue::from_snapshot`. +Hydration is independent of live commands; restored users remain explicitly +overwritable users, while built-ins remain immutable. Workspace descriptors, +remembered full envelopes, and rejected recovery bytes are included. The versioned +snapshot uses `SCPCAT01`, then length-prefixed little-endian u32 counts/UTF-8 names +and raw byte records, in built-ins/users/workspaces/remembered order. Each envelope +record contains length-prefixed envelope JSON, a recovery-presence byte (0/1), and, +when present, length-prefixed exact recovery bytes. Workspace descriptors contain +ID/title-key/default-name strings. The snapshot has an additional 8192-byte framing +allowance above the existing aggregate payload/metadata caps (4218880 bytes total). +Every count/string/record is bounded before allocation, and hydration rejects +duplicate names across users/built-ins, duplicate workspace keys, corrupt framing, +trailing data, invalid envelope identities and all existing aggregate/node/depth +limits before a candidate can be published. This seam performs no disk storage. + +Reading a retained envelope does not consume quarantine merely because the registry +has grown. `decode_retained_record` validates an already-retained record exactly; +`decode_retained` additionally checks its workspace. Neither reader generates +section order/projections or performs quarantine migration/reappearance. Hydration +preserves the original validated record bytes and rejected binary data, including +records at the per-envelope or aggregate cap when optional panel kinds disappear +or return. Missing registrations do not invalidate unrelated users, built-ins or +workspace memories. Retained validation checks structural ownership, placement +bounds and all applicable known-kind constraints, without invented descriptors. +An exact retained layout can still contain absent kinds and is not live admission. +`StoredEnvelope::project_envelope` (or foundation `project_retained_record`) stages +missing-kind quarantine before a guarded live use, preserving full section order, +activation and opaque records. This staging does not consume existing quarantine; +ordinary save/live overlays therefore keep reappearance retryable after registry +growth. Foundation `decode` also stages migration and attempts restoration, with +its existing fallback/rejected-input result contract. +Materialization may legitimately exceed a cap and reject its staged candidate; +reading/hydrating the accepted original record does not materialize it. +Apply/reset/workspace replacement +explicitly stage restoration, and consume it only with a successful authoritative +Replace and catalogue publication. A failed action leaves the restore obligation +retryable. `panel.popout` requires the panel's `features.popout` on both web and +native policies before any enabled web fallback; `panel.float` remains separate. + +Application command, atomic-batch and GUI action boundaries refresh the current +read-only provider/document environment and availability. A document or contextual +model change earlier in a sequential batch/script is visible to the next panel +step without a tick. Queries and failed actions cannot borrow the previous +document's context. No content tick, document edit, geometry work or camera tail is +added to this boundary. All application GUI and command routes use one stored +native adapter, installed once; redock its native sections before disabling it. +Unsupported atomic intent mixtures are rejected by pure structural preflight +before any context/controller publication as well as before layout/native effects. + +At MCP tool level, an atomic batch containing any panel/layout command must reach +the authoritative batch transaction. If the endpoint is unavailable or the encoded +request exceeds its transport margin, a structured zero-effect capability/size +refusal replaces the old sequential fallback. No document checkpoint or individual +layout command is sent. Explicit `rollback:false` keeps the sequential fallback +and reports completed layout changes honestly. Document-only batch fallback keeps +its existing checkpoint/rollback behaviour. Explicit null parameters normalize to +an empty object in single, atomic, sequential and script routes for GUI/headless. + +Compatibility: `view.layout` still means Floating/Compact **surface styling**. +History-in-Browser, History Bodies/Origin and Render search/options remain content +preferences. Existing `view.history_layout`/`view.render_dock` controls continue to +serve the existing shell. There is no safe universal alias without registered +instance identities: `browser`/`under_browser` combine content with placement, and +Render dock changes can affect a pair. They are not silently mapped to universal +instances. Integrations with explicit identities can issue typed `panel.move`, +`panel.resize` and `panel.collapse` requests for safe placement changes. No command +implicitly selects a layout workspace on a document, ribbon, tool or context change. + For UI-kit review, `ui.status_fixture {"preset":"mode"}` shows bounded status specimens in the real viewport. Presets are `off`, `mode`, `result`, `attention`, `row`, `kinds`, `many` and `key`; the reply carries the preset and item count. This diff --git a/docs/panel-foundation.md b/docs/panel-foundation.md new file mode 100644 index 000000000..ef3d792b1 --- /dev/null +++ b/docs/panel-foundation.md @@ -0,0 +1,309 @@ +# Universal panel foundation + +The public foundation is `solidcraft_engine::panels` and +`solidcraft_ui_egui::panel_runtime`. It establishes contracts and executable +synthetic fixtures for #11302. The current shell and defaults remain in use. +No panel commands, preferences, content migrations, native windows or docking +gestures are enabled by this change. Classic remains a permanent compatibility +preset. Production adapters land in the separate children of #11218. + +## Ownership and integration boundaries + +| Owner | Public contract | Responsibility | +| --- | --- | --- | +| Foundation / engine | `PanelRegistry`, `PanelSpec`, `Layout`, `LayoutService`, `ActionSink` | Stable identities, bounded wire values, constraints, atomic actions and inspection. No egui or Session dependency. | +| Foundation / UI | `PanelRuntime`, `ControllerBinding`, `PanelController`, `RuntimeActionSink` | Retained state, ownership, lifecycle preflight, live availability, independent service ticks. | +| Host child | `PanelHost`, `PanelContext`, `ResolvedLayout`, `EguiPanelHost` | Geometry, host composition and later docking interactions. Existing `ui_kit::Container` remains the outer boundary. | +| Command child | `LayoutAction`, `LayoutReply`, `PanelError`, `LayoutTarget` | Register schemas and route GUI/agent requests to the live runtime sink. Do not construct a second service from a saved snapshot. | +| Persistence child | `LayoutEnvelope`, `LayoutPersistence`, `decode`, `encode` | Workspace preference key, atomic storage, presets and future migrations. Keep unrelated preferences. | +| Native child | `NativeHostAdapter`, `HostEffect`, `HostCapabilities` | Preflight resources, native host realization, focus and redock. No native implementation is included here. | +| Surface/accessibility children | `InputRegion`, `ControlId`, `Direction`, `Motion`, `ContrastOutcome` | Painted/input bounds, semantic roles, keyboard routing, mirrored edges, reduced motion and validated theme surfaces. | +| Content children | `PanelModels`, `ContentCommandSink`, `PanelLocalServices`, content slots | Model access, explicit content commands, controllers, owner-scoped services and independently scrolling content. | + +Panel kind, instance, section, workspace, document, viewport, native host and +semantic control IDs are different Rust types. Their wire values are bounded +lowercase identifiers. Registry specs and serializable layout never contain +callbacks, document state, egui state or live editors. Only `allowed_zones`, +`edge_rule` and `surface` express placement exceptions. Normal capabilities +(close, tabs, collapse, popout, multiple instances) are shared feature flags. + +Layout belongs to the application/workspace; it never enters a design file, +Session revision, dirty flag, undo stack, evaluator or tessellation cache. +`ContentOwner` independently chooses application, workspace, document or window +ownership. A native reparent does not change content ownership. Document switching +retains existing controllers and creates only missing owner/instance bindings. +Complete layout application changes the live workspace without replacing the +runtime or service. Application/document/window controllers keep matching instance +identities; workspace controllers remain under their original workspace owner and +continue ticking while hidden. Switching back reuses those controllers and drafts. +All retained controllers receive service updates even when closed, unavailable, +inactive, collapsed or on another document. Providers must expose models for +retained owners, not redirect old-document reads to the current document. + +`SolveApp::enable_panel_runtime` accepts a runtime and `AppPanelServices` explicitly. +Its optional field defaults to `None`, remains on the app across document tabs, +and is ticked from `SolveApp::logic` independently of presentation. Refresh receives +only `&Session`. `disable_panel_runtime` preflights cleanup and requires native +sections to be redocked before dropping their adapter. Tick failures remain +inspectable on `AppPanelRuntime::last_error`; they do not inject untranslated UI. +This is an internal adapter seam, not a preference, environment switch or control +method. `dispatch_panel_layout`, `mount_panels`, `panel_content_action` and +`tick_panel_runtime` forward through the same injected provider. Application +command, atomic-batch and GUI dispatch boundaries refresh the read-only provider +and current document environment before inspection/projection. Availability is +refreshed without ticking content, evaluating models or creating geometry; retained +service failures still require a successful real update to recover. Sequential +programmatic model/document changes are therefore visible to the next panel step +without waiting for a frame tick. + +`AppPanelRuntime::set_command_adapters` installs one catalogue and one native +adapter once, before native hosts exist. Both `SolveApp::dispatch_panel_layout(action)` +and command routes use that stored adapter; there is no per-call native argument. +`AppPanelRuntime::dispatch`, content actions and command/batch methods take the current `&Session` +for read-only context refresh. Its runtime is private with a read-only `runtime()` +accessor; service borrowing is internal, so consumers cannot replace the runtime or +dispatch through another adapter through a mutable services callback. Standalone +`PanelRuntime`/`RuntimeActionSink` fixtures retain their explicit fake-adapter seam. +Changing the installed application adapter is refused rather than abandoning its +created hosts. These are integration APIs, not a production native implementation. + +## Actions and atomicity + +`ActionSink::dispatch` accepts `Inspect`, `Apply { expected_revision, mutations }` +or `Replace { expected_revision, layout }`. +GUI, keyboard and agent adapters share this reducer. `RuntimeActionSink` adds +controller/native lifecycle guards around the same engine service. Runtime users +receive immutable layout inspection; there is no mutable bare-service escape. +Replies describe committed layout, revision, availability, interaction, capabilities +and host effects. Layout revision is independent of document revision. + +`Replace` validates a complete preset/saved layout and atomically changes the +workspace on the same authoritative service/revision. It stages availability, +controller factories and native create/rebind/release effects before committing. +Omitted entries and entries marked closed are noncanceling hides: their retained +controllers keep drafts, conversations and service updates, with no collapsed rail +unless the snapshot actually requests one. Restoring the snapshot restores those +controllers. Instance IDs cannot change kind across workspace switches; the service +retains a bounded identity catalogue until explicit Destroy releases an identity +and all of its retained owners. Unknown kinds fail atomically; persistence +adapters first decode/quarantine unknown data and apply the known layout portion. +Registered kinds with missing bindings or unavailable context remain dormant. +After successful replacement, old local input/overlay ownership is released; +failure leaves environment, revision, controllers and local/native hosts intact. +Use this operation for workspace switching rather than rebuilding a runtime or +synthesizing Close/Open batches. `set_environment` changes document/window/viewport +context within the already committed workspace. + +- `Open` targets kind **and** instance. New instances require an explicit destination; + an existing closed instance can reopen from its remembered placement and size. + Repeating an open is idempotent unless a new placement is supplied; use `Move`. +- `NewSection` and `JoinTab` are distinct destinations. Section insertion indexes + address the global ordered section list **after** detachment; tab indexes address + the destination list after detachment. Both reject invalid indexes. Empty groups + are removed. Joining retains the group's active tab, dimensions and collapse state. +- `Activate` selects an already-open tab, without requesting keyboard focus or + uncollapsing it. `Focus` can reopen retained closed state, select its tab, + uncollapse it and request host focus. `Peek` temporarily presents a collapsed + tab, without changing persisted size or collapse. Dismiss is transient too. +- `ResizePair` requires adjacent sections of one dock, conserves their split-axis + extent and changes no cross-axis dimension. `ResetPair` returns the pair to + the ratio of active members' registered defaults within intersected bounds. + `SetSize` is a typed explicit outer-size mutation. +- `Close` retains placement/size memory. `Destroy` removes an already-closed + instance and its retained controllers across workspaces/owners. `NativeClose` redocks the whole section + to its recorded return destination, optionally rejoining a stable former tab + group. Missing/reparented groups use the recorded dock fallback; valid joins + retain target activation. It does not close/cancel the content. + +A transaction is prepared on a bounded copy and validated before commit. Rejected +transactions preserve layout, revision, interaction, retained controllers and hosts. +Lifecycle preflight is side-effect-free. It checks explicit Close/Reopen/Reparent/ +Destroy events before committing; applying those prepared events is infallible. +State notifications are observational and cannot veto a mutation. Factories stage +fresh controllers without publishing external effects, since staging can be +discarded. Native preflight similarly must establish that commit can finish. +Adapters must reserve/stage fallible work, not discover a failure after commit. +Only explicit content actions may Apply/Finish/Cancel/Stop; hiding, tab changes, +collapse, reparent and native redock never implicitly invoke them. Explicit close +cancels transactional controllers for the affected instance across retained owners; +one cancellation refusal rejects the entire batch. +Close or Destroy combined with any other instance-targeted operation on the same +instance in a batch is rejected with `Lifecycle` before mutations/effects. This +includes Close/Open, Close/Move/Open and Destroy/Open; independent instance and +section mutations can still be batched. Explicit Close cancels a live hidden +transaction even if its saved entry was already marked closed by `Replace`. + +`ControllerState` distinguishes requested-open, available, presented, activated +and destroyed. Presented requires usable resolved geometry; activated additionally +requires the selected tab/peek. Keyboard focus is separate in `PanelContext`. +`destroy_owner` performs explicit cleanup without editing layout, leaves a bounded +tombstone, and requires `revive_owner` to create fresh content again. `shutdown` +preflights all owners before clearing any and makes the runtime terminal. + +Independent updates attempt every retained controller even when staging or another +controller fails. `update_errors` aggregates at most two bounded typed errors per +controller plus staging/reconciliation errors (258 total). Invalid availability +reports become `Availability` failures. Failing content is unavailable, loses stale +presentation/input ownership and cannot become healthy merely by moving it; a +successful later update restores availability. Reconciliation still runs before +the aggregate failure is returned. Injected-provider refresh failures also do not +skip the independent controller update loop. + +## Final product decisions + +- Zones are logical Left, Right, Bottom, Floating and Window. Top remains reserved + for ribbon/application chrome. RTL mirrors the physical side; persisted IDs and + tab order remain logical. +- `PinOuter` follows whichever logical side the panel occupies, requires its section + first on that edge and excludes Bottom in registry data. It is inactive in free/ + native hosts. Competing pinned **instances**, including in one group, are rejected; + no existing panel is silently displaced. +- Tab groups use the intersection of every member's minimum and maximum **width + and height**. Impossible joins and dimensions outside that intersection fail. +- min/default/max are outer logical dimensions. Geometry reports actual outer and + usable body bounds separately. egui applies scale once. Free/native flow starts + Wide at aspect >= 1, otherwise Tall; Tall switches above 1.1 and Wide below 0.9. + Size classes use the shorter usable edge: Compact < 240, Regular 240..480, + Wide > 480. Invalid/nonfinite/oversized dimensions are rejected. +- Capacity shortages produce transient unpresented/overflow records, never reduced + below-minimum content or saved-dimension/collapse rewrites. Collapsed rails are + chrome. Hosts expose overflow access and retry presentation when capacity returns. +- New Open/Focus/Activate/Peek requests for unavailable content fail with an + availability reason. Saved requested-open content remains dormant and reappears + when its owner/context is available. Missing bindings are dormant too. +- Combined History-in-Browser and History Bodies/Origin stay content preferences + or shared components. They do not merge or depend on panel host identity. +- Opaque surface requests win over Translucent, then zone defaults apply (bottom/ + native opaque, side/free translucent). Contrast resolution can raise background + alpha only. If full opacity cannot make authored tokens readable, return + `RetainReadableFallback` with a typed reason and keep the validated fallback/last + good tokens and raw imported intent. No claim of 4.5:1 or text recolouring is + permitted to disguise failure. Theme resolution is implemented by the surface child. + +## Geometry and local services + +`ResolvedPanel` contains outer/body geometry plus explicit paint and input regions. +Validation bounds regions and requires input inside paint; the viewport outside +these regions belongs to the existing camera/navigation path. Semantic controls +carry stable IDs, roles, accessible names and keyboard-focusability. Hosts may use +`consumes_pointer` to compose input ownership without a full-window shield. +The reference `resolve_geometry` is deterministic synthetic mounting geometry, +not production docking. It reports overflow instead of changing desired state. + +`PanelContext` carries presentation geometry, owner/scope identities, flow, size +class, direction, focus and motion; services are a separate argument. Content +has Header/Body/Footer slots and chooses scrolling itself. `EguiPanelHost` uses +one kit Container, title/status/attention and semantic content actions; its action +strip can scroll independently of the body. Reduced motion resolves duration to +zero, without delaying identity/focus/lifecycle changes. +The reference egui adapter accepts exactly one full-outer paint rectangle and one +full-outer Surface input region. It rejects sparse, empty-input or partial-input +records with `Capability` before painting or creating widgets. Rich region-aware +surfaces belong to #11307. Every child clip intersects the existing parent clip. + +Keyboard ownership, focus, file/pointer drops, overlays, clipboard and picking use +`PanelLocalServices` with explicit workspace/document/viewport scope. Native viewport +identity uses the native host's stable string in the viewport ID domain; platform +adapters map that identity to their actual viewport handle. Reparenting releases +old host-local focus/overlays/drop routing; the controller survives. Never route +a native service request through the root viewport or a different document. + +## Persistence and bounds + +Envelope format is `solidcraft.panel-layout`, envelope/layout versions are both 1. +`PANEL_API_VERSION` and each live reply's `api_version` are also 1. +Public schema functions describe actions, replies and envelopes. Serde/schema +values are **untrusted wire data**, not validity proofs. Use `decode_action`, +`decode`, `encode` and the reducer. The engine owns versions; persistence adapters +own atomic storage and migration policy, not a second layout model. + +Limits: 64-byte IDs, 128 kinds/layout instances/retained instance identities, +64 sections, +32 tabs per section, 64 mutations per transaction, 262144-byte encoded envelope, +32768 logical units per positive size dimension, finite bounded coordinates. +Opaque JSON is limited to 8192 nodes and depth 32; availability reasons to 256 +bytes. Region/control, service payload and retained-owner collections are bounded. +Encoding uses a capped writer, not an unbounded serialization followed by a check. +Runtime retention has separate limits: 32 document owners, 128 other owners, +128 controllers per owner, and 20,480 controllers overall. These limits preserve +the application's supported document count without evicting live drafts. + +Unknown panel records and raw future fields are retained in bounded quarantine. +`section_snapshots` stores each raw section once, including future fields, desired +tab order and pending activation; quarantined/retained records refer to its ID. +The bounded `section_order` list ranks **all** saved sections, including dormant +sections and known survivors without snapshots. Restoration uses those ranks, not +insertion indexes clamped into an incomplete list, so instance/quarantine processing +order and staged registry reappearance cannot reorder the saved complete layout. +Known live ordering remains authoritative when edited: surviving visible entries +take their latest relative order while dormant gaps remain; newly added entries +anchor before their next surviving visible neighbour. + +A retained snapshot from a fully restored episode is opaque metadata, not stale +layout authority. Before newly unknown members are removed on load, current saved +section semantics refresh its tabs, activation, placement, dimensions, collapse +state and rank. Existing opaque keys absent from typed live data are preserved; +current raw values for the same keys supply the latest saved intent. In an active +partial episode, still-dormant members remain in the complete order. Each snapshot's +optional `projected` section records the last materialized state: changed visible +activation overrides a pending choice, while an unchanged generated fallback does +not replace the desired dormant active member. Newly generated fallback selections +are recorded after quarantine filtering, so they cannot be mistaken for user edits. +The same merge runs before direct restoration after an in-memory live edit. + +These v1 fields have serde defaults. Earlier v1 envelopes without `section_order` +derive missing section ranks from sorted snapshot indexes; missing projections +conservatively retain dormant activation until a materialized baseline is recorded. +Both the complete rank list and projected sections obey the existing section/tab/ +ID limits, plus the envelope's global byte/node/depth bounds. Known layout starts +independently, and known survivors/extra current tabs remain intact during restores. +`restore_quarantine_with_availability` can defer unavailable entries; invalid bounds +or constraints also leave entries quarantined. Successful restoration preserves +raw instance fields in `retained_data` and shared raw section fields/order in +`section_snapshots`, even across later unregister/register cycles. Adapters consume +these explicitly. Restore stages the whole envelope and applies it only if encoding +fits global byte/node/depth caps; successful decode is guaranteed encodable by this +version. An unrepresentable lossless result returns fallback/recovery, not silent +field loss. Unknown corruption, invalid known layouts or future versions +return a validated preset fallback plus a once-reportable notice and bounded rejected +bytes for recovery. The adapter must preserve unrelated preference keys. + +## Executable fixtures + +`synthetic_registry`, `fixture_service`, `fixture_open`, `transaction`, +`FakePersistence` and `FIXTURE_LAYOUT_V1` are public engine fixtures. The v1 JSON +lives at `crates/engine/src/panels/fixtures/layout-v1.json`. It is authored contract +data, not a captured production design or a generated schema snapshot. + +`PanelMountHarness` combines the actual runtime/action service with synthetic +application-owned content, document-owned transactional editor, workspace-owned multi-instance log/pin +controllers, fake models/command sink/local services/native adapter, fake mount +host and persistence adapter. `FixtureProbe` provides snapshots and bounded draft/ +failure controls. `apply_layout` exercises saved-layout/workspace transitions through +the actual sink; `without_content` exercises dormant missing bindings. Fake host mounting invokes all three real controller slots with +an egui context; it is headless and does not establish visual correctness. + +```rust +use solidcraft_engine::panels::*; +use solidcraft_ui_egui::panel_runtime::PanelMountHarness; + +fn specimen() -> PanelResult<()> { + let mut h = PanelMountHarness::new(false)?; + h.dispatch(vec![fixture_open( + "fixture.editor", "editor", "editor-section", Zone::Left, 0, + )?])?; + h.tick()?; // independent services, even with no host mounted + h.mount(LogicalRect { + origin: Point { x: 0.0, y: 0.0 }, + size: Size { width: 1200.0, height: 800.0 }, + })?; + h.save()?; + Ok(()) +} +``` + +Engine and UI domain test modules contain hostile action sequences, bounds and +collection limits, exactly-once constraints, pins, atomic failures, incompatible +tabs, overflow restoration, availability, close/reopen, schema/envelope fixtures, +controller retention, hidden service updates, explicit editor actions, native +preflight/redock, scoped input, RTL/reduced motion and document/cache isolation. diff --git a/docs/ui-kit.md b/docs/ui-kit.md index 3ecd9a99e..104f216eb 100644 --- a/docs/ui-kit.md +++ b/docs/ui-kit.md @@ -1,5 +1,14 @@ # SolidCraft UI kit +The internal opt-in [universal panel foundation](panel-foundation.md) separates +engine layout/specs from retained UI controllers and host-local services. +`panel_runtime::EguiPanelHost` mounts bounded Header/Body/Footer slots through one +existing `ui_kit::Container`; content controls its own scrolling. This reference +adapter requires a full rectangular paint/input surface, rejects sparse geometry, +and preserves parent clipping. `SolveApp::mount_panels` uses the enabled runtime's +injected services. It adds no default +placement/content change. Production docking and panel migrations remain separate. + `viewport_status_item` and `viewport_status_row` draw persistent viewport pills on `Surface::ViewportStatus`. Callers supply translated names, formatted settings, kind, stable identity and key availability, and dispatch returned clear/edit actions. diff --git a/tests/kernel-cases/EXEMPT b/tests/kernel-cases/EXEMPT index b11151e4e..bd42b41c9 100644 --- a/tests/kernel-cases/EXEMPT +++ b/tests/kernel-cases/EXEMPT @@ -91,6 +91,11 @@ inspect.curvature_map display analysis: shading inspect.environment_map display analysis: shading inspect.silhouette display analysis: outline inspect.zebra display analysis: shading +layout.apply application panel layout; no geometry (engine/UI/MCP tests) +layout.get application panel layout; no geometry (engine/UI/MCP tests) +layout.reset application panel layout; no geometry (engine/UI/MCP tests) +layout.save application panel layout; no geometry (engine/UI/MCP tests) +layout.workspace.select application panel layout; no geometry (engine/UI/MCP tests) library.apply material and appearance libraries library.export material and appearance libraries library.inspect material and appearance libraries @@ -107,6 +112,21 @@ motion.delete removes a motion study motion.export writes a study's results to a file motion.export_animation writes an animation motion.list a listing of motion studies +panel.activate application panel layout; no geometry (engine/UI/MCP tests) +panel.close application panel layout; no geometry (engine/UI/MCP tests) +panel.collapse application panel layout; no geometry (engine/UI/MCP tests) +panel.dismiss application panel layout; no geometry (engine/UI/MCP tests) +panel.float application panel layout; no geometry (engine/UI/MCP tests) +panel.focus application panel layout; no geometry (engine/UI/MCP tests) +panel.list application panel layout; no geometry (engine/UI/MCP tests) +panel.move application panel layout; no geometry (engine/UI/MCP tests) +panel.native_close application panel layout; no geometry (engine/UI/MCP tests) +panel.open application panel layout; no geometry (engine/UI/MCP tests) +panel.peek application panel layout; no geometry (engine/UI/MCP tests) +panel.popout application panel layout; no geometry (engine/UI/MCP tests) +panel.reset_pair application panel layout; no geometry (engine/UI/MCP tests) +panel.resize application panel layout; no geometry (engine/UI/MCP tests) +panel.resize_pair application panel layout; no geometry (engine/UI/MCP tests) parameters.comment parameter bookkeeping; a value change that rebuilds is parameters.change, which cases use parameters.complete parameter bookkeeping; a value change that rebuilds is parameters.change, which cases use parameters.delete parameter bookkeeping; a value change that rebuilds is parameters.change, which cases use