+ {panelHead('left', 'px-2')}
+
{closeBesideControls && composerCloseButton}
- {/* The left panel's button at the start, the right one's at the end: where each panel is. */}
+ {/* A folded panel's Show button where the panel goes: the left one's at the start, the right one's before the window buttons. */}
{leftPanelToggle &&
{leftPanelToggle}
}
@@ -5214,23 +5256,31 @@ export function EmailComposer({
))}
{rightPanelToggle}
- {canMaximize && (
- setMaximized((v) => !v)}
- className="hidden md:grid h-8 w-8 place-items-center rounded-md text-muted-foreground hover:bg-muted hover:text-foreground"
- aria-label={maximized ? t('restore') : t('maximize')}
- title={maximized ? t('restore') : t('maximize')}
- data-testid="composer-maximize"
- >
- {maximized ? : }
-
- )}
- {popOutButton(cn(phoneLayout ? "hidden md:grid" : "grid", "h-8 w-8 place-items-center rounded-md text-muted-foreground hover:bg-muted hover:text-foreground"), "w-4 h-4")}
- {!closeBesideControls && composerCloseButton}
+ {!rightPanelOpen && windowButtons}
+
+ {panelHead('right', 'gap-3 ps-2 pe-4', windowButtons)}
)}
+ {/* The left panel, the message and the right panel, under the header. */}
+
+
pluginSidebars.setSideWidth('left', w)} />
+
+ {/* Drag overlay */}
+ {isDraggingOver && (
+
+ )}
{/* Fields + body. While pinFields holds, the fields sit outside the
body's scroll container so From/To/Cc/Bcc/Subject stay reachable
while scrolling long bodies, matching the pinned formatting toolbar
@@ -6305,6 +6355,7 @@ export function EmailComposer({
)}
pluginSidebars.setSideWidth('right', w)} />
+
);
diff --git a/locales/ar/common.json b/locales/ar/common.json
index f5921dc67..0a2286844 100644
--- a/locales/ar/common.json
+++ b/locales/ar/common.json
@@ -7673,6 +7673,10 @@
"offline_send_saved": "أنت دون اتصال. الرسالة محفوظة في المسودات.",
"offline_send_unsaved": "أنت دون اتصال. تبقى الرسالة هنا وتُحفظ في المسودات عند عودة الاتصال."
},
+ "composer_panel": {
+ "show_panel": "إظهار {name}",
+ "hide_panel": "إخفاء {name}"
+ },
"desktopDevTools": {
"section_title": "استكشاف الأخطاء وإصلاحها",
"label": "أدوات المطورين ({shortcut})",
diff --git a/locales/ca/common.json b/locales/ca/common.json
index 9fde0d888..705591747 100644
--- a/locales/ca/common.json
+++ b/locales/ca/common.json
@@ -7673,6 +7673,10 @@
"offline_send_saved": "No teniu connexió. El missatge està desat a Esborranys.",
"offline_send_unsaved": "No teniu connexió. El missatge es queda aquí i es desa a Esborranys quan torneu a tenir connexió."
},
+ "composer_panel": {
+ "show_panel": "Mostra {name}",
+ "hide_panel": "Amaga {name}"
+ },
"desktopDevTools": {
"section_title": "Resolució de problemes",
"label": "Eines per a desenvolupadors ({shortcut})",
diff --git a/locales/cs/common.json b/locales/cs/common.json
index e8199be5a..bb545640a 100644
--- a/locales/cs/common.json
+++ b/locales/cs/common.json
@@ -7673,6 +7673,10 @@
"offline_send_saved": "Jste offline. Zpráva je uložená v Konceptech.",
"offline_send_unsaved": "Jste offline. Zpráva tu zůstane a uloží se do Konceptů, až budete znovu online."
},
+ "composer_panel": {
+ "show_panel": "Zobrazit {name}",
+ "hide_panel": "Skrýt {name}"
+ },
"desktopDevTools": {
"section_title": "Řešení potíží",
"label": "Nástroje pro vývojáře ({shortcut})",
diff --git a/locales/da/common.json b/locales/da/common.json
index 4d8c7681a..3b6e82d6f 100644
--- a/locales/da/common.json
+++ b/locales/da/common.json
@@ -7673,6 +7673,10 @@
"offline_send_saved": "Du er offline. Beskeden er gemt i Kladder.",
"offline_send_unsaved": "Du er offline. Beskeden bliver her og gemmes i Kladder, når du er online igen."
},
+ "composer_panel": {
+ "show_panel": "Vis {name}",
+ "hide_panel": "Skjul {name}"
+ },
"desktopDevTools": {
"section_title": "Fejlfinding",
"label": "Udviklerværktøjer ({shortcut})",
diff --git a/locales/de/common.json b/locales/de/common.json
index 9c39c5a69..7c58391bb 100644
--- a/locales/de/common.json
+++ b/locales/de/common.json
@@ -7673,6 +7673,10 @@
"offline_send_saved": "Sie sind offline. Die Nachricht ist in den Entwürfen gespeichert.",
"offline_send_unsaved": "Sie sind offline. Die Nachricht bleibt hier und wird in den Entwürfen gespeichert, sobald Sie wieder online sind."
},
+ "composer_panel": {
+ "show_panel": "{name} einblenden",
+ "hide_panel": "{name} ausblenden"
+ },
"desktopDevTools": {
"section_title": "Fehlerbehebung",
"label": "Entwicklertools ({shortcut})",
diff --git a/locales/en/common.json b/locales/en/common.json
index a2e0f400c..a7e3e248c 100644
--- a/locales/en/common.json
+++ b/locales/en/common.json
@@ -7673,6 +7673,10 @@
"offline_send_saved": "You're offline. The message is saved in Drafts.",
"offline_send_unsaved": "You're offline. The message stays here and is saved in Drafts when you're back online."
},
+ "composer_panel": {
+ "show_panel": "Show {name}",
+ "hide_panel": "Hide {name}"
+ },
"desktopDevTools": {
"section_title": "Troubleshooting",
"label": "Developer tools ({shortcut})",
diff --git a/locales/es/common.json b/locales/es/common.json
index 7b9d02613..db6652b53 100644
--- a/locales/es/common.json
+++ b/locales/es/common.json
@@ -7673,6 +7673,10 @@
"offline_send_saved": "No tienes conexión. El mensaje está guardado en Borradores.",
"offline_send_unsaved": "No tienes conexión. El mensaje se queda aquí y se guarda en Borradores cuando vuelvas a tener conexión."
},
+ "composer_panel": {
+ "show_panel": "Mostrar {name}",
+ "hide_panel": "Ocultar {name}"
+ },
"desktopDevTools": {
"section_title": "Solución de problemas",
"label": "Herramientas para desarrolladores ({shortcut})",
diff --git a/locales/et/common.json b/locales/et/common.json
index 19ab50447..336b04ed0 100644
--- a/locales/et/common.json
+++ b/locales/et/common.json
@@ -7673,6 +7673,10 @@
"offline_send_saved": "Oled võrguta. Kiri on salvestatud mustanditesse.",
"offline_send_unsaved": "Oled võrguta. Kiri jääb siia ja salvestatakse mustanditesse, kui oled jälle võrgus."
},
+ "composer_panel": {
+ "show_panel": "Kuva {name}",
+ "hide_panel": "Peida {name}"
+ },
"desktopDevTools": {
"section_title": "Tõrkeotsing",
"label": "Arendaja tööriistad ({shortcut})",
diff --git a/locales/fa/common.json b/locales/fa/common.json
index 4e1219635..9253da444 100644
--- a/locales/fa/common.json
+++ b/locales/fa/common.json
@@ -7673,6 +7673,10 @@
"offline_send_saved": "آفلاین هستید. پیام در پیشنویسها ذخیره شده است.",
"offline_send_unsaved": "آفلاین هستید. پیام همینجا میماند و وقتی دوباره آنلاین شدید در پیشنویسها ذخیره میشود."
},
+ "composer_panel": {
+ "show_panel": "نمایش {name}",
+ "hide_panel": "پنهان کردن {name}"
+ },
"desktopDevTools": {
"section_title": "عیبیابی",
"label": "ابزارهای توسعهدهنده ({shortcut})",
diff --git a/locales/fr/common.json b/locales/fr/common.json
index 83460df07..9d5ac7416 100644
--- a/locales/fr/common.json
+++ b/locales/fr/common.json
@@ -7673,6 +7673,10 @@
"offline_send_saved": "Vous êtes hors ligne. Le message est enregistré dans les Brouillons.",
"offline_send_unsaved": "Vous êtes hors ligne. Le message reste ici et sera enregistré dans les Brouillons dès que vous serez de nouveau en ligne."
},
+ "composer_panel": {
+ "show_panel": "Afficher {name}",
+ "hide_panel": "Masquer {name}"
+ },
"desktopDevTools": {
"section_title": "Dépannage",
"label": "Outils de développement ({shortcut})",
diff --git a/locales/he/common.json b/locales/he/common.json
index 6fd019a89..c8144b369 100644
--- a/locales/he/common.json
+++ b/locales/he/common.json
@@ -7674,6 +7674,10 @@
"offline_send_saved": "אין חיבור. ההודעה שמורה בטיוטות.",
"offline_send_unsaved": "אין חיבור. ההודעה נשארת כאן ותישמר בטיוטות כשתחזרו לרשת."
},
+ "composer_panel": {
+ "show_panel": "הצגת {name}",
+ "hide_panel": "הסתרת {name}"
+ },
"desktopDevTools": {
"section_title": "פתרון בעיות",
"label": "כלים למפתחים ({shortcut})",
diff --git a/locales/hu/common.json b/locales/hu/common.json
index 1cef7c650..d02f4cb08 100644
--- a/locales/hu/common.json
+++ b/locales/hu/common.json
@@ -7673,6 +7673,10 @@
"offline_send_saved": "Offline állapotban van. Az üzenet a Piszkozatok között van mentve.",
"offline_send_unsaved": "Offline állapotban van. Az üzenet itt marad, és a Piszkozatok közé kerül, amint újra online lesz."
},
+ "composer_panel": {
+ "show_panel": "{name} megjelenítése",
+ "hide_panel": "{name} elrejtése"
+ },
"desktopDevTools": {
"section_title": "Hibaelhárítás",
"label": "Fejlesztői eszközök ({shortcut})",
diff --git a/locales/it/common.json b/locales/it/common.json
index cca81e26e..3860e544d 100644
--- a/locales/it/common.json
+++ b/locales/it/common.json
@@ -7673,6 +7673,10 @@
"offline_send_saved": "Sei offline. Il messaggio è salvato nelle Bozze.",
"offline_send_unsaved": "Sei offline. Il messaggio resta qui e viene salvato nelle Bozze quando torni online."
},
+ "composer_panel": {
+ "show_panel": "Mostra {name}",
+ "hide_panel": "Nascondi {name}"
+ },
"desktopDevTools": {
"section_title": "Risoluzione dei problemi",
"label": "Strumenti per sviluppatori ({shortcut})",
diff --git a/locales/ja/common.json b/locales/ja/common.json
index 2c7fe67d6..909f0511c 100644
--- a/locales/ja/common.json
+++ b/locales/ja/common.json
@@ -7673,6 +7673,10 @@
"offline_send_saved": "オフラインです。メッセージは下書きに保存されています。",
"offline_send_unsaved": "オフラインです。メッセージはここに残り、オンラインに戻ると下書きに保存されます。"
},
+ "composer_panel": {
+ "show_panel": "{name}を表示",
+ "hide_panel": "{name}を非表示"
+ },
"desktopDevTools": {
"section_title": "トラブルシューティング",
"label": "デベロッパー ツール ({shortcut})",
diff --git a/locales/ko/common.json b/locales/ko/common.json
index 4a5501456..68a313526 100644
--- a/locales/ko/common.json
+++ b/locales/ko/common.json
@@ -7673,6 +7673,10 @@
"offline_send_saved": "오프라인 상태입니다. 메시지는 임시보관함에 저장되어 있습니다.",
"offline_send_unsaved": "오프라인 상태입니다. 메시지는 여기에 남아 있으며 다시 온라인이 되면 임시보관함에 저장됩니다."
},
+ "composer_panel": {
+ "show_panel": "{name} 표시",
+ "hide_panel": "{name} 숨기기"
+ },
"desktopDevTools": {
"section_title": "문제 해결",
"label": "개발자 도구 ({shortcut})",
diff --git a/locales/lv/common.json b/locales/lv/common.json
index f12fb9faf..36c6b4df4 100644
--- a/locales/lv/common.json
+++ b/locales/lv/common.json
@@ -7673,6 +7673,10 @@
"offline_send_saved": "Jūs esat bezsaistē. Ziņojums ir saglabāts melnrakstos.",
"offline_send_unsaved": "Jūs esat bezsaistē. Ziņojums paliek šeit un tiks saglabāts melnrakstos, kad atkal būsiet tiešsaistē."
},
+ "composer_panel": {
+ "show_panel": "Rādīt {name}",
+ "hide_panel": "Paslēpt {name}"
+ },
"desktopDevTools": {
"section_title": "Problēmu novēršana",
"label": "Izstrādātāju rīki ({shortcut})",
diff --git a/locales/mn/common.json b/locales/mn/common.json
index ad1ce7427..81566b789 100644
--- a/locales/mn/common.json
+++ b/locales/mn/common.json
@@ -7673,6 +7673,10 @@
"offline_send_saved": "Та офлайн байна. Мессеж нооргонд хадгалагдсан.",
"offline_send_unsaved": "Та офлайн байна. Мессеж энд үлдэж, онлайн болмогц нооргонд хадгалагдана."
},
+ "composer_panel": {
+ "show_panel": "{name} харуулах",
+ "hide_panel": "{name} нуух"
+ },
"desktopDevTools": {
"section_title": "Алдаа засах",
"label": "Хөгжүүлэгчийн хэрэгсэл ({shortcut})",
diff --git a/locales/nb/common.json b/locales/nb/common.json
index e0c43c990..bc7296b99 100644
--- a/locales/nb/common.json
+++ b/locales/nb/common.json
@@ -7673,6 +7673,10 @@
"offline_send_saved": "Du er frakoblet. Meldingen er lagret i Utkast.",
"offline_send_unsaved": "Du er frakoblet. Meldingen blir her og lagres i Utkast når du er på nett igjen."
},
+ "composer_panel": {
+ "show_panel": "Vis {name}",
+ "hide_panel": "Skjul {name}"
+ },
"desktopDevTools": {
"section_title": "Feilsøking",
"label": "Utviklerverktøy ({shortcut})",
diff --git a/locales/nl/common.json b/locales/nl/common.json
index 4d04e4400..4380cef06 100644
--- a/locales/nl/common.json
+++ b/locales/nl/common.json
@@ -7673,6 +7673,10 @@
"offline_send_saved": "Je bent offline. Het bericht is opgeslagen in Concepten.",
"offline_send_unsaved": "Je bent offline. Het bericht blijft hier en wordt in Concepten opgeslagen zodra je weer online bent."
},
+ "composer_panel": {
+ "show_panel": "{name} tonen",
+ "hide_panel": "{name} verbergen"
+ },
"desktopDevTools": {
"section_title": "Probleemoplossing",
"label": "Ontwikkelaarstools ({shortcut})",
diff --git a/locales/pl/common.json b/locales/pl/common.json
index 3d23c4671..e973b3634 100644
--- a/locales/pl/common.json
+++ b/locales/pl/common.json
@@ -7673,6 +7673,10 @@
"offline_send_saved": "Jesteś offline. Wiadomość jest zapisana w Szkicach.",
"offline_send_unsaved": "Jesteś offline. Wiadomość zostaje tutaj i zostanie zapisana w Szkicach, gdy wrócisz do sieci."
},
+ "composer_panel": {
+ "show_panel": "Pokaż: {name}",
+ "hide_panel": "Ukryj: {name}"
+ },
"desktopDevTools": {
"section_title": "Rozwiązywanie problemów",
"label": "Narzędzia dla deweloperów ({shortcut})",
diff --git a/locales/pt/common.json b/locales/pt/common.json
index 2b39bb565..ace709678 100644
--- a/locales/pt/common.json
+++ b/locales/pt/common.json
@@ -7673,6 +7673,10 @@
"offline_send_saved": "Está offline. A mensagem está guardada em Rascunhos.",
"offline_send_unsaved": "Está offline. A mensagem fica aqui e é guardada em Rascunhos quando voltar a estar online."
},
+ "composer_panel": {
+ "show_panel": "Mostrar {name}",
+ "hide_panel": "Ocultar {name}"
+ },
"desktopDevTools": {
"section_title": "Resolução de problemas",
"label": "Ferramentas de programador ({shortcut})",
diff --git a/locales/ro/common.json b/locales/ro/common.json
index b8b274456..4c66b85fe 100644
--- a/locales/ro/common.json
+++ b/locales/ro/common.json
@@ -7673,6 +7673,10 @@
"offline_send_saved": "Sunteți offline. Mesajul este salvat în Ciorne.",
"offline_send_unsaved": "Sunteți offline. Mesajul rămâne aici și este salvat în Ciorne când sunteți din nou online."
},
+ "composer_panel": {
+ "show_panel": "Afișează {name}",
+ "hide_panel": "Ascunde {name}"
+ },
"desktopDevTools": {
"section_title": "Depanare",
"label": "Instrumente pentru dezvoltatori ({shortcut})",
diff --git a/locales/ru/common.json b/locales/ru/common.json
index 1056ad03b..a15eec34e 100644
--- a/locales/ru/common.json
+++ b/locales/ru/common.json
@@ -7673,6 +7673,10 @@
"offline_send_saved": "Вы не в сети. Сообщение сохранено в черновиках.",
"offline_send_unsaved": "Вы не в сети. Сообщение останется здесь и сохранится в черновиках, когда вы снова будете в сети."
},
+ "composer_panel": {
+ "show_panel": "Показать: {name}",
+ "hide_panel": "Скрыть: {name}"
+ },
"desktopDevTools": {
"section_title": "Устранение неполадок",
"label": "Инструменты разработчика ({shortcut})",
diff --git a/locales/sk/common.json b/locales/sk/common.json
index 16209de6f..6cd0b797b 100644
--- a/locales/sk/common.json
+++ b/locales/sk/common.json
@@ -7673,6 +7673,10 @@
"offline_send_saved": "Ste offline. Správa je uložená v Konceptoch.",
"offline_send_unsaved": "Ste offline. Správa tu zostane a uloží sa do Konceptov, keď budete znova online."
},
+ "composer_panel": {
+ "show_panel": "Zobraziť {name}",
+ "hide_panel": "Skryť {name}"
+ },
"desktopDevTools": {
"section_title": "Riešenie problémov",
"label": "Nástroje pre vývojárov ({shortcut})",
diff --git a/locales/th/common.json b/locales/th/common.json
index 659796f68..297c92761 100644
--- a/locales/th/common.json
+++ b/locales/th/common.json
@@ -7681,6 +7681,10 @@
"offline_send_saved": "คุณออฟไลน์อยู่ ข้อความถูกบันทึกไว้ในจดหมายร่างแล้ว",
"offline_send_unsaved": "คุณออฟไลน์อยู่ ข้อความจะอยู่ที่นี่และถูกบันทึกในจดหมายร่างเมื่อคุณกลับมาออนไลน์"
},
+ "composer_panel": {
+ "show_panel": "แสดง {name}",
+ "hide_panel": "ซ่อน {name}"
+ },
"desktopDevTools": {
"section_title": "การแก้ไขปัญหา",
"label": "เครื่องมือสำหรับนักพัฒนาซอฟต์แวร์ ({shortcut})",
diff --git a/locales/tr/common.json b/locales/tr/common.json
index a4e1787c5..d2e8b9057 100644
--- a/locales/tr/common.json
+++ b/locales/tr/common.json
@@ -7673,6 +7673,10 @@
"offline_send_saved": "Çevrimdışısınız. İleti Taslaklar'a kaydedildi.",
"offline_send_unsaved": "Çevrimdışısınız. İleti burada kalır ve yeniden çevrimiçi olduğunuzda Taslaklar'a kaydedilir."
},
+ "composer_panel": {
+ "show_panel": "{name} panelini göster",
+ "hide_panel": "{name} panelini gizle"
+ },
"desktopDevTools": {
"section_title": "Sorun giderme",
"label": "Geliştirici araçları ({shortcut})",
diff --git a/locales/uk/common.json b/locales/uk/common.json
index 129e93f22..f37d89731 100644
--- a/locales/uk/common.json
+++ b/locales/uk/common.json
@@ -7673,6 +7673,10 @@
"offline_send_saved": "Ви не в мережі. Повідомлення збережено в чернетках.",
"offline_send_unsaved": "Ви не в мережі. Повідомлення залишиться тут і збережеться в чернетках, коли ви знову будете в мережі."
},
+ "composer_panel": {
+ "show_panel": "Показати: {name}",
+ "hide_panel": "Сховати: {name}"
+ },
"desktopDevTools": {
"section_title": "Усунення несправностей",
"label": "Інструменти розробника ({shortcut})",
diff --git a/locales/vi/common.json b/locales/vi/common.json
index 0cd5746c6..b7bf55de9 100644
--- a/locales/vi/common.json
+++ b/locales/vi/common.json
@@ -7685,6 +7685,10 @@
"offline_send_saved": "Bạn đang ngoại tuyến. Thư đã được lưu trong Bản nháp.",
"offline_send_unsaved": "Bạn đang ngoại tuyến. Thư vẫn ở đây và sẽ được lưu vào Bản nháp khi bạn trực tuyến trở lại."
},
+ "composer_panel": {
+ "show_panel": "Hiện {name}",
+ "hide_panel": "Ẩn {name}"
+ },
"desktopDevTools": {
"section_title": "Khắc phục sự cố",
"label": "Công cụ cho nhà phát triển ({shortcut})",
diff --git a/locales/zh-TW/common.json b/locales/zh-TW/common.json
index 0f3ae2457..3ddca4003 100644
--- a/locales/zh-TW/common.json
+++ b/locales/zh-TW/common.json
@@ -7673,6 +7673,10 @@
"offline_send_saved": "你已離線。郵件已儲存在草稿中。",
"offline_send_unsaved": "你已離線。郵件會留在這裡,恢復連線後儲存到草稿。"
},
+ "composer_panel": {
+ "show_panel": "顯示{name}",
+ "hide_panel": "隱藏{name}"
+ },
"desktopDevTools": {
"section_title": "疑難排解",
"label": "開發人員工具({shortcut})",
diff --git a/locales/zh/common.json b/locales/zh/common.json
index e22f4805e..f386804ab 100644
--- a/locales/zh/common.json
+++ b/locales/zh/common.json
@@ -7673,6 +7673,10 @@
"offline_send_saved": "你已离线。邮件已保存在草稿中。",
"offline_send_unsaved": "你已离线。邮件会留在这里,恢复联网后保存到草稿。"
},
+ "composer_panel": {
+ "show_panel": "显示{name}",
+ "hide_panel": "隐藏{name}"
+ },
"desktopDevTools": {
"section_title": "故障排除",
"label": "开发者工具({shortcut})",
From baee0234d6a9f0ebf617f3178a5b7a5eb77c0e46 Mon Sep 17 00:00:00 2001
From: Linus Rath <139418639+rathlinus@users.noreply.github.com>
Date: Wed, 4 Nov 2026 17:31:30 +0100
Subject: [PATCH 06/12] fix: start the lines of a long plugin link at its icon
instead of centring them
---
lib/__tests__/plugin-ui-kit.test.tsx | 10 ++++++++++
lib/plugin-sandbox/ui-kit/components.tsx | 10 +++++++---
2 files changed, 17 insertions(+), 3 deletions(-)
diff --git a/lib/__tests__/plugin-ui-kit.test.tsx b/lib/__tests__/plugin-ui-kit.test.tsx
index 81057b238..cdff99ff2 100644
--- a/lib/__tests__/plugin-ui-kit.test.tsx
+++ b/lib/__tests__/plugin-ui-kit.test.tsx
@@ -22,6 +22,16 @@ const source = (file: string) => readFileSync(path.join(ROOT, file), 'utf8');
const classesOf = (el: Element) => el.getAttribute('class')!.split(/\s+/).filter((c) => c !== 'bk').sort();
describe('plugin UI kit components', () => {
+ it('starts a long LinkButton\'s lines at its icon, as a paragraph, not centred as a button would', () => {
+ // The AI assistant's examples in its panel ("Decline the invitation politely and suggest next month instead").
+ render(
Decline the invitation politely and suggest next month instead );
+ const link = screen.getByRole('button');
+ expect(link.className).toMatch(/(^|\s)text-start(\s|$)/);
+ // The icon stays beside the first line rather than the middle of the text.
+ expect(link.className).toMatch(/(^|\s)items-start(\s|$)/);
+ expect(link.querySelector('svg')!.getAttribute('class')).toContain('mt-');
+ });
+
it('renders the app\'s own Button and Input', () => {
render(<>
Cancel
diff --git a/lib/plugin-sandbox/ui-kit/components.tsx b/lib/plugin-sandbox/ui-kit/components.tsx
index 9eea05bc0..328777195 100644
--- a/lib/plugin-sandbox/ui-kit/components.tsx
+++ b/lib/plugin-sandbox/ui-kit/components.tsx
@@ -103,11 +103,15 @@ export const Button = React.forwardRef
(functi
);
});
-/** A text link styled like the app's inline links ("Add condition"). */
+/**
+ * A text link styled like the app's inline links ("Add condition"). A long one
+ * wraps like a paragraph: lines start at the icon's side (a button centres its
+ * text otherwise), with the icon beside the first line.
+ */
export function LinkButton({ icon, children, className, ...rest }: React.ButtonHTMLAttributes & { icon?: string }) {
return (
-
- {icon && }
+
+ {icon && }
{children}
);
From c63d04aa98aa04ffe19f2fb00cf1fb3494f0dde3 Mon Sep 17 00:00:00 2001
From: Linus Rath <139418639+rathlinus@users.noreply.github.com>
Date: Wed, 4 Nov 2026 17:37:33 +0100
Subject: [PATCH 07/12] fix: keep the folded folder column tidy with many
folders: one rule between sections, shared accounts as items, counters beside
the icons, and the drawer opening at the hovered folder
---
app/globals.css | 12 +
.../sidebar-folded-rail-scroll.test.tsx | 224 +++++++++++++++
components/layout/sidebar.tsx | 255 +++++++++++++++---
3 files changed, 451 insertions(+), 40 deletions(-)
create mode 100644 components/layout/__tests__/sidebar-folded-rail-scroll.test.tsx
diff --git a/app/globals.css b/app/globals.css
index 4e41210eb..8ffd7cd9c 100644
--- a/app/globals.css
+++ b/app/globals.css
@@ -313,6 +313,18 @@ optgroup {
background-color: var(--color-muted-foreground);
}
+/* The folded folder column (components/layout/sidebar.tsx) leaves its 48px
+ to the icons: a 4px scrollbar, in a gutter kept on both sides. */
+:root:not([data-native-scrollbars="on"]) [data-folder-rail]::-webkit-scrollbar {
+ width: 4px;
+}
+
+@supports not selector(::-webkit-scrollbar) {
+ :root:not([data-native-scrollbars="on"]) [data-folder-rail] {
+ scrollbar-width: thin;
+ }
+}
+
/* Enhanced Email Content Styling */
.email-content-wrapper {
diff --git a/components/layout/__tests__/sidebar-folded-rail-scroll.test.tsx b/components/layout/__tests__/sidebar-folded-rail-scroll.test.tsx
new file mode 100644
index 000000000..484b666a7
--- /dev/null
+++ b/components/layout/__tests__/sidebar-folded-rail-scroll.test.tsx
@@ -0,0 +1,224 @@
+import { act, render, screen, fireEvent, cleanup } from '@testing-library/react';
+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
+import type { Mailbox } from '@/lib/jmap/types';
+
+// The folded folder column (600 to 1024 px) of a mailbox with many folders,
+// scrolled: shared accounts left only their headings' rules behind, stacked
+// into a ladder of lines; the unread counter sat on the icon; one folder of
+// one's own was a letter in a box; and the drawer a hover opened kept the
+// column's scroll offset, so the hovered folder was somewhere else.
+
+vi.mock('@/components/plugins/plugin-slot', () => ({ PluginSlot: () => null }));
+vi.mock('@/components/tour/tour-provider', () => ({
+ useTour: () => ({ startTour: vi.fn(), resetTourCompletion: vi.fn(), activeTour: null, endTour: vi.fn(), registerStep: vi.fn() }),
+}));
+vi.mock('@/contexts/drag-drop-context', () => ({
+ useDragDropContext: () => ({ isDragging: false }),
+}));
+vi.mock('@/hooks/use-mailbox-drop', () => ({
+ useMailboxDrop: () => ({ dropHandlers: {}, isValidDropTarget: false, isInvalidDropTarget: false }),
+}));
+vi.mock('@/hooks/use-tag-drop', () => ({
+ useTagDrop: () => ({ dropHandlers: {}, isValidDropTarget: false }),
+}));
+vi.mock('../account-switcher', () => ({ AccountSwitcher: () => null }));
+
+const { Sidebar } = await import('../sidebar');
+const { useAuthStore } = await import('@/stores/auth-store');
+const { useSettingsStore } = await import('@/stores/settings-store');
+const { useUIStore } = await import('@/stores/ui-store');
+
+const box = (id: string, name: string, role: string | null, extra: Partial = {}) => ({
+ id, name, role, parentId: null, totalEmails: 0, unreadEmails: 0, myRights: { mayAddItems: true }, ...extra,
+}) as unknown as Mailbox;
+
+const shared = (id: string, name: string, role: string | null, extra: Partial = {}) =>
+ box(`g1:${id}`, name, role, { originalId: id, accountId: 'g1', accountName: 'Sam Ortega', isShared: true, ...extra });
+
+const own = [
+ box('inbox', 'Inbox', 'inbox', { totalEmails: 120, unreadEmails: 9 }),
+ box('clients', 'Clients', null, { parentId: 'inbox', unreadEmails: 132 }),
+ box('trash', 'Trash', 'trash', { unreadEmails: 3 }),
+ box('news', 'Newsletters', null, { unreadEmails: 150 }),
+];
+// A shared account without an inbox: two folders someone shared.
+const sharedNoInbox = [shared('team', 'Team', null, { unreadEmails: 2 }), shared('board', 'Board', null, { unreadEmails: 1 })];
+
+const nav = () => document.querySelector('[data-folder-nav]')!;
+const drawer = () => document.querySelector('[data-folder-drawer]');
+const row = (key: string) => document.querySelector(`[data-rail-key="${key}"]`)!;
+const railButtons = () => Array.from(nav().querySelectorAll('[data-testid="folder-row"] > button'));
+
+describe('the folded folder column with many folders', () => {
+ beforeEach(() => {
+ localStorage.clear();
+ useAuthStore.setState({ activeAccountId: 'login-a', client: { getAccountId: () => 'me', getCapabilities: () => ({}) } } as never);
+ useSettingsStore.setState({
+ hideAccountSwitcher: true, interfaceLayout: 'default', openOnHover: true, unreadCountStyle: 'count',
+ showSharedMailAccounts: true, hiddenSharedMailAccounts: {}, compactSharedMailboxes: false,
+ } as never);
+ useUIStore.setState({ sidebarCollapsed: true, compactSidebarExpanded: false } as never);
+ });
+ afterEach(() => {
+ cleanup();
+ vi.useRealTimers();
+ vi.restoreAllMocks();
+ useUIStore.setState({ sidebarCollapsed: false } as never);
+ });
+
+ it('draws one rule between sections, never two in a row', () => {
+ render( );
+ // Folders, Your folders, Shared (with its account inside), Tags.
+ const rules = nav().querySelectorAll('[data-rail-separator]');
+ expect(rules).toHaveLength(2 + 1);
+ // Walk the column in order: something to click between any two rules.
+ const order = Array.from(nav().querySelectorAll('[data-rail-separator], [data-testid="folder-row"]'));
+ order.forEach((el, i) => {
+ if (i === 0) return;
+ const both = el.hasAttribute('data-rail-separator') && order[i - 1].hasAttribute('data-rail-separator');
+ expect(both, `two rules in a row at ${i}`).toBe(false);
+ });
+ });
+
+ it('lists a shared account as one item, which opens the drawer with it unfolded when it has no inbox', () => {
+ render( );
+ const item = row('shared-account-g1');
+ expect(item.getAttribute('data-testid')).toBe('folder-row');
+ const button = item.querySelector('button')!;
+ expect(button.getAttribute('title')).toBe('name_unread');
+ expect(item.querySelector('[data-testid="folded-unread"]')?.textContent).toBe('3');
+ fireEvent.click(button);
+ expect(drawer()).not.toBeNull();
+ expect(screen.getByText('Team')).toBeTruthy();
+ });
+
+ it('opens a shared account\'s inbox from its item, and marks it while one of its folders is open', () => {
+ const onMailboxSelect = vi.fn();
+ const mailboxes = [...own, shared('in', 'Inbox', 'inbox', { unreadEmails: 4 }), ...sharedNoInbox];
+ const { rerender } = render( );
+ fireEvent.click(row('shared-account-g1').querySelector('button')!);
+ expect(onMailboxSelect).toHaveBeenCalledWith('g1:in');
+ rerender( );
+ expect(row('shared-account-g1').querySelector('[data-testid="folded-selected"]')).not.toBeNull();
+ });
+
+ it('puts the counter at the icon\'s corner, beside the glyph, and says 99+ for more', () => {
+ render( );
+ const badge = row('trash').querySelector('[data-testid="folded-unread"]')!;
+ expect(badge.textContent).toBe('3');
+ // On the 36px item, above the 16px icon's box, not inside it over the glyph.
+ expect(badge.parentElement!.tagName).toBe('BUTTON');
+ expect(badge.parentElement!.className).toContain('h-9');
+ expect(badge.className.split(/\s+/)).toEqual(expect.arrayContaining(['absolute', 'top-0', 'end-0', 'h-3']));
+ expect(badge.className).not.toContain('ring-2');
+ expect(row('news').querySelector('[data-testid="folded-unread"]')!.textContent).toBe('99+');
+ });
+
+ it('gives every item a tooltip with its name and count', () => {
+ render( );
+ for (const button of railButtons()) {
+ const title = button.getAttribute('title');
+ expect(title, button.outerHTML.slice(0, 120)).toBeTruthy();
+ expect(title).toBe(button.getAttribute('aria-label'));
+ }
+ // With unread mail the name carries the count.
+ expect(row('inbox').querySelector('button')!.getAttribute('title')).toBe('name_unread');
+ });
+
+ it('draws one folder of one\'s own as a plain folder, several with their first letter inside the folder', () => {
+ render( );
+ expect(row('news').querySelector('[data-testid="folder-initial"]')).toBeNull();
+ expect(row('news').querySelector('svg')).not.toBeNull();
+ cleanup();
+ render( );
+ const letter = row('receipts').querySelector('[data-testid="folder-initial"]')!;
+ expect(letter.textContent).toBe('R');
+ // Inside the folder glyph, an icon like the others, not a box of its own.
+ expect(letter.closest('svg')?.querySelector('path')).not.toBeNull();
+ expect(letter.closest('svg')!.getAttribute('class')).toContain('w-4');
+ });
+
+ it('marks the open folder with a bar at the edge and a filled item', () => {
+ render( );
+ // Over the filled item, not under it.
+ expect(row('trash').querySelector('[data-testid="folded-selected"]')!.className).toContain('z-10');
+ expect(row('trash').querySelector('button')!.className).toContain('bg-accent');
+ expect(row('inbox').querySelector('[data-testid="folded-selected"]')).toBeNull();
+ expect(row('inbox').querySelector('button')!.className).not.toContain('bg-accent');
+ });
+
+ it('scrolls on its own, never sideways, with a thin scrollbar', () => {
+ render( );
+ expect(nav().hasAttribute('data-folder-rail')).toBe(true);
+ expect(nav().className.split(/\s+/)).toEqual(expect.arrayContaining(['overflow-y-auto', 'overflow-x-hidden', 'min-h-0']));
+ });
+
+ it('moves through the items with the arrows, Home and End', () => {
+ render( );
+ const buttons = railButtons().filter((b) => !(b as HTMLButtonElement).disabled);
+ buttons[0].focus();
+ fireEvent.keyDown(buttons[0], { key: 'ArrowDown' });
+ expect(document.activeElement).toBe(buttons[1]);
+ fireEvent.keyDown(buttons[1], { key: 'ArrowUp' });
+ expect(document.activeElement).toBe(buttons[0]);
+ fireEvent.keyDown(buttons[0], { key: 'End' });
+ expect(document.activeElement).toBe(buttons[buttons.length - 1]);
+ fireEvent.keyDown(buttons[buttons.length - 1], { key: 'Home' });
+ expect(document.activeElement).toBe(buttons[0]);
+ });
+
+ describe('the drawer opened from the scrolled column', () => {
+ // jsdom has no layout: the list's items sit at fixed places in the
+ // content, further down in the longer tree of the drawer.
+ let scrollTop = 0;
+ const NAV_TOP = 100;
+ const place = (el: Element) => {
+ const key = (el as HTMLElement).dataset?.railKey;
+ if (key !== 'news') return null;
+ return drawer() ? 900 : 500;
+ };
+ beforeEach(() => {
+ scrollTop = 0;
+ vi.spyOn(Element.prototype, 'getBoundingClientRect').mockImplementation(function (this: Element) {
+ // The list shows 600px; anything else is somewhere inside it.
+ const isNav = this.hasAttribute('data-folder-nav');
+ const at = place(this);
+ const top = isNav ? NAV_TOP : at === null ? NAV_TOP + 10 : NAV_TOP + at - scrollTop;
+ const height = isNav ? 600 : 36;
+ return { top, bottom: top + height, left: 0, right: 48, width: 48, height, x: 0, y: top, toJSON: () => ({}) } as DOMRect;
+ });
+ });
+ const trackScroll = () => Object.defineProperty(nav(), 'scrollTop', {
+ configurable: true,
+ get: () => scrollTop,
+ set: (v: number) => { scrollTop = v; },
+ });
+
+ it('puts the hovered item back under the pointer, and the column back where it was', () => {
+ vi.useFakeTimers();
+ const { container } = render( );
+ trackScroll();
+ scrollTop = 200;
+ const news = row('news');
+ document.elementFromPoint = vi.fn(() => news.querySelector('button'));
+ // At 400 on screen in the column: 100 + 500 - 200.
+ fireEvent.mouseEnter(container.firstElementChild!, { clientX: 20, clientY: 410 });
+ act(() => { vi.advanceTimersByTime(400); });
+ expect(drawer()).not.toBeNull();
+ // In the drawer it is 900 down the list: scrolled so it is at 400 again.
+ expect(scrollTop).toBe(600);
+ fireEvent.mouseLeave(container.firstElementChild!);
+ expect(drawer()).toBeNull();
+ expect(scrollTop).toBe(200);
+ });
+
+ it('starts at the top when All folders opens it', () => {
+ render( );
+ trackScroll();
+ scrollTop = 200;
+ fireEvent.click(screen.getByTestId('folded-all-folders'));
+ expect(drawer()).not.toBeNull();
+ expect(scrollTop).toBe(0);
+ });
+ });
+});
diff --git a/components/layout/sidebar.tsx b/components/layout/sidebar.tsx
index dbe7db61f..2708f4f24 100644
--- a/components/layout/sidebar.tsx
+++ b/components/layout/sidebar.tsx
@@ -1,7 +1,7 @@
"use client";
import { hoverOpens } from "@/lib/open-on-hover";
-import { memo, useState, useEffect, useMemo, useCallback, useRef, useId, Fragment, ReactNode } from "react";
+import { memo, useState, useEffect, useLayoutEffect, useMemo, useCallback, useRef, useId, Fragment, ReactNode } from "react";
import { useTranslations } from "next-intl";
import { useRouter } from "@/i18n/navigation";
import { PluginSlot } from "@/components/plugins/plugin-slot";
@@ -396,6 +396,9 @@ interface SidebarRowProps {
testName?: string;
testMailboxId?: string;
testShared?: boolean;
+ /** Names the row the same folded and unfolded, so the drawer opened by a
+ * hover can put the hovered item back under the pointer. */
+ railKey?: string;
}
function SidebarRow({
@@ -420,6 +423,7 @@ function SidebarRow({
testName,
testMailboxId,
testShared,
+ railKey,
}: SidebarRowProps) {
const t = useTranslations('sidebar');
const tShell = useTranslations('shell');
@@ -436,6 +440,8 @@ function SidebarRow({
unread, total, role: testRole, mode: countMode, showTotalGlobally: showFolderTotalCount, mountainView,
}).unread;
const accessibleName = unreadForName > 0 ? tShell('name_unread', { name: label, count: unreadForName }) : undefined;
+ // The default layout's folded column: one grid of square items.
+ const railItem = isCollapsed && !mountainView;
const [labelRef, shortenedLabel] = useShortenedText(labelCandidates ?? [label]);
// Touch has no right-click: a long-press opens the same menu (R7), and a
// ⋮ shows it too.
@@ -473,21 +479,31 @@ function SidebarRow({
data-shared={testShared ? 'true' : undefined}
data-selected={isSelected ? 'true' : undefined}
data-has-unread={(unread ?? 0) > 0 && testRole !== 'drafts' ? '' : undefined}
- style={{ paddingBlock: 'var(--density-sidebar-py)' }}
+ data-rail-key={railKey ?? testMailboxId ?? undefined}
+ style={railItem ? undefined : { paddingBlock: 'var(--density-sidebar-py)' }}
className={cn(
"group w-full flex items-center tap:min-h-[44px] text-sm transition-colors duration-150",
- isCollapsed ? "justify-center px-1" : "pe-2",
+ // Folded, every item is the same square on one grid, as in Outlook's
+ // folded pane: the button carries the hover and the selection, and a
+ // bar at the column's edge marks the open one.
+ // Mountain View's 72px rail keeps its own pill rows (globals.css).
+ railItem ? "relative justify-center py-px" : isCollapsed ? "justify-center px-1" : "pe-2",
openFromRow && "cursor-pointer select-none",
- isVirtual
- ? "text-muted-foreground"
- : isSelected
- ? "bg-accent text-accent-foreground font-semibold border-s-2 border-primary"
- : "hover:bg-muted/50 text-foreground border-s-2 border-transparent",
+ railItem
+ ? (isVirtual ? "text-muted-foreground" : isSelected ? "text-accent-foreground font-semibold" : "text-foreground")
+ : isVirtual
+ ? "text-muted-foreground"
+ : isSelected
+ ? "bg-accent text-accent-foreground font-semibold border-s-2 border-primary"
+ : "hover:bg-muted/50 text-foreground border-s-2 border-transparent",
// Only a folder that takes the drop lights up. Elsewhere the pointer
// says no (dropEffect none), as in a native mail client.
isValidDropTarget && "bg-primary/20 ring-2 ring-primary ring-inset"
)}
>
+ {railItem && isSelected && (
+
+ )}
{!isCollapsed && (
{icon}
- {/* Folded to icons, the count rides on the icon (p2-9); the name says it already. */}
- {isCollapsed && unreadForName > 0 && (
- unreadCountStyle === 'dot' ? (
-
- ) : (
-
- {unreadForName > 99 ? '99+' : unreadForName}
-
- )
- )}
+ {/* Folded to icons, a small counter at the icon's top corner (p2-9); the name says it already. */}
+ {isCollapsed && unreadForName > 0 && (
+ unreadCountStyle === 'dot' ? (
+
+ ) : (
+
+ {unreadForName > 99 ? '99+' : unreadForName}
+
+ )
+ )}
{!isCollapsed && (
<>
- {initial}
-
+ {/* Lucide's folder outline. */}
+
+
+ {initial}
+
+
);
}
+/** Whether the folder `id` is this node or below it. */
+const subtreeHas = (node: MailboxNode, id: string): boolean =>
+ node.id === id || node.children.some((child) => subtreeHas(child, id));
+/** Unread mail in the folders below a node (a shared account counts nothing itself). */
+const subtreeUnread = (node: MailboxNode): number =>
+ node.children.reduce((sum, child) => sum + (child.unreadEmails ?? 0) + subtreeUnread(child), 0);
+
/** A folder the server gave a role (inbox, sent, trash...), as opposed to one the user made. */
const isSystemFolder = (node: MailboxNode) => !!node.role;
/** Key of the single-account "Your folders" section in the collapsed set. */
@@ -634,6 +690,7 @@ function SidebarSectionHeader({
status,
onAdd,
addTitle,
+ railKey,
}: {
label: string;
expanded: boolean;
@@ -650,9 +707,14 @@ function SidebarSectionHeader({
onContextMenu?: (event: React.MouseEvent) => void;
/** A short note after the label, e.g. how many accounts have loaded. */
status?: ReactNode;
+ /** The folded column's item for the same thing (see SidebarRow). */
+ railKey?: string;
}) {
if (isCollapsed) {
- return first ? null :
;
+ // One thin rule between sections. A sub-section (a shared account, the
+ // folders inside a Pro account group) draws none: under a section's own
+ // rule they stacked into a ladder of lines.
+ return first || sub ? null :
;
}
const paddingY = sub ? "pt-2" : first ? "pt-3" : "pt-5";
@@ -670,6 +732,7 @@ function SidebarSectionHeader({
return (
React.ReactNode;
+ /** Folded: several folders of one's own are listed, so each carries its
+ * first letter. One alone is a plain folder. */
+ initials?: boolean;
}) {
const tNotifications = useTranslations('notifications');
const tListExtra = useTranslations('mail_list_extra');
const tSidebar = useTranslations('sidebar');
const hasChildren = node.children.length > 0;
const isExpanded = expandedFolders.has(node.id);
- const Icon = sharedAccountName ? User : getIconForMailbox(node.role, hasChildren, isExpanded, node.id);
+ // Folded, no subfolders show, so no folder is drawn open.
+ const Icon = sharedAccountName ? User : getIconForMailbox(node.role, hasChildren, isExpanded && !isCollapsed, node.id);
const isVirtualNode = node.id.startsWith('shared-');
const isSelected = selectedMailbox === node.id;
const label = sharedAccountName ?? localizeMailboxName(node.role, node.name, (k) => tSidebar(`mailboxes.${k}`));
// Folded to icons, eight folders of one's own were eight identical folder
- // icons (p2-9): each shows its first letter instead.
- const letterIcon = isCollapsed && !node.role && !sharedAccountName && !isVirtualNode;
+ // icons (p2-9): each carries its first letter inside the folder glyph.
+ const letterIcon = isCollapsed && initials && !node.role && !sharedAccountName && !isVirtualNode;
// Only for the active login's folders: its client tells a missing
// accountId (own mailbox) apart.
const muted = useMutedMailbox(isVirtualNode || dragAccountId || pickOnly ? null : node);
@@ -969,6 +1037,7 @@ function TagItem({
isCollapsed={isCollapsed}
dropHandlers={globalDragging ? (dropHandlers as Record) : undefined}
isValidDropTarget={isValidDropTarget}
+ railKey={`tag:${node.id}`}
/>
{hasChildren && isExpanded && !isCollapsed && node.children.map((child) => (
@@ -1299,9 +1368,26 @@ function SidebarImpl({
}, [railOpen]);
// The pointer resting on the folders floats the tree out; on the header
// (expand, compose) it doesn't, so the expand button can still be clicked.
- const armRailHover = useCallback((target: EventTarget | null) => {
+ const navRef = useRef(null);
+ // The item the pointer rests on in the folded column, and where on screen.
+ const hoveredRailItem = useRef<{ key: string; top: number } | null>(null);
+ const lastPointer = useRef<{ x: number; y: number; target: EventTarget | null }>({ x: 0, y: 0, target: null });
+ // Read when the tree floats out, not when the pointer arrived: the column
+ // may have been scrolled under a resting pointer in between.
+ const noteHoveredRailItem = useCallback(() => {
+ const { x, y, target } = lastPointer.current;
+ const under = typeof document.elementFromPoint === 'function' ? document.elementFromPoint(x, y) : null;
+ const from = under ?? (target instanceof Element ? target : null);
+ const item = from?.closest('[data-rail-key]');
+ hoveredRailItem.current = item?.dataset.railKey && navRef.current?.contains(item)
+ ? { key: item.dataset.railKey, top: item.getBoundingClientRect().top }
+ : null;
+ }, []);
+ const armRailHover = useCallback((e: React.MouseEvent) => {
if (!hoverOpens()) return;
- if (mvShell) { setRailHovered(true); return; }
+ const target = e.target;
+ lastPointer.current = { x: e.clientX, y: e.clientY, target };
+ if (mvShell) { noteHoveredRailItem(); setRailHovered(true); return; }
if (target instanceof Element && target.closest('[data-sidebar-head]')) {
if (railHoverTimer.current) clearTimeout(railHoverTimer.current);
railHoverTimer.current = null;
@@ -1310,9 +1396,59 @@ function SidebarImpl({
if (railHoverTimer.current) return;
railHoverTimer.current = setTimeout(() => {
railHoverTimer.current = null;
+ noteHoveredRailItem();
setRailHovered(true);
}, RAIL_HOVER_DELAY_MS);
- }, [mvShell]);
+ }, [mvShell, noteHoveredRailItem]);
+ // The folded column and the tree floated out of it share one scrolling
+ // list. Scrolled down the column, the tree opened at that same offset, which
+ // in the longer tree was somewhere else: a hover now puts the hovered item
+ // back under the pointer, All folders starts at the top (and the focus
+ // brings the open folder into view), and folding back returns the column
+ // to where it was.
+ const railScrollTop = useRef(null);
+ useLayoutEffect(() => {
+ const nav = navRef.current;
+ if (!nav) return;
+ if (hoverExpanded) {
+ if (railScrollTop.current !== null) return;
+ railScrollTop.current = nav.scrollTop;
+ const hovered = railOpen ? null : hoveredRailItem.current;
+ const item = hovered
+ ? Array.from(nav.querySelectorAll('[data-rail-key]')).find((el) => el.dataset.railKey === hovered.key)
+ : null;
+ nav.scrollTop = item && hovered ? nav.scrollTop + item.getBoundingClientRect().top - hovered.top : 0;
+ return;
+ }
+ if (railScrollTop.current === null) return;
+ const railTop = railScrollTop.current;
+ railScrollTop.current = null;
+ // Unfolded meanwhile: the full list keeps its own place.
+ if (!isCollapsed) return;
+ nav.scrollTop = railTop;
+ // A folder picked in the tree is shown in the column too.
+ const current = nav.querySelector('[aria-current="page"]');
+ if (!current) return;
+ const view = nav.getBoundingClientRect();
+ const box = current.getBoundingClientRect();
+ if (box.top < view.top) nav.scrollTop += box.top - view.top;
+ else if (box.bottom > view.bottom) nav.scrollTop += box.bottom - view.bottom;
+ }, [hoverExpanded, railOpen, isCollapsed]);
+ // Folded, the arrows, Home and End go from item to item, Enter opens.
+ const moveInRail = useCallback((e: React.KeyboardEvent) => {
+ if (e.key !== 'ArrowDown' && e.key !== 'ArrowUp' && e.key !== 'Home' && e.key !== 'End') return;
+ if (e.altKey || e.ctrlKey || e.metaKey || e.shiftKey) return;
+ const items = Array.from(e.currentTarget.querySelectorAll('[data-testid="folder-row"] > button:not(:disabled)'));
+ if (items.length === 0) return;
+ const at = items.indexOf(document.activeElement as HTMLElement);
+ const next = e.key === 'Home' ? 0
+ : e.key === 'End' ? items.length - 1
+ : at < 0 ? 0
+ : e.key === 'ArrowDown' ? Math.min(at + 1, items.length - 1) : Math.max(at - 1, 0);
+ e.preventDefault();
+ e.stopPropagation();
+ items[next].focus();
+ }, []);
const { primaryIdentity: _primaryIdentity, activeAccountId } = useAuthStore(useShallow((state) => ({ primaryIdentity: state.primaryIdentity, activeAccountId: state.activeAccountId })));
const [expandedFolders, setExpandedFolders] = useState>(new Set());
const [expandedTags, setExpandedTags] = useState>(new Set());
@@ -1681,6 +1817,7 @@ function SidebarImpl({
colorful={colorfulSidebarIcons}
onContextMenu={active ? handleMailboxContextMenu : undefined}
dragAccountId={dragAccountId}
+ initials={tree.length > 1}
/>
))}
@@ -1770,6 +1907,31 @@ function SidebarImpl({
);
}
+ if (isCollapsed) {
+ // Folded, a shared account is one item: its inbox opens, or
+ // without one the drawer with the account unfolded. It was
+ // left out, and only its heading's rule stayed behind.
+ const inbox = account.children.find((child) => child.role === 'inbox');
+ const selectedHere = !!selected && subtreeHas(account, selected);
+ return (
+ }
+ label={account.name}
+ isSelected={selectedHere}
+ unread={subtreeUnread(account)}
+ onClick={() => {
+ if (inbox) { onSelect?.(inbox.id); return; }
+ if (!expanded) onToggle();
+ if (!accountExpanded) toggleSharedAccount(account.id);
+ setRailOpen(true);
+ }}
+ isCollapsed
+ testShared
+ railKey={account.id}
+ />
+ );
+ }
return (
}
testId="section-shared-account"
+ railKey={account.id}
onContextMenu={active && menuAccountId
? (e) => handleSharedAccountContextMenu(e, menuAccountId)
: undefined}
@@ -2067,8 +2230,8 @@ function SidebarImpl({
armRailHover(e.target) : undefined}
- onMouseMove={sidebarCollapsed && !isDrawer && !mvShell && !railHovered ? (e) => armRailHover(e.target) : undefined}
+ onMouseEnter={sidebarCollapsed && !isDrawer ? armRailHover : undefined}
+ onMouseMove={sidebarCollapsed && !isDrawer && !mvShell && !railHovered ? armRailHover : undefined}
onMouseLeave={sidebarCollapsed && !isDrawer ? () => {
if (railHoverTimer.current) clearTimeout(railHoverTimer.current);
railHoverTimer.current = null;
@@ -2211,7 +2374,19 @@ function SidebarImpl({
{!isCollapsed &&
}
{/* Mailbox List */}
-
+
{unifiedSectionShown && (
Date: Wed, 4 Nov 2026 17:38:56 +0100
Subject: [PATCH 08/12] feat: attach recently used files from the Attach menu
in the desktop app
---
.../__tests__/composer-attach-recent.test.tsx | 401 ++++++++++++++++++
components/email/email-composer.tsx | 33 +-
.../email/recent-files-menu-section.tsx | 88 ++++
desktop-policies/Bulwark.admx | 6 +
desktop-policies/de-DE/Bulwark.adml | 2 +
desktop-policies/en-US/Bulwark.adml | 2 +
.../org.bulwarkmail.desktop.mobileconfig | 2 +
desktop-policies/policies.json | 1 +
lib/desktop/__tests__/policy-schema.test.ts | 9 +-
lib/desktop/__tests__/recent-files.test.ts | 87 ++++
lib/desktop/policy-schema.ts | 16 +
lib/desktop/recent-files.ts | 80 ++++
lib/desktop/types.ts | 35 ++
locales/ar/common.json | 8 +
locales/ca/common.json | 8 +
locales/cs/common.json | 8 +
locales/da/common.json | 8 +
locales/de/common.json | 8 +
locales/en/common.json | 8 +
locales/es/common.json | 8 +
locales/et/common.json | 8 +
locales/fa/common.json | 8 +
locales/fr/common.json | 8 +
locales/he/common.json | 8 +
locales/hu/common.json | 8 +
locales/it/common.json | 8 +
locales/ja/common.json | 8 +
locales/ko/common.json | 8 +
locales/lv/common.json | 8 +
locales/mn/common.json | 8 +
locales/nb/common.json | 8 +
locales/nl/common.json | 8 +
locales/pl/common.json | 8 +
locales/pt/common.json | 8 +
locales/ro/common.json | 8 +
locales/ru/common.json | 8 +
locales/sk/common.json | 8 +
locales/th/common.json | 8 +
locales/tr/common.json | 8 +
locales/uk/common.json | 8 +
locales/vi/common.json | 8 +
locales/zh-TW/common.json | 8 +
locales/zh/common.json | 8 +
43 files changed, 997 insertions(+), 5 deletions(-)
create mode 100644 components/email/__tests__/composer-attach-recent.test.tsx
create mode 100644 components/email/recent-files-menu-section.tsx
create mode 100644 lib/desktop/__tests__/recent-files.test.ts
create mode 100644 lib/desktop/recent-files.ts
diff --git a/components/email/__tests__/composer-attach-recent.test.tsx b/components/email/__tests__/composer-attach-recent.test.tsx
new file mode 100644
index 000000000..0c5d37c9a
--- /dev/null
+++ b/components/email/__tests__/composer-attach-recent.test.tsx
@@ -0,0 +1,401 @@
+import { render, screen, fireEvent, act, waitFor, within } from '@testing-library/react';
+import { describe, it, expect, vi, afterEach } from 'vitest';
+import React from 'react';
+import { EmailComposer } from '../email-composer';
+import { useAuthStore } from '@/stores/auth-store';
+import { DEFAULT_POLICY_SNAPSHOT, type PolicySnapshot } from '@/lib/desktop/policy-schema';
+import type { BulwarkDesktopBridge, DesktopRecentFile } from '@/lib/desktop/types';
+
+// Recent files in the Attach menu, in the desktop app: the shell's side is
+// repos/desktop's test/recent-files.spec.ts; here the bridge is a stub.
+
+const hoisted = vi.hoisted(() => ({
+ picked: [] as unknown[],
+ beforeAttachmentUpload: vi.fn(async (_info: { name: string }) => true),
+ toastError: vi.fn(),
+}));
+
+vi.mock('@/components/files/file-picker-dialog', () => ({
+ FilePickerDialog: ({ onPick }: { onPick: (nodes: unknown[]) => void }) =>
+ React.createElement(
+ 'button',
+ { type: 'button', 'data-testid': 'fake-file-picker', onClick: () => onPick(hoisted.picked) },
+ 'pick',
+ ),
+}));
+
+// ─── Heavy component mocks (mirrors composer-plugin-attachment-source.test.tsx) ─
+
+vi.mock('@/components/email/rich-text-editor', () => ({
+ RichTextEditor: () => React.createElement('div', { 'data-testid': 'rich-text-editor' }),
+}));
+vi.mock('@/components/plugins/plugin-slot', () => ({ PluginSlot: () => null }));
+
+vi.mock('@/components/identity/sub-address-helper', () => ({ SubAddressHelper: () => null }));
+vi.mock('@/components/templates/template-picker', () => ({ TemplatePicker: () => null }));
+vi.mock('@/components/templates/template-form', () => ({ TemplateForm: () => null }));
+vi.mock('@/components/files/file-preview-modal', () => ({ FilePreviewModal: () => null }));
+vi.mock('@/hooks/use-focus-trap', () => ({
+ useFocusTrap: () => ({ current: null }),
+}));
+vi.mock('@/hooks/use-pro-multi-account-identities', () => ({
+ useProMultiAccountIdentities: () => ({ enabled: false, groups: [], allIdentities: [] }),
+ stripCrossAccountIdentityPrefix: (id: string) => ({ localAccountId: null, rawId: id }),
+}));
+
+// ─── Store mocks ──────────────────────────────────────────────────────────────
+
+vi.mock('@/stores/auth-store', () => {
+ const state = {
+ client: null,
+ identities: [],
+ primaryIdentity: null,
+ isAuthenticated: false,
+ isDemoMode: false,
+ activeAccountId: null,
+ connectionLost: false,
+ getClientForAccount: () => undefined,
+ getAllConnectedClients: () => new Map(),
+ syncIdentities: () => {},
+ refreshIdentities: async () => {},
+ };
+ const hook = (sel?: (s: typeof state) => unknown) =>
+ typeof sel === 'function' ? sel(state) : state;
+ hook.getState = () => state;
+ hook.setState = (p: Partial) => Object.assign(state, p);
+ return { useAuthStore: hook };
+});
+
+vi.mock('@/stores/identity-store', () => {
+ const state = {
+ identities: [{ id: 'id-me', email: 'me@example.com', name: 'Me' }],
+ defaultIdentityId: 'id-me',
+ };
+ const hook = (sel?: (s: typeof state) => unknown) =>
+ typeof sel === 'function' ? sel(state) : state;
+ hook.getState = () => state;
+ hook.setState = (p: Partial) => Object.assign(state, p);
+ return { useIdentityStore: hook };
+});
+
+vi.mock('@/stores/account-store', () => {
+ const state = { accounts: [], getAccountById: () => undefined };
+ const hook = (sel?: (s: typeof state) => unknown) =>
+ typeof sel === 'function' ? sel(state) : state;
+ hook.getState = () => state;
+ hook.setState = (p: Partial) => Object.assign(state, p);
+ return { useAccountStore: hook };
+});
+
+vi.mock('@/stores/email-store', () => {
+ const state = {
+ draftSaveEnabled: false,
+ sendRawEmail: async () => ({ sent: true }),
+ };
+ const hook = (sel?: (s: typeof state) => unknown) =>
+ typeof sel === 'function' ? sel(state) : state;
+ hook.getState = () => state;
+ hook.setState = (p: Partial) => Object.assign(state, p);
+ return { useEmailStore: hook };
+});
+
+vi.mock('@/stores/settings-store', () => {
+ const state = {
+ timeFormat: '24h',
+ plainTextMode: false,
+ subAddressDelimiter: '+',
+ autoSelectReplyIdentity: true,
+ attachmentReminderEnabled: false,
+ attachmentReminderKeywords: [],
+ emptySubjectWarningEnabled: true,
+ sendDelaySeconds: 0,
+ signaturePosition: 'above_quote',
+ signatureSeparatorEnabled: false,
+ requestReadReceiptDefault: false,
+ addTrustedSender: () => {},
+ trustedSendersAddressBook: null,
+ updateSetting: () => {},
+ };
+ const hook = (sel?: (s: typeof state) => unknown) =>
+ typeof sel === 'function' ? sel(state) : state;
+ hook.getState = () => state;
+ hook.setState = (p: Partial) => Object.assign(state, p);
+ return { useSettingsStore: hook };
+});
+
+vi.mock('@/stores/contact-store', () => {
+ const state = {
+ contacts: [],
+ getAutocomplete: async () => [],
+ addToTrustedSendersBook: async () => {},
+ };
+ const hook = (sel?: (s: typeof state) => unknown) =>
+ typeof sel === 'function' ? sel(state) : state;
+ hook.getState = () => state;
+ hook.setState = (p: Partial) => Object.assign(state, p);
+ return { useContactStore: hook };
+});
+
+vi.mock('@/stores/template-store', () => {
+ const state = { templates: [], addTemplate: async () => {} };
+ const hook = (sel?: (s: typeof state) => unknown) =>
+ typeof sel === 'function' ? sel(state) : state;
+ hook.getState = () => state;
+ hook.setState = (p: Partial) => Object.assign(state, p);
+ return { useTemplateStore: hook };
+});
+
+// ─── Misc dependency mocks ────────────────────────────────────────────────────
+
+vi.mock('@/stores/toast-store', () => ({
+ toast: { info: () => {}, error: hoisted.toastError, success: () => {} },
+}));
+
+vi.mock('@/lib/plugin-hooks', () => ({
+ identityHooks: {
+ onSignatureRender: { size: 0, transform: async (value: unknown) => value },
+ onIdentitySelect: { size: 0, emit: async () => {} },
+ },
+ templateHooks: {
+ onTemplateRender: { size: 0, transform: async (value: unknown) => value },
+ onTemplateApply: { size: 0, emit: async () => {} },
+ },
+ emailHooks: {
+ onComposerOpen: { call: async () => [] },
+ onRecipientChange: { call: async () => [] },
+ getRecipientSuggestions: { call: async () => [] },
+ onRecipientChipsChange: { transform: async (chips: unknown) => chips },
+ onDraftChange: { emit: () => {} },
+ onBeforeDraftAutoSave: { transform: async (draft: unknown) => draft },
+ onBeforeEmailSend: { intercept: async () => true, interceptOutcome: async () => 'allowed' },
+ onBeforeAttachmentUpload: { intercept: hoisted.beforeAttachmentUpload },
+ onComposeSend: { takeOver: async () => 'default' },
+ onTransformOutgoingEmail: { transform: async (email: unknown) => email },
+ },
+ contactHooks: {
+ search: { call: async () => [] },
+ onProvideRecipientSuggestions: { transform: async (initial: unknown) => initial },
+ },
+}));
+
+vi.mock('@/lib/email-sanitization', () => ({
+ sanitizeSignatureHtml: (v: string) => v,
+ sanitizeEmailHtml: (v: string) => v,
+ parseHtmlSafely: (html: string) => new DOMParser().parseFromString(html, 'text/html'),
+}));
+
+vi.mock('@/lib/email-threading', () => ({
+ computeReplyThreadingHeaders: () => ({ inReplyTo: [], references: [] }),
+}));
+vi.mock('@/lib/signature-utils', () => ({
+ appendPlainTextSignature: (body: string) => body,
+ getPlainTextSignature: () => '',
+ plainTextBodyHasSignature: () => false,
+ plainTextBodyWithoutSignature: (body: string) => body,
+}));
+vi.mock('@/lib/sub-addressing', () => ({ generateSubAddress: () => '' }));
+vi.mock('@/lib/debug', () => ({ debug: { log: () => {}, warn: () => {}, error: () => {} } }));
+vi.mock('@/components/email/quoted-html', () => ({
+ buildQuotedHtmlBlock: () => '',
+ serializeEditorContent: () => '',
+}));
+vi.mock('@/lib/template-utils', () => ({ substitutePlaceholders: (s: string) => s }));
+
+// ─── Tests ────────────────────────────────────────────────────────────────────
+
+const NOW = Date.now();
+const RECENT: DesktopRecentFile[] = [
+ { id: 'id-report', name: 'Quarterly report.docx', folder: '\\\\files\\team\\Reports', path: '\\\\files\\team\\Reports\\Quarterly report.docx', usedAt: NOW - 5 * 60_000, icon: 'data:image/png;base64,iVBORw0KGgo=' },
+ { id: 'id-budget', name: 'Budget 2027.xlsx', folder: 'C:\\Users\\me\\Documents', path: 'C:\\Users\\me\\Documents\\Budget 2027.xlsx', usedAt: NOW - 3 * 60 * 60_000 },
+];
+
+interface DesktopOptions {
+ files?: DesktopRecentFile[];
+ policyOff?: boolean;
+ /** The shell's native menus: the Attach menu must stay HTML all the same. */
+ popup?: ReturnType;
+}
+
+function desktop({ files = RECENT, policyOff = false, popup }: DesktopOptions = {}) {
+ const snapshot: PolicySnapshot = {
+ ...DEFAULT_POLICY_SNAPSHOT,
+ ...(policyOff ? { RecentFilesInAttach: { value: false, source: 'forced-machine', locked: true } } : {}),
+ } as PolicySnapshot;
+ const list = vi.fn(async () => ({ ok: true as const, files }));
+ const attach = vi.fn(async (id: string) => {
+ const file = files.find((f) => f.id === id);
+ return file
+ ? { ok: true as const, file: { name: file.name, data: new TextEncoder().encode(`bytes of ${file.name}`) } }
+ : { ok: false as const, reason: 'unknown' as const };
+ });
+ window.bulwarkDesktop = {
+ version: 1,
+ platform: 'win32',
+ policy: { get: () => snapshot, onChange: () => () => {} },
+ recentFiles: { list, attach },
+ ...(popup ? { menu: { popup, setState: () => {}, onCommand: () => () => {} } } : {}),
+ } as unknown as BulwarkDesktopBridge;
+ return { list, attach };
+}
+
+function client(overrides: Record = {}) {
+ return {
+ createDraft: vi.fn().mockResolvedValue('draft-1'),
+ getEmail: vi.fn(),
+ hasDelayedSend: () => false,
+ getMaxDelayedSend: () => 0,
+ // No Files, no plugins: in a browser, Attach is a plain button.
+ supportsFiles: () => false,
+ getMaxSizeAttachmentsPerEmail: () => 0,
+ getMaxSizeUpload: () => 0,
+ uploadBlob: vi.fn(() => new Promise(() => {})),
+ ...overrides,
+ };
+}
+
+const rows = () => screen.queryAllByTestId('composer-recent-file');
+
+async function openMenu() {
+ fireEvent.click(screen.getByTestId('composer-attach-menu'));
+ await act(async () => {});
+}
+
+describe('recent files in the Attach menu', () => {
+ afterEach(() => {
+ window.bulwarkDesktop = undefined;
+ useAuthStore.setState({ client: null });
+ vi.clearAllMocks();
+ hoisted.beforeAttachmentUpload.mockImplementation(async () => true);
+ });
+
+ it('in a browser the paperclip is the plain button it was', () => {
+ useAuthStore.setState({ client: client() as never });
+ render( );
+ expect(screen.queryByTestId('composer-attach-menu')).toBeNull();
+ expect(screen.getByRole('button', { name: 'attach' })).toBeInTheDocument();
+ });
+
+ it('in the desktop app the paperclip opens a menu: recent files first, then the file dialog', async () => {
+ const { list } = desktop();
+ useAuthStore.setState({ client: client() as never });
+ render( );
+ expect(list).not.toHaveBeenCalled();
+ await openMenu();
+ expect(list).toHaveBeenCalledTimes(1);
+
+ const menu = screen.getByRole('menu');
+ const items = within(menu).getAllByRole('menuitem');
+ expect(items.map((item) => item.getAttribute('data-testid'))).toEqual(['composer-recent-file', 'composer-recent-file', 'composer-attach-from-device']);
+ expect(within(menu).getByText('heading')).toBeInTheDocument();
+ expect(items[2]).toHaveTextContent('browse');
+
+ const [report, budget] = rows();
+ expect(report).toHaveTextContent('Quarterly report.docx');
+ expect(report).toHaveTextContent('\\\\files\\team\\Reports');
+ expect(report).toHaveTextContent('5 minutes ago');
+ expect(report).toHaveAttribute('title', '\\\\files\\team\\Reports\\Quarterly report.docx');
+ expect(report.querySelector('img')).toHaveAttribute('src', RECENT[0].icon);
+ // No icon from the shell: the app's own for the type.
+ expect(budget.querySelector('img')).toBeNull();
+ expect(budget.querySelector('svg')).not.toBeNull();
+ expect(budget).toHaveTextContent('3 hours ago');
+ });
+
+ it('one click attaches that file through the composer\'s own checks and closes the menu', async () => {
+ const { attach } = desktop();
+ useAuthStore.setState({ client: client() as never });
+ render( );
+ await openMenu();
+ fireEvent.click(rows()[1]);
+ expect(screen.queryByRole('menu')).toBeNull();
+ expect(attach).toHaveBeenCalledWith('id-budget');
+ expect(await screen.findByText('Budget 2027.xlsx')).toBeInTheDocument();
+ expect(hoisted.beforeAttachmentUpload).toHaveBeenCalledWith(expect.objectContaining({ name: 'Budget 2027.xlsx', size: 'bytes of Budget 2027.xlsx'.length }));
+ });
+
+ it('a plugin can refuse it, as it can a file from the dialog', async () => {
+ hoisted.beforeAttachmentUpload.mockImplementation(async (info) => info.name !== 'Budget 2027.xlsx');
+ desktop();
+ useAuthStore.setState({ client: client() as never });
+ render( );
+ await openMenu();
+ fireEvent.click(rows()[1]);
+ await act(async () => {});
+ expect(hoisted.beforeAttachmentUpload).toHaveBeenCalled();
+ expect(screen.queryByText('Budget 2027.xlsx')).toBeNull();
+ });
+
+ it('the server\'s size limit applies too', async () => {
+ desktop();
+ useAuthStore.setState({ client: client({ getMaxSizeUpload: () => 5 }) as never });
+ render( );
+ await openMenu();
+ fireEvent.click(rows()[0]);
+ await act(async () => {});
+ expect(hoisted.toastError).toHaveBeenCalledWith('attachment_too_large');
+ expect(screen.queryByText('Quarterly report.docx')).toBeNull();
+ });
+
+ it('says so when the file is gone or too large for the app', async () => {
+ const { attach } = desktop();
+ useAuthStore.setState({ client: client() as never });
+ render( );
+ attach.mockResolvedValueOnce({ ok: false, reason: 'missing' } as never);
+ await openMenu();
+ fireEvent.click(rows()[0]);
+ await act(async () => {});
+ expect(hoisted.toastError).toHaveBeenLastCalledWith('missing');
+
+ attach.mockResolvedValueOnce({ ok: false, reason: 'too-large' } as never);
+ await openMenu();
+ fireEvent.click(rows()[0]);
+ await act(async () => {});
+ expect(hoisted.toastError).toHaveBeenLastCalledWith('too_large');
+ });
+
+ it('with nothing recent the menu has only its other entries', async () => {
+ desktop({ files: [] });
+ useAuthStore.setState({ client: client() as never });
+ render( );
+ await openMenu();
+ const menu = screen.getByRole('menu');
+ expect(within(menu).queryByText('heading')).toBeNull();
+ expect(within(menu).queryByRole('separator')).toBeNull();
+ expect(within(menu).getAllByRole('menuitem').map((item) => item.getAttribute('data-testid'))).toEqual(['composer-attach-from-device']);
+ });
+
+ it('with the policy off there\'s no list, and Attach is what it was', async () => {
+ const { list } = desktop({ policyOff: true });
+ useAuthStore.setState({ client: client() as never });
+ render( );
+ expect(screen.queryByTestId('composer-attach-menu')).toBeNull();
+ fireEvent.click(screen.getByRole('button', { name: 'attach' }));
+ await act(async () => {});
+ expect(list).not.toHaveBeenCalled();
+ });
+
+ it('keys: the first file has the focus, arrows move, Escape closes', async () => {
+ desktop();
+ useAuthStore.setState({ client: client() as never });
+ render( );
+ await openMenu();
+ await waitFor(() => expect(document.activeElement).toBe(rows()[0]));
+ fireEvent.keyDown(document.activeElement!, { key: 'ArrowDown' });
+ expect(document.activeElement).toBe(rows()[1]);
+ fireEvent.keyDown(document.activeElement!, { key: 'ArrowDown' });
+ expect(document.activeElement).toHaveAttribute('data-testid', 'composer-attach-from-device');
+ fireEvent.keyDown(document.activeElement!, { key: 'Escape' });
+ expect(screen.queryByRole('menu')).toBeNull();
+ });
+
+ it('stays an HTML menu where the shell would draw it natively', async () => {
+ const popup = vi.fn(async () => null);
+ desktop({ popup });
+ useAuthStore.setState({ client: client() as never });
+ render( );
+ await openMenu();
+ await act(async () => { await new Promise((resolve) => setTimeout(resolve, 300)); });
+ expect(popup).not.toHaveBeenCalled();
+ expect(rows()).toHaveLength(2);
+ });
+});
diff --git a/components/email/email-composer.tsx b/components/email/email-composer.tsx
index a1384e37c..a36e5133f 100644
--- a/components/email/email-composer.tsx
+++ b/components/email/email-composer.tsx
@@ -188,7 +188,11 @@ import { fileStorage } from "@/lib/plugin-storage";
import { usePolicyStore } from "@/stores/policy-store";
import { isAppLockedNow } from "@/lib/app-lock/state";
import { registerComposeFlush, registerComposeSnapshot } from "@/lib/compose-flush-registry";
-import { getDesktopBridge } from "@/lib/desktop/bridge";
+import { getDesktopBridge, isDesktopApp } from "@/lib/desktop/bridge";
+import { useDesktopPolicy } from "@/lib/desktop/policy";
+import { readRecentFile, RECENT_FILE_MAX_BYTES, recentFilesOffered } from "@/lib/desktop/recent-files";
+import type { DesktopRecentFile } from "@/lib/desktop/types";
+import { RecentFilesMenuSection } from "@/components/email/recent-files-menu-section";
import { useDesktopCommands } from "@/lib/desktop/commands";
import { noteComposerLanguage } from "@/lib/desktop/languages";
import { noteOpenDraft } from "@/lib/desktop/window-restore";
@@ -650,6 +654,7 @@ export function EmailComposer({
const tEdit = useTranslations('desktopEdit');
const tOfflineDrafts = useTranslations('offlineDrafts');
const tOffline = useTranslations('offline');
+ const tRecent = useTranslations('desktopAttachRecent');
const tOfflineNotes = useTranslations('offlineConflicts');
const tSendGuards = useTranslations('send_guards');
const tWords = useTranslations('compose_words');
@@ -2778,6 +2783,21 @@ export function EmailComposer({
void addFiles(initialFiles, { handedIn: true });
}, [client, initialFiles, addFiles]);
+ // The Attach menu's recent files, in the desktop app (lib/desktop/recent-files.ts). The
+ // shell reads the file; from there it's a file like one from the file dialog.
+ const desktopPolicy = useDesktopPolicy();
+ const recentOffered = recentFilesOffered(desktopPolicy);
+ const attachRecentFile = useCallback(async (file: DesktopRecentFile) => {
+ const result = await readRecentFile(file.id);
+ if (result.ok) {
+ await addFiles([result.file]);
+ return;
+ }
+ if (result.reason === 'missing') toast.error(tRecent('missing', { name: file.name }));
+ else if (result.reason === 'too-large') toast.error(tRecent('too_large', { name: file.name, max: formatFileSize(RECENT_FILE_MAX_BYTES) }));
+ else if (result.reason === 'failed') toast.error(tRecent('failed', { name: file.name }));
+ }, [addFiles, tRecent]);
+
const handleFileSelect = async (event: React.ChangeEvent) => {
if (!event.target.files) return;
await addFiles(Array.from(event.target.files));
@@ -5890,14 +5910,19 @@ export function EmailComposer({
className="hidden"
accept="*/*"
/>
- {(filesEnabled && composerClient?.supportsFiles?.()) || hasAttachMenuActions ? (
+ {recentOffered || (filesEnabled && composerClient?.supportsFiles?.()) || hasAttachMenuActions ? (
{(close) => <>
+ {/* As Outlook's: the recent files first, one click attaches one and closes. */}
+ {recentOffered && (
+ { close(); void attachRecentFile(file); }} />
+ )}
{ close(); fileInputRef.current?.click(); }}
+ testId="composer-attach-from-device"
>
- {t('attach_from_device')}
+ {isDesktopApp() ? tRecent('browse') : t('attach_from_device')}
{filesEnabled && composerClient?.supportsFiles?.() && (
{ close(); setFilesPicker({ client: composerClient, accountId: composerAccountId }); }}
testId="composer-attach-from-files"
>
- {t('attach_from_files')}
+ {isDesktopApp() ? tRecent('from_files') : t('attach_from_files')}
)}
diff --git a/components/email/recent-files-menu-section.tsx b/components/email/recent-files-menu-section.tsx
new file mode 100644
index 000000000..075a88167
--- /dev/null
+++ b/components/email/recent-files-menu-section.tsx
@@ -0,0 +1,88 @@
+"use client";
+
+import { useEffect, useLayoutEffect, useRef, useState } from "react";
+import { useLocale, useTranslations } from "next-intl";
+import { CONTEXT_MENU_ITEM_CLASS, menuLevelItems } from "@/components/ui/context-menu";
+import { attachmentIcon } from "@/components/email/attachment-chips";
+import { listRecentFiles, recentWhen } from "@/lib/desktop/recent-files";
+import type { DesktopRecentFile } from "@/lib/desktop/types";
+import { cn } from "@/lib/utils";
+
+/** Only an icon the shell made: a PNG as a data: URL. */
+const ICON_URL = /^data:image\/png;base64,[A-Za-z0-9+/=]+$/;
+
+/**
+ * The top of the composer's Attach menu in the desktop app: the files the OS says were
+ * used last, as Outlook lists them. Mounted when the menu opens, from that click, which is
+ * what the shell asks for. Until the list is there, and when it's empty, it takes no room.
+ * It stays an HTML menu (data-native-menu): a native one can't show the icons and folders.
+ */
+export function RecentFilesMenuSection({ onPick }: { onPick: (file: DesktopRecentFile) => void }) {
+ const t = useTranslations("desktopAttachRecent");
+ const locale = useLocale();
+ const [files, setFiles] = useState(null);
+ // One request per opening, also when a strict-mode remount runs the effect twice.
+ const request = useRef | null>(null);
+ const rootRef = useRef(null);
+
+ useEffect(() => {
+ let cancelled = false;
+ request.current ??= listRecentFiles();
+ void request.current.then((list) => {
+ if (!cancelled) setFiles(list);
+ });
+ return () => {
+ cancelled = true;
+ };
+ }, []);
+
+ // The menu put the focus on its first entry before the list came. If it's still
+ // there, the first file takes it: the list is what comes first.
+ useLayoutEffect(() => {
+ const root = rootRef.current;
+ const menu = root?.closest('[role="menu"]');
+ if (!root || !menu || !files?.length) return;
+ const active = document.activeElement;
+ const others = menuLevelItems(menu).filter((item) => !root.contains(item));
+ if (active && active === others[0]) root.querySelector('[role="menuitem"]')?.focus({ preventScroll: true });
+ }, [files]);
+
+ const now = Date.now();
+ return (
+
+ {files && files.length > 0 && (
+ <>
+
+ {t("heading")}
+
+ {files.map((file) => {
+ const Fallback = attachmentIcon(null, file.name).icon;
+ return (
+
onPick(file)}
+ data-testid="composer-recent-file"
+ className={cn(CONTEXT_MENU_ITEM_CLASS, "w-[min(24rem,calc(100vw-3rem))] gap-2.5")}
+ >
+ {file.icon && ICON_URL.test(file.icon) ? (
+
+ ) : (
+
+ )}
+
+ {file.name}
+ {file.folder}
+
+ {recentWhen(file.usedAt, now, locale)}
+
+ );
+ })}
+
+ >
+ )}
+
+ );
+}
diff --git a/desktop-policies/Bulwark.admx b/desktop-policies/Bulwark.admx
index 1b60d0497..1d040ac07 100644
--- a/desktop-policies/Bulwark.admx
+++ b/desktop-policies/Bulwark.admx
@@ -224,5 +224,11 @@
+
+
+
+
+
+
diff --git a/desktop-policies/de-DE/Bulwark.adml b/desktop-policies/de-DE/Bulwark.adml
index 2975e98f9..e32e66dfc 100644
--- a/desktop-policies/de-DE/Bulwark.adml
+++ b/desktop-policies/de-DE/Bulwark.adml
@@ -67,6 +67,8 @@
Wenn aktiviert oder nicht konfiguriert, trägt sich die App unter Windows in die Liste „Öffnen mit“ für gängige Dokumente und Bilder und in das Menü „Senden an“ ein, damit Benutzer eine Datei aus dem Dateimanager an eine neue Nachricht anhängen können. Sie wird nie zum Standardprogramm für diese Dateien. Wenn deaktiviert, entfernt die App diese Einträge für den Benutzer. Mail-Links und .eml-, .ics- und .vcf-Dateien sind nicht betroffen.
Entwicklertools
Dieselben Werte wie die gleichnamige Richtlinie von Chrome. 2: Die Entwicklertools sind aus und die Einstellung ist gesperrt. 0 oder 1 oder nicht konfiguriert: Benutzer können sie nach einer Warnung in den Einstellungen einschalten. Mit den Entwicklertools kann jeder an der Tastatur alles lesen, was die App enthält, auch E-Mails und Passwörter im Speicher.
+ Zuletzt verwendete Dateien im Menü „Anfügen“ anzeigen
+ Wenn aktiviert oder nicht konfiguriert, listet die Schaltfläche „Anfügen“ in einer neuen Nachricht die Dateien auf, die der Benutzer zuletzt geöffnet hat, so wie das Betriebssystem sie erfasst. Ein Klick fügt eine davon an. Die Liste wird beim Öffnen des Menüs gelesen und bleibt auf dem Gerät. Wenn deaktiviert, fehlt die Liste und die App lehnt es ab, sie zu lesen. Das Anfügen über den Dateidialog ist nicht betroffen.
Adresse des Bulwark-Servers
diff --git a/desktop-policies/en-US/Bulwark.adml b/desktop-policies/en-US/Bulwark.adml
index 9ae91340a..1d50fd303 100644
--- a/desktop-policies/en-US/Bulwark.adml
+++ b/desktop-policies/en-US/Bulwark.adml
@@ -67,6 +67,8 @@
When enabled or not configured, the app adds itself to the "Open with" list for common documents and pictures and to the "Send to" menu on Windows, so people can attach a file to a new message from the file manager. It never becomes the default program for those files. When disabled, the app removes these entries for the user. Mail links and .eml, .ics and .vcf files are not affected.
Developer tools
The same values as Chrome's policy of this name. 2: developer tools are off and the setting is locked. 0 or 1, or not configured: people can turn them on under Settings, after a warning. Developer tools let anyone at the keyboard read everything the app holds, mail and passwords in memory included.
+ Show recent files in the Attach menu
+ When enabled or not configured, the Attach button in a new message lists the files the user opened recently, as the operating system records them, so one click attaches one. The list is read when the menu opens and stays on the device. When disabled, the list is gone and the app refuses to read it. Attaching through the file dialog is not affected.
Address of the Bulwark server
diff --git a/desktop-policies/org.bulwarkmail.desktop.mobileconfig b/desktop-policies/org.bulwarkmail.desktop.mobileconfig
index 23ddb522c..cb9db7430 100644
--- a/desktop-policies/org.bulwarkmail.desktop.mobileconfig
+++ b/desktop-policies/org.bulwarkmail.desktop.mobileconfig
@@ -69,6 +69,8 @@
DeveloperToolsAvailability
2
+ RecentFilesInAttach
+
Recommended
UpdateChannel
diff --git a/desktop-policies/policies.json b/desktop-policies/policies.json
index 89dd1e510..27934322f 100644
--- a/desktop-policies/policies.json
+++ b/desktop-policies/policies.json
@@ -29,6 +29,7 @@
"BrowserSignIn": true,
"OpenWithEnabled": true,
"DeveloperToolsAvailability": 2,
+ "RecentFilesInAttach": true,
"Recommended": {
"UpdateChannel": "stable"
}
diff --git a/lib/desktop/__tests__/policy-schema.test.ts b/lib/desktop/__tests__/policy-schema.test.ts
index 07b11863c..377cddc93 100644
--- a/lib/desktop/__tests__/policy-schema.test.ts
+++ b/lib/desktop/__tests__/policy-schema.test.ts
@@ -32,7 +32,7 @@ describe('the schema', () => {
'PluginsMode', 'PluginAllowlist', 'OfflineEnabled', 'AppLockRequired', 'AppLockTimeoutMinutes', 'TelemetryAllowed',
'CrashReportsAllowed', 'QuickComposeShortcut', 'AuthServerAllowlist', 'AuthNegotiateDelegateAllowlist',
'AutoSelectCertificateForUrls', 'KeystoreEnabled', 'KeystoreAllowedOrigins', 'BrowserSignIn', 'WipeOfflineData',
- 'OpenWithEnabled', 'DeveloperToolsAvailability',
+ 'OpenWithEnabled', 'DeveloperToolsAvailability', 'RecentFilesInAttach',
]);
for (const key of POLICY_KEYS) {
const { title, description } = POLICY_SCHEMA[key];
@@ -56,6 +56,13 @@ describe('developer tools and Open with', () => {
expect(resolvePolicies(layers({ forcedMachine: { OpenWithEnabled: 0 } })).OpenWithEnabled).toMatchObject({ value: false, locked: true });
expect(resolvePolicies(layers({ forcedMachine: { OpenWithEnabled: 'maybe' } })).OpenWithEnabled).toMatchObject({ value: false, locked: true });
});
+
+ it('hide recent files in the Attach menu only by force, and a value nobody can read hides them', () => {
+ expect(resolvePolicies(layers({})).RecentFilesInAttach).toMatchObject({ value: true, locked: false });
+ expect(resolvePolicies(layers({ recommendedMachine: { RecentFilesInAttach: 0 } })).RecentFilesInAttach).toMatchObject({ value: true, locked: false });
+ expect(resolvePolicies(layers({ forcedUser: { RecentFilesInAttach: 0 } })).RecentFilesInAttach).toMatchObject({ value: false, locked: true });
+ expect(resolvePolicies(layers({ forcedMachine: { RecentFilesInAttach: 'yes please' } })).RecentFilesInAttach).toMatchObject({ value: false, locked: true });
+ });
});
describe('precedence', () => {
diff --git a/lib/desktop/__tests__/recent-files.test.ts b/lib/desktop/__tests__/recent-files.test.ts
new file mode 100644
index 000000000..a240e754c
--- /dev/null
+++ b/lib/desktop/__tests__/recent-files.test.ts
@@ -0,0 +1,87 @@
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import { DEFAULT_POLICY_SNAPSHOT, type PolicySnapshot } from '../policy-schema';
+import type { BulwarkDesktopBridge, DesktopRecentFilesBridge } from '../types';
+import { listRecentFiles, readRecentFile, recentFilesOffered, recentWhen } from '../recent-files';
+
+function setBridge(recentFiles?: Partial, policy: Partial = {}) {
+ const snapshot = { ...DEFAULT_POLICY_SNAPSHOT, ...policy };
+ window.bulwarkDesktop = {
+ version: 1,
+ platform: 'win32',
+ policy: { get: () => snapshot, onChange: () => () => {} },
+ ...(recentFiles ? { recentFiles: recentFiles as DesktopRecentFilesBridge } : {}),
+ } as BulwarkDesktopBridge;
+}
+
+const off = { RecentFilesInAttach: { value: false, source: 'forced-machine', locked: true } } as Partial;
+
+afterEach(() => {
+ window.bulwarkDesktop = undefined;
+});
+
+describe('whether the Attach menu lists recent files', () => {
+ it('not in a browser, not under a shell without the list, not when the policy says no', () => {
+ expect(recentFilesOffered()).toBe(false);
+ setBridge();
+ expect(recentFilesOffered()).toBe(false);
+ setBridge({ list: vi.fn(), attach: vi.fn() });
+ expect(recentFilesOffered()).toBe(true);
+ setBridge({ list: vi.fn(), attach: vi.fn() }, off);
+ expect(recentFilesOffered()).toBe(false);
+ });
+});
+
+describe('listRecentFiles', () => {
+ it('gives the files, and nothing when main says no or fails', async () => {
+ const file = { id: 'a', name: 'a.pdf', folder: 'C:\\Docs', path: 'C:\\Docs\\a.pdf', usedAt: 1 };
+ setBridge({ list: vi.fn(async () => ({ ok: true as const, files: [file] })) });
+ expect(await listRecentFiles()).toEqual([file]);
+ setBridge({ list: vi.fn(async () => ({ ok: false as const, reason: 'gesture' as const })) });
+ expect(await listRecentFiles()).toEqual([]);
+ setBridge({ list: vi.fn(async () => { throw new Error('gone'); }) });
+ expect(await listRecentFiles()).toEqual([]);
+ window.bulwarkDesktop = undefined;
+ expect(await listRecentFiles()).toEqual([]);
+ });
+});
+
+describe('readRecentFile', () => {
+ it('turns the bytes into a File with the name main gave', async () => {
+ const attach = vi.fn(async () => ({ ok: true as const, file: { name: 'Report.docx', data: new TextEncoder().encode('hello') } }));
+ setBridge({ attach });
+ const result = await readRecentFile('id-1');
+ expect(attach).toHaveBeenCalledWith('id-1');
+ expect(result.ok).toBe(true);
+ if (!result.ok) return;
+ expect(result.file.name).toBe('Report.docx');
+ expect(await result.file.text()).toBe('hello');
+ });
+
+ it('says what the user can act on, and keeps quiet about a lock or a policy', async () => {
+ const answer = (reason: string) => {
+ setBridge({ attach: vi.fn(async () => ({ ok: false, reason }) as never) });
+ return readRecentFile('x');
+ };
+ expect(await answer('missing')).toEqual({ ok: false, reason: 'missing' });
+ expect(await answer('too-large')).toEqual({ ok: false, reason: 'too-large' });
+ expect(await answer('unknown')).toEqual({ ok: false, reason: 'failed' });
+ expect(await answer('gesture')).toEqual({ ok: false, reason: 'failed' });
+ expect(await answer('locked')).toEqual({ ok: false, reason: 'quiet' });
+ expect(await answer('policy')).toEqual({ ok: false, reason: 'quiet' });
+ });
+});
+
+describe('recentWhen', () => {
+ const now = new Date(2026, 10, 4, 15, 0).getTime();
+ it('counts minutes and hours today, calendar days this week, then weeks and months', () => {
+ expect(recentWhen(now - 20_000, now, 'en')).toBe('now');
+ expect(recentWhen(now - 5 * 60_000, now, 'en')).toBe('5 minutes ago');
+ expect(recentWhen(now - 3 * 60 * 60_000, now, 'en')).toBe('3 hours ago');
+ // Last night at 23:00, 16 hours ago: yesterday.
+ expect(recentWhen(new Date(2026, 10, 3, 23, 0).getTime(), now, 'en')).toBe('yesterday');
+ expect(recentWhen(new Date(2026, 10, 1, 9, 0).getTime(), now, 'en')).toBe('3 days ago');
+ expect(recentWhen(now - 15 * 24 * 60 * 60_000, now, 'en')).toBe('2 weeks ago');
+ expect(recentWhen(now - 70 * 24 * 60 * 60_000, now, 'en')).toBe('2 months ago');
+ expect(recentWhen(now - 3 * 60 * 60_000, now, 'de')).toBe('vor 3 Stunden');
+ });
+});
diff --git a/lib/desktop/policy-schema.ts b/lib/desktop/policy-schema.ts
index e3229f2dd..54fca1a4c 100644
--- a/lib/desktop/policy-schema.ts
+++ b/lib/desktop/policy-schema.ts
@@ -82,6 +82,7 @@ export interface PolicyValues {
WipeOfflineData: string | null;
OpenWithEnabled: boolean;
DeveloperToolsAvailability: number | null;
+ RecentFilesInAttach: boolean;
}
export type PolicyKey = keyof PolicyValues;
@@ -466,6 +467,19 @@ export const POLICY_SCHEMA: Record = {
de: 'Dieselben Werte wie die gleichnamige Richtlinie von Chrome. 2: Die Entwicklertools sind aus und die Einstellung ist gesperrt. 0 oder 1 oder nicht konfiguriert: Benutzer können sie nach einer Warnung in den Einstellungen einschalten. Mit den Entwicklertools kann jeder an der Tastatur alles lesen, was die App enthält, auch E-Mails und Passwörter im Speicher.',
},
},
+ RecentFilesInAttach: {
+ category: 'privacy',
+ type: 'boolean',
+ default: true,
+ onInvalid: false,
+ forcedOnly: true,
+ sample: true,
+ title: { en: 'Show recent files in the Attach menu', de: 'Zuletzt verwendete Dateien im Menü „Anfügen“ anzeigen' },
+ description: {
+ en: 'When enabled or not configured, the Attach button in a new message lists the files the user opened recently, as the operating system records them, so one click attaches one. The list is read when the menu opens and stays on the device. When disabled, the list is gone and the app refuses to read it. Attaching through the file dialog is not affected.',
+ de: 'Wenn aktiviert oder nicht konfiguriert, listet die Schaltfläche „Anfügen“ in einer neuen Nachricht die Dateien auf, die der Benutzer zuletzt geöffnet hat, so wie das Betriebssystem sie erfasst. Ein Klick fügt eine davon an. Die Liste wird beim Öffnen des Menüs gelesen und bleibt auf dem Gerät. Wenn deaktiviert, fehlt die Liste und die App lehnt es ab, sie zu lesen. Das Anfügen über den Dateidialog ist nicht betroffen.',
+ },
+ },
};
export const POLICY_KEYS = Object.keys(POLICY_SCHEMA) as PolicyKey[];
@@ -916,6 +930,7 @@ const PAGE_POLICY_KEYS: readonly PolicyKey[] = [
'AppLockRequired',
'AppLockTimeoutMinutes',
'CrashReportsAllowed',
+ 'RecentFilesInAttach',
];
/**
@@ -965,6 +980,7 @@ export const POLICY_CONSUMERS: Record = {
BrowserSignIn: { repo: 'shell', file: 'src/main/features/browser-sign-in.ts' },
OpenWithEnabled: { repo: 'shell', file: 'src/main/features/os-default-app.ts' },
DeveloperToolsAvailability: { repo: 'shell', file: 'src/main/features/dev-tools.ts' },
+ RecentFilesInAttach: { repo: 'shell', file: 'src/main/features/os-recent.ts' },
};
/** The part the embedded server enforces. Sent to it by message. */
diff --git a/lib/desktop/recent-files.ts b/lib/desktop/recent-files.ts
new file mode 100644
index 000000000..8030c6d63
--- /dev/null
+++ b/lib/desktop/recent-files.ts
@@ -0,0 +1,80 @@
+/**
+ * Recent files in the composer's Attach menu, in the desktop app only. The shell reads the
+ * OS's list when the menu opens and hands over what the menu shows; attaching sends back an
+ * id, and the bytes come back as a File for the composer's own checks, as a file from the
+ * file dialog does. In a browser there's no bridge, and nothing here offers anything.
+ */
+
+import { getDesktopBridge } from './bridge';
+import { getDesktopPolicy } from './policy';
+import type { PolicySnapshot } from './policy-schema';
+import type { DesktopRecentFile } from './types';
+
+/** The shell's limit for one file, the same as for a file from "Open with" (HANDOFF_MAX_BYTES). */
+export const RECENT_FILE_MAX_BYTES = 100 * 1024 * 1024;
+
+/** The shell has the list and the RecentFilesInAttach policy doesn't hide it. */
+export function recentFilesOffered(policy: PolicySnapshot = getDesktopPolicy()): boolean {
+ return !!getDesktopBridge()?.recentFiles && policy.RecentFilesInAttach?.value !== false;
+}
+
+/** Straight from the click that opened the menu: main wants one. Empty when there's nothing to show. */
+export async function listRecentFiles(): Promise {
+ const bridge = getDesktopBridge()?.recentFiles;
+ if (!bridge) return [];
+ try {
+ const result = await bridge.list();
+ return result.ok ? result.files : [];
+ } catch {
+ return [];
+ }
+}
+
+export type RecentFileAttach =
+ | { ok: true; file: File }
+ | { ok: false; reason: 'missing' | 'too-large' | 'failed' | 'quiet' };
+
+/** Straight from the click on the row. `quiet`: nothing worth telling the user (locked, or switched off). */
+export async function readRecentFile(id: string): Promise {
+ const bridge = getDesktopBridge()?.recentFiles;
+ if (!bridge) return { ok: false, reason: 'quiet' };
+ try {
+ const result = await bridge.attach(id);
+ if (result.ok) return { ok: true, file: new File([new Uint8Array(result.file.data)], result.file.name) };
+ if (result.reason === 'missing' || result.reason === 'too-large') return { ok: false, reason: result.reason };
+ // Locked or switched off since the menu opened: the page shows that itself.
+ if (result.reason === 'locked' || result.reason === 'policy') return { ok: false, reason: 'quiet' };
+ // An id from a list a newer one replaced, or a click main didn't see: worth another try.
+ return { ok: false, reason: 'failed' };
+ } catch {
+ return { ok: false, reason: 'failed' };
+ }
+}
+
+const UNITS: [Intl.RelativeTimeFormatUnit, number][] = [
+ ['year', 365 * 24 * 60 * 60_000],
+ ['month', 30 * 24 * 60 * 60_000],
+ ['week', 7 * 24 * 60 * 60_000],
+ ['day', 24 * 60 * 60_000],
+ ['hour', 60 * 60_000],
+ ['minute', 60_000],
+];
+
+/** "5 minutes ago", "yesterday", "3 weeks ago", in the UI's language. Under a minute: "now". */
+export function recentWhen(usedAt: number, now: number, locale: string): string {
+ const format = new Intl.RelativeTimeFormat(locale, { numeric: 'auto' });
+ const ago = Math.max(0, now - usedAt);
+ // Whole days by the calendar, so something from last night is "yesterday", not "10 hours ago".
+ if (ago >= 12 * 60 * 60_000 && ago < 7 * 24 * 60 * 60_000) {
+ const day = (time: number) => {
+ const date = new Date(time);
+ return Date.UTC(date.getFullYear(), date.getMonth(), date.getDate()) / (24 * 60 * 60_000);
+ };
+ const days = day(now) - day(usedAt);
+ if (days >= 1) return format.format(-days, 'day');
+ }
+ for (const [unit, size] of UNITS) {
+ if (ago >= size) return format.format(-Math.floor(ago / size), unit);
+ }
+ return format.format(0, 'second');
+}
diff --git a/lib/desktop/types.ts b/lib/desktop/types.ts
index 467f918d1..528150273 100644
--- a/lib/desktop/types.ts
+++ b/lib/desktop/types.ts
@@ -752,6 +752,39 @@ export interface DesktopDevToolsBridge {
onChange: (listener: (state: DesktopDevToolsState) => void) => () => void;
}
+/** One of the user's recently used files, as the Attach menu shows it. Nothing more of it reaches the page. */
+export interface DesktopRecentFile {
+ /** Opaque. `attach` takes it, from the window that listed it, until that window lists again. */
+ id: string;
+ name: string;
+ /** The folder it's in, for display. */
+ folder: string;
+ /** The whole path, for a tooltip. */
+ path: string;
+ /** When it was last used, in milliseconds since 1970. */
+ usedAt: number;
+ /** A small icon as a data: URL, when the OS gave one in time. */
+ icon?: string;
+}
+
+/** `gesture`: no click or key press just now. `policy`: RecentFilesInAttach is off. */
+export type DesktopRecentFilesResult =
+ | { ok: true; files: DesktopRecentFile[] }
+ | { ok: false; reason: 'policy' | 'locked' | 'gesture' };
+
+export type DesktopRecentFileAttachResult =
+ | { ok: true; file: DesktopOsFile }
+ | { ok: false; reason: 'policy' | 'locked' | 'gesture' | 'unknown' | 'missing' | 'too-large' | 'failed' };
+
+/**
+ * The files the OS says were used last, for the composer's Attach menu. Main wants a click
+ * or key press of its own for each call, reads only a file it just listed, and never logs.
+ */
+export interface DesktopRecentFilesBridge {
+ list: () => Promise;
+ attach: (id: string) => Promise;
+}
+
/** An attachment copied to a private folder and open in its default program. */
export interface DesktopEditSession {
id: string;
@@ -874,6 +907,8 @@ export interface BulwarkDesktopBridge {
edit?: DesktopEditBridge;
/** Absent on older shells. */
devTools?: DesktopDevToolsBridge;
+ /** Absent on older shells. */
+ recentFiles?: DesktopRecentFilesBridge;
}
declare global {
diff --git a/locales/ar/common.json b/locales/ar/common.json
index f5921dc67..b909b52bd 100644
--- a/locales/ar/common.json
+++ b/locales/ar/common.json
@@ -7665,6 +7665,14 @@
"types_character": "تكتب هذه المفاتيح حرفًا على لوحة مفاتيحك، وسيتوقف عن العمل في كل التطبيقات. جرّب مفاتيح أخرى.",
"reserved": "يستخدم النظام أو معظم التطبيقات هذه المفاتيح. جرّب مفاتيح أخرى."
},
+ "desktopAttachRecent": {
+ "heading": "الملفات الأخيرة",
+ "browse": "استعراض هذا الكمبيوتر…",
+ "from_files": "من الملفات…",
+ "missing": "\"{name}\" لم يعد موجودًا.",
+ "too_large": "\"{name}\" أكبر من {max} ولا يمكن إرفاقه.",
+ "failed": "تعذّر إرفاق \"{name}\". حاول مرة أخرى."
+ },
"compose_windows": {
"more_formatting": "مزيد من التنسيق",
"offline": "دون اتصال",
diff --git a/locales/ca/common.json b/locales/ca/common.json
index 9fde0d888..c3fbf0124 100644
--- a/locales/ca/common.json
+++ b/locales/ca/common.json
@@ -7665,6 +7665,14 @@
"types_character": "Aquestes tecles escriuen un caràcter al teu teclat, i deixaria de funcionar a totes les aplicacions. Prova altres tecles.",
"reserved": "El sistema o la majoria d'aplicacions fan servir aquestes tecles. Prova altres tecles."
},
+ "desktopAttachRecent": {
+ "heading": "Fitxers recents",
+ "browse": "Explora aquest ordinador…",
+ "from_files": "Des de Fitxers…",
+ "missing": "«{name}» ja no hi és.",
+ "too_large": "«{name}» supera {max} i no es pot adjuntar.",
+ "failed": "No s'ha pogut adjuntar «{name}». Torneu-ho a provar."
+ },
"compose_windows": {
"more_formatting": "Més format",
"offline": "Sense connexió",
diff --git a/locales/cs/common.json b/locales/cs/common.json
index e8199be5a..434d850af 100644
--- a/locales/cs/common.json
+++ b/locales/cs/common.json
@@ -7665,6 +7665,14 @@
"types_character": "Tyto klávesy na vaší klávesnici píší znak, který by pak nefungoval v žádné aplikaci. Zkuste jiné klávesy.",
"reserved": "Tyto klávesy používá systém nebo většina aplikací. Zkuste jiné klávesy."
},
+ "desktopAttachRecent": {
+ "heading": "Poslední soubory",
+ "browse": "Procházet tento počítač…",
+ "from_files": "Ze Souborů…",
+ "missing": "„{name}“ už neexistuje.",
+ "too_large": "„{name}“ je větší než {max} a nelze ho připojit.",
+ "failed": "„{name}“ se nepodařilo připojit. Zkuste to znovu."
+ },
"compose_windows": {
"more_formatting": "Další formátování",
"offline": "Offline",
diff --git a/locales/da/common.json b/locales/da/common.json
index 4d8c7681a..b257270d7 100644
--- a/locales/da/common.json
+++ b/locales/da/common.json
@@ -7665,6 +7665,14 @@
"types_character": "Disse taster skriver et tegn på dit tastatur, og det ville holde op med at virke i alle apps. Prøv andre taster.",
"reserved": "Dit system eller de fleste apps bruger disse taster. Prøv andre taster."
},
+ "desktopAttachRecent": {
+ "heading": "Seneste filer",
+ "browse": "Gennemse denne computer…",
+ "from_files": "Fra Filer…",
+ "missing": "\"{name}\" findes ikke længere.",
+ "too_large": "\"{name}\" er større end {max} og kan ikke vedhæftes.",
+ "failed": "\"{name}\" kunne ikke vedhæftes. Prøv igen."
+ },
"compose_windows": {
"more_formatting": "Mere formatering",
"offline": "Offline",
diff --git a/locales/de/common.json b/locales/de/common.json
index 9c39c5a69..3fc09547f 100644
--- a/locales/de/common.json
+++ b/locales/de/common.json
@@ -7665,6 +7665,14 @@
"types_character": "Diese Tasten erzeugen auf Ihrer Tastatur ein Zeichen, das dann in keiner App mehr funktionieren würde. Versuchen Sie andere Tasten.",
"reserved": "Ihr System oder die meisten Apps verwenden diese Tasten. Versuchen Sie andere Tasten."
},
+ "desktopAttachRecent": {
+ "heading": "Zuletzt verwendete Dateien",
+ "browse": "Diesen Computer durchsuchen…",
+ "from_files": "Aus Dateien…",
+ "missing": "\"{name}\" ist nicht mehr vorhanden.",
+ "too_large": "\"{name}\" ist größer als {max} und kann nicht angehängt werden.",
+ "failed": "\"{name}\" konnte nicht angehängt werden. Versuchen Sie es erneut."
+ },
"compose_windows": {
"more_formatting": "Weitere Formatierung",
"offline": "Offline",
diff --git a/locales/en/common.json b/locales/en/common.json
index a2e0f400c..6e8f0c269 100644
--- a/locales/en/common.json
+++ b/locales/en/common.json
@@ -7665,6 +7665,14 @@
"types_character": "These keys type a character on your keyboard, and it would stop working in every app. Try other keys.",
"reserved": "Your system or most apps use these keys. Try other keys."
},
+ "desktopAttachRecent": {
+ "heading": "Recent files",
+ "browse": "Browse this computer…",
+ "from_files": "From Files…",
+ "missing": "\"{name}\" isn't there any more.",
+ "too_large": "\"{name}\" is larger than {max} and can't be attached.",
+ "failed": "\"{name}\" couldn't be attached. Try again."
+ },
"compose_windows": {
"more_formatting": "More formatting",
"offline": "Offline",
diff --git a/locales/es/common.json b/locales/es/common.json
index 7b9d02613..e4c1b8380 100644
--- a/locales/es/common.json
+++ b/locales/es/common.json
@@ -7665,6 +7665,14 @@
"types_character": "Estas teclas escriben un carácter en tu teclado, y dejaría de funcionar en todas las aplicaciones. Prueba otras teclas.",
"reserved": "Tu sistema o la mayoría de las aplicaciones usan estas teclas. Prueba otras teclas."
},
+ "desktopAttachRecent": {
+ "heading": "Archivos recientes",
+ "browse": "Examinar este equipo…",
+ "from_files": "Desde Archivos…",
+ "missing": "\"{name}\" ya no existe.",
+ "too_large": "\"{name}\" supera {max} y no se puede adjuntar.",
+ "failed": "No se pudo adjuntar \"{name}\". Inténtalo de nuevo."
+ },
"compose_windows": {
"more_formatting": "Más formato",
"offline": "Sin conexión",
diff --git a/locales/et/common.json b/locales/et/common.json
index 19ab50447..bc715db21 100644
--- a/locales/et/common.json
+++ b/locales/et/common.json
@@ -7665,6 +7665,14 @@
"types_character": "Need klahvid kirjutavad teie klaviatuuril märgi, mis lakkaks kõigis rakendustes töötamast. Proovige teisi klahve.",
"reserved": "Neid klahve kasutab süsteem või enamik rakendusi. Proovige teisi klahve."
},
+ "desktopAttachRecent": {
+ "heading": "Viimati kasutatud failid",
+ "browse": "Sirvi seda arvutit…",
+ "from_files": "Failidest…",
+ "missing": "„{name}” pole enam olemas.",
+ "too_large": "„{name}” on suurem kui {max} ja seda ei saa lisada.",
+ "failed": "Faili „{name}” ei saanud lisada. Proovi uuesti."
+ },
"compose_windows": {
"more_formatting": "Rohkem vormindust",
"offline": "Võrguta",
diff --git a/locales/fa/common.json b/locales/fa/common.json
index 4e1219635..991304c95 100644
--- a/locales/fa/common.json
+++ b/locales/fa/common.json
@@ -7665,6 +7665,14 @@
"types_character": "این کلیدها روی صفحهکلید شما نویسهای مینویسند و آن نویسه دیگر در هیچ برنامهای کار نمیکند. کلیدهای دیگری را امتحان کنید.",
"reserved": "سیستم یا بیشتر برنامهها از این کلیدها استفاده میکنند. کلیدهای دیگری را امتحان کنید."
},
+ "desktopAttachRecent": {
+ "heading": "فایلهای اخیر",
+ "browse": "مرور این رایانه…",
+ "from_files": "از فایلها…",
+ "missing": "«{name}» دیگر وجود ندارد.",
+ "too_large": "«{name}» بزرگتر از {max} است و نمیتوان آن را پیوست کرد.",
+ "failed": "پیوست «{name}» ممکن نشد. دوباره امتحان کنید."
+ },
"compose_windows": {
"more_formatting": "قالببندی بیشتر",
"offline": "آفلاین",
diff --git a/locales/fr/common.json b/locales/fr/common.json
index 83460df07..82a6cf07f 100644
--- a/locales/fr/common.json
+++ b/locales/fr/common.json
@@ -7665,6 +7665,14 @@
"types_character": "Ces touches produisent un caractère sur votre clavier, et il ne fonctionnerait plus dans aucune application. Essayez d'autres touches.",
"reserved": "Votre système ou la plupart des applications utilisent ces touches. Essayez d'autres touches."
},
+ "desktopAttachRecent": {
+ "heading": "Fichiers récents",
+ "browse": "Parcourir cet ordinateur…",
+ "from_files": "Depuis Fichiers…",
+ "missing": "« {name} » n'existe plus.",
+ "too_large": "« {name} » dépasse {max} et ne peut pas être joint.",
+ "failed": "Impossible de joindre « {name} ». Réessayez."
+ },
"compose_windows": {
"more_formatting": "Plus de mise en forme",
"offline": "Hors ligne",
diff --git a/locales/he/common.json b/locales/he/common.json
index 6fd019a89..30c3745bb 100644
--- a/locales/he/common.json
+++ b/locales/he/common.json
@@ -7666,6 +7666,14 @@
"types_character": "המקשים האלה מקלידים תו במקלדת שלכם, והוא יפסיק לעבוד בכל האפליקציות. נסו מקשים אחרים.",
"reserved": "המערכת או רוב האפליקציות משתמשות במקשים האלה. נסו מקשים אחרים."
},
+ "desktopAttachRecent": {
+ "heading": "קבצים אחרונים",
+ "browse": "עיון במחשב הזה…",
+ "from_files": "מקבצים…",
+ "missing": "\"{name}\" כבר לא קיים.",
+ "too_large": "\"{name}\" גדול מ־{max} ולא ניתן לצרף אותו.",
+ "failed": "לא ניתן היה לצרף את \"{name}\". נסו שוב."
+ },
"compose_windows": {
"more_formatting": "עוד עיצוב",
"offline": "אין חיבור",
diff --git a/locales/hu/common.json b/locales/hu/common.json
index 1cef7c650..498843fd9 100644
--- a/locales/hu/common.json
+++ b/locales/hu/common.json
@@ -7665,6 +7665,14 @@
"types_character": "Ezek a billentyűk karaktert írnak az Ön billentyűzetén, amely többé egyik alkalmazásban sem működne. Próbáljon más billentyűket.",
"reserved": "Ezeket a billentyűket a rendszer vagy a legtöbb alkalmazás használja. Próbáljon más billentyűket."
},
+ "desktopAttachRecent": {
+ "heading": "Legutóbbi fájlok",
+ "browse": "A számítógép tallózása…",
+ "from_files": "A Fájlokból…",
+ "missing": "A(z) „{name}” már nem létezik.",
+ "too_large": "A(z) „{name}” nagyobb, mint {max}, ezért nem csatolható.",
+ "failed": "A(z) „{name}” csatolása nem sikerült. Próbálja újra."
+ },
"compose_windows": {
"more_formatting": "További formázás",
"offline": "Offline",
diff --git a/locales/it/common.json b/locales/it/common.json
index cca81e26e..d0b881bf4 100644
--- a/locales/it/common.json
+++ b/locales/it/common.json
@@ -7665,6 +7665,14 @@
"types_character": "Questi tasti scrivono un carattere sulla tua tastiera, che smetterebbe di funzionare in tutte le app. Prova altri tasti.",
"reserved": "Il sistema o la maggior parte delle app usano questi tasti. Prova altri tasti."
},
+ "desktopAttachRecent": {
+ "heading": "File recenti",
+ "browse": "Sfoglia questo computer…",
+ "from_files": "Da File…",
+ "missing": "\"{name}\" non esiste più.",
+ "too_large": "\"{name}\" supera {max} e non può essere allegato.",
+ "failed": "Impossibile allegare \"{name}\". Riprova."
+ },
"compose_windows": {
"more_formatting": "Altre opzioni di formattazione",
"offline": "Offline",
diff --git a/locales/ja/common.json b/locales/ja/common.json
index 2c7fe67d6..fd78ed407 100644
--- a/locales/ja/common.json
+++ b/locales/ja/common.json
@@ -7665,6 +7665,14 @@
"types_character": "このキーはお使いのキーボードで文字を入力します。割り当てると、すべてのアプリでその文字を入力できなくなります。別のキーをお試しください。",
"reserved": "このキーはシステムまたは多くのアプリが使用しています。別のキーをお試しください。"
},
+ "desktopAttachRecent": {
+ "heading": "最近使ったファイル",
+ "browse": "このコンピューターを参照…",
+ "from_files": "ファイルから…",
+ "missing": "「{name}」はもうありません。",
+ "too_large": "「{name}」は {max} を超えているため添付できません。",
+ "failed": "「{name}」を添付できませんでした。もう一度お試しください。"
+ },
"compose_windows": {
"more_formatting": "その他の書式",
"offline": "オフライン",
diff --git a/locales/ko/common.json b/locales/ko/common.json
index 4a5501456..6c7bf54e9 100644
--- a/locales/ko/common.json
+++ b/locales/ko/common.json
@@ -7665,6 +7665,14 @@
"types_character": "이 키는 사용 중인 키보드에서 문자를 입력하며, 지정하면 모든 앱에서 그 문자를 입력할 수 없게 됩니다. 다른 키를 사용해 보세요.",
"reserved": "시스템 또는 대부분의 앱이 이 키를 사용합니다. 다른 키를 사용해 보세요."
},
+ "desktopAttachRecent": {
+ "heading": "최근 파일",
+ "browse": "이 컴퓨터 찾아보기…",
+ "from_files": "파일에서…",
+ "missing": "\"{name}\"이(가) 더 이상 없어요.",
+ "too_large": "\"{name}\"이(가) {max}보다 커서 첨부할 수 없어요.",
+ "failed": "\"{name}\"을(를) 첨부하지 못했어요. 다시 시도해 주세요."
+ },
"compose_windows": {
"more_formatting": "추가 서식",
"offline": "오프라인",
diff --git a/locales/lv/common.json b/locales/lv/common.json
index f12fb9faf..21a92f57d 100644
--- a/locales/lv/common.json
+++ b/locales/lv/common.json
@@ -7665,6 +7665,14 @@
"types_character": "Šie taustiņi jūsu tastatūrā raksta rakstzīmi, kas pārstātu darboties visās lietotnēs. Izmēģiniet citus taustiņus.",
"reserved": "Šos taustiņus izmanto sistēma vai lielākā daļa lietotņu. Izmēģiniet citus taustiņus."
},
+ "desktopAttachRecent": {
+ "heading": "Nesen izmantotie faili",
+ "browse": "Pārlūkot šo datoru…",
+ "from_files": "No Failiem…",
+ "missing": "“{name}” vairs nav pieejams.",
+ "too_large": "“{name}” ir lielāks par {max}, un to nevar pievienot.",
+ "failed": "Neizdevās pievienot “{name}”. Mēģiniet vēlreiz."
+ },
"compose_windows": {
"more_formatting": "Vairāk formatēšanas",
"offline": "Bezsaistē",
diff --git a/locales/mn/common.json b/locales/mn/common.json
index ad1ce7427..0d926d587 100644
--- a/locales/mn/common.json
+++ b/locales/mn/common.json
@@ -7665,6 +7665,14 @@
"types_character": "Эдгээр товч таны гар дээр тэмдэгт бичдэг тул тэр тэмдэгт бүх аппад ажиллахаа болино. Өөр товч туршина уу.",
"reserved": "Систем эсвэл ихэнх апп эдгээр товчийг ашигладаг. Өөр товч туршина уу."
},
+ "desktopAttachRecent": {
+ "heading": "Сүүлийн файлууд",
+ "browse": "Энэ компьютерээс хайх…",
+ "from_files": "Файлаас…",
+ "missing": "\"{name}\" байхгүй болсон байна.",
+ "too_large": "\"{name}\" {max}-аас том тул хавсаргах боломжгүй.",
+ "failed": "\"{name}\"-г хавсаргаж чадсангүй. Дахин оролдоно уу."
+ },
"compose_windows": {
"more_formatting": "Бусад хэлбэржүүлэлт",
"offline": "Офлайн",
diff --git a/locales/nb/common.json b/locales/nb/common.json
index e0c43c990..ace0d6e1e 100644
--- a/locales/nb/common.json
+++ b/locales/nb/common.json
@@ -7665,6 +7665,14 @@
"types_character": "Disse tastene skriver et tegn på tastaturet ditt, og det ville slutte å virke i alle apper. Prøv andre taster.",
"reserved": "Systemet ditt eller de fleste apper bruker disse tastene. Prøv andre taster."
},
+ "desktopAttachRecent": {
+ "heading": "Nylige filer",
+ "browse": "Bla gjennom denne datamaskinen…",
+ "from_files": "Fra Filer…",
+ "missing": "«{name}» finnes ikke lenger.",
+ "too_large": "«{name}» er større enn {max} og kan ikke legges ved.",
+ "failed": "Kunne ikke legge ved «{name}». Prøv igjen."
+ },
"compose_windows": {
"more_formatting": "Mer formatering",
"offline": "Frakoblet",
diff --git a/locales/nl/common.json b/locales/nl/common.json
index 4d04e4400..920a93870 100644
--- a/locales/nl/common.json
+++ b/locales/nl/common.json
@@ -7665,6 +7665,14 @@
"types_character": "Deze toetsen typen een teken op je toetsenbord, en dat zou in geen enkele app meer werken. Probeer andere toetsen.",
"reserved": "Je systeem of de meeste apps gebruiken deze toetsen. Probeer andere toetsen."
},
+ "desktopAttachRecent": {
+ "heading": "Recente bestanden",
+ "browse": "Deze computer doorzoeken…",
+ "from_files": "Uit Bestanden…",
+ "missing": "\"{name}\" bestaat niet meer.",
+ "too_large": "\"{name}\" is groter dan {max} en kan niet worden bijgevoegd.",
+ "failed": "\"{name}\" kon niet worden bijgevoegd. Probeer het opnieuw."
+ },
"compose_windows": {
"more_formatting": "Meer opmaak",
"offline": "Offline",
diff --git a/locales/pl/common.json b/locales/pl/common.json
index 3d23c4671..b231c72c4 100644
--- a/locales/pl/common.json
+++ b/locales/pl/common.json
@@ -7665,6 +7665,14 @@
"types_character": "Te klawisze wpisują znak na Twojej klawiaturze i przestałby on działać we wszystkich aplikacjach. Wypróbuj inne klawisze.",
"reserved": "Te klawisze są używane przez system lub większość aplikacji. Wypróbuj inne klawisze."
},
+ "desktopAttachRecent": {
+ "heading": "Ostatnie pliki",
+ "browse": "Przeglądaj ten komputer…",
+ "from_files": "Z Plików…",
+ "missing": "„{name}” już nie istnieje.",
+ "too_large": "„{name}” jest większy niż {max} i nie można go dołączyć.",
+ "failed": "Nie udało się dołączyć „{name}”. Spróbuj ponownie."
+ },
"compose_windows": {
"more_formatting": "Więcej formatowania",
"offline": "Offline",
diff --git a/locales/pt/common.json b/locales/pt/common.json
index 2b39bb565..bb01cccae 100644
--- a/locales/pt/common.json
+++ b/locales/pt/common.json
@@ -7665,6 +7665,14 @@
"types_character": "Estas teclas escrevem um carácter no seu teclado, e ele deixaria de funcionar em todas as aplicações. Experimente outras teclas.",
"reserved": "O seu sistema ou a maioria das aplicações usam estas teclas. Experimente outras teclas."
},
+ "desktopAttachRecent": {
+ "heading": "Arquivos recentes",
+ "browse": "Procurar neste computador…",
+ "from_files": "De Arquivos…",
+ "missing": "\"{name}\" não existe mais.",
+ "too_large": "\"{name}\" é maior que {max} e não pode ser anexado.",
+ "failed": "Não foi possível anexar \"{name}\". Tente novamente."
+ },
"compose_windows": {
"more_formatting": "Mais formatação",
"offline": "Offline",
diff --git a/locales/ro/common.json b/locales/ro/common.json
index b8b274456..01e941e7d 100644
--- a/locales/ro/common.json
+++ b/locales/ro/common.json
@@ -7665,6 +7665,14 @@
"types_character": "Aceste taste scriu un caracter pe tastatura ta, iar el n-ar mai funcționa în nicio aplicație. Încearcă alte taste.",
"reserved": "Sistemul sau majoritatea aplicațiilor folosesc aceste taste. Încearcă alte taste."
},
+ "desktopAttachRecent": {
+ "heading": "Fișiere recente",
+ "browse": "Răsfoiește acest computer…",
+ "from_files": "Din Fișiere…",
+ "missing": "„{name}” nu mai există.",
+ "too_large": "„{name}” depășește {max} și nu poate fi atașat.",
+ "failed": "„{name}” nu a putut fi atașat. Încearcă din nou."
+ },
"compose_windows": {
"more_formatting": "Mai multe opțiuni de formatare",
"offline": "Offline",
diff --git a/locales/ru/common.json b/locales/ru/common.json
index 1056ad03b..f51642279 100644
--- a/locales/ru/common.json
+++ b/locales/ru/common.json
@@ -7665,6 +7665,14 @@
"types_character": "На вашей клавиатуре эти клавиши вводят символ, и он перестал бы работать во всех приложениях. Попробуйте другие клавиши.",
"reserved": "Эти клавиши использует система или большинство приложений. Попробуйте другие клавиши."
},
+ "desktopAttachRecent": {
+ "heading": "Недавние файлы",
+ "browse": "Обзор этого компьютера…",
+ "from_files": "Из Файлов…",
+ "missing": "«{name}» больше не существует.",
+ "too_large": "«{name}» больше {max}, его нельзя прикрепить.",
+ "failed": "Не удалось прикрепить «{name}». Попробуйте ещё раз."
+ },
"compose_windows": {
"more_formatting": "Дополнительное форматирование",
"offline": "Не в сети",
diff --git a/locales/sk/common.json b/locales/sk/common.json
index 16209de6f..a93ea875e 100644
--- a/locales/sk/common.json
+++ b/locales/sk/common.json
@@ -7665,6 +7665,14 @@
"types_character": "Tieto klávesy na vašej klávesnici píšu znak, ktorý by potom nefungoval v žiadnej aplikácii. Skúste iné klávesy.",
"reserved": "Tieto klávesy používa systém alebo väčšina aplikácií. Skúste iné klávesy."
},
+ "desktopAttachRecent": {
+ "heading": "Nedávne súbory",
+ "browse": "Prehľadávať tento počítač…",
+ "from_files": "Zo Súborov…",
+ "missing": "„{name}“ už neexistuje.",
+ "too_large": "„{name}“ je väčší ako {max} a nedá sa priložiť.",
+ "failed": "„{name}“ sa nepodarilo priložiť. Skúste to znova."
+ },
"compose_windows": {
"more_formatting": "Ďalšie formátovanie",
"offline": "Offline",
diff --git a/locales/th/common.json b/locales/th/common.json
index 659796f68..cff78c048 100644
--- a/locales/th/common.json
+++ b/locales/th/common.json
@@ -7673,6 +7673,14 @@
"types_character": "ปุ่มเหล่านี้พิมพ์อักขระบนแป้นพิมพ์ของคุณ และอักขระนั้นจะใช้ไม่ได้ในทุกแอป ลองใช้ปุ่มอื่น",
"reserved": "ระบบหรือแอปส่วนใหญ่ใช้ปุ่มเหล่านี้ ลองใช้ปุ่มอื่น"
},
+ "desktopAttachRecent": {
+ "heading": "ไฟล์ล่าสุด",
+ "browse": "เรียกดูคอมพิวเตอร์เครื่องนี้…",
+ "from_files": "จากไฟล์…",
+ "missing": "“{name}” ไม่มีอยู่แล้ว",
+ "too_large": "“{name}” มีขนาดใหญ่กว่า {max} จึงแนบไม่ได้",
+ "failed": "แนบ “{name}” ไม่สำเร็จ ลองอีกครั้ง"
+ },
"compose_windows": {
"more_formatting": "การจัดรูปแบบเพิ่มเติม",
"offline": "ออฟไลน์",
diff --git a/locales/tr/common.json b/locales/tr/common.json
index a4e1787c5..d9a60433c 100644
--- a/locales/tr/common.json
+++ b/locales/tr/common.json
@@ -7665,6 +7665,14 @@
"types_character": "Bu tuşlar klavyenizde bir karakter yazar ve bu karakter hiçbir uygulamada çalışmaz olur. Başka tuşlar deneyin.",
"reserved": "Bu tuşları sisteminiz veya çoğu uygulama kullanıyor. Başka tuşlar deneyin."
},
+ "desktopAttachRecent": {
+ "heading": "Son dosyalar",
+ "browse": "Bu bilgisayara göz at…",
+ "from_files": "Dosyalar'dan…",
+ "missing": "\"{name}\" artık yok.",
+ "too_large": "\"{name}\" {max} boyutundan büyük ve eklenemez.",
+ "failed": "\"{name}\" eklenemedi. Yeniden deneyin."
+ },
"compose_windows": {
"more_formatting": "Daha fazla biçimlendirme",
"offline": "Çevrimdışı",
diff --git a/locales/uk/common.json b/locales/uk/common.json
index 129e93f22..cc2bec555 100644
--- a/locales/uk/common.json
+++ b/locales/uk/common.json
@@ -7665,6 +7665,14 @@
"types_character": "На вашій клавіатурі ці клавіші вводять символ, і він перестав би працювати в усіх застосунках. Спробуйте інші клавіші.",
"reserved": "Ці клавіші використовує система або більшість застосунків. Спробуйте інші клавіші."
},
+ "desktopAttachRecent": {
+ "heading": "Нещодавні файли",
+ "browse": "Огляд цього комп'ютера…",
+ "from_files": "З Файлів…",
+ "missing": "«{name}» більше не існує.",
+ "too_large": "«{name}» більший за {max}, його не можна прикріпити.",
+ "failed": "Не вдалося прикріпити «{name}». Спробуйте ще раз."
+ },
"compose_windows": {
"more_formatting": "Додаткове форматування",
"offline": "Не в мережі",
diff --git a/locales/vi/common.json b/locales/vi/common.json
index 0cd5746c6..f342289d2 100644
--- a/locales/vi/common.json
+++ b/locales/vi/common.json
@@ -7677,6 +7677,14 @@
"types_character": "Các phím này gõ một ký tự trên bàn phím của bạn, và ký tự đó sẽ không dùng được trong mọi ứng dụng. Hãy thử phím khác.",
"reserved": "Hệ thống hoặc hầu hết ứng dụng dùng các phím này. Hãy thử phím khác."
},
+ "desktopAttachRecent": {
+ "heading": "Tệp gần đây",
+ "browse": "Duyệt máy tính này…",
+ "from_files": "Từ Tệp…",
+ "missing": "\"{name}\" không còn nữa.",
+ "too_large": "\"{name}\" lớn hơn {max} nên không thể đính kèm.",
+ "failed": "Không thể đính kèm \"{name}\". Hãy thử lại."
+ },
"compose_windows": {
"more_formatting": "Thêm định dạng",
"offline": "Ngoại tuyến",
diff --git a/locales/zh-TW/common.json b/locales/zh-TW/common.json
index 0f3ae2457..6391a93bb 100644
--- a/locales/zh-TW/common.json
+++ b/locales/zh-TW/common.json
@@ -7665,6 +7665,14 @@
"types_character": "這些鍵在您的鍵盤上會輸入一個字元,占用後該字元在所有應用程式中都無法輸入。請試試其他按鍵。",
"reserved": "系統或大多數應用程式正在使用這些鍵。請試試其他按鍵。"
},
+ "desktopAttachRecent": {
+ "heading": "最近的檔案",
+ "browse": "瀏覽這部電腦…",
+ "from_files": "從檔案…",
+ "missing": "「{name}」已不存在。",
+ "too_large": "「{name}」超過 {max},無法附加。",
+ "failed": "無法附加「{name}」。請再試一次。"
+ },
"compose_windows": {
"more_formatting": "更多格式",
"offline": "離線",
diff --git a/locales/zh/common.json b/locales/zh/common.json
index e22f4805e..737c6ed8e 100644
--- a/locales/zh/common.json
+++ b/locales/zh/common.json
@@ -7665,6 +7665,14 @@
"types_character": "这些键在您的键盘上会输入一个字符,占用后该字符在所有应用中都无法输入。请试试其他按键。",
"reserved": "系统或大多数应用在使用这些键。请试试其他按键。"
},
+ "desktopAttachRecent": {
+ "heading": "最近的文件",
+ "browse": "浏览此电脑…",
+ "from_files": "从文件…",
+ "missing": "“{name}”已不存在。",
+ "too_large": "“{name}”超过 {max},无法添加为附件。",
+ "failed": "无法将“{name}”添加为附件。请重试。"
+ },
"compose_windows": {
"more_formatting": "更多格式",
"offline": "离线",
From dc1a7be0bd079b9db8521beac8e7515197f377c1 Mon Sep 17 00:00:00 2001
From: Linus Rath <139418639+rathlinus@users.noreply.github.com>
Date: Wed, 4 Nov 2026 17:44:39 +0100
Subject: [PATCH 09/12] fix: keep the panel's Hide button at the panel's edge
next to the desktop app's window controls
---
components/email/composer-plugin-sidebars.tsx | 8 ++++++--
components/email/email-composer.tsx | 9 +++++----
2 files changed, 11 insertions(+), 6 deletions(-)
diff --git a/components/email/composer-plugin-sidebars.tsx b/components/email/composer-plugin-sidebars.tsx
index c6fcb2c3c..1c6adb14d 100644
--- a/components/email/composer-plugin-sidebars.tsx
+++ b/components/email/composer-plugin-sidebars.tsx
@@ -279,6 +279,7 @@ export function ComposerPanelHead({
name = null,
onToggle,
className,
+ childrenClassName,
children,
}: {
side: ComposerSidebarSide;
@@ -286,8 +287,10 @@ export function ComposerPanelHead({
width?: number;
name?: string | null;
onToggle: () => void;
- /** Padding and gaps of the row it is part of. */
+ /** Padding of the row it is part of. */
className?: string;
+ /** The gap between what it holds besides Hide, as in the row it is part of. */
+ childrenClassName?: string;
children?: ReactNode;
}) {
if (!isPanelOpen(mode)) return null;
@@ -308,7 +311,8 @@ export function ComposerPanelHead({
>
{side === "right" && hide}
- {children}
+ {/* No gap of the head's own around Hide and the space: a 260 px panel in the desktop app has just enough room for the buttons. */}
+ {children && {children}
}
{side === "left" && hide}
);
diff --git a/components/email/email-composer.tsx b/components/email/email-composer.tsx
index 86ce8a605..82a3d72eb 100644
--- a/components/email/email-composer.tsx
+++ b/components/email/email-composer.tsx
@@ -3630,7 +3630,7 @@ export function EmailComposer({
? pluginSidebars.toggle('right')} />
: null;
const rightPanelOpen = isPanelOpen(pluginSidebars.modes.right);
- const panelHead = (side: 'left' | 'right', className: string, children?: React.ReactNode) => (
+ const panelHead = (side: 'left' | 'right', className: string, children?: React.ReactNode, childrenClassName?: string) => (
pluginSidebars.toggle(side)}
className={className}
+ childrenClassName={childrenClassName}
>
{children}
@@ -5155,7 +5156,7 @@ export function EmailComposer({
{rightPanelToggle}
{!rightPanelOpen && mvInlineButtons}
- {panelHead('right', 'gap-2 ps-1.5 pe-1.5', mvInlineButtons)}
+ {panelHead('right', 'ps-1.5 pe-1.5', mvInlineButtons, 'gap-2')}
) : mvWindow ? (
- {mvWindow.state !== "minimized" && panelHead('right', 'gap-1 ps-1.5 pe-1.5', mvWindowButtons)}
+ {mvWindow.state !== "minimized" && panelHead('right', 'ps-1.5 pe-1.5', mvWindowButtons, 'gap-1')}
) : (
@@ -5258,7 +5259,7 @@ export function EmailComposer({
{rightPanelToggle}
{!rightPanelOpen && windowButtons}
- {panelHead('right', 'gap-3 ps-2 pe-4', windowButtons)}
+ {panelHead('right', 'ps-1.5 pe-4', windowButtons, 'gap-3')}
)}
From c21829170ab4af9c1215f83e42a77447eb6ff195 Mon Sep 17 00:00:00 2001
From: Linus Rath <139418639+rathlinus@users.noreply.github.com>
Date: Wed, 4 Nov 2026 17:48:46 +0100
Subject: [PATCH 10/12] fix: render the Attach button the same on the server
and in the page's first render
---
components/email/email-composer.tsx | 6 ++----
lib/desktop/__tests__/recent-files.test.ts | 10 +++++++++-
lib/desktop/recent-files.ts | 8 +++++++-
3 files changed, 18 insertions(+), 6 deletions(-)
diff --git a/components/email/email-composer.tsx b/components/email/email-composer.tsx
index a36e5133f..c28ff1ce1 100644
--- a/components/email/email-composer.tsx
+++ b/components/email/email-composer.tsx
@@ -189,8 +189,7 @@ import { usePolicyStore } from "@/stores/policy-store";
import { isAppLockedNow } from "@/lib/app-lock/state";
import { registerComposeFlush, registerComposeSnapshot } from "@/lib/compose-flush-registry";
import { getDesktopBridge, isDesktopApp } from "@/lib/desktop/bridge";
-import { useDesktopPolicy } from "@/lib/desktop/policy";
-import { readRecentFile, RECENT_FILE_MAX_BYTES, recentFilesOffered } from "@/lib/desktop/recent-files";
+import { readRecentFile, RECENT_FILE_MAX_BYTES, useRecentFilesOffered } from "@/lib/desktop/recent-files";
import type { DesktopRecentFile } from "@/lib/desktop/types";
import { RecentFilesMenuSection } from "@/components/email/recent-files-menu-section";
import { useDesktopCommands } from "@/lib/desktop/commands";
@@ -2785,8 +2784,7 @@ export function EmailComposer({
// The Attach menu's recent files, in the desktop app (lib/desktop/recent-files.ts). The
// shell reads the file; from there it's a file like one from the file dialog.
- const desktopPolicy = useDesktopPolicy();
- const recentOffered = recentFilesOffered(desktopPolicy);
+ const recentOffered = useRecentFilesOffered();
const attachRecentFile = useCallback(async (file: DesktopRecentFile) => {
const result = await readRecentFile(file.id);
if (result.ok) {
diff --git a/lib/desktop/__tests__/recent-files.test.ts b/lib/desktop/__tests__/recent-files.test.ts
index a240e754c..3ad518b8a 100644
--- a/lib/desktop/__tests__/recent-files.test.ts
+++ b/lib/desktop/__tests__/recent-files.test.ts
@@ -1,7 +1,9 @@
import { afterEach, describe, expect, it, vi } from 'vitest';
import { DEFAULT_POLICY_SNAPSHOT, type PolicySnapshot } from '../policy-schema';
import type { BulwarkDesktopBridge, DesktopRecentFilesBridge } from '../types';
-import { listRecentFiles, readRecentFile, recentFilesOffered, recentWhen } from '../recent-files';
+import { createElement } from 'react';
+import { renderToString } from 'react-dom/server';
+import { listRecentFiles, readRecentFile, recentFilesOffered, recentWhen, useRecentFilesOffered } from '../recent-files';
function setBridge(recentFiles?: Partial