| 1 | import React, { useEffect, useRef, useState } from "react"; |
| 2 | import { Folder, ListFilter, RefreshCw, Search, Trash2 } from "lucide-react"; |
| 3 | import { api } from "./api"; |
| 4 | import { InlineSelect } from "./inline-select"; |
| 5 | import "./cli-sessions.css"; |
| 6 | |
| 7 | export const desktopSessionRequest = (path, options = {}) => api("/cli" + path, options.body); |
| 8 | export const sessionsChanged = () => window.dispatchEvent(new Event("cage-cli-sessions-changed")); |
| 9 | const archiveDate = new Intl.DateTimeFormat("zh-CN", {year:"numeric",month:"long",day:"numeric",hour:"2-digit",minute:"2-digit",hour12:false}); |
| 10 | const projectLabel = path => path.replaceAll("\\", "/").split("/").filter(Boolean).at(-1) || path; |
| 11 | const archiveFilters = {all:"全部会话",pinned:"已置顶",deleting:"删除未完成"}; |
| 12 | |
| 13 | function ArchiveSelection({ items, selected, onToggle, disabled, label, children }) { |
| 14 | const input = useRef(null); |
| 15 | const count = items.filter(item => selected.has(item.id)).length; |
| 16 | useEffect(() => { input.current.indeterminate = count > 0 && count < items.length; }, [count, items.length]); |
| 17 | return <label className="archive-selection check-line"> |
| 18 | <input ref={input} type="checkbox" aria-label={label} checked={items.length > 0 && count === items.length} |
| 19 | disabled={disabled} onChange={() => onToggle(items)} /> |
| 20 | {children && <span>{children}</span>} |
| 21 | </label>; |
| 22 | } |
| 23 | |
| 24 | export function useCLISessions(enabled, visible) { |
| 25 | const [sessions, setSessions] = useState([]); |
| 26 | const [error, setError] = useState(""); |
| 27 | const [loading, setLoading] = useState(false); |
| 28 | const [revision, setRevision] = useState(0); |
| 29 | const refresh = () => { setLoading(true); setRevision(value => value + 1); }; |
| 30 | useEffect(() => { |
| 31 | window.addEventListener("cage-cli-sessions-changed", refresh); |
| 32 | return () => window.removeEventListener("cage-cli-sessions-changed", refresh); |
| 33 | }, []); |
| 34 | useEffect(() => { |
| 35 | if (!enabled || !visible) { setLoading(false); return; } |
| 36 | let live = true, timer; |
| 37 | const load = async () => { |
| 38 | setLoading(true); |
| 39 | try { |
| 40 | const result = await desktopSessionRequest("/sessions"); |
| 41 | if (!live) return; |
| 42 | setSessions((result.sessions || []).map(session => result.notice ? { ...session, active: false, running: false } : session)); |
| 43 | setError(result.notice || ""); |
| 44 | } catch (error) { |
| 45 | if (live) { |
| 46 | setError(error.message); |
| 47 | setSessions(previous => previous.map(session => ({ ...session, active: false, running: false }))); |
| 48 | } |
| 49 | } finally { if (live) setLoading(false); } |
| 50 | if (live) timer = setTimeout(load, 5000); |
| 51 | }; |
| 52 | void load(); |
| 53 | return () => { live = false; clearTimeout(timer); }; |
| 54 | }, [enabled, visible, revision]); |
| 55 | return { sessions, error, loading, refresh }; |
| 56 | } |
| 57 | |
| 58 | export function ArchivedSessions({ request = desktopSessionRequest, ready, onRestored }) { |
| 59 | const [sessions, setSessions] = useState(null); |
| 60 | const [error, setError] = useState(""); |
| 61 | const [readError, setReadError] = useState(""); |
| 62 | const [busy, setBusy] = useState(false); |
| 63 | const [confirming, setConfirming] = useState(""); |
| 64 | const [revision, setRevision] = useState(0); |
| 65 | const [query, setQuery] = useState(""); |
| 66 | const [filter, setFilter] = useState("all"); |
| 67 | const [project, setProject] = useState(""); |
| 68 | const [selected, setSelected] = useState(new Set()); |
| 69 | const [bulkConfirm, setBulkConfirm] = useState(null); |
| 70 | const [resultMessage, setResultMessage] = useState(""); |
| 71 | const [progress, setProgress] = useState(null); |
| 72 | useEffect(() => { |
| 73 | let live = true, timer; |
| 74 | const load = async () => { |
| 75 | try { |
| 76 | const result = await request("/sessions?archived=true"); |
| 77 | if (live) { |
| 78 | const list = result.sessions || []; |
| 79 | setSessions(list); setReadError(result.notice || ""); |
| 80 | setSelected(previous => new Set([...previous].filter(id => list.some(session => session.id === id)))); |
| 81 | } |
| 82 | } catch (error) { if (live) setReadError(error.message); } |
| 83 | if (live) timer = setTimeout(load, 5000); |
| 84 | }; |
| 85 | if (!busy) void load(); |
| 86 | return () => { live = false; clearTimeout(timer); }; |
| 87 | }, [request, revision, busy]); |
| 88 | const change = async (items, operation) => { |
| 89 | if (busy) return; |
| 90 | setBusy(true); setError(""); setResultMessage(""); |
| 91 | setProgress({done:0, total:items.length}); |
| 92 | const completed = new Set(), failures = []; |
| 93 | try { |
| 94 | for (const session of items) { |
| 95 | try { |
| 96 | await request("/sessions/" + session.id + "/" + operation, {body:operation === "purge" ? {confirm:true} : {}}); |
| 97 | completed.add(session.id); |
| 98 | } catch (error) { failures.push({session, message:error.message}); } |
| 99 | setProgress({done:completed.size + failures.length, total:items.length}); |
| 100 | } |
| 101 | setSessions(list => list.filter(item => !completed.has(item.id))); |
| 102 | setSelected(previous => new Set([...previous].filter(id => !completed.has(id)))); |
| 103 | if (completed.size) { |
| 104 | setConfirming(""); |
| 105 | setResultMessage(`已${operation === "restore" ? "取消归档" : "永久删除"} ${completed.size} 个会话。`); |
| 106 | sessionsChanged(); |
| 107 | } |
| 108 | setBulkConfirm(null); |
| 109 | if (failures.length) setError(`${failures.length} 个会话处理失败:${failures.map(({session,message}) => `“${session.title || "新会话"}”:${message}`).join(";")}`); |
| 110 | if (operation === "restore") for (const id of completed) onRestored?.(id); |
| 111 | } finally { setBusy(false); setProgress(null); } |
| 112 | }; |
| 113 | const resetSelection = (setter, value) => { |
| 114 | setter(value); setSelected(new Set()); setBulkConfirm(null); setConfirming(""); setResultMessage(""); |
| 115 | }; |
| 116 | const toggleSelection = items => { |
| 117 | const all = items.every(item => selected.has(item.id)); |
| 118 | setSelected(previous => { |
| 119 | const next = new Set(previous); |
| 120 | for (const item of items) { if (all) next.delete(item.id); else next.add(item.id); } |
| 121 | return next; |
| 122 | }); |
| 123 | setBulkConfirm(null); setConfirming(""); setResultMessage(""); |
| 124 | }; |
| 125 | const projects = [...new Set(sessions?.map(session => session.workspace) || [])]; |
| 126 | const selectedProject = projects.includes(project) ? project : ""; |
| 127 | const search = query.trim().toLocaleLowerCase(); |
| 128 | const groups = new Map(); |
| 129 | for (const session of sessions || []) { |
| 130 | if (selectedProject && session.workspace !== selectedProject) continue; |
| 131 | if (filter === "pinned" && !session.pinned || filter === "deleting" && !session.deleting) continue; |
| 132 | if (search && !(session.title + " " + session.workspace).toLocaleLowerCase().includes(search)) continue; |
| 133 | if (!groups.has(session.workspace)) groups.set(session.workspace, []); |
| 134 | groups.get(session.workspace).push(session); |
| 135 | } |
| 136 | const visible = [...groups.values()].flat(); |
| 137 | const selectedItems = visible.filter(session => selected.has(session.id)); |
| 138 | const hasDeleting = selectedItems.some(session => session.deleting); |
| 139 | return <section className="archived-sessions" aria-label="已归档会话"> |
| 140 | <h2 className="archive-page-title">已归档会话</h2> |
| 141 | <div className="archive-toolbar"> |
| 142 | <div className="archive-search"><Search size={18} aria-hidden="true" /> |
| 143 | <input type="search" aria-label="搜索已归档的会话" placeholder="搜索已归档的会话" value={query} disabled={busy} onChange={event => resetSelection(setQuery, event.target.value)} /> |
| 144 | </div> |
| 145 | <InlineSelect aria-label="会话筛选" value={filter} disabled={busy} onValueChange={value => resetSelection(setFilter, value)} |
| 146 | displayLabel={<span className="archive-filter-label"><ListFilter size={17}/><span>{archiveFilters[filter]}</span></span>}> |
| 147 | {Object.entries(archiveFilters).map(([value,label]) => <option key={value} value={value}>{label}</option>)} |
| 148 | </InlineSelect> |
| 149 | <InlineSelect aria-label="项目筛选" value={selectedProject} disabled={busy} onValueChange={value => resetSelection(setProject, value)} |
| 150 | displayLabel={<span className="archive-filter-label"><Folder size={17}/><span>{selectedProject ? projectLabel(selectedProject) : "所有项目"}</span></span>}> |
| 151 | <option value="">所有项目</option> |
| 152 | {projects.map(path => <option key={path} value={path}>{projects.some(other => other !== path && projectLabel(other) === projectLabel(path)) ? path : projectLabel(path)}</option>)} |
| 153 | </InlineSelect> |
| 154 | </div> |
| 155 | {visible.length > 0 && <div className="archive-bulk-toolbar" role="group" aria-label="批量处理会话"> |
| 156 | <ArchiveSelection items={visible} selected={selected} onToggle={toggleSelection} disabled={busy} label="全选当前筛选结果">全选</ArchiveSelection> |
| 157 | <span className="archive-note">已选择 {selectedItems.length} 个会话</span> |
| 158 | <div className="archived-session-actions"> |
| 159 | <button className="archive-button" disabled={busy || !selectedItems.length} onClick={() => resetSelection(setSelected, new Set())}>清空选择</button> |
| 160 | <button className="archive-restore" disabled={busy || !selectedItems.length || hasDeleting} onClick={() => change(selectedItems, "restore")}>批量取消归档</button> |
| 161 | <button className="archive-button archive-delete" disabled={busy || !ready || !selectedItems.length} onClick={() => { setConfirming(""); setBulkConfirm(selectedItems); }}>批量删除</button> |
| 162 | </div> |
| 163 | {hasDeleting && <p className="archive-note archive-bulk-note">所选会话包含删除未完成项,请取消选择这些会话后再取消归档。</p>} |
| 164 | </div>} |
| 165 | {progress && <p role="status" className="archive-note">正在处理 {progress.done} / {progress.total} 个会话…</p>} |
| 166 | {resultMessage && <p role="status" className="archive-note">{resultMessage}</p>} |
| 167 | {bulkConfirm && <div className="archive-confirm" role="group" aria-label="确认批量永久删除会话"> |
| 168 | <p>永久删除所选的 {bulkConfirm.length} 个会话及其 Claude Code 原始对话和子代理记录?此操作无法撤销。</p> |
| 169 | <div className="archived-session-actions"><button className="archive-button" disabled={busy} onClick={() => setBulkConfirm(null)}>取消</button> |
| 170 | <button className="archive-button archive-delete" disabled={busy || !ready} onClick={() => change(bulkConfirm, "purge")}>永久删除所选会话</button></div> |
| 171 | </div>} |
| 172 | {(error || readError) && <div role="alert" className="archive-error">{error || readError} |
| 173 | {readError && <button className="archive-button" onClick={() => setRevision(value => value + 1)} disabled={busy}>重新读取</button>} |
| 174 | </div>} |
| 175 | {!sessions && !readError && <p role="status">正在读取…</p>} |
| 176 | {sessions?.length === 0 && <p className="archive-note">暂无已归档会话。</p>} |
| 177 | {Boolean(sessions?.length) && !groups.size && <p className="archive-note">没有符合筛选条件的已归档会话。</p>} |
| 178 | {[...groups].map(([path,items]) => <section className="archive-project" key={path} aria-label={projectLabel(path) + "的已归档会话"}> |
| 179 | <header className="archive-project-heading"> |
| 180 | <ArchiveSelection items={items} selected={selected} onToggle={toggleSelection} disabled={busy} label={`全选项目 ${path} 的当前筛选结果`} /> |
| 181 | <Folder size={18}/><h3 title={path}>{projectLabel(path)}</h3><span>{items.length} 个会话</span></header> |
| 182 | <div className="archive-project-list">{items.map(session => { |
| 183 | const date = new Date(session.updated_at); |
| 184 | return <article className="archived-session" key={session.id}> |
| 185 | <div className="archived-session-row"> |
| 186 | <ArchiveSelection items={[session]} selected={selected} onToggle={toggleSelection} disabled={busy} label={`选择会话 ${session.title || "新会话"}`} /> |
| 187 | <div className="archived-session-title"><h4>{session.title || "新会话"}</h4> |
| 188 | {!Number.isNaN(date.valueOf()) && <time dateTime={session.updated_at}>{archiveDate.format(date)}</time>} |
| 189 | </div> |
| 190 | <div className="archived-session-actions"> |
| 191 | <button className="archive-icon-button" aria-label={session.deleting ? "重试删除" : "删除会话"} title={session.deleting ? "重试删除" : "删除会话"} |
| 192 | disabled={busy || !ready} onClick={() => { setBulkConfirm(null); session.deleting ? change([session], "purge") : setConfirming(session.id); }}> |
| 193 | {session.deleting ? <RefreshCw size={16}/> : <Trash2 size={16}/>}</button> |
| 194 | <button className="archive-restore" disabled={busy || session.deleting} onClick={() => change([session], "restore")}>取消归档</button> |
| 195 | </div> |
| 196 | </div> |
| 197 | {session.deleting && <p className="archive-note">永久删除尚未完成,连接恢复后可重试。</p>} |
| 198 | {confirming === session.id && <div className="archive-confirm" role="group" aria-label="确认永久删除会话"> |
| 199 | <p>永久删除“{session.title || "新会话"}”及其 Claude Code 原始对话和子代理记录?此操作无法撤销。</p> |
| 200 | <div className="archived-session-actions"><button className="archive-button" disabled={busy} onClick={() => setConfirming("")}>取消</button> |
| 201 | <button className="archive-button archive-delete" disabled={busy || !ready} onClick={() => change([session], "purge")}>永久删除</button></div> |
| 202 | </div>} |
| 203 | </article>; |
| 204 | })}</div> |
| 205 | </section>)} |
| 206 | {!ready && <p className="archive-note">启动主机环境后可以永久删除 Claude Code 原始记录。</p>} |
| 207 | </section>; |
| 208 | } |