fix(sidechat): disable archiving a side thread the host can never recover (#949)

The host's session list hides every subagent-origin row in ALL archive filters (sessionVisible() returns false before the filter), and its unarchive control only lives on those rows. Archiving a side conversation is therefore a one-way door with no entry left to recover it, so the composer-bar action is disabled for any bound session the list cannot show again, with a hover tip (all 21 dictionaries) explaining why and pointing at Save as new session. The handler keeps the same guard.
The archive-and-rebind path stays covered for a host-visible binding.
This commit is contained in:
Menghuan1918 committed 2026-10-29 23:51:47 +08:00
1 parent af0e7b7c9d
commit d7483f6b33
22 files changed
+117 -19

No files matched your search

+27 -6
View File
@@ -813,6 +813,24 @@ export function SideChatView(props: {
const summary = threadId === undefined ? undefined : list.byId[threadId]
const running = summary?.running === true
/**
* Whether the host's own session list can ever show the bound session again
* after archiving it. It cannot for a subagent-origin row: the host's
* `sessionVisible()` returns false for `origin === 'subagent'` BEFORE the
* archived filter runs, and the only "unarchive" control lives on that list,
* so archiving a side thread is a one-way door (issue #949). Every thread
* this view binds is such a row; an absent summary is treated the same way —
* this view must not archive a session it cannot classify. The composer tip
* says why the action is disabled.
*/
const archiveBlocked = summary === undefined || summary.origin === 'subagent'
/** The archive control's hover text: the blocked reason wins over the
* running hint — stopping the thread would not make archiving recoverable. */
const archiveTip = archiveBlocked
? t('sideChatArchiveBlocked')
: running
? t('sideChatArchiveRunning')
: t('sideChatArchive')
// Connection recovery state (DSH 0.1.2-alpha.2+): drives the disconnect
// banner and an immediate catch-up pull when the wire comes back. The poll
@@ -1355,11 +1373,14 @@ export function SideChatView(props: {
/** Archive the bound thread on the host (the same capability the session
* list's own archive action uses; `stopActivity` settles a running agent
* first). The tab then moves to another live thread: leaving it bound to an
* archived session would dead-end the panel, because the host refuses to
* open archived sessions. */
* first). Disabled for a side thread: the host session list never lists a
* subagent-origin row, so no "unarchive" entry could ever recover it (issue
* #949) — the guard below makes that a hard rule, not just a disabled
* styling. For a recoverable binding the tab then moves to another live
* thread: leaving it bound to an archived session would dead-end the panel,
* because the host refuses to open archived sessions. */
const handleArchive = async (): Promise<void> => {
if (threadId === undefined || busy !== null) return
if (threadId === undefined || busy !== null || archiveBlocked) return
setBusy('archiving')
setError(null)
setSaved(false)
@@ -1546,12 +1567,12 @@ export function SideChatView(props: {
<IconSaveOutline16 />
</button>
</ComposerTip>
<ComposerTip label={running ? t('sideChatArchiveRunning') : t('sideChatArchive')}>
<ComposerTip label={archiveTip}>
<button
type="button"
className={css.sidechatIconBtn}
onClick={() => void handleArchive()}
disabled={running || busy !== null}
disabled={archiveBlocked || running || busy !== null}
aria-label={t('sideChatArchive')}
>
<IconArchiveOutlineRegular size={16} />
+1
View File
@@ -430,6 +430,7 @@ export const ar: Record<string, string> = {
sideChatSaveTitle: 'ترقية هذا الخيط إلى جلسة عالية المستوى في قائمة الجلسات الرئيسية',
sideChatArchive: 'أرشفة هذه المحادثة الجانبية (يمكن العثور عليها مجددًا عبر «إظهار المؤرشفة» في قائمة الجلسات)',
sideChatArchiveRunning: 'هذا الخيط قيد التشغيل — أوقفه قبل الأرشفة',
sideChatArchiveBlocked: 'لا يمكن العثور على المحادثة الجانبية مرة أخرى بعد أرشفتها (تُخفي قائمة جلسات المضيف المحادثات الجانبية في كل عوامل التصفية)، لذلك تم تعطيل الأرشفة — استخدم "حفظ كجلسة جديدة" أولاً للاحتفاظ بها',
sideChatSaved: 'تم الحفظ كجلسة جديدة',
sideChatNoTurn: 'الحفظ متاح بعد أول دور مكتمل',
sideChatPendingDrop: 'لن يُضمَّ آخر متابعة لم يُجَب عنها في الجلسة المحفوظة',
+1
View File
@@ -415,6 +415,7 @@ export const de: Record<string, string> = {
sideChatSaveTitle: 'Diesen Thread in der Hauptsitzungsliste zu einer Top-Level-Sitzung erheben',
sideChatArchive: 'Diese Nebenunterhaltung archivieren (über „Archivierte anzeigen“ in der Sitzungsliste wiederzufinden)',
sideChatArchiveRunning: 'Dieser Thread läuft — vor dem Archivieren stoppen',
sideChatArchiveBlocked: 'Eine Nebenunterhaltung ist nach dem Archivieren nicht wiederzufinden (die Sitzungsliste des Hosts blendet Nebenunterhaltungen in jedem Filter aus), daher ist das Archivieren deaktiviert — zum Behalten zuerst „Als neue Sitzung speichern“ verwenden',
sideChatSaved: 'Als neue Sitzung gespeichert',
sideChatNoTurn: 'Das Speichern ist nach der ersten abgeschlossenen Runde verfügbar',
sideChatPendingDrop: 'Die letzte unbeantwortete Nachfrage wird in der gespeicherten Sitzung nicht enthalten sein',
+1
View File
@@ -422,6 +422,7 @@ export const fr: Record<string, string> = {
sideChatSaveTitle: 'Promouvoir ce fil en session de premier niveau, visible dans la liste des sessions principales',
sideChatArchive: 'Archiver cette conversation latérale (la retrouver via « Afficher les archivées » dans la liste des sessions)',
sideChatArchiveRunning: 'Ce fil est en cours d’exécution — arrêtez-le avant de l’archiver',
sideChatArchiveBlocked: 'Une conversation latérale ne peut plus être retrouvée après archivage (la liste des sessions de l’hôte masque les conversations latérales dans tous les filtres), l’archivage est donc désactivé — utilisez d’abord « Enregistrer comme nouvelle session » pour la conserver',
sideChatSaved: 'Enregistré comme nouvelle session',
sideChatNoTurn: 'Au moins un tour de discussion doit être terminé avant l’enregistrement',
sideChatPendingDrop: 'La dernière relance inachevée ne sera pas incluse dans la nouvelle session',
+1
View File
@@ -429,6 +429,7 @@ export const hi: Record<string, string> = {
sideChatSaveTitle: 'इस थ्रेड को मुख्य सत्र सूची में शीर्ष-स्तरीय सत्र में प्रमोट करें',
sideChatArchive: 'इस साइड बातचीत को संग्रहित करें (सत्र सूची में “संग्रहित दिखाएँ” से दोबारा पा सकते हैं)',
sideChatArchiveRunning: 'यह थ्रेड चल रहा है — संग्रहित करने से पहले इसे रोकें',
sideChatArchiveBlocked: 'साइड बातचीत संग्रहित होने के बाद फिर कभी नहीं मिल सकती (होस्ट की सेशन सूची हर फ़िल्टर में साइड बातचीत छिपाती है), इसलिए संग्रहित करना अक्षम है — इसे रखने के लिए पहले "नई सेशन के रूप में सहेजें" करें',
sideChatSaved: 'नए सत्र के रूप में सहेजा',
sideChatNoTurn: 'पहला टर्न पूरा होने के बाद सहेजना उपलब्ध',
sideChatPendingDrop: 'अंतिम अनुत्तरित फ़ॉलो-अप सहेजे गए सत्र में शामिल नहीं होगा',
+1
View File
@@ -427,6 +427,7 @@ export const id: Record<string, string> = {
sideChatSaveTitle: 'Promosikan thread ini ke sesi tingkat atas dalam daftar sesi utama',
sideChatArchive: 'Arsipkan percakapan samping ini (temukan lagi lewat “Tampilkan yang diarsipkan” di daftar sesi)',
sideChatArchiveRunning: 'Utas ini sedang berjalan — hentikan sebelum mengarsipkan',
sideChatArchiveBlocked: 'Percakapan samping tidak akan pernah ditemukan lagi setelah diarsipkan (daftar sesi host menyembunyikan percakapan samping di semua filter), jadi pengarsipan dinonaktifkan — gunakan "Simpan sebagai sesi baru" dulu untuk menyimpannya',
sideChatSaved: 'Tersimpan sebagai sesi baru',
sideChatNoTurn: 'Simpan tersedia setelah giliran pertama selesai',
sideChatPendingDrop: 'Tindak lanjut yang belum terjawab terakhir tidak akan disertakan dalam sesi yang disimpan',
+1
View File
@@ -420,6 +420,7 @@ export const it: Record<string, string> = {
sideChatSaveTitle: 'Promuove questa conversazione a sessione di primo livello nella lista delle sessioni principali',
sideChatArchive: 'Archivia questa conversazione laterale (la ritrovi con «Mostra archiviate» nell’elenco delle sessioni)',
sideChatArchiveRunning: 'Questa conversazione è in esecuzione — interrompila prima di archiviarla',
sideChatArchiveBlocked: 'Una conversazione laterale non può più essere ritrovata una volta archiviata (l’elenco sessioni dell’host nasconde le conversazioni laterali in ogni filtro), quindi l’archiviazione è disattivata — usa prima «Salva come nuova sessione» per conservarla',
sideChatSaved: 'Salvata come nuova sessione',
sideChatNoTurn: 'Il salvataggio è disponibile dopo il primo turno completato',
sideChatPendingDrop: 'L’ultima domanda di follow-up senza risposta non sarà inclusa nella sessione salvata',
+1
View File
@@ -429,6 +429,7 @@ export const ja: Record<string, string> = {
sideChatSaveTitle: 'このスレッドをトップレベルの会話に昇格、メイン会話リストに表示',
sideChatArchive: 'このサイド会話をアーカイブ(セッションリストの「アーカイブを表示」から再表示できます)',
sideChatArchiveRunning: 'このスレッドは実行中です — 停止してからアーカイブしてください',
sideChatArchiveBlocked: 'サイド会話はアーカイブ後にセッションリストから二度と見つかりません(ホストのセッションリストはどのフィルターでもサイド会話を表示しません)。そのためアーカイブは無効です — 残すには先に「新規会話として保存」を使用してください',
sideChatSaved: '新規会話として保存しました',
sideChatNoTurn: '最初のターンを完了してから保存可能',
sideChatPendingDrop: '最後の未回答フォローアップは保存される会話に含まれません',
+1
View File
@@ -421,6 +421,7 @@ export const ko: Record<string, string> = {
sideChatSaveTitle: '이 스레드를 최상위 세션으로 승격하여 주 세션 목록에 표시합니다',
sideChatArchive: '이 사이드 대화 보관(세션 목록의 "보관됨 표시"에서 다시 찾을 수 있습니다)',
sideChatArchiveRunning: '이 스레드가 실행 중입니다 — 중지한 후 보관하세요',
sideChatArchiveBlocked: '사이드 대화는 보관 후 세션 목록에서 다시 찾을 수 없습니다(호스트 세션 목록은 모든 필터에서 사이드 대화를 숨깁니다). 따라서 보관이 비활성화되었습니다 — 유지하려면 먼저 "새 세션으로 저장"을 사용하세요',
sideChatSaved: '새 세션으로 저장됨',
sideChatNoTurn: '최소 한 턴의 대화를 완료해야 저장할 수 있습니다',
sideChatPendingDrop: '마지막으로 완료되지 않은 후속 질문은 새 세션에 포함되지 않습니다',
+1
View File
@@ -427,6 +427,7 @@ export const nl: Record<string, string> = {
sideChatSaveTitle: 'Promoveer deze thread naar een top-level sessie in de hoofd-sessielijst',
sideChatArchive: 'Dit zijgesprek archiveren (terug te vinden via “Gearchiveerd tonen” in de sessielijst)',
sideChatArchiveRunning: 'Deze thread draait — stop hem voordat je archiveert',
sideChatArchiveBlocked: 'Een zijgesprek is na archivering nooit meer terug te vinden (de sessielijst van de host verbergt zijgesprekken in elk filter), daarom is archiveren uitgeschakeld — gebruik eerst "Opslaan als nieuwe sessie" om het te bewaren',
sideChatSaved: 'Opgeslagen als een nieuwe sessie',
sideChatNoTurn: 'Opslaan is pas beschikbaar na de eerste voltooide beurt',
sideChatPendingDrop: 'De laatste onbeantwoorde follow-up wordt niet meegenomen in de opgeslagen sessie',
+1
View File
@@ -431,6 +431,7 @@ export const pl: Record<string, string> = {
sideChatSaveTitle: 'Promuj ten wątek do sesji najwyższego poziomu na głównej liście sesji',
sideChatArchive: 'Zarchiwizuj tę rozmowę boczną (znajdziesz ją ponownie przez „Pokaż zarchiwizowane” na liście sesji)',
sideChatArchiveRunning: 'Ten wątek działa — zatrzymaj go przed archiwizacją',
sideChatArchiveBlocked: 'Rozmowa boczna po zarchiwizowaniu nie będzie już możliwa do odnalezienia (lista sesji hosta ukrywa rozmowy boczne we wszystkich filtrach), dlatego archiwizacja jest wyłączona — aby ją zachować, najpierw użyj „Zapisz jako nową sesję”',
sideChatSaved: 'Zapisano jako nową sesję',
sideChatNoTurn: 'Zapis jest dostępny po pierwszej ukończonej turze',
sideChatPendingDrop: 'Ostatnie niezakończone pytanie następcze nie zostanie uwzględnione w zapisanej sesji',
+1
View File
@@ -412,6 +412,7 @@ export const pt: Record<string, string> = {
sideChatSaveTitle: 'Promover este tópico a uma sessão de nível superior na lista principal de sessões',
sideChatArchive: 'Arquivar esta conversa lateral (encontre-a novamente em “Mostrar arquivadas” na lista de sessões)',
sideChatArchiveRunning: 'Este tópico está em execução — pare-o antes de arquivar',
sideChatArchiveBlocked: 'Uma conversa lateral nunca mais será encontrada depois de arquivada (a lista de sessões do host oculta conversas laterais em todos os filtros), então o arquivamento está desativado — use "Salvar como nova sessão" primeiro para mantê-la',
sideChatSaved: 'Salvo como nova sessão',
sideChatNoTurn: 'O salvamento está disponível após o primeiro turno concluído',
sideChatPendingDrop: 'A última pergunta não respondida não será incluída na sessão salva',
+1
View File
@@ -427,6 +427,7 @@ export const ru: Record<string, string> = {
sideChatSaveTitle: 'Повысить поток до сессии верхнего уровня в основном списке сессий',
sideChatArchive: 'Архивировать этот боковой диалог (найти снова можно через «Показать архивированные» в списке сессий)',
sideChatArchiveRunning: 'Этот поток выполняется — остановите его перед архивацией',
sideChatArchiveBlocked: 'Боковой диалог после архивации больше нельзя будет найти (список сессий хоста скрывает боковые диалоги при любом фильтре), поэтому архивация отключена — чтобы сохранить его, сначала используйте «Сохранить как новую сессию»',
sideChatSaved: 'Сохранено как новая сессия',
sideChatNoTurn: 'Сохранение доступно после первого завершённого хода',
sideChatPendingDrop: 'Последний незавершённый уточняющий вопрос не попадёт в сохранённую сессию',
+1
View File
@@ -412,6 +412,7 @@ export const sv: Record<string, string> = {
sideChatSaveTitle: 'Höj denna tråd till en toppnivå-session i huvudsessionslistan',
sideChatArchive: 'Arkivera den här sidkonversationen (hitta den igen via ”Visa arkiverade” i sessionslistan)',
sideChatArchiveRunning: 'Den här tråden körs — stoppa den innan du arkiverar',
sideChatArchiveBlocked: 'En sidokonversation går aldrig att hitta igen efter arkivering (värdens sessionslista döljer sidokonversationer i alla filter), därför är arkivering inaktiverad — använd "Spara som ny session" först för att behålla den',
sideChatSaved: 'Sparad som ny session',
sideChatNoTurn: 'Spara är tillgängligt efter den första slutförda vändan',
sideChatPendingDrop: 'Den senaste obesvarade följdfrågan inkluderas inte i den sparade sessionen',
+1
View File
@@ -429,6 +429,7 @@ export const th: Record<string, string> = {
sideChatSaveTitle: 'เลื่อนเธรดนี้เป็นเซสชันระดับบนสุดในรายการเซสชันหลัก',
sideChatArchive: 'เก็บถาวรบทสนทนาข้างนี้ (ค้นหาอีกครั้งได้จาก “แสดงรายการที่เก็บถาวร” ในรายการเซสชัน)',
sideChatArchiveRunning: 'เธรดนี้กำลังทำงาน — หยุดก่อนเก็บถาวร',
sideChatArchiveBlocked: 'บทสนทนาข้างจะค้นหาไม่พบอีกหลังเก็บถาวร (รายการเซสชันของโฮสต์ซ่อนบทสนทนาข้างในทุกตัวกรอง) จึงปิดใช้งานการเก็บถาวร — ใช้ "บันทึกเป็นเซสชันใหม่" ก่อนหากต้องการเก็บไว้',
sideChatSaved: 'บันทึกเป็นเซสชันใหม่แล้ว',
sideChatNoTurn: 'การบันทึกพร้อมใช้งานหลังจากรอบแรกเสร็จสมบูรณ์',
sideChatPendingDrop: 'การติดตามที่ยังไม่ได้ตอบครั้งสุดท้ายจะไม่รวมในเซสชันที่บันทึก',
+1
View File
@@ -429,6 +429,7 @@ export const tr: Record<string, string> = {
sideChatSaveTitle: 'Bu iş parçacığını ana oturum listesinde üst düzey oturuma yükselt',
sideChatArchive: 'Bu yan sohbeti arşivle (oturum listesindeki “Arşivlenenleri göster” ile tekrar bulabilirsiniz)',
sideChatArchiveRunning: 'Bu iş parçacığı çalışıyor — arşivlemeden önce durdurun',
sideChatArchiveBlocked: 'Yan sohbet arşivlendikten sonra oturum listesinde bir daha bulunamaz (ana oturum listesi tüm filtrelerde yan sohbetleri gizler), bu nedenle arşivleme devre dışı — saklamak için önce "Yeni oturum olarak kaydet"i kullanın',
sideChatSaved: 'Yeni oturum olarak kaydedildi',
sideChatNoTurn: 'Kaydetme ilk tamamlanan turdan sonra kullanılabilir',
sideChatPendingDrop: 'Son yanıtlanmamış devam sorusu kaydedilen oturuma dahil edilmez',
+1
View File
@@ -429,6 +429,7 @@ export const vi: Record<string, string> = {
sideChatSaveTitle: 'Nâng luồng này thành phiên cấp cao nhất, xuất hiện trong danh sách phiên chính',
sideChatArchive: 'Lưu trữ cuộc trò chuyện bên này (tìm lại qua “Hiện mục đã lưu trữ” trong danh sách phiên)',
sideChatArchiveRunning: 'Luồng này đang chạy — hãy dừng trước khi lưu trữ',
sideChatArchiveBlocked: 'Hội thoại bên sẽ không thể tìm lại sau khi lưu trữ (danh sách phiên của máy chủ ẩn hội thoại bên ở mọi bộ lọc), vì vậy lưu trữ bị tắt — hãy dùng "Lưu thành phiên mới" trước nếu muốn giữ lại',
sideChatSaved: 'Đã lưu thành phiên mới',
sideChatNoTurn: 'Cần hoàn thành ít nhất một vòng trò chuyện trước khi lưu',
sideChatPendingDrop: 'Tin nhắn theo dõi chưa hoàn thành cuối cùng sẽ không được đưa vào phiên đã lưu',
+1
View File
@@ -444,6 +444,7 @@ export const zhHK: Record<string, string> = {
sideChatSaveTitle: '把該執行緒提升為頂層工作階段,出現在主工作階段列表中',
sideChatArchive: '歸檔這條側邊對話(在工作階段列表的「顯示已歸檔」裡可找回)',
sideChatArchiveRunning: '該執行緒正在執行,停止後才能歸檔',
sideChatArchiveBlocked: '側邊對話歸檔後將無法找回(宿主的工作階段清單在任何篩選下都不顯示側邊對話),因此已停用歸檔;如需保留,請先「儲存為新工作階段」',
sideChatSaved: '已儲存為新工作階段',
sideChatNoTurn: '至少完成一輪對話後才能儲存',
sideChatPendingDrop: '最後一則未完成的追問不會包含在新工作階段中',
+1
View File
@@ -444,6 +444,7 @@ export const zhMO: Record<string, string> = {
sideChatSaveTitle: '把該執行緒提升為頂層工作階段,出現在主工作階段列表中',
sideChatArchive: '歸檔這條側邊對話(在工作階段列表的「顯示已歸檔」裡可找回)',
sideChatArchiveRunning: '該執行緒正在執行,停止後才能歸檔',
sideChatArchiveBlocked: '側邊對話歸檔後將無法找回(宿主的工作階段清單在任何篩選下都不顯示側邊對話),因此已停用歸檔;如需保留,請先「儲存為新工作階段」',
sideChatSaved: '已儲存為新工作階段',
sideChatNoTurn: '至少完成一輪對話後才能儲存',
sideChatPendingDrop: '最後一則未完成的追問不會包含在新工作階段中',
+1
View File
@@ -444,6 +444,7 @@ export const zhTW: Record<string, string> = {
sideChatSaveTitle: '把該執行緒提升為頂層工作階段,出現在主工作階段列表中',
sideChatArchive: '歸檔這條側邊對話(在工作階段列表的「顯示已歸檔」裡可找回)',
sideChatArchiveRunning: '該執行緒正在執行,停止後才能歸檔',
sideChatArchiveBlocked: '側邊對話歸檔後將無法找回(宿主的工作階段清單在任何篩選下都不顯示側邊對話),因此已停用歸檔;如需保留,請先「儲存為新工作階段」',
sideChatSaved: '已儲存為新工作階段',
sideChatNoTurn: '至少完成一輪對話後才能儲存',
sideChatPendingDrop: '最後一則未完成的追問不會包含在新工作階段中',
+2
View File
@@ -441,6 +441,7 @@ export const zh = {
sideChatSaveTitle: '把该线程提升为顶层会话,出现在主会话列表中',
sideChatArchive: '归档这条侧边对话(在会话列表的「显示已归档」里可找回)',
sideChatArchiveRunning: '该线程正在运行,停止后才能归档',
sideChatArchiveBlocked: '侧边对话归档后无法找回(宿主会话列表在任何筛选下都不显示侧边对话),因此已禁用归档;如需保留,请先「保存为新会话」',
sideChatSaved: '已保存为新会话',
sideChatNoTurn: '至少完成一轮对话后才能保存',
sideChatPendingDrop: '最后一条未完成的追问不会包含在新会话中',
@@ -1085,6 +1086,7 @@ export const en: Record<keyof typeof zh, string> = {
sideChatSaveTitle: 'Promote this thread to a top-level session in the main session list',
sideChatArchive: 'Archive this side conversation (find it again via “Show archived” in the session list)',
sideChatArchiveRunning: 'This thread is running — stop it before archiving',
sideChatArchiveBlocked: 'A side conversation can never be found again once archived (the host session list hides side conversations in every filter), so archiving is disabled — use “Save as new session” first to keep it',
sideChatSaved: 'Saved as a new session',
sideChatNoTurn: 'Save is available after the first completed turn',
sideChatPendingDrop: 'The last unanswered follow-up will not be included in the saved session',
+69 -13
View File
@@ -186,6 +186,40 @@ async function clickArchive(button: HTMLButtonElement): Promise<void> {
})
}
/** jsdom ships no ResizeObserver; a visible Tooltip bubble measures itself
* with one. The measurement result is irrelevant here — only the rendered
* label is asserted. */
function stubResizeObserver(): () => void {
const original = (globalThis as Record<string, unknown>).ResizeObserver
class Fake {
observe(): void {}
unobserve(): void {}
disconnect(): void {}
}
;(globalThis as Record<string, unknown>).ResizeObserver = Fake
return () => {
if (original === undefined) delete (globalThis as Record<string, unknown>).ResizeObserver
else (globalThis as Record<string, unknown>).ResizeObserver = original
}
}
/** Open a composer-bar control's hover bubble and return its text. */
async function tooltipOf(control: HTMLElement): Promise<string> {
const restore = stubResizeObserver()
try {
const anchor = control.parentElement
if (anchor === null) throw new Error('the control is missing its hover anchor')
await act(async () => {
anchor.dispatchEvent(new MouseEvent('mouseover', { bubbles: true }))
// ComposerTip's 120 ms hover delay (TIP_DELAY_MS).
await new Promise(resolve => setTimeout(resolve, 180))
})
return document.body.querySelector('[role="tooltip"]')?.textContent ?? ''
} finally {
restore()
}
}
function jsonResponse(value: unknown): Response {
return { ok: true, status: 200, json: async () => value } as unknown as Response
}
@@ -372,12 +406,42 @@ describe('SideChatView rendering', () => {
})
describe('SideChatView archive', () => {
it('archives the bound thread with stopActivity and rebinds the tab to the newest remaining thread', async () => {
/** A bound session the host's own session list CAN show (no subagent
* origin): the only case in which the archive action stays enabled, so the
* handler's archive-and-rebind contract is pinned on it. */
const recoverableStore = (running = false) => makeStore({
byId: {
root: { id: 'root', displayTitle: '主会话', running: false },
t1: { id: 't1', displayTitle: '线程一', running },
},
})
it('disables archiving a side thread and explains that the host can never show it again', async () => {
const host = makeArchiveHost()
const props = viewProps(makeArchiveCtx(threadStore(), host))
const { container, unmount } = renderRoot(createElement(SideChatView, props))
await act(async () => {}) // flush the initial transcript pull
// Every thread this view binds is `origin: 'subagent'`, and the host's
// session list hides those rows in ALL archive filters (its
// sessionVisible() returns false BEFORE the filter runs), so archiving one
// is a one-way door: no list entry can ever offer "unarchive".
const button = archiveButton(container)
expect(button.disabled).toBe(true)
expect(await tooltipOf(button)).toContain('归档后无法找回')
// A disabled control swallows the click: no request, no rebind.
await clickArchive(button)
expect(host.archiveSession).not.toHaveBeenCalled()
expect(host.betterSidebar.updateTab).not.toHaveBeenCalled()
unmount()
})
it('archives a recoverable bound session with stopActivity and rebinds to the newest remaining thread', async () => {
const host = makeArchiveHost()
const store = makeStore({
byId: {
root: { id: 'root', displayTitle: '主会话', running: false },
t1: { id: 't1', displayTitle: 'Side: 线程一', origin: 'subagent', parentId: 'root', running: false },
t1: { id: 't1', displayTitle: '线程一', running: false },
t2: { id: 't2', displayTitle: 'Side: 线程二', origin: 'subagent', parentId: 'root', running: false },
},
// The host's own catalog carries the creation order the fallback ranks by.
@@ -385,7 +449,6 @@ describe('SideChatView archive', () => {
root: {
values: {
subagentCatalog: [
{ id: 't1', createdAt: 1_000, mode: 'continuable', label: 'Side: 线程一' },
{ id: 't2', createdAt: 2_000, mode: 'continuable', label: 'Side: 线程二' },
],
},
@@ -403,7 +466,7 @@ describe('SideChatView archive', () => {
// The host's own archive capability, once, with a running agent settled.
expect(host.archiveSession).toHaveBeenCalledTimes(1)
expect(host.archiveSession).toHaveBeenCalledWith('t1', { stopActivity: true })
// The tab moves to the newest remaining thread (t2 outranks t1 in the catalog).
// The tab moves to the newest remaining thread.
expect(host.betterSidebar.updateTab).toHaveBeenCalledTimes(1)
expect(host.betterSidebar.updateTab).toHaveBeenCalledWith('tab1', { meta: { threadId: 't2' } })
unmount()
@@ -411,13 +474,7 @@ describe('SideChatView archive', () => {
it('disables the archive button while the thread runs and archives nothing on click', async () => {
const host = makeArchiveHost()
const store = makeStore({
byId: {
root: { id: 'root', displayTitle: '主会话', running: false },
t1: { id: 't1', displayTitle: 'Side: 线程一', origin: 'subagent', parentId: 'root', running: true },
},
})
const props = viewProps(makeArchiveCtx(store, host))
const props = viewProps(makeArchiveCtx(recoverableStore(true), host))
const { container, unmount } = renderRoot(createElement(SideChatView, props))
await act(async () => {}) // flush the initial transcript pull
@@ -432,8 +489,7 @@ describe('SideChatView archive', () => {
it('unbinds the tab to the empty state once no thread is left to switch to', async () => {
const host = makeArchiveHost()
const store = threadStore() // the bound thread t1 is the only one under 'root'
const props = viewProps(makeArchiveCtx(store, host))
const props = viewProps(makeArchiveCtx(recoverableStore(), host))
const { container, unmount } = renderRoot(createElement(SideChatView, props))
await act(async () => {}) // flush the initial transcript pull