diff --git a/src/client/SideChatView.tsx b/src/client/SideChatView.tsx index 1dad1f52..c42618bc 100644 --- a/src/client/SideChatView.tsx +++ b/src/client/SideChatView.tsx @@ -30,6 +30,7 @@ import { ConnectionIndicator, DiffBlock, IconApiOutlineRegular, + IconArchiveOutlineRegular, IconBrowseOutlineRegular, IconChevronRightOutlineRegular, IconEditOutlineRegular, @@ -133,6 +134,56 @@ interface RowLabels { read: ReadBlockLabels } +/** The host services this view reaches for archiving. Neither face lives on + * the plugin's own context type — `workspaces` is the session-list service and + * `uiWorkspace` the session surface — so they are read through the same + * structural probe the other views use for host services. */ +interface ArchivedSessionsFace { + list?: { + getSnapshot?: () => { archivedSessionIds?: readonly string[] } + subscribe?: (callback: () => void) => () => void + } +} + +interface ArchiveSessionFace { + archiveSession?: (sessionId: string, options: { stopActivity: boolean }) => Promise +} + +/** A stable "nothing is archived" snapshot: the archive set feeds + * `useSyncExternalStore`, and a fresh `[]` per read would re-render forever. */ +const NO_ARCHIVED_SESSIONS: readonly string[] = [] + +/** The sessions the host currently hides as archived. A host without the + * `workspaces` service (or a context that throws on `get`) reads as "nothing + * is archived", so the thread menu simply keeps every thread. */ +function archivedSessionIdsOf(ctx: Context): readonly string[] { + try { + const service = ctx.get('workspaces') as unknown as ArchivedSessionsFace | undefined + return service?.list?.getSnapshot?.()?.archivedSessionIds ?? NO_ARCHIVED_SESSIONS + } catch { + return NO_ARCHIVED_SESSIONS + } +} + +/** Subscribe to the host's archive set. DSH hides archived sessions from the + * session list, so the thread menu has to follow the same set — otherwise it + * would keep offering a thread the host refuses to open. */ +function useArchivedSessionIds(ctx: Context): readonly string[] { + const subscribe = useMemo( + () => (callback: () => void) => { + try { + const service = ctx.get('workspaces') as unknown as ArchivedSessionsFace | undefined + return service?.list?.subscribe?.(callback) ?? (() => {}) + } catch { + return () => {} + } + }, + [ctx], + ) + const getSnapshot = useCallback(() => archivedSessionIdsOf(ctx), [ctx]) + return useSyncExternalStore(subscribe, getSnapshot) +} + /** Merge history entries by event seq (newest wins), log order preserved. */ function mergeBySeq( previous: readonly SidebarHistoryEntry[], @@ -386,17 +437,21 @@ export function SideChatView(props: { useMemo(() => (callback: () => void) => ctx.sessions.list.subscribe(callback), [ctx]), useCallback(() => ctx.sessions.list.getSnapshot(), [ctx]), ) - const threads = useMemo( - () => sideThreadRows(list.byId, scope.sessionId), - [list, scope.sessionId], - ) + // Archived threads are dropped from the menu (and from the switch targets): + // the host hides archived sessions itself, and binding a tab to one would + // strand the panel on a session it refuses to open. + const archivedIds = useArchivedSessionIds(ctx) + const threads = useMemo(() => { + const archived = new Set(archivedIds) + return sideThreadRows(list.byId, scope.sessionId).filter(row => !archived.has(row.id)) + }, [list, scope.sessionId, archivedIds]) // The thread this tab is bound to rides tab.meta (refresh-restored). const threadId = sidechatThreadIdOf(tab) const autoCreate = (tab.meta as { autoCreate?: unknown } | undefined)?.autoCreate === true const [composer, setComposer] = useState('') - const [busy, setBusy] = useState<'starting' | 'sending' | 'saving' | null>(null) + const [busy, setBusy] = useState<'starting' | 'sending' | 'saving' | 'archiving' | null>(null) const [error, setError] = useState(null) const [saved, setSaved] = useState(false) const [revision, setRevision] = useState(0) @@ -661,6 +716,21 @@ export function SideChatView(props: { } } + /** The thread that should replace `excludeId` once it is archived: the newest + * real thread first (the host's own subagent catalog carries the creation + * order), the newest placeholder only when nothing else is left, and + * `undefined` when the thread menu is empty — the tab then unbinds to the + * empty state instead of staying bound to an archived session. */ + const fallbackThreadId = useCallback((excludeId: string): string | undefined => { + const candidates = threads.filter(row => row.id !== excludeId) + const catalog = list.projectionsBySession?.[scope.sessionId]?.values.subagentCatalog + const rank = (id: string): number => catalog?.find(entry => entry.id === id)?.createdAt ?? 0 + const real = candidates.filter(row => row.title !== SIDE_NEW_THREAD_TITLE) + const pool = real.length > 0 ? real : candidates + if (pool.length === 0) return undefined + return pool.reduce((newest, row) => (rank(row.id) > rank(newest.id) ? row : newest)).id + }, [list, scope.sessionId, threads]) + const handleSave = async (): Promise => { if (threadId === undefined || !canSave || busy !== null) return setBusy('saving') @@ -686,6 +756,29 @@ 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. */ + const handleArchive = async (): Promise => { + if (threadId === undefined || busy !== null) return + setBusy('archiving') + setError(null) + setSaved(false) + try { + const service = ctx.get('uiWorkspace') as unknown as ArchiveSessionFace | undefined + if (service?.archiveSession === undefined) throw new Error('the workspace service is unavailable') + await service.archiveSession(threadId, { stopActivity: true }) + const next = fallbackThreadId(threadId) + ctx.get('betterSidebar')?.updateTab(tab.id, { meta: next === undefined ? {} : { threadId: next } }) + } catch (cause) { + setError(cause instanceof Error ? cause.message : String(cause)) + } finally { + setBusy(null) + } + } + // ── unbound tab: the hero (fresh autoCreate tabs flash a creating state // until the thread lands; legacy persisted tabs offer a manual start) ── if (threadId === undefined) { @@ -752,6 +845,16 @@ export function SideChatView(props: { > + {connectionState !== undefined && connectionState !== 'connected' && ( = { sideChatThreads: 'تبديل خيط / جديد', sideChatSave: 'حفظ كجلسة جديدة', sideChatSaveTitle: 'ترقية هذا الخيط إلى جلسة عالية المستوى في قائمة الجلسات الرئيسية', + sideChatArchive: 'أرشفة هذه المحادثة الجانبية (يمكن العثور عليها مجددًا عبر «إظهار المؤرشفة» في قائمة الجلسات)', + sideChatArchiveRunning: 'هذا الخيط قيد التشغيل — أوقفه قبل الأرشفة', sideChatSaved: 'تم الحفظ كجلسة جديدة', sideChatNoTurn: 'الحفظ متاح بعد أول دور مكتمل', sideChatPendingDrop: 'لن يُضمَّ آخر متابعة لم يُجَب عنها في الجلسة المحفوظة', diff --git a/src/client/locales-de.ts b/src/client/locales-de.ts index 63c2157c..9560ae0c 100644 --- a/src/client/locales-de.ts +++ b/src/client/locales-de.ts @@ -335,6 +335,8 @@ export const de: Record = { sideChatThreads: 'Thread wechseln / neu', sideChatSave: 'Als neue Sitzung speichern', 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', 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', diff --git a/src/client/locales-fr.ts b/src/client/locales-fr.ts index 4f4ad35f..60802f8f 100644 --- a/src/client/locales-fr.ts +++ b/src/client/locales-fr.ts @@ -342,6 +342,8 @@ export const fr: Record = { sideChatThreads: 'Changer de fil / nouveau', sideChatSave: 'Enregistrer comme nouvelle session', 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', 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', diff --git a/src/client/locales-hi.ts b/src/client/locales-hi.ts index a26ed656..e5be0c66 100644 --- a/src/client/locales-hi.ts +++ b/src/client/locales-hi.ts @@ -349,6 +349,8 @@ export const hi: Record = { sideChatThreads: 'थ्रेड स्विच / नया', sideChatSave: 'नए सत्र के रूप में सहेजें', sideChatSaveTitle: 'इस थ्रेड को मुख्य सत्र सूची में शीर्ष-स्तरीय सत्र में प्रमोट करें', + sideChatArchive: 'इस साइड बातचीत को संग्रहित करें (सत्र सूची में “संग्रहित दिखाएँ” से दोबारा पा सकते हैं)', + sideChatArchiveRunning: 'यह थ्रेड चल रहा है — संग्रहित करने से पहले इसे रोकें', sideChatSaved: 'नए सत्र के रूप में सहेजा', sideChatNoTurn: 'पहला टर्न पूरा होने के बाद सहेजना उपलब्ध', sideChatPendingDrop: 'अंतिम अनुत्तरित फ़ॉलो-अप सहेजे गए सत्र में शामिल नहीं होगा', diff --git a/src/client/locales-id.ts b/src/client/locales-id.ts index 6ebd9490..58943570 100644 --- a/src/client/locales-id.ts +++ b/src/client/locales-id.ts @@ -347,6 +347,8 @@ export const id: Record = { sideChatThreads: 'Beralih thread / baru', sideChatSave: 'Simpan sebagai sesi baru', 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', 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', diff --git a/src/client/locales-it.ts b/src/client/locales-it.ts index 9e8b5adf..ee9dd9c7 100644 --- a/src/client/locales-it.ts +++ b/src/client/locales-it.ts @@ -340,6 +340,8 @@ export const it: Record = { sideChatThreads: 'Cambia conversazione / nuova', sideChatSave: 'Salva come nuova sessione', 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', 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', diff --git a/src/client/locales-ja.ts b/src/client/locales-ja.ts index 4ba924e1..37df4962 100644 --- a/src/client/locales-ja.ts +++ b/src/client/locales-ja.ts @@ -349,6 +349,8 @@ export const ja: Record = { sideChatThreads: 'スレッド切替 / 新規', sideChatSave: '新規会話として保存', sideChatSaveTitle: 'このスレッドをトップレベルの会話に昇格、メイン会話リストに表示', + sideChatArchive: 'このサイド会話をアーカイブ(セッションリストの「アーカイブを表示」から再表示できます)', + sideChatArchiveRunning: 'このスレッドは実行中です — 停止してからアーカイブしてください', sideChatSaved: '新規会話として保存しました', sideChatNoTurn: '最初のターンを完了してから保存可能', sideChatPendingDrop: '最後の未回答フォローアップは保存される会話に含まれません', diff --git a/src/client/locales-ko.ts b/src/client/locales-ko.ts index 331f6161..a6d9348f 100644 --- a/src/client/locales-ko.ts +++ b/src/client/locales-ko.ts @@ -341,6 +341,8 @@ export const ko: Record = { sideChatThreads: '스레드 전환 / 새로 만들기', sideChatSave: '새 세션으로 저장', sideChatSaveTitle: '이 스레드를 최상위 세션으로 승격하여 주 세션 목록에 표시합니다', + sideChatArchive: '이 사이드 대화 보관(세션 목록의 "보관됨 표시"에서 다시 찾을 수 있습니다)', + sideChatArchiveRunning: '이 스레드가 실행 중입니다 — 중지한 후 보관하세요', sideChatSaved: '새 세션으로 저장됨', sideChatNoTurn: '최소 한 턴의 대화를 완료해야 저장할 수 있습니다', sideChatPendingDrop: '마지막으로 완료되지 않은 후속 질문은 새 세션에 포함되지 않습니다', diff --git a/src/client/locales-nl.ts b/src/client/locales-nl.ts index eef2a842..bee318dc 100644 --- a/src/client/locales-nl.ts +++ b/src/client/locales-nl.ts @@ -347,6 +347,8 @@ export const nl: Record = { sideChatThreads: 'Thread wisselen / nieuw', sideChatSave: 'Opslaan als nieuwe sessie', 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', 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', diff --git a/src/client/locales-pl.ts b/src/client/locales-pl.ts index 6bc28db2..658314d3 100644 --- a/src/client/locales-pl.ts +++ b/src/client/locales-pl.ts @@ -351,6 +351,8 @@ export const pl: Record = { sideChatThreads: 'Przełącz wątek / nowy', sideChatSave: 'Zapisz jako nową sesję', 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ą', 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', diff --git a/src/client/locales-pt.ts b/src/client/locales-pt.ts index e4c5f26a..22d37691 100644 --- a/src/client/locales-pt.ts +++ b/src/client/locales-pt.ts @@ -332,6 +332,8 @@ export const pt: Record = { sideChatThreads: 'Alternar tópico / novo', sideChatSave: 'Salvar como nova sessão', 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', 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', diff --git a/src/client/locales-ru.ts b/src/client/locales-ru.ts index 54a4c9e4..13672599 100644 --- a/src/client/locales-ru.ts +++ b/src/client/locales-ru.ts @@ -347,6 +347,8 @@ export const ru: Record = { sideChatThreads: 'Сменить поток / новый', sideChatSave: 'Сохранить как новую сессию', sideChatSaveTitle: 'Повысить поток до сессии верхнего уровня в основном списке сессий', + sideChatArchive: 'Архивировать этот боковой диалог (найти снова можно через «Показать архивированные» в списке сессий)', + sideChatArchiveRunning: 'Этот поток выполняется — остановите его перед архивацией', sideChatSaved: 'Сохранено как новая сессия', sideChatNoTurn: 'Сохранение доступно после первого завершённого хода', sideChatPendingDrop: 'Последний незавершённый уточняющий вопрос не попадёт в сохранённую сессию', diff --git a/src/client/locales-sv.ts b/src/client/locales-sv.ts index 1c0019cf..f4f655c0 100644 --- a/src/client/locales-sv.ts +++ b/src/client/locales-sv.ts @@ -332,6 +332,8 @@ export const sv: Record = { sideChatThreads: 'Byt tråd / ny', sideChatSave: 'Spara som ny session', 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', 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', diff --git a/src/client/locales-th.ts b/src/client/locales-th.ts index 54fc3c0d..68927162 100644 --- a/src/client/locales-th.ts +++ b/src/client/locales-th.ts @@ -349,6 +349,8 @@ export const th: Record = { sideChatThreads: 'สลับเธรด / ใหม่', sideChatSave: 'บันทึกเป็นเซสชันใหม่', sideChatSaveTitle: 'เลื่อนเธรดนี้เป็นเซสชันระดับบนสุดในรายการเซสชันหลัก', + sideChatArchive: 'เก็บถาวรบทสนทนาข้างนี้ (ค้นหาอีกครั้งได้จาก “แสดงรายการที่เก็บถาวร” ในรายการเซสชัน)', + sideChatArchiveRunning: 'เธรดนี้กำลังทำงาน — หยุดก่อนเก็บถาวร', sideChatSaved: 'บันทึกเป็นเซสชันใหม่แล้ว', sideChatNoTurn: 'การบันทึกพร้อมใช้งานหลังจากรอบแรกเสร็จสมบูรณ์', sideChatPendingDrop: 'การติดตามที่ยังไม่ได้ตอบครั้งสุดท้ายจะไม่รวมในเซสชันที่บันทึก', diff --git a/src/client/locales-tr.ts b/src/client/locales-tr.ts index 38173fe9..6d298e7f 100644 --- a/src/client/locales-tr.ts +++ b/src/client/locales-tr.ts @@ -349,6 +349,8 @@ export const tr: Record = { sideChatThreads: 'İş parçacığını değiştir / yeni', sideChatSave: 'Yeni oturum olarak kaydet', 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', sideChatSaved: 'Yeni oturum olarak kaydedildi', sideChatNoTurn: 'Kaydetme ilk tamamlanan turdan sonra kullanılabilir', sideChatPendingDrop: 'Son yanıtlanmamış devam sorusu kaydedilen oturuma dahil edilmez', diff --git a/src/client/locales-vi.ts b/src/client/locales-vi.ts index ebfd8647..5283efcd 100644 --- a/src/client/locales-vi.ts +++ b/src/client/locales-vi.ts @@ -349,6 +349,8 @@ export const vi: Record = { sideChatThreads: 'Chuyển luồng / mới', sideChatSave: 'Lưu thành phiên mới', 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ữ', 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', diff --git a/src/client/locales-zh-HK.ts b/src/client/locales-zh-HK.ts index d89b8d65..e8aea884 100644 --- a/src/client/locales-zh-HK.ts +++ b/src/client/locales-zh-HK.ts @@ -364,6 +364,8 @@ export const zhHK: Record = { sideChatThreads: '切換執行緒 / 新增', sideChatSave: '儲存為新工作階段', sideChatSaveTitle: '把該執行緒提升為頂層工作階段,出現在主工作階段列表中', + sideChatArchive: '歸檔這條側邊對話(在工作階段列表的「顯示已歸檔」裡可找回)', + sideChatArchiveRunning: '該執行緒正在執行,停止後才能歸檔', sideChatSaved: '已儲存為新工作階段', sideChatNoTurn: '至少完成一輪對話後才能儲存', sideChatPendingDrop: '最後一則未完成的追問不會包含在新工作階段中', diff --git a/src/client/locales-zh-MO.ts b/src/client/locales-zh-MO.ts index ec636790..cd47a9c9 100644 --- a/src/client/locales-zh-MO.ts +++ b/src/client/locales-zh-MO.ts @@ -364,6 +364,8 @@ export const zhMO: Record = { sideChatThreads: '切換執行緒 / 新增', sideChatSave: '儲存為新工作階段', sideChatSaveTitle: '把該執行緒提升為頂層工作階段,出現在主工作階段列表中', + sideChatArchive: '歸檔這條側邊對話(在工作階段列表的「顯示已歸檔」裡可找回)', + sideChatArchiveRunning: '該執行緒正在執行,停止後才能歸檔', sideChatSaved: '已儲存為新工作階段', sideChatNoTurn: '至少完成一輪對話後才能儲存', sideChatPendingDrop: '最後一則未完成的追問不會包含在新工作階段中', diff --git a/src/client/locales-zh-TW.ts b/src/client/locales-zh-TW.ts index 293911a9..f520d801 100644 --- a/src/client/locales-zh-TW.ts +++ b/src/client/locales-zh-TW.ts @@ -364,6 +364,8 @@ export const zhTW: Record = { sideChatThreads: '切換執行緒 / 新增', sideChatSave: '儲存為新工作階段', sideChatSaveTitle: '把該執行緒提升為頂層工作階段,出現在主工作階段列表中', + sideChatArchive: '歸檔這條側邊對話(在工作階段列表的「顯示已歸檔」裡可找回)', + sideChatArchiveRunning: '該執行緒正在執行,停止後才能歸檔', sideChatSaved: '已儲存為新工作階段', sideChatNoTurn: '至少完成一輪對話後才能儲存', sideChatPendingDrop: '最後一則未完成的追問不會包含在新工作階段中', diff --git a/src/client/locales.ts b/src/client/locales.ts index 632591fa..ae8e4814 100644 --- a/src/client/locales.ts +++ b/src/client/locales.ts @@ -361,6 +361,8 @@ export const zh = { sideChatThreads: '切换线程 / 新建', sideChatSave: '保存为新会话', sideChatSaveTitle: '把该线程提升为顶层会话,出现在主会话列表中', + sideChatArchive: '归档这条侧边对话(在会话列表的「显示已归档」里可找回)', + sideChatArchiveRunning: '该线程正在运行,停止后才能归档', sideChatSaved: '已保存为新会话', sideChatNoTurn: '至少完成一轮对话后才能保存', sideChatPendingDrop: '最后一条未完成的追问不会包含在新会话中', @@ -897,6 +899,8 @@ export const en: Record = { sideChatThreads: 'Switch thread / new', sideChatSave: 'Save as new session', 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', 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', diff --git a/tests/sidechat-view.spec.tsx b/tests/sidechat-view.spec.tsx index 61051691..3e925d80 100644 --- a/tests/sidechat-view.spec.tsx +++ b/tests/sidechat-view.spec.tsx @@ -106,6 +106,55 @@ function makeCtx(store: ReturnType, connection?: Connection): } as unknown as Context } +/** The archive set feed + the archiving service — the two host faces the + * header's archive button reaches for, neither of them on the plugin's own + * context type (`workspaces` is the session list, `uiWorkspace` the session + * surface), so both ride the same `get` probe the view uses. */ +interface ArchiveHost { + archivedIds: string[] + archiveSession: ReturnType + betterSidebar: { updateTab: ReturnType; openTab: ReturnType } +} + +function makeArchiveHost(archivedIds: string[] = []): ArchiveHost { + return { + archivedIds, + archiveSession: vi.fn(async () => {}), + betterSidebar: { updateTab: vi.fn(), openTab: vi.fn() }, + } +} + +/** makeCtx plus the archive host faces (the archive cases' whole subject). */ +function makeArchiveCtx(store: ReturnType, host: ArchiveHost): Context { + return { + sessions: { list: store }, + get: (key: string) => { + if (key === 'betterSidebar') return host.betterSidebar + if (key === 'workspaces') { + return { list: { getSnapshot: () => ({ archivedSessionIds: host.archivedIds }), subscribe: vi.fn(() => () => {}) } } + } + if (key === 'uiWorkspace') return { archiveSession: host.archiveSession } + return undefined + }, + } as unknown as Context +} + +/** The header archive button (its aria-label is the only such name in the view). */ +function archiveButton(container: HTMLElement): HTMLButtonElement { + const button = container.querySelector('button[aria-label="归档这条侧边对话(在会话列表的「显示已归档」里可找回)"]') + if (button === null) throw new Error('the header archive button is absent') + return button +} + +/** Flush the click's promise chain (the archive request and the rebind). */ +async function clickArchive(button: HTMLButtonElement): Promise { + await act(async () => { + button.click() + await Promise.resolve() + await Promise.resolve() + }) +} + function jsonResponse(value: unknown): Response { return { ok: true, status: 200, json: async () => value } as unknown as Response } @@ -206,3 +255,80 @@ describe('SideChatView rendering', () => { connected.unmount() }) }) + +describe('SideChatView archive', () => { + it('archives the bound thread with stopActivity and rebinds the tab 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 }, + t2: { id: 't2', displayTitle: 'Side: 线程二', origin: 'subagent', parentId: 'root', running: false }, + }, + // The host's own catalog carries the creation order the fallback ranks by. + projectionsBySession: { + root: { + values: { + subagentCatalog: [ + { id: 't1', createdAt: 1_000, mode: 'continuable', label: 'Side: 线程一' }, + { id: 't2', createdAt: 2_000, mode: 'continuable', label: 'Side: 线程二' }, + ], + }, + state: 'ready', + error: null, + }, + }, + }) + const props = viewProps(makeArchiveCtx(store, host)) + const { container, unmount } = renderRoot(createElement(SideChatView, props)) + await act(async () => {}) // flush the initial transcript pull + + await clickArchive(archiveButton(container)) + + // 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). + expect(host.betterSidebar.updateTab).toHaveBeenCalledTimes(1) + expect(host.betterSidebar.updateTab).toHaveBeenCalledWith('tab1', { meta: { threadId: 't2' } }) + unmount() + }) + + 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 { container, unmount } = renderRoot(createElement(SideChatView, props)) + await act(async () => {}) // flush the initial transcript pull + + const button = archiveButton(container) + expect(button.disabled).toBe(true) + // A disabled button swallows the click: no request, no rebind. + await clickArchive(button) + expect(host.archiveSession).not.toHaveBeenCalled() + expect(host.betterSidebar.updateTab).not.toHaveBeenCalled() + unmount() + }) + + 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 { container, unmount } = renderRoot(createElement(SideChatView, props)) + await act(async () => {}) // flush the initial transcript pull + + await clickArchive(archiveButton(container)) + + expect(host.archiveSession).toHaveBeenCalledWith('t1', { stopActivity: true }) + // `{}` rather than a dangling threadId: the panel unbinds instead of + // staying bound to the session the host just archived. + expect(host.betterSidebar.updateTab).toHaveBeenCalledTimes(1) + expect(host.betterSidebar.updateTab).toHaveBeenCalledWith('tab1', { meta: {} }) + unmount() + }) +})