Merge pull request #840 from Waser750/feat/sidechat-archive-thread

feat(sidechat): archive the bound side chat thread from the header
This commit is contained in:
Atlas Zeng authored and GitHub committed 2026-10-05 01:50:41 +08:00
commit bbae8b812c
22 files changed
+276 -5

No files matched your search

+108 -5
View File
@@ -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<void>
}
/** 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<string | null>(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<void> => {
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<void> => {
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: {
>
<IconSaveOutline16 />
</button>
<button
type="button"
className={css.sidechatIconBtn}
onClick={() => void handleArchive()}
disabled={running || busy !== null}
title={running ? t('sideChatArchiveRunning') : t('sideChatArchive')}
aria-label={t('sideChatArchive')}
>
<IconArchiveOutlineRegular size={16} />
</button>
</div>
{connectionState !== undefined && connectionState !== 'connected' && (
<ConnectionIndicator
+2
View File
@@ -350,6 +350,8 @@ export const ar: Record<string, string> = {
sideChatThreads: 'تبديل خيط / جديد',
sideChatSave: 'حفظ كجلسة جديدة',
sideChatSaveTitle: 'ترقية هذا الخيط إلى جلسة عالية المستوى في قائمة الجلسات الرئيسية',
sideChatArchive: 'أرشفة هذه المحادثة الجانبية (يمكن العثور عليها مجددًا عبر «إظهار المؤرشفة» في قائمة الجلسات)',
sideChatArchiveRunning: 'هذا الخيط قيد التشغيل — أوقفه قبل الأرشفة',
sideChatSaved: 'تم الحفظ كجلسة جديدة',
sideChatNoTurn: 'الحفظ متاح بعد أول دور مكتمل',
sideChatPendingDrop: 'لن يُضمَّ آخر متابعة لم يُجَب عنها في الجلسة المحفوظة',
+2
View File
@@ -335,6 +335,8 @@ export const de: Record<string, string> = {
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',
+2
View File
@@ -342,6 +342,8 @@ export const fr: Record<string, string> = {
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',
+2
View File
@@ -349,6 +349,8 @@ export const hi: Record<string, string> = {
sideChatThreads: 'थ्रेड स्विच / नया',
sideChatSave: 'नए सत्र के रूप में सहेजें',
sideChatSaveTitle: 'इस थ्रेड को मुख्य सत्र सूची में शीर्ष-स्तरीय सत्र में प्रमोट करें',
sideChatArchive: 'इस साइड बातचीत को संग्रहित करें (सत्र सूची में “संग्रहित दिखाएँ” से दोबारा पा सकते हैं)',
sideChatArchiveRunning: 'यह थ्रेड चल रहा है — संग्रहित करने से पहले इसे रोकें',
sideChatSaved: 'नए सत्र के रूप में सहेजा',
sideChatNoTurn: 'पहला टर्न पूरा होने के बाद सहेजना उपलब्ध',
sideChatPendingDrop: 'अंतिम अनुत्तरित फ़ॉलो-अप सहेजे गए सत्र में शामिल नहीं होगा',
+2
View File
@@ -347,6 +347,8 @@ export const id: Record<string, string> = {
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',
+2
View File
@@ -340,6 +340,8 @@ export const it: Record<string, string> = {
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',
+2
View File
@@ -349,6 +349,8 @@ export const ja: Record<string, string> = {
sideChatThreads: 'スレッド切替 / 新規',
sideChatSave: '新規会話として保存',
sideChatSaveTitle: 'このスレッドをトップレベルの会話に昇格、メイン会話リストに表示',
sideChatArchive: 'このサイド会話をアーカイブ(セッションリストの「アーカイブを表示」から再表示できます)',
sideChatArchiveRunning: 'このスレッドは実行中です — 停止してからアーカイブしてください',
sideChatSaved: '新規会話として保存しました',
sideChatNoTurn: '最初のターンを完了してから保存可能',
sideChatPendingDrop: '最後の未回答フォローアップは保存される会話に含まれません',
+2
View File
@@ -341,6 +341,8 @@ export const ko: Record<string, string> = {
sideChatThreads: '스레드 전환 / 새로 만들기',
sideChatSave: '새 세션으로 저장',
sideChatSaveTitle: '이 스레드를 최상위 세션으로 승격하여 주 세션 목록에 표시합니다',
sideChatArchive: '이 사이드 대화 보관(세션 목록의 "보관됨 표시"에서 다시 찾을 수 있습니다)',
sideChatArchiveRunning: '이 스레드가 실행 중입니다 — 중지한 후 보관하세요',
sideChatSaved: '새 세션으로 저장됨',
sideChatNoTurn: '최소 한 턴의 대화를 완료해야 저장할 수 있습니다',
sideChatPendingDrop: '마지막으로 완료되지 않은 후속 질문은 새 세션에 포함되지 않습니다',
+2
View File
@@ -347,6 +347,8 @@ export const nl: Record<string, string> = {
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',
+2
View File
@@ -351,6 +351,8 @@ export const pl: Record<string, string> = {
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',
+2
View File
@@ -332,6 +332,8 @@ export const pt: Record<string, string> = {
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',
+2
View File
@@ -347,6 +347,8 @@ export const ru: Record<string, string> = {
sideChatThreads: 'Сменить поток / новый',
sideChatSave: 'Сохранить как новую сессию',
sideChatSaveTitle: 'Повысить поток до сессии верхнего уровня в основном списке сессий',
sideChatArchive: 'Архивировать этот боковой диалог (найти снова можно через «Показать архивированные» в списке сессий)',
sideChatArchiveRunning: 'Этот поток выполняется — остановите его перед архивацией',
sideChatSaved: 'Сохранено как новая сессия',
sideChatNoTurn: 'Сохранение доступно после первого завершённого хода',
sideChatPendingDrop: 'Последний незавершённый уточняющий вопрос не попадёт в сохранённую сессию',
+2
View File
@@ -332,6 +332,8 @@ export const sv: Record<string, string> = {
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',
+2
View File
@@ -349,6 +349,8 @@ export const th: Record<string, string> = {
sideChatThreads: 'สลับเธรด / ใหม่',
sideChatSave: 'บันทึกเป็นเซสชันใหม่',
sideChatSaveTitle: 'เลื่อนเธรดนี้เป็นเซสชันระดับบนสุดในรายการเซสชันหลัก',
sideChatArchive: 'เก็บถาวรบทสนทนาข้างนี้ (ค้นหาอีกครั้งได้จาก “แสดงรายการที่เก็บถาวร” ในรายการเซสชัน)',
sideChatArchiveRunning: 'เธรดนี้กำลังทำงาน — หยุดก่อนเก็บถาวร',
sideChatSaved: 'บันทึกเป็นเซสชันใหม่แล้ว',
sideChatNoTurn: 'การบันทึกพร้อมใช้งานหลังจากรอบแรกเสร็จสมบูรณ์',
sideChatPendingDrop: 'การติดตามที่ยังไม่ได้ตอบครั้งสุดท้ายจะไม่รวมในเซสชันที่บันทึก',
+2
View File
@@ -349,6 +349,8 @@ export const tr: Record<string, string> = {
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',
+2
View File
@@ -349,6 +349,8 @@ export const vi: Record<string, string> = {
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',
+2
View File
@@ -364,6 +364,8 @@ export const zhHK: Record<string, string> = {
sideChatThreads: '切換執行緒 / 新增',
sideChatSave: '儲存為新工作階段',
sideChatSaveTitle: '把該執行緒提升為頂層工作階段,出現在主工作階段列表中',
sideChatArchive: '歸檔這條側邊對話(在工作階段列表的「顯示已歸檔」裡可找回)',
sideChatArchiveRunning: '該執行緒正在執行,停止後才能歸檔',
sideChatSaved: '已儲存為新工作階段',
sideChatNoTurn: '至少完成一輪對話後才能儲存',
sideChatPendingDrop: '最後一則未完成的追問不會包含在新工作階段中',
+2
View File
@@ -364,6 +364,8 @@ export const zhMO: Record<string, string> = {
sideChatThreads: '切換執行緒 / 新增',
sideChatSave: '儲存為新工作階段',
sideChatSaveTitle: '把該執行緒提升為頂層工作階段,出現在主工作階段列表中',
sideChatArchive: '歸檔這條側邊對話(在工作階段列表的「顯示已歸檔」裡可找回)',
sideChatArchiveRunning: '該執行緒正在執行,停止後才能歸檔',
sideChatSaved: '已儲存為新工作階段',
sideChatNoTurn: '至少完成一輪對話後才能儲存',
sideChatPendingDrop: '最後一則未完成的追問不會包含在新工作階段中',
+2
View File
@@ -364,6 +364,8 @@ export const zhTW: Record<string, string> = {
sideChatThreads: '切換執行緒 / 新增',
sideChatSave: '儲存為新工作階段',
sideChatSaveTitle: '把該執行緒提升為頂層工作階段,出現在主工作階段列表中',
sideChatArchive: '歸檔這條側邊對話(在工作階段列表的「顯示已歸檔」裡可找回)',
sideChatArchiveRunning: '該執行緒正在執行,停止後才能歸檔',
sideChatSaved: '已儲存為新工作階段',
sideChatNoTurn: '至少完成一輪對話後才能儲存',
sideChatPendingDrop: '最後一則未完成的追問不會包含在新工作階段中',
+4
View File
@@ -361,6 +361,8 @@ export const zh = {
sideChatThreads: '切换线程 / 新建',
sideChatSave: '保存为新会话',
sideChatSaveTitle: '把该线程提升为顶层会话,出现在主会话列表中',
sideChatArchive: '归档这条侧边对话(在会话列表的「显示已归档」里可找回)',
sideChatArchiveRunning: '该线程正在运行,停止后才能归档',
sideChatSaved: '已保存为新会话',
sideChatNoTurn: '至少完成一轮对话后才能保存',
sideChatPendingDrop: '最后一条未完成的追问不会包含在新会话中',
@@ -897,6 +899,8 @@ export const en: Record<keyof typeof zh, string> = {
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',
+126
View File
@@ -106,6 +106,55 @@ function makeCtx(store: ReturnType<typeof makeStore>, 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<typeof vi.fn>
betterSidebar: { updateTab: ReturnType<typeof vi.fn>; openTab: ReturnType<typeof vi.fn> }
}
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<typeof makeStore>, 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<HTMLButtonElement>('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<void> {
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()
})
})