From ef9487628251bced655c777111b4bb679227d02e Mon Sep 17 00:00:00 2001 From: lehhair Date: Mon, 19 Oct 2026 20:01:47 +0800 Subject: [PATCH 01/67] =?UTF-8?q?fix(reasoning):=20=E6=8A=98=E5=8F=A0?= =?UTF-8?q?=E8=A1=8C=E9=87=8C=E7=9A=84=E8=A1=8C=E5=86=85=E4=BB=A3=E7=A0=81?= =?UTF-8?q?=E5=8E=BB=E6=8E=89=E7=9B=92=E5=AD=90=EF=BC=8C=E4=B8=8D=E5=86=8D?= =?UTF-8?q?=E8=A2=AB=E8=A3=81=E6=8E=89=E4=B8=8A=E4=B8=8B=E8=BE=B9=E6=A1=86?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 折叠态是一行 20px 高、overflow-hidden + 省略号的盒子,而内联代码 chip 带 0.5px 描边 + 1px 纵向内边距 + 圆角,盒子比行高还高一点 → 上下边框被裁。 现在只在折叠态把 chip 的盒子去掉(底色/描边/内边距/圆角),保留等宽字体: [&_code]:bg-transparent [&_code]:border-0 [&_code]:px-0 [&_code]:py-0 [&_code]:rounded-none 粗体/斜体等行内样式照常渲染;展开态完全没有改动(展开时 chip 依旧有底色和描边)。 --- src/features/message/parts/ReasoningPartView.tsx | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/features/message/parts/ReasoningPartView.tsx b/src/features/message/parts/ReasoningPartView.tsx index 74639c864..632e1a91f 100644 --- a/src/features/message/parts/ReasoningPartView.tsx +++ b/src/features/message/parts/ReasoningPartView.tsx @@ -155,6 +155,9 @@ export const ReasoningPartView = memo(function ReasoningPartView({ '[&_ul]:!my-0 [&_ol]:!my-0 [&_li]:inline [&_li]:!my-0', '[&_pre]:!my-0 [&_pre]:inline', '[&_code]:inline', + // 行内代码在折叠行里只留等宽,去掉盒子(底色/描边/内边距/圆角): + // 折叠行只有 20px 高且 overflow-hidden,带盒子的 chip 会被裁掉上下边框 + '[&_code]:bg-transparent [&_code]:border-0 [&_code]:px-0 [&_code]:py-0 [&_code]:rounded-none', '[&_blockquote]:!my-0 [&_blockquote]:inline', '[&_br]:hidden', ].join(' ') From 08877a092e389198fcc77d67925ecb9c809f40bf Mon Sep 17 00:00:00 2001 From: lehhair Date: Mon, 19 Oct 2026 21:45:15 +0800 Subject: [PATCH 02/67] =?UTF-8?q?style(markdown):=20=E5=86=85=E8=81=94?= =?UTF-8?q?=E4=BB=A3=E7=A0=81=E6=94=B9=E7=94=A8=200.875em/19px=20=E7=9A=84?= =?UTF-8?q?=E8=A1=8C=E5=86=85=E9=85=8D=E6=AF=94=EF=BC=8C=E4=BF=AE=E6=AD=A3?= =?UTF-8?q?=E5=9E=82=E7=9B=B4=E4=B8=8D=E5=B1=85=E4=B8=AD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 根因不是行高:行高只把字形上下留白等比拉长,等宽字体 ascent/descent 的 不对称(13px 时 12/3)不变,实测行高 19/22/24 怎么调都不居中 - 换字号才是有效手段:13px 时拉丁偏下 2.25px、中文偏上 1.5px;降到 0.875em(14px 正文 → 12.25px)配 19px 行高后为拉丁 −1.5px / 中文 +1.5px, 两边各让一半,是偏差最小的平衡点 - 配方对齐 DeepSeek Harness 的内联代码(12px/19px + font-size:0.875em, 上下 padding 为 0),chip 高度 24px → 21px,不再显得压字 - html 渲染路径与 React 渲染路径同步修改,避免同一条消息出现两种 chip --- src/components/MarkdownRenderer.test.tsx | 18 ++++++++++++------ src/components/MarkdownRenderer.tsx | 2 +- src/components/markdownHtmlRenderer.ts | 21 ++++++++++----------- 3 files changed, 23 insertions(+), 18 deletions(-) diff --git a/src/components/MarkdownRenderer.test.tsx b/src/components/MarkdownRenderer.test.tsx index aa842aafc..f8553c406 100644 --- a/src/components/MarkdownRenderer.test.tsx +++ b/src/components/MarkdownRenderer.test.tsx @@ -101,17 +101,22 @@ describe('MarkdownRenderer', () => { render() const codeEl = screen.getByText('code') - // chip 样式:等宽 + 淡底 + 细描边 + flex 垂直居中;颜色继承正文 + // chip:等宽 + 淡底 + 细描边 + flex 垂直居中;颜色继承正文 expect(codeEl.className).toMatch(/font-mono/) expect(codeEl.className).not.toMatch(/text-text-\d/) expect(codeEl.className).toMatch(/bg-bg-200/) expect(codeEl.className).toMatch(/border-\[0\.5px\]/) expect(codeEl.className).toMatch(/rounded-md/) expect(codeEl.className).toMatch(/px-\[5px\]/) - // 纵向不能靠继承段落行高(leading-7=28px):chip 会高出一截,和正文对不上 expect(codeEl.className).toMatch(/inline-flex/) expect(codeEl.className).toMatch(/items-center/) - expect(codeEl.className).toMatch(/leading-tight/) + // 居中不是靠调行高(行高只等比拉长上下留白,字体 ascent/descent 的不对称不变), + // 而是靠字号比例:0.875em(14px 正文 → 12.25px)+ 19px 行高,实测拉丁 −1.5px / + // 中文 +1.5px,是偏差最小的平衡点(配方对齐 DeepSeek Harness 的内联代码) + expect(codeEl.className).toMatch(/leading-\[19px\]/) + expect(codeEl.className).toMatch(/text-\[0\.875em\]/) + expect(codeEl.className).not.toMatch(/pb-\[/) + expect(codeEl.className).not.toMatch(/leading-none/) expect(codeEl.className).not.toMatch(/text-accent-main/) }) @@ -122,8 +127,8 @@ describe('MarkdownRenderer', () => { expect(codeEl).toBeInTheDocument() expect(codeEl).toHaveTextContent('单行代码') expect(codeEl).toHaveClass('font-mono') - expect(codeEl).toHaveClass('bg-bg-200') expect(codeEl).toHaveClass('inline-flex') + expect(codeEl).toHaveClass('bg-bg-200') }) it('keeps inline emphasis styles on the markdown path', () => { @@ -550,9 +555,10 @@ $$ expect(paragraph.className).toMatch(/text-text-400/) const codeEl = screen.getByText('code') - // chip 也有描边(0.5px 细边),但底色不能是强调色 - expect(codeEl.className).toMatch(/border-\[0\.5px\]/) + // reasoning 里 chip 与正文同款(不是强调色、行高/内边距与正文版一致) expect(codeEl.className).not.toMatch(/bg-accent/) + expect(codeEl.className).toMatch(/leading-\[19px\]/) + expect(codeEl.className).toMatch(/text-\[0\.875em\]/) }) it('passes reasoning variant to CodeBlock', () => { diff --git a/src/components/MarkdownRenderer.tsx b/src/components/MarkdownRenderer.tsx index c998c5ad7..e1152befb 100644 --- a/src/components/MarkdownRenderer.tsx +++ b/src/components/MarkdownRenderer.tsx @@ -701,7 +701,7 @@ function renderInlineTokensToReact(tokens: unknown[], _isReasoning: boolean): Re return ( {String(item.text ?? '')} diff --git a/src/components/markdownHtmlRenderer.ts b/src/components/markdownHtmlRenderer.ts index b1c41246b..0b8f7b158 100644 --- a/src/components/markdownHtmlRenderer.ts +++ b/src/components/markdownHtmlRenderer.ts @@ -393,18 +393,17 @@ function createMarkdownHtmlRenderer(isReasoning: boolean, renderHtml: boolean) { renderer.codespan = ({ text }) => { // 内联代码 chip。要点: // 1) **文字颜色继承正文**,不自己指定:正文是 text-text-200,给主题色或更亮的 - // 色阶都会比正文突出(看着像被"特意强调");继承还有个好处——reasoning 里 - // 正文变暗时它会自动跟着变暗 - // 2) **inline-flex + items-center,纵向 padding 为 0**:靠 padding 撑高会把 - // 行盒撑起来,同一行的中文和代码基线对不齐,整行看着起伏;改成 flex 居中 - // 后,高度跟着行走,纵向只留 0 - // 3) **淡底色 + 0.5px 细描边**:底色只是比页面底色抬一档,靠描边给边界; - // 只给底色(没有描边)在各主题下都会糊在一起 - // 4) **必须显式给 leading**:段落是 leading-7(28px),inline-flex 的盒子会 - // 把这个行高继承成自己的高度,于是 chip 高 28px、文字只有 12px,看着比 - // 正文高一截。给个紧凑行高 + 1px 纵向内边距,高度才和正文文字齐平 + // 色阶都会比正文突出;继承还有个好处——reasoning 里正文变暗时它自动跟着暗 + // 2) **居中不能靠调行高**:行高只是把字形上下的留白等比拉长,字体自身 + // ascent/descent 的不对称(等宽字体 13px 时 12 / 3)一点没变,所以怎么调 + // 都不居中。4x 像素实测:13px + 行高 22px 时拉丁偏下 2.25px、中文偏上 + // 1.5px;把字号降到 0.875em(14px 正文 → 12.25px)配 19px 行高后变成 + // 拉丁 −1.5px / 中文 +1.5px,两边各让一半,是偏差最小的平衡点。 + // 配方对齐 DeepSeek Harness 的内联代码(--dsw-font-markdown-code = 12px/19px, + // 再用 font-size: 0.875em 覆盖成正文字号的 7/8,上下 padding 都为 0) + // 3) **淡底色 + 0.5px 细描边**:靠描边给边界(只给底色在各主题下会和页面糊在一起) const className = - 'inline-flex items-center font-mono text-[0.875em] leading-tight py-px break-words bg-bg-200 border-[0.5px] border-text-100/10 rounded-md px-[5px]' + 'inline-flex items-center font-mono text-[0.875em] leading-[19px] break-words bg-bg-200 border-[0.5px] border-text-100/10 rounded-md px-[5px]' return `${escapeHtml(text)}` } From 8e02ce371d1bbba603f0f69c4ce8f4efbdffb85e Mon Sep 17 00:00:00 2001 From: lehhair Date: Mon, 19 Oct 2026 21:45:15 +0800 Subject: [PATCH 03/67] =?UTF-8?q?fix(mobile):=20=E8=A7=A6=E6=91=B8?= =?UTF-8?q?=E7=9B=AE=E6=A0=87=E6=94=B9=E4=B8=BA=E6=98=BE=E5=BC=8F=20opt-in?= =?UTF-8?q?=EF=BC=8C=E6=89=8B=E6=9C=BA=E4=B8=8D=E5=86=8D=E6=8A=8A=E6=8C=89?= =?UTF-8?q?=E9=92=AE=E5=8D=95=E6=96=B9=E9=9D=A2=E9=A1=B6=E9=AB=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 原来的 utton:not(.touch-target-sm)... { min-height: 32px } 会给所有小于 32px 的按钮兜底增高:内联权限/提问卡里的按钮比桌面高出一截、整行被撑开, 工具卡片/附件胶囊/侧栏会话行里的 20~24px 小按钮被顶成 32px,密集行对齐全乱; 且只改高度不改宽度,方形图标按钮会变成 24x32 的竖长条 - 规则反转为 utton.touch-target(同时补上 min-width),尺寸交回组件自己 用 h-*/py-* 决定,手机与桌面保持一致;目前没有按钮需要该标记 - 移除随之失效的 ouch-target-sm(PanelContainer 的 tab 关闭按钮)与 data-compact(DiffViewer 两处、TaskRenderer 一处),避免留下无消费者的死代码 --- src/components/DiffViewer.tsx | 3 +-- src/components/PanelContainer.tsx | 1 - .../message/tools/renderers/TaskRenderer.tsx | 1 - src/index.css | 15 +++++++++++++-- 4 files changed, 14 insertions(+), 6 deletions(-) diff --git a/src/components/DiffViewer.tsx b/src/components/DiffViewer.tsx index cb762bdb0..5bdafe107 100644 --- a/src/components/DiffViewer.tsx +++ b/src/components/DiffViewer.tsx @@ -419,7 +419,6 @@ function CollapsedExpandButton({ diff --git a/src/components/PanelContainer.tsx b/src/components/PanelContainer.tsx index e3aeb6b4f..8edaeb005 100644 --- a/src/components/PanelContainer.tsx +++ b/src/components/PanelContainer.tsx @@ -658,7 +658,6 @@ const PanelTabButton = memo(function PanelTabButton({ onMouseDown={e => e.stopPropagation()} aria-label={t('common:close')} className={` - touch-target-sm p-1 -mr-0.5 rounded shrink-0 transition-all duration-150 ease-out hover:bg-danger-100/20 text-text-400 hover:text-danger-100 diff --git a/src/features/message/tools/renderers/TaskRenderer.tsx b/src/features/message/tools/renderers/TaskRenderer.tsx index d1c9bac0f..ddc5f6e29 100644 --- a/src/features/message/tools/renderers/TaskRenderer.tsx +++ b/src/features/message/tools/renderers/TaskRenderer.tsx @@ -278,7 +278,6 @@ export const TaskHeader = memo(function TaskHeader({ {sessionId ? ( + + + ) + })} + + )} void + onSave: (updates: { + name: string + url: string + username?: string + password?: string + endpoints?: ServerEndpoint[] + }) => void onCancel: () => void }) { const { t } = useTranslation(['settings', 'common']) const [name, setName] = useState(server.name) const [url, setUrl] = useState(server.url) + /** + * 配对拿到的全部地址(Issue #183)。与 `url`(主地址)分开存: + * 用户手改 url 不会动这个集合,保存时按「url 优先 + 集合去重」合成 endpoints。 + */ + const [pairedUrls, setPairedUrls] = useState(() => + (server.endpoints ?? []).map(endpoint => endpoint.url), + ) const [username, setUsername] = useState(server.auth?.username || '') const [password, setPassword] = useState(server.auth?.password || '') const [showAuth, setShowAuth] = useState(!!server.auth?.password) @@ -225,8 +335,9 @@ function EditServerForm({ // 与添加表单同一条配对链:重新扫码 / 粘贴 pair 链接兑换后回填地址与凭据, // 保存时才落库——适合换了端口 / 重装了服务端后原地更新连接配置 - const applyPairing = useCallback((pairedUrl: string, token: string) => { + const applyPairing = useCallback((pairedUrl: string, token: string, urls: string[]) => { setUrl(pairedUrl) + setPairedUrls(urls) setUsername('opencode') setPassword(token) setShowAuth(true) @@ -267,6 +378,7 @@ function EditServerForm({ url: url.trim(), username: password.trim() ? username.trim() || 'opencode' : undefined, password: password.trim() || undefined, + endpoints: buildEndpoints(url, pairedUrls), }) } @@ -395,19 +507,22 @@ function AddServerForm({ onAdd, onCancel, }: { - onAdd: (name: string, url: string, username?: string, password?: string) => void + onAdd: (name: string, url: string, username?: string, password?: string, endpoints?: ServerEndpoint[]) => void onCancel: () => void }) { const { t } = useTranslation(['settings', 'common']) const [name, setName] = useState('') const [url, setUrl] = useState('') + /** 配对拿到的全部地址;与 url(主地址)分开存,保存时合成 endpoints */ + const [pairedUrls, setPairedUrls] = useState([]) const [username, setUsername] = useState('') const [password, setPassword] = useState('') const [showAuth, setShowAuth] = useState(false) const [error, setError] = useState('') - const applyPairing = useCallback((pairedUrl: string, token: string) => { + const applyPairing = useCallback((pairedUrl: string, token: string, urls: string[]) => { setUrl(pairedUrl) + setPairedUrls(urls) setUsername('opencode') setPassword(token) setShowAuth(true) @@ -451,6 +566,7 @@ function AddServerForm({ url.trim(), password.trim() ? username.trim() || 'opencode' : undefined, password.trim() || undefined, + buildEndpoints(url, pairedUrls), ) } @@ -619,9 +735,12 @@ export function ServersSettings() { removeServer, updateServer, setActiveServer, + setActiveEndpoint, + setLockedEndpoint, checkHealth, checkAllHealth, getHealth, + endpointStates, } = useServerStore() const { navigateHome, sessionId: routeSessionId } = useRouter() const orderedServers = useMemo(() => { @@ -803,12 +922,15 @@ export function ServersSettings() { const auth = updates.password ? { username: updates.username || 'opencode', password: updates.password } : undefined - updateServer(s.id, { name: updates.name, url: updates.url, auth }) + updateServer(s.id, { name: updates.name, url: updates.url, auth, endpoints: updates.endpoints }) void checkHealth(s.id) }} onCheckHealth={() => void checkHealth(s.id)} onPair={() => setPairingServer(s)} onToggleSubscribe={() => multiServerStore.setSubscribed(s.id, !multiServerStore.isSubscribed(s.id))} + endpointState={endpointStates.get(s.id) ?? { activeUrl: null, lockedUrl: null, lastSwitchAt: 0 }} + onUseEndpoint={url => setActiveEndpoint(s.id, url)} + onLockEndpoint={url => setLockedEndpoint(s.id, url)} /> ) })} @@ -829,9 +951,9 @@ export function ServersSettings() { {addingServer && ( { + onAdd={(n, u, user, pass, endpoints) => { const auth = pass ? { username: user || 'opencode', password: pass } : undefined - const s = addServer({ name: n, url: u, auth }) + const s = addServer({ name: n, url: u, auth, endpoints }) setAddingServer(false) void checkHealth(s.id) }} diff --git a/src/features/settings/components/usePairLinkRedeem.ts b/src/features/settings/components/usePairLinkRedeem.ts index fd8174014..6bd372b32 100644 --- a/src/features/settings/components/usePairLinkRedeem.ts +++ b/src/features/settings/components/usePairLinkRedeem.ts @@ -23,15 +23,18 @@ export function usePairLinkRedeem({ onPaired, onInput, }: { - /** 兑换成功:回填 url + token(服务端约定用户名固定为 opencode,token 作密码) */ - onPaired: (url: string, token: string) => void + /** + * 兑换成功:回填 url + token(服务端约定用户名固定为 opencode,token 作密码)。 + * `urls` 是 QR 载荷里的全部地址(Issue #183),调用方保存为多地址。 + */ + onPaired: (url: string, token: string, urls: string[]) => void /** 配对输入变化(清表单级错误) */ onInput?: () => void }) { const [pairLink, setPairLink] = useState('') const [pairState, setPairState] = useState({ kind: 'idle' }) const [pairScanOpen, setPairScanOpen] = useState(false) - const redeemedRef = useRef<{ code: string; url: string; token: string } | null>(null) + const redeemedRef = useRef<{ code: string; url: string; urls: string[]; token: string } | null>(null) const pairSeqRef = useRef(0) const pairTimerRef = useRef | null>(null) @@ -60,7 +63,8 @@ export function usePairLinkRedeem({ } const cached = redeemedRef.current if (cached && cached.code === link.code) { - onPaired(link.urls.includes(cached.url) ? cached.url : link.urls[0], cached.token) + const preferred = link.urls.includes(cached.url) ? cached.url : link.urls[0] + onPaired(preferred, cached.token, link.urls) setPairState({ kind: 'paired', url: cached.url }) return } @@ -72,8 +76,8 @@ export function usePairLinkRedeem({ void redeemPairingLink(link).then(result => { if (seq !== pairSeqRef.current) return if (result.type === 'paired') { - redeemedRef.current = { code: link.code, url: result.url, token: result.token } - onPaired(result.url, result.token) + redeemedRef.current = { code: link.code, url: result.url, urls: result.urls, token: result.token } + onPaired(result.url, result.token, result.urls) setPairState({ kind: 'paired', url: result.url }) return } diff --git a/src/hooks/useServerStore.ts b/src/hooks/useServerStore.ts index e714e5934..ef65d8697 100644 --- a/src/hooks/useServerStore.ts +++ b/src/hooks/useServerStore.ts @@ -3,8 +3,8 @@ // ============================================ import { useSyncExternalStore, useCallback } from 'react' -import { serverStore, type ServerConfig, type ServerHealth } from '../store/serverStore' -export type { ServerConfig, ServerHealth } +import { serverStore, type ServerConfig, type ServerHealth, type EndpointRuntime } from '../store/serverStore' +export type { ServerConfig, ServerHealth, EndpointRuntime } /** * 订阅 serverStore 的 React hook @@ -35,6 +35,13 @@ export function useServerStore() { () => serverStore.getDefaultServerId(), ) + // 多地址运行时状态(生效地址 / 锁定地址) + const endpointStates = useSyncExternalStore( + serverStore.subscribe.bind(serverStore), + () => serverStore.getEndpointStates(), + () => serverStore.getEndpointStates(), + ) + const addServer = useCallback((config: Omit) => { return serverStore.addServer(config) }, []) @@ -51,6 +58,14 @@ export function useServerStore() { return serverStore.setActiveServer(id) }, []) + const setActiveEndpoint = useCallback((serverId: string, url: string) => { + return serverStore.setActiveEndpoint(serverId, url) + }, []) + + const setLockedEndpoint = useCallback((serverId: string, url: string | null) => { + return serverStore.setLockedEndpoint(serverId, url) + }, []) + const checkHealth = useCallback((serverId: string) => { return serverStore.checkHealth(serverId) }, []) @@ -71,10 +86,13 @@ export function useServerStore() { activeServer, healthMap, defaultServerId, + endpointStates, addServer, updateServer, removeServer, setActiveServer, + setActiveEndpoint, + setLockedEndpoint, checkHealth, checkAllHealth, getHealth, diff --git a/src/locales/en/settings.json b/src/locales/en/settings.json index 014c6cec5..fbd6da19a 100644 --- a/src/locales/en/settings.json +++ b/src/locales/en/settings.json @@ -151,7 +151,11 @@ "pairScanInvalid": "Not a valid pairing QR code", "pairScanLegacy": "Legacy pairing QR — upgrade the server and regenerate", "pairCameraError": "Cannot access the camera — check permissions", - "pairCameraStarting": "Starting camera…" + "pairCameraStarting": "Starting camera…", + "endpointActive": "In use", + "endpointUse": "Use this address", + "endpointLock": "Lock to this address (no auto-switch)", + "endpointUnlock": "Unlock" }, "chat": { "pathsFormatting": "Paths & Formatting", diff --git a/src/locales/zh-CN/settings.json b/src/locales/zh-CN/settings.json index c9dbecdea..812aaee73 100644 --- a/src/locales/zh-CN/settings.json +++ b/src/locales/zh-CN/settings.json @@ -151,7 +151,11 @@ "pairScanInvalid": "无效的配对二维码", "pairScanLegacy": "旧版配对二维码,请升级服务端后重新生成", "pairCameraError": "无法打开摄像头,请检查权限", - "pairCameraStarting": "正在启动摄像头…" + "pairCameraStarting": "正在启动摄像头…", + "endpointActive": "使用中", + "endpointUse": "使用此地址", + "endpointLock": "锁定此地址(不自动切换)", + "endpointUnlock": "解除锁定" }, "chat": { "pathsFormatting": "路径和格式", diff --git a/src/main.tsx b/src/main.tsx index 42d766038..45db9d07a 100644 --- a/src/main.tsx +++ b/src/main.tsx @@ -9,10 +9,11 @@ import { DirectoryProvider, FullscreenProvider, SessionProvider } from './contex import { themeStore } from './store/themeStore' import { affectsBoundServer } from './store/serverChangeScope' import { serverStore } from './store/serverStore' +import { startEndpointProbe } from './store/endpointProbe' import { autoApproveStore } from './store/autoApproveStore' import { serviceStore } from './store/serviceStore' import { wslStore } from './store/wslStore' -import { reconnectSSE } from './api/events' +import { reconnectSSE, reconnectServerSSE } from './api/events' import { getSDKClientAsync, invalidateSDKClient } from './api/sdk' import { resetPathModeCache } from './utils/directoryUtils' import { isTauri, isTauriMobile } from './utils/tauri' @@ -72,6 +73,17 @@ serverStore.onServerChange((serverId, reason) => { // 多服务器模式:messageStore / childSessionStore 的数据按 `serverId::sessionId` // 分片存储,切换 active server 不应清空其他 pane 正在使用的服务器数据,因此不再 clearAll。 + // 换入口地址(Issue #183:内网 ↔ 公网):同一台服务器、同一份数据, + // 只需要让连接跟着新地址走。不走下面的「重置数据类缓存」分支—— + // 路径模式/autoApprove 都由服务器身份决定,换入口不变。 + if (reason === 'endpoint-switch') { + // 重连的是「这台服务器」的连接,不限于 active:多服务器模式下 + // 非 active 的订阅连接同样挂在旧地址上,不重连就会一直连着死地址。 + // reason 'network' 让重连成功后走补偿拉取,而不是按'换服务器'跳过。 + reconnectServerSSE(serverId, { reason: 'network' }) + return + } + // 以下动作只作用于「当前 active 服务器的数据/连接」,必须按 reason 门控: // - server-switch:active 本身变了(含删除回退)→ 缓存与 SSE 目标都换了 // - server-runtime-updated / local-runtime-url:仅当变的这台就是 active 才相关; @@ -89,6 +101,10 @@ serverStore.onServerChange((serverId, reason) => { reconnectSSE() }) +// 多地址自动探测(Issue #183):内网优先、不可达降级、恢复后带滞回升回。 +// 内部只对配了 >1 个地址的服务器发请求,单地址用户零开销。 +startEndpointProbe() + const isNativeTauri = isTauri() const isNativeTauriMobile = isNativeTauri && isTauriMobile() diff --git a/src/store/endpointProbe.test.ts b/src/store/endpointProbe.test.ts new file mode 100644 index 000000000..09987e009 --- /dev/null +++ b/src/store/endpointProbe.test.ts @@ -0,0 +1,507 @@ +// 多地址自动探测(Issue #183):决策纯函数 + 一轮探测的集成行为。 +import { beforeEach, describe, expect, it, vi } from 'vitest' +import type { EndpointProbeState } from './endpointProbe' +import type { ConnectionInfo } from '../api/events' + +const LAN = 'http://192.168.1.5:4096' +const WAN = 'https://public.example.com' +const THIRD = 'https://third.example.com' + +function state(reachable: boolean, ok = 0, fail = 0): EndpointProbeState { + return { reachable, consecutiveOk: ok, consecutiveFail: fail, lastChecked: 0 } +} + +function endpointsOf(...urls: string[]) { + return urls.map((url, index) => ({ url, priority: index })) +} + +const DWELL = 30_000 + +beforeEach(() => { + vi.resetModules() + localStorage.clear() + sessionStorage.clear() +}) + +describe('decideEndpointSwitch', () => { + it('单地址服务器不参与决策', async () => { + const { decideEndpointSwitch } = await import('./endpointProbe') + const states = new Map([[LAN, state(false, 0, 5)]]) + + expect(decideEndpointSwitch(endpointsOf(LAN), null, states, Infinity)).toBeNull() + expect(decideEndpointSwitch(undefined, null, states, Infinity)).toBeNull() + }) + + it('启动时默认地址不可达 → 立刻退到备用(首次选择不等失败阈值)', async () => { + const { decideEndpointSwitch } = await import('./endpointProbe') + const states = new Map([ + [LAN, state(false, 0, 1)], + [WAN, state(true, 1)], + ]) + + expect(decideEndpointSwitch(endpointsOf(LAN, WAN), null, states, DWELL)).toEqual({ + url: WAN, + reason: 'failover', + }) + }) + + it('启动时默认地址可达 → 不动', async () => { + const { decideEndpointSwitch } = await import('./endpointProbe') + const states = new Map([ + [LAN, state(true, 1)], + [WAN, state(true, 1)], + ]) + + expect(decideEndpointSwitch(endpointsOf(LAN, WAN), null, states, DWELL)).toBeNull() + }) + + it('连续失败未达阈值不降级(抗单次抖动)', async () => { + const { decideEndpointSwitch } = await import('./endpointProbe') + const states = new Map([ + [LAN, state(false, 0, 1)], + [WAN, state(true, 5)], + ]) + + expect(decideEndpointSwitch(endpointsOf(LAN, WAN), LAN, states, 0)).toBeNull() + }) + + it('连续失败达阈值 → 降级到可达的备用地址', async () => { + const { decideEndpointSwitch } = await import('./endpointProbe') + const states = new Map([ + [LAN, state(false, 0, 2)], + [WAN, state(true, 1)], + ]) + + expect(decideEndpointSwitch(endpointsOf(LAN, WAN), LAN, states, 0)).toEqual({ + url: WAN, + reason: 'failover', + }) + }) + + it('全部不可达 → 保持现状,不随机切', async () => { + const { decideEndpointSwitch } = await import('./endpointProbe') + const states = new Map([ + [LAN, state(false, 0, 5)], + [WAN, state(false, 0, 5)], + ]) + + expect(decideEndpointSwitch(endpointsOf(LAN, WAN), LAN, states, 0)).toBeNull() + }) + + it('当前是备用地址且失效 → 切到可达的高优先级地址(不卡在更低优先级)', async () => { + const { decideEndpointSwitch } = await import('./endpointProbe') + const states = new Map([ + [LAN, state(true, 1)], + [WAN, state(false, 0, 5)], + [THIRD, state(true, 5)], + ]) + + expect(decideEndpointSwitch(endpointsOf(LAN, WAN, THIRD), WAN, states, 0)).toEqual({ + url: LAN, + reason: 'failover', + }) + }) + + it('高优先级恢复但未满成功阈值 → 不切回', async () => { + const { decideEndpointSwitch } = await import('./endpointProbe') + const states = new Map([ + [LAN, state(true, 2)], + [WAN, state(true, 10)], + ]) + + expect(decideEndpointSwitch(endpointsOf(LAN, WAN), WAN, states, DWELL)).toBeNull() + }) + + it('高优先级满成功阈值但滞回未到 → 不切回', async () => { + const { decideEndpointSwitch } = await import('./endpointProbe') + const states = new Map([ + [LAN, state(true, 3)], + [WAN, state(true, 10)], + ]) + + expect(decideEndpointSwitch(endpointsOf(LAN, WAN), WAN, states, DWELL - 1)).toBeNull() + }) + + it('高优先级满成功阈值 + 滞回已到 → 切回', async () => { + const { decideEndpointSwitch } = await import('./endpointProbe') + const states = new Map([ + [LAN, state(true, 3)], + [WAN, state(true, 10)], + ]) + + expect(decideEndpointSwitch(endpointsOf(LAN, WAN), WAN, states, DWELL)).toEqual({ + url: LAN, + reason: 'recover', + }) + }) + + it('当前地址不健康时不走升级分支(交给降级处理)', async () => { + const { decideEndpointSwitch } = await import('./endpointProbe') + const states = new Map([ + [LAN, state(true, 5)], + [WAN, state(false, 0, 1)], + ]) + + // WAN 只是 1 次失败(未达降级阈值),也不该因为 LAN 恢复就切过去后 + // 又立刻依据升级逻辑……总之未达阈值一律不动 + expect(decideEndpointSwitch(endpointsOf(LAN, WAN), WAN, states, DWELL)).toBeNull() + }) +}) + +describe('applyProbeResult', () => { + it('可达累加 ok、清零 fail', async () => { + const { applyProbeResult } = await import('./endpointProbe') + + const first = applyProbeResult({ reachable: false, consecutiveOk: 0, consecutiveFail: 3, lastChecked: 0 }, true, 42, 100) + expect(first).toEqual({ reachable: true, latency: 42, consecutiveOk: 1, consecutiveFail: 0, lastChecked: 100 }) + + const second = applyProbeResult(first, true, 50, 200) + expect(second.consecutiveOk).toBe(2) + }) + + it('不可达累加 fail、清零 ok、丢弃延迟', async () => { + const { applyProbeResult } = await import('./endpointProbe') + + const next = applyProbeResult({ reachable: true, latency: 30, consecutiveOk: 5, consecutiveFail: 0, lastChecked: 0 }, false, undefined, 100) + expect(next).toEqual({ reachable: false, latency: undefined, consecutiveOk: 0, consecutiveFail: 1, lastChecked: 100 }) + }) + + it('首次探测(无前值)也能正确计数', async () => { + const { applyProbeResult } = await import('./endpointProbe') + + expect(applyProbeResult(undefined, false, undefined, 7)).toEqual({ + reachable: false, + latency: undefined, + consecutiveOk: 0, + consecutiveFail: 1, + lastChecked: 7, + }) + }) +}) + +describe('probeServerOnce(集成)', () => { + it('并发探测所有地址,并按降级决策切换生效地址', async () => { + const { serverStore } = await import('./serverStore') + const { probeServerOnce, resetAllProbeStates } = await import('./endpointProbe') + resetAllProbeStates() + + const server = serverStore.addServer({ + name: 'dual', + url: LAN, + endpoints: [ + { url: LAN, priority: 0 }, + { url: WAN, priority: 1 }, + ], + }) + + // 内网不可达、公网可达 + const probeSpy = vi.spyOn(serverStore, 'probeEndpoint').mockImplementation(async url => + url === LAN ? null : 12, + ) + + // 第一轮:启动时默认地址不可达 → 立刻换 + await probeServerOnce(server.id) + expect(serverStore.getServerBaseUrl(server.id)).toBe(WAN) + + // 第二轮:公网健康,保持 + await probeServerOnce(server.id) + expect(serverStore.getServerBaseUrl(server.id)).toBe(WAN) + + expect(probeSpy).toHaveBeenCalledTimes(4) + probeSpy.mockRestore() + }) + + it('锁定期间完全让位,不改生效地址', async () => { + const { serverStore } = await import('./serverStore') + const { probeServerOnce, resetAllProbeStates } = await import('./endpointProbe') + resetAllProbeStates() + + const server = serverStore.addServer({ + name: 'dual', + url: LAN, + endpoints: [ + { url: LAN, priority: 0 }, + { url: WAN, priority: 1 }, + ], + }) + serverStore.setLockedEndpoint(server.id, WAN) + + const probeSpy = vi.spyOn(serverStore, 'probeEndpoint').mockResolvedValue(null) + await probeServerOnce(server.id) + + expect(serverStore.getServerBaseUrl(server.id)).toBe(WAN) + // 锁定后连探测都不发 + expect(probeSpy).not.toHaveBeenCalled() + probeSpy.mockRestore() + }) + + it('并发探测同一台只跑一轮(15s 主循环与 3s 归位探测会撞车)', async () => { + const { serverStore } = await import('./serverStore') + const { probeServerOnce, resetAllProbeStates, getProbeState } = await import('./endpointProbe') + resetAllProbeStates() + + const server = serverStore.addServer({ + name: 'dual', + url: LAN, + endpoints: [ + { url: LAN, priority: 0 }, + { url: WAN, priority: 1 }, + ], + }) + + const resolvers: Array<() => void> = [] + const probeSpy = vi.spyOn(serverStore, 'probeEndpoint').mockImplementation( + () => + new Promise(resolve => { + resolvers.push(() => resolve(10)) + }), + ) + + // 两个入口同时进来:第二个必须被去重,否则一轮里 consecutiveOk 涨两次, + // 升级/降级阈值被变相减半 → 来回横跳 + const first = probeServerOnce(server.id) + const second = probeServerOnce(server.id) + await Promise.resolve() + for (const resolve of resolvers) resolve() + await Promise.all([first, second]) + + // 每台地址每轮只探一次 + expect(probeSpy.mock.calls.length).toBe(2) // 两个地址各一次,不是四个 + expect(getProbeState(server.id, LAN)?.consecutiveOk).toBe(1) + + probeSpy.mockRestore() + }) + + it('单地址服务器不发探测', async () => { const { serverStore } = await import('./serverStore') + const { probeServerOnce, resetAllProbeStates } = await import('./endpointProbe') + resetAllProbeStates() + + const server = serverStore.addServer({ name: 'single', url: LAN }) + const probeSpy = vi.spyOn(serverStore, 'probeEndpoint').mockResolvedValue(10) + + await probeServerOnce(server.id) + expect(probeSpy).not.toHaveBeenCalled() + probeSpy.mockRestore() + }) + + it('内网恢复后累计成功 + 滞回到期 → 切回内网', async () => { + const { serverStore } = await import('./serverStore') + const { probeServerOnce, resetAllProbeStates } = await import('./endpointProbe') + resetAllProbeStates() + + const server = serverStore.addServer({ + name: 'dual', + url: LAN, + endpoints: [ + { url: LAN, priority: 0 }, + { url: WAN, priority: 1 }, + ], + }) + + const probeSpy = vi.spyOn(serverStore, 'probeEndpoint').mockImplementation(async url => + url === LAN ? 5 : 20, + ) + + // 现在在公网(模拟此前已降级) + serverStore.setActiveEndpoint(server.id, WAN) + + // 连续 3 轮内网可达 → 满足成功阈值;但滞回窗口按真实时间算,直接 + // 用「未来时刻」驱动探测,模拟已经稳定运行很久 + const future = performance.now() + 60_000 + await probeServerOnce(server.id, future) + await probeServerOnce(server.id, future) + await probeServerOnce(server.id, future) + + expect(serverStore.getServerBaseUrl(server.id)).toBe(LAN) + probeSpy.mockRestore() + }) +}) + +// ============================================ +// 传输层信号驱动的快速探测 +// +// SSE 断开是「当前入口可能死了」的最快信号。只靠 15s 轮询的话,切网络后 +// 要等下一轮才知道;这里验证断线会立刻触发探测并在确认失败后尽快切走。 +// ============================================ + +describe('传输层报错 → 快速探测', () => { + it('曾经连上过、现在掉了 → 立刻探测(不等 15s 轮询)', async () => { + vi.resetModules() + const { serverStore } = await import('./serverStore') + const { startEndpointProbe, stopEndpointProbe, resetAllProbeStates } = await import('./endpointProbe') + + resetAllProbeStates() + const server = serverStore.addServer({ + name: 'dual', + url: LAN, + endpoints: [ + { url: LAN, priority: 0 }, + { url: WAN, priority: 1 }, + ], + }) + + // 捕获连接状态订阅回调 + const connectionCallbacks = new Map void>() + const eventsModule = await import('../api/events') + vi.spyOn(eventsModule, 'subscribeToServerConnectionState').mockImplementation( + (serverId: string, fn: (info: ConnectionInfo) => void) => { + connectionCallbacks.set(serverId, fn) + return () => connectionCallbacks.delete(serverId) + }, + ) + + const probeSpy = vi.spyOn(serverStore, 'probeEndpoint').mockImplementation(async url => + url === LAN ? null : 20, + ) + + vi.useFakeTimers() + try { + startEndpointProbe() + // 首轮立即探测:内网已不可达 → 首次选择直接切到公网 + await vi.advanceTimersByTimeAsync(0) + expect(serverStore.getServerBaseUrl(server.id)).toBe(WAN) + + // 模拟:当前生效的公网地址也掉了(连接状态从 connected 变 error) + connectionCallbacks.get(server.id)?.({ state: 'connected', lastEventTime: 0, reconnectAttempt: 0 }) + const callsBefore = probeSpy.mock.calls.length + connectionCallbacks.get(server.id)?.({ state: 'error', lastEventTime: 0, reconnectAttempt: 1 }) + + // 确认延迟后立刻探测,而不是等 15s + await vi.advanceTimersByTimeAsync(1_600) + expect(probeSpy.mock.calls.length).toBeGreaterThan(callsBefore) + } finally { + stopEndpointProbe() + vi.useRealTimers() + probeSpy.mockRestore() + } + }) + + it('从未连上过就不触发(首次连接失败不该反复探测)', async () => { + vi.resetModules() + const { serverStore } = await import('./serverStore') + const { startEndpointProbe, stopEndpointProbe, resetAllProbeStates } = await import('./endpointProbe') + + resetAllProbeStates() + serverStore.addServer({ + name: 'dual', + url: LAN, + endpoints: [ + { url: LAN, priority: 0 }, + { url: WAN, priority: 1 }, + ], + }) + + const connectionCallbacks = new Map void>() + const eventsModule = await import('../api/events') + vi.spyOn(eventsModule, 'subscribeToServerConnectionState').mockImplementation( + (serverId: string, fn: (info: ConnectionInfo) => void) => { + connectionCallbacks.set(serverId, fn) + return () => connectionCallbacks.delete(serverId) + }, + ) + + const probeSpy = vi.spyOn(serverStore, 'probeEndpoint').mockResolvedValue(20) + + vi.useFakeTimers() + try { + startEndpointProbe() + await vi.advanceTimersByTimeAsync(0) + const callsBefore = probeSpy.mock.calls.length + + // 只有 error,没有先连上 → 不出手 + for (const [, cb] of connectionCallbacks) cb({ state: 'error', lastEventTime: 0, reconnectAttempt: 1 }) + await vi.advanceTimersByTimeAsync(1_600) + expect(probeSpy.mock.calls.length).toBe(callsBefore) + } finally { + stopEndpointProbe() + vi.useRealTimers() + probeSpy.mockRestore() + } + }) +}) + +// ============================================ +// 归位探测:降级状态下加密探测,别让用户干等 15s 轮询 +// ============================================ + +describe('降级状态的归位探测', () => { + it('停在低优先级地址时,用 3s 节奏探测并在连续成功后切回', async () => { + vi.resetModules() + const { serverStore } = await import('./serverStore') + const { startEndpointProbe, stopEndpointProbe, resetAllProbeStates } = await import('./endpointProbe') + + resetAllProbeStates() + const server = serverStore.addServer({ + name: 'dual', + url: LAN, + endpoints: [ + { url: LAN, priority: 0 }, + { url: WAN, priority: 1 }, + ], + }) + + // 两个地址都可达 + const probeSpy = vi.spyOn(serverStore, 'probeEndpoint').mockResolvedValue(15) + + vi.useFakeTimers() + try { + startEndpointProbe() + await vi.advanceTimersByTimeAsync(0) + + // 先手动降到公网(模拟「内网刚挂了」之后的状态) + serverStore.setActiveEndpoint(server.id, WAN) + expect(serverStore.getServerBaseUrl(server.id)).toBe(WAN) + + // 滞回窗口未过 → 即使连续成功也不切回 + await vi.advanceTimersByTimeAsync(3_500) + expect(serverStore.getServerBaseUrl(server.id)).toBe(WAN) + + // 把「上次切换时刻」推回 60s 前(等价于已经稳定运行很久) + const runtime = serverStore.getEndpointRuntime(server.id) + // @ts-expect-error 测试里直接改运行时状态,模拟时间流逝 + runtime.lastSwitchAt = performance.now() - 60_000 + + // 3s 节奏下,3 次成功 ≈ 9s 内就该切回(而不是等 15s 轮询的 45s) + await vi.advanceTimersByTimeAsync(10_000) + expect(serverStore.getServerBaseUrl(server.id)).toBe(LAN) + } finally { + stopEndpointProbe() + vi.useRealTimers() + probeSpy.mockRestore() + } + }) + + it('未降级时归位探测不发多余请求', async () => { + vi.resetModules() + const { serverStore } = await import('./serverStore') + const { startEndpointProbe, stopEndpointProbe, resetAllProbeStates } = await import('./endpointProbe') + + resetAllProbeStates() + serverStore.addServer({ + name: 'dual', + url: LAN, + endpoints: [ + { url: LAN, priority: 0 }, + { url: WAN, priority: 1 }, + ], + }) + + const probeSpy = vi.spyOn(serverStore, 'probeEndpoint').mockResolvedValue(15) + + vi.useFakeTimers() + try { + startEndpointProbe() + await vi.advanceTimersByTimeAsync(0) + const afterFirstRound = probeSpy.mock.calls.length + + // 正常状态(生效的是 priority 0):归位探测应该什么都不做。 + // 只推进 10s(不足 15s 全局轮询周期),请求数不该增长。 + await vi.advanceTimersByTimeAsync(10_000) + expect(probeSpy.mock.calls.length).toBe(afterFirstRound) + } finally { + stopEndpointProbe() + vi.useRealTimers() + probeSpy.mockRestore() + } + }) +}) diff --git a/src/store/endpointProbe.ts b/src/store/endpointProbe.ts new file mode 100644 index 000000000..83a62f534 --- /dev/null +++ b/src/store/endpointProbe.ts @@ -0,0 +1,460 @@ +// ============================================ +// endpointProbe - 多地址自动探测与主备切换(Issue #183) +// +// 设计取舍(详见 docs/plan-multi-endpoint-and-reconnect.md): +// +// 1. **主备,不是负载均衡**。按 priority 升序,高优先级可达就用它, +// 不与低优先级比延迟。内外网场景里「内网快」是结构性的,测速只会引入抖动。 +// +// 2. **降级快、升级慢**。高优先级连续 K 次失败就降级;低优先级要连续 N 次 +// 成功、且已稳定运行 dwell 时间才升回。这是防抖的核心 —— 只做降级会永久 +// 卡在公网,只做升级会来回横跳。 +// +// 3. **全部不可达时保持现状**。不随机挑一个,避免把「网络还没恢复」误判成 +// 「换条路试试」。用户此时看到的是原有的断线重连逻辑在起作用。 +// +// 4. **探测历史不跨网络事件保留**(RFC 8305 §4):`online` / `offline` 时清空 +// 所有探测状态。断网期间所有地址都会失败,带着这些失败的计数恢复网络后 +// 会立刻误判降级。 +// +// 5. **锁定优先**。`lockedUrl` 非空时本模块完全让位,一个字都不改。 +// ============================================ + +import { serverStore, type ServerEndpoint, type ServerAuth } from './serverStore' +import { subscribeToServerConnectionState } from '../api/events' +import { logger } from '../utils/logger' + +/** 探测周期。多地址服务器才探测,单地址零成本 */ +const PROBE_INTERVAL_MS = 15_000 +/** 单次探测超时。要小于探测周期,否则请求会堆积 */ +const PROBE_TIMEOUT_MS = 4_000 +/** 连续失败多少次判定「这条不可用」→ 降级 */ +const DEGRADE_FAIL_THRESHOLD = 2 +/** 连续成功多少次判定「高优先级恢复了」→ 允许升级 */ +const UPGRADE_OK_THRESHOLD = 3 +/** 升级前必须在当前地址上停留多久,避免刚切完立刻切回 */ +const UPGRADE_DWELL_MS = 30_000 +/** + * 降级状态下的「归位探测」节奏。 + * + * 全局轮询是 15s,但当前正停在低优先级地址时(内网挂了、走公网), + * 用 15s 去等内网恢复等于让用户白等 30~45s。这里对降级中的服务器 + * 单独加密探测,连续 3 次成功 ≈ 9s 就能切回。 + * + * 只在降级时启用:正常情况下不多发请求。 + */ +const RECOVERY_PROBE_INTERVAL_MS = 3_000 +/** + * 传输层报错后的确认探测间隔。 + * + * SSE 断开是「当前地址可能死了」的最快信号(比 15s 轮询快得多), + * 收到就立刻探一轮;若当前地址确实不可达,再等这一小段补一轮凑够 + * 降级阈值 K,把「切网络 → 换地址」压到秒级,而不是等下一个周期。 + */ +const CONFIRM_DELAY_MS = 1_500 +/** 传输层报错触发快速探测的节流(SSE 会反复重试,别跟着刷探测) */ +const FAST_PROBE_THROTTLE_MS = 3_000 + +export interface EndpointProbeState { + /** 最近一次探测是否可达 */ + reachable: boolean + /** 最近一次探测延迟(ms),不可达时 undefined */ + latency?: number + /** 连续可达次数 */ + consecutiveOk: number + /** 连续不可达次数 */ + consecutiveFail: number + /** 最近一次探测时刻(performance.now()) */ + lastChecked: number +} + +export interface ProbeDecision { + url: string + /** failover = 当前地址失效被迫换路;recover = 高优先级恢复后按滞回切回 */ + reason: 'failover' | 'recover' +} + +/** 探测状态集合:`serverId → (url → state)` */ +type ProbeStateMap = Map> + +const probeStates: ProbeStateMap = new Map() + +/** + * 决定要不要换地址。**纯函数**,不含任何 IO / 全局状态,便于单测。 + * + * 返回 null 表示保持现状。 + * + * @param endpoints 该服务器的地址列表(已按 priority 升序) + * @param activeUrl 当前生效地址;null 表示从未显式选过(按主地址对待) + * @param states 每条地址的最新探测状态 + * @param elapsedSinceSwitchMs 距上次切换的毫秒数(升级滞回用) + */ +export function decideEndpointSwitch( + endpoints: ServerEndpoint[] | undefined, + activeUrl: string | null, + states: Map, + elapsedSinceSwitchMs: number, +): ProbeDecision | null { + if (!endpoints || endpoints.length < 2) return null + + // 未选过 / 选了个已不在列表里的地址,都按主地址(priority 最小)对待 + const currentIndex = (() => { + if (!activeUrl) return 0 + const index = endpoints.findIndex(endpoint => endpoint.url === activeUrl) + return index === -1 ? 0 : index + })() + const currentUrl = endpoints[currentIndex].url + const currentState = states.get(currentUrl) + + // 首次选择:默认地址已确认不可达,且别处可达 → 立刻换(一次探测即可定性)。 + // 只在前方不可达时动手:默认地址好好的就别多发一次切换广播。 + if (!activeUrl) { + if (currentState && !currentState.reachable) { + const backup = bestReachable(endpoints, states, currentIndex) + if (backup) return { url: backup, reason: 'failover' } + } + return null + } + + // 当前地址连续失败 → 换到「可达地址里优先级最高的那条」。 + // 注意是全局挑最优,不是只往后找:当前若是低优先级地址失效, + // 而高优先级恰好恢复,也该直接切过去,不该卡在更低优先级上。 + if (currentState && currentState.consecutiveFail >= DEGRADE_FAIL_THRESHOLD) { + const target = bestReachable(endpoints, states, currentIndex) + return target ? { url: target, reason: 'failover' } : null + } + + // 当前地址健康 → 只有当更高优先级的地址连续成功够多、且已稳定运行 + // 超过滞回窗口,才切回去。只做降级会永久停在公网,只做升级会来回横跳。 + if (!currentState?.reachable) return null + if (elapsedSinceSwitchMs < UPGRADE_DWELL_MS) return null + + for (let i = 0; i < currentIndex; i++) { + const state = states.get(endpoints[i].url) + if (state?.reachable && state.consecutiveOk >= UPGRADE_OK_THRESHOLD) { + return { url: endpoints[i].url, reason: 'recover' } + } + } + + return null +} + +/** + * 在「除 currentIndex 外」的地址里挑可达且优先级最高(index 最小)的那条。 + * 全部不可达时返回 null —— 调用方据此「保持现状」,不随机挑。 + */ +function bestReachable( + endpoints: ServerEndpoint[], + states: Map, + currentIndex: number, +): string | null { + for (let i = 0; i < endpoints.length; i++) { + if (i === currentIndex) continue + if (states.get(endpoints[i].url)?.reachable) return endpoints[i].url + } + return null +} + +/** + * 用一次探测结果更新状态(纯函数,返回新状态,不改原对象)。 + */ +export function applyProbeResult( + previous: EndpointProbeState | undefined, + reachable: boolean, + latency: number | undefined, + now: number, +): EndpointProbeState { + const base = previous ?? { reachable: false, consecutiveOk: 0, consecutiveFail: 0, lastChecked: 0 } + return { + reachable, + latency: reachable ? latency : undefined, + consecutiveOk: reachable ? base.consecutiveOk + 1 : 0, + consecutiveFail: reachable ? 0 : base.consecutiveFail + 1, + lastChecked: now, + } +} + +/** 读取某服务器某地址的探测状态(测试与调试用) */ +export function getProbeState(serverId: string, url: string): EndpointProbeState | undefined { + return probeStates.get(serverId)?.get(url) +} + +/** 清空全部探测状态(网络事件、测试用) */ +export function resetAllProbeStates(): void { + probeStates.clear() +} + +let timer: ReturnType | null = null +let listenersRegistered = false +/** + * 正在探测的服务器。主线轮询(15s)和归位探测(3s)是两个独立定时器, + * 相位总会撞上;并发探同一台会让 consecutiveOk/Fail 一轮涨两次, + * 升级/降级阈值被变相减半,切地址开始抖动。 + */ +const inFlightServers = new Set() + +/** + * 对一台多地址服务器跑一轮探测,并按结果决定是否切换。 + * 导出供测试直接驱动,不需等真实定时器。 + */ +export async function probeServerOnce(serverId: string, now = performance.now()): Promise { + if (inFlightServers.has(serverId)) return + inFlightServers.add(serverId) + try { + await probeServerOnceInner(serverId, now) + } finally { + inFlightServers.delete(serverId) + } +} + +async function probeServerOnceInner(serverId: string, now: number): Promise { + const server = serverStore.getServer(serverId) + if (!server?.endpoints || server.endpoints.length < 2) { + // 地址被删光 / 退回单地址:连带清掉陈旧状态,避免 Map 只增不减 + probeStates.delete(serverId) + return + } + + const runtime = serverStore.getEndpointRuntime(serverId) + // 锁定期间完全让位 + if (runtime.lockedUrl) return + + const states = probeStates.get(serverId) ?? new Map() + probeStates.set(serverId, states) + + // 用户改过地址列表:丢掉已不存在的地址的历史,避免陈旧计数参与决策 + const live = new Set(server.endpoints.map(endpoint => endpoint.url)) + for (const url of states.keys()) { + if (!live.has(url)) states.delete(url) + } + + const auth: ServerAuth | undefined = server.auth + + // 并发探测所有地址:地址数很少(通常 2 个),并发能压缩单轮耗时 + const results = await Promise.all( + server.endpoints.map(async endpoint => ({ + url: endpoint.url, + latency: await serverStore.probeEndpoint(endpoint.url, auth, PROBE_TIMEOUT_MS), + })), + ) + + for (const { url, latency } of results) { + states.set(url, applyProbeResult(states.get(url), latency !== null, latency ?? undefined, now)) + } + + const decision = decideEndpointSwitch( + server.endpoints, + runtime.activeUrl, + states, + now - runtime.lastSwitchAt, + ) + if (!decision) return + + const switched = serverStore.setActiveEndpoint(serverId, decision.url) + if (switched) { + logger.log( + `[endpointProbe] ${serverId}: ${decision.reason} → ${decision.url} ` + + `(latency ${states.get(decision.url)?.latency ?? '?'}ms)`, + ) + } +} + +/** + * 传输层报错 → 立刻探测并补一轮。 + * + * SSE 断开/报错是「当前入口可能不可达」的最快信号。15s 轮询要等到下一个 + * 周期才知道网络变了;这里收到信号就探,探出当前地址死掉后补一轮凑够降级 + * 阈值,把换地址压到秒级。 + * + * 节流:SSE 会自动重试,每次失败都来一遍会把探测刷爆。 + */ +const fastProbeState = new Map | null }>() + +function handleTransportFailure(serverId: string): void { + // 只关心配了多地址、且没锁定的服务器 + const server = serverStore.getServer(serverId) + if (!server?.endpoints || server.endpoints.length < 2) return + if (serverStore.getEndpointRuntime(serverId).lockedUrl) return + + const now = Date.now() + const entry = fastProbeState.get(serverId) ?? { lastAt: 0, confirmTimer: null } + if (now - entry.lastAt < FAST_PROBE_THROTTLE_MS) return + entry.lastAt = now + + if (entry.confirmTimer) clearTimeout(entry.confirmTimer) + entry.confirmTimer = setTimeout(() => { + entry.confirmTimer = null + // 第一轮:确认当前地址是否真死了 + void probeServerOnce(serverId).then(() => { + const runtime = serverStore.getEndpointRuntime(serverId) + const activeStillFailing = probeStates + .get(serverId) + ?.get(runtime.activeUrl ?? server.endpoints![0].url) + if (!activeStillFailing || activeStillFailing.reachable) return + // 第二轮:当前地址确实不可达 → 再探一次凑够降级阈值,尽快切走 + entry.confirmTimer = setTimeout(() => { + entry.confirmTimer = null + void probeServerOnce(serverId) + }, CONFIRM_DELAY_MS) + }) + }, CONFIRM_DELAY_MS) + fastProbeState.set(serverId, entry) +} + +/** 观察到的连接状态(只在「从可用变成不可用」时触发快速探测) */ +const observedConnectionStates = new Map() +const observedServers = new Set() +/** 每个已观察服务器的退订函数。服务器删除时必须调用,否则 connectionListeners 只增不减 */ +const observedUnsubscribes = new Map void>() + +function registerConnectionObservers(): void { + const liveIds = new Set() + for (const server of serverStore.getStoredServers()) { + const serverId = server.id + liveIds.add(serverId) + if (observedServers.has(serverId)) continue + observedServers.add(serverId) + const unsubscribe = subscribeToServerConnectionState(serverId, info => { + const previous = observedConnectionStates.get(serverId) + observedConnectionStates.set(serverId, info.state) + // 只对「曾经连上过、现在掉了」出手;首次连接中的 error 不算 + if (previous === 'connected' && info.state !== 'connected') { + handleTransportFailure(serverId) + } + }) + observedUnsubscribes.set(serverId, unsubscribe) + } + // 服务器被删 → 退订并清掉观察状态,否则删了再加会漏订阅、 + // 且 events 模块里的监听器集合只增不减(旧连接对象被永久持有) + for (const serverId of [...observedServers]) { + if (liveIds.has(serverId)) continue + observedUnsubscribes.get(serverId)?.() + observedUnsubscribes.delete(serverId) + observedServers.delete(serverId) + observedConnectionStates.delete(serverId) + const entry = fastProbeState.get(serverId) + if (entry?.confirmTimer) clearTimeout(entry.confirmTimer) + fastProbeState.delete(serverId) + } +} + +async function runProbeRound(): Promise { + // 离线 / 页面隐藏时不探测:离线时全部地址必然失败,探了只会污染计数; + // 隐藏时省电。恢复在线 / 可见时事件会立即补一轮。 + if (typeof navigator !== 'undefined' && navigator.onLine === false) return + if (typeof document !== 'undefined' && document.visibilityState === 'hidden') return + const servers = serverStore.getStoredServers() + // 逐台快照:probeServerOnce 内部已按 serverId 去重,这里不需要全局闸门 + await Promise.allSettled(servers.map(server => probeServerOnce(server.id))) +} + +/** + * 该服务器是否处于「降级状态」——即当前生效的不是最高优先级地址。 + * 只有这种状态下才需要加密探测等高优先级恢复。 + */ +function isDegraded(serverId: string): boolean { + const server = serverStore.getServer(serverId) + if (!server?.endpoints || server.endpoints.length < 2) return false + const runtime = serverStore.getEndpointRuntime(serverId) + if (runtime.lockedUrl) return false + const active = runtime.activeUrl ?? server.endpoints[0].url + return active !== server.endpoints[0].url +} + +let recoveryTimer: ReturnType | null = null + +/** + * 归位探测:处于降级状态时,用更快的节奏探(默认 3s), + * 连续 N 次成功 + 滞回满足就能尽快切回内网。 + * + * 代价可控:只有「当前没走最优地址」的服务器才会被高频探测, + * 正常状态下这个循环什么都不做。 + */ +async function runRecoveryRound(): Promise { + if (typeof navigator !== 'undefined' && navigator.onLine === false) return + if (typeof document !== 'undefined' && document.visibilityState === 'hidden') return + const degraded = serverStore.getStoredServers().filter(server => isDegraded(server.id)) + if (degraded.length === 0) return + await Promise.allSettled(degraded.map(server => probeServerOnce(server.id))) +} + +/** 已注册的全局监听撤销函数(stop 时统一回收,避免重复注册 / 泄漏) */ +const listenerDisposers: Array<() => void> = [] + +function registerProbeListeners(): void { + if (listenersRegistered) return + if (typeof window === 'undefined') return + listenersRegistered = true + + // 网络切换后探测历史一律作废(RFC 8305 §4):断网期间的失败计数 + // 不能带到恢复后的判断里 + const onOnline = () => { + resetAllProbeStates() + void runProbeRound() + } + const onOffline = () => resetAllProbeStates() + window.addEventListener('online', onOnline) + window.addEventListener('offline', onOffline) + listenerDisposers.push(() => { + window.removeEventListener('online', onOnline) + window.removeEventListener('offline', onOffline) + }) + + // 回到前台立即补一轮:后台期间没探测,回来时可能已经换了网络环境 + if (typeof document !== 'undefined') { + const onVisibility = () => { + if (document.visibilityState === 'visible') { + void runProbeRound() + void runRecoveryRound() + } + } + document.addEventListener('visibilitychange', onVisibility) + listenerDisposers.push(() => document.removeEventListener('visibilitychange', onVisibility)) + } + + // 服务器增删也会影响观察集合(新加的多地址服务器也要能吃到快速探测) + const unsubscribeStore = serverStore.subscribe(() => registerConnectionObservers()) + listenerDisposers.push(unsubscribeStore) + registerConnectionObservers() +} + +/** + * 启动自动探测循环。重复调用安全(幂等)。 + * 只在存在多地址服务器时才产生网络开销。 + */ +export function startEndpointProbe(): void { + if (timer) return + registerProbeListeners() + // 首轮立即跑,让「初次启动按内外网选一个」尽快生效; + // 但错开一个宏任务,避免挡住首屏渲染 + void runProbeRound() + timer = setInterval(() => void runProbeRound(), PROBE_INTERVAL_MS) + + // 归位探测:降级状态下加密探测高优先级地址,别让用户干等 15s 轮询 + recoveryTimer = setInterval(() => void runRecoveryRound(), RECOVERY_PROBE_INTERVAL_MS) +} + +/** 停止探测循环(测试 / 卸载用) */ +export function stopEndpointProbe(): void { + if (timer) { + clearInterval(timer) + timer = null + } + if (recoveryTimer) { + clearInterval(recoveryTimer) + recoveryTimer = null + } + for (const entry of fastProbeState.values()) { + if (entry.confirmTimer) clearTimeout(entry.confirmTimer) + } + fastProbeState.clear() + // 观察订阅也要断开:否则停了线性循环、旧监听器还在触发快速探测 + for (const unsubscribe of observedUnsubscribes.values()) unsubscribe() + observedUnsubscribes.clear() + observedServers.clear() + observedConnectionStates.clear() + // 全局监听同样回收,允许 stop 之后重新 start + for (const dispose of listenerDisposers) dispose() + listenerDisposers.length = 0 + listenersRegistered = false +} diff --git a/src/store/serverChangeScope.ts b/src/store/serverChangeScope.ts index bf0faa3b9..637897c89 100644 --- a/src/store/serverChangeScope.ts +++ b/src/store/serverChangeScope.ts @@ -13,9 +13,16 @@ import type { ServerChangeReason } from './serverStore' * * - boundServerId 为空(数据主体跟随 active 服务器): * - server-switch:active 本身换了(含删除回退)→ 影响 + * - endpoint-switch:同一台服务器换入口地址,数据主体(会话/消息/布局)**不变**, + * 补偿刷新交给 SSE 重连后的 onReconnected → 不影响 * - 端点变化类 reason(WSL 换端口等):只有变的这台恰好是当前 active 才影响 * (非 active 重启不该让 active 数据「清空 → 重拉」闪烁) * - boundServerId 指定(面板/订阅固定绑定这台服务器):变化发生在这台本身才影响 + * + * 注意 endpoint-switch 对**两种**绑定都返回 false: + * 换入口地址时旧地址可能仍然可达,数据也没变,做「清空 → 重拉」只会闪。 + * 需要跟着新地址走的副作用(SSE / 终端 WebSocket)由 events.ts 与各面板 + * 自己监听 endpoint-switch 处理,不走这个「数据是否失效」的判据。 */ export function affectsBoundServer( boundServerId: string | undefined | null, @@ -23,6 +30,9 @@ export function affectsBoundServer( reason: ServerChangeReason, activeServerId: string, ): boolean { + // 换入口地址不改数据主体:避免触发「清空 → 重拉」的可见闪烁, + // 由 SSE 重连的 onReconnected 做补偿(见 events.ts 的 endpoint-switch 分支) + if (reason === 'endpoint-switch') return false if (boundServerId) return changedServerId === boundServerId if (reason === 'server-switch') return true return activeServerId === changedServerId diff --git a/src/store/serverEndpoints.test.ts b/src/store/serverEndpoints.test.ts new file mode 100644 index 000000000..e6084c404 --- /dev/null +++ b/src/store/serverEndpoints.test.ts @@ -0,0 +1,294 @@ +// 多地址(Issue #183):地址归一化、生效地址切换、锁定、持久化与门控语义。 +import { beforeEach, describe, expect, it, vi } from 'vitest' + +beforeEach(() => { + vi.resetModules() + localStorage.clear() + sessionStorage.clear() +}) + +describe('normalizeEndpoints', () => { + it('去尾部斜杠、去重、按 priority 升序', async () => { + const { normalizeEndpoints } = await import('./serverStore') + + expect( + normalizeEndpoints([ + { url: 'https://public.example.com/', priority: 1 }, + { url: 'http://192.168.1.5:4096', priority: 0 }, + { url: 'http://192.168.1.5:4096/', priority: 0 }, + ]), + ).toEqual([ + { url: 'http://192.168.1.5:4096', priority: 0 }, + { url: 'https://public.example.com', priority: 1 }, + ]) + }) + + it('丢弃非法项,空结果返回 undefined(退回单地址语义)', async () => { + const { normalizeEndpoints } = await import('./serverStore') + + expect(normalizeEndpoints([])).toBeUndefined() + expect(normalizeEndpoints(null)).toBeUndefined() + expect(normalizeEndpoints([null, 42, 'x', { url: '' }, {}])).toBeUndefined() + expect(normalizeEndpoints([{ url: ' http://a.test// ', priority: 'bad' }])).toEqual([ + { url: 'http://a.test', priority: 0 }, + ]) + }) + + it('保留 label,空 label 剔除', async () => { + const { normalizeEndpoints } = await import('./serverStore') + + expect( + normalizeEndpoints([ + { url: 'http://lan.test', priority: 0, label: ' 内网 ' }, + { url: 'http://wan.test', priority: 1, label: ' ' }, + ]), + ).toEqual([ + { url: 'http://lan.test', priority: 0, label: '内网' }, + { url: 'http://wan.test', priority: 1 }, + ]) + }) +}) + +describe('serverStore 多地址', () => { + it('默认退化:无 endpoints 时 baseUrl 就是 server.url', async () => { + const { serverStore } = await import('./serverStore') + const server = serverStore.addServer({ name: 'single', url: 'http://only.test/' }) + + expect(server.endpoints).toBeUndefined() + expect(serverStore.getServerBaseUrl(server.id)).toBe('http://only.test') + expect(serverStore.getActiveEndpointUrl(server.id)).toBe('http://only.test') + }) + + it('addServer 归一化 endpoints 并按优先级排序', async () => { + const { serverStore } = await import('./serverStore') + const server = serverStore.addServer({ + name: 'dual', + url: 'https://wan.test', + endpoints: [ + { url: 'https://wan.test/', priority: 1 }, + { url: 'http://lan.test/', priority: 0 }, + ], + }) + + expect(server.endpoints).toEqual([ + { url: 'http://lan.test', priority: 0 }, + { url: 'https://wan.test', priority: 1 }, + ]) + // endpoints 存在时以「优先级最高」为默认入口——这就是 issue 要的 + // 「默认优先内网」:配对时把内网排第一即可,无需额外开关 + expect(serverStore.getServerBaseUrl(server.id)).toBe('http://lan.test') + expect(serverStore.getActiveEndpointUrl(server.id)).toBe('http://lan.test') + }) + + it('setActiveEndpoint 切换 baseUrl 并广播 endpoint-switch(不是 server-switch)', async () => { + const { serverStore } = await import('./serverStore') + const server = serverStore.addServer({ + name: 'dual', + url: 'http://lan.test', + endpoints: [ + { url: 'http://lan.test', priority: 0 }, + { url: 'https://wan.test', priority: 1 }, + ], + }) + const listener = vi.fn() + serverStore.onServerChange(listener) + + expect(serverStore.setActiveEndpoint(server.id, 'https://wan.test')).toBe(true) + + expect(serverStore.getServerBaseUrl(server.id)).toBe('https://wan.test') + expect(listener).toHaveBeenCalledWith(server.id, 'endpoint-switch') + }) + + it('setActiveEndpoint 拒绝不属于该服务器的地址', async () => { + const { serverStore } = await import('./serverStore') + const server = serverStore.addServer({ name: 'single', url: 'http://only.test' }) + + expect(serverStore.setActiveEndpoint(server.id, 'http://evil.test')).toBe(false) + expect(serverStore.getServerBaseUrl(server.id)).toBe('http://only.test') + }) + + it('重复切到同一地址不广播(幂等)', async () => { + const { serverStore } = await import('./serverStore') + const server = serverStore.addServer({ + name: 'dual', + url: 'http://a.test', + endpoints: [ + { url: 'http://a.test', priority: 0 }, + { url: 'http://b.test', priority: 1 }, + ], + }) + const listener = vi.fn() + + serverStore.setActiveEndpoint(server.id, 'http://b.test') + serverStore.onServerChange(listener) + expect(serverStore.setActiveEndpoint(server.id, 'http://b.test')).toBe(false) + expect(listener).not.toHaveBeenCalled() + }) + + it('锁定地址后自动探测必须让位(lockedUrl 可读)', async () => { + const { serverStore } = await import('./serverStore') + const server = serverStore.addServer({ + name: 'dual', + url: 'http://lan.test', + endpoints: [ + { url: 'http://lan.test', priority: 0 }, + { url: 'https://wan.test', priority: 1 }, + ], + }) + + expect(serverStore.setLockedEndpoint(server.id, 'https://wan.test')).toBe(true) + expect(serverStore.getLockedEndpointUrl(server.id)).toBe('https://wan.test') + expect(serverStore.getServerBaseUrl(server.id)).toBe('https://wan.test') + + // 解锁恢复自动模式 + expect(serverStore.setLockedEndpoint(server.id, null)).toBe(true) + expect(serverStore.getLockedEndpointUrl(server.id)).toBeNull() + }) + + it('删除地址后回收生效/锁定指针,避免指向已不存在的地址', async () => { + const { serverStore } = await import('./serverStore') + const server = serverStore.addServer({ + name: 'dual', + url: 'http://lan.test', + endpoints: [ + { url: 'http://lan.test', priority: 0 }, + { url: 'https://wan.test', priority: 1 }, + ], + }) + serverStore.setLockedEndpoint(server.id, 'https://wan.test') + + // 编辑时把 wan 地址删掉 + serverStore.updateServer(server.id, { endpoints: [{ url: 'http://lan.test', priority: 0 }] }) + + expect(serverStore.getLockedEndpointUrl(server.id)).toBeNull() + expect(serverStore.getServerBaseUrl(server.id)).toBe('http://lan.test') + }) + + it('upsertServer 删掉地址后同样回收指针(WSL 重启重注册走这条路)', async () => { + const { serverStore } = await import('./serverStore') + const server = serverStore.upsertServer({ + id: 'wsl-like', + name: 'dual', + url: 'http://lan.test', + endpoints: [ + { url: 'http://lan.test', priority: 0 }, + { url: 'https://wan.test', priority: 1 }, + ], + }) + serverStore.setLockedEndpoint(server.id, 'https://wan.test') + expect(serverStore.getServerBaseUrl(server.id)).toBe('https://wan.test') + + // 外部模块(WSL 就绪推送)用新地址集覆盖:wan 没了 + serverStore.upsertServer({ + id: 'wsl-like', + name: 'dual', + url: 'http://lan.test', + endpoints: [{ url: 'http://lan.test', priority: 0 }], + }) + + // 不回收的话 baseUrl 会一直停在已经不存在的 wan 上 + expect(serverStore.getLockedEndpointUrl(server.id)).toBeNull() + expect(serverStore.getServerBaseUrl(server.id)).toBe('http://lan.test') + }) + + it('getActiveBaseUrl 跟随生效地址(sdk/http 不传 serverId 时走这条路)', async () => { + const { serverStore } = await import('./serverStore') + const server = serverStore.addServer({ + name: 'dual', + url: 'http://lan.test', + endpoints: [ + { url: 'http://lan.test', priority: 0 }, + { url: 'https://wan.test', priority: 1 }, + ], + }) + serverStore.setActiveServer(server.id) + + expect(serverStore.getActiveBaseUrl()).toBe('http://lan.test') + + serverStore.setActiveEndpoint(server.id, 'https://wan.test') + expect(serverStore.getActiveBaseUrl()).toBe('https://wan.test') + }) + + it('isLocalServer 判的是当前生效地址,不是配置主地址', async () => { + const { serverStore } = await import('./serverStore') + const server = serverStore.addServer({ + name: 'dual', + url: 'http://127.0.0.1:4096', + endpoints: [ + { url: 'http://127.0.0.1:4096', priority: 0 }, + { url: 'http://192.168.1.5:4096', priority: 1 }, + ], + }) + + // 走回环入口 → 同机 + expect(serverStore.isLocalServer(server.id)).toBe(true) + + // 降级到内网 IP → 不再同机(拖入的文件必须上传) + serverStore.setActiveEndpoint(server.id, 'http://192.168.1.5:4096') + expect(serverStore.isLocalServer(server.id)).toBe(false) + }) + + it('endpoints 走 localStorage 持久化,重载后仍在', async () => { + const { serverStore } = await import('./serverStore') + const server = serverStore.addServer({ + name: 'dual', + url: 'http://lan.test', + endpoints: [ + { url: 'http://lan.test', priority: 0 }, + { url: 'https://wan.test', priority: 1 }, + ], + }) + + const stored = JSON.parse(localStorage.getItem('opencode-servers') ?? '[]') as Array<{ + id: string + endpoints?: unknown + }> + const persisted = stored.find(item => item.id === server.id) + expect(persisted?.endpoints).toEqual([ + { url: 'http://lan.test', priority: 0 }, + { url: 'https://wan.test', priority: 1 }, + ]) + + // 重载:运行时的 activeUrl / lockedUrl 不持久化,必须重新判断 + vi.resetModules() + const reloaded = await import('./serverStore') + expect(reloaded.serverStore.getServer(server.id)?.endpoints).toHaveLength(2) + expect(reloaded.serverStore.getServerBaseUrl(server.id)).toBe('http://lan.test') + }) + + it('删除服务器时清理运行时状态', async () => { + const { serverStore } = await import('./serverStore') + const server = serverStore.addServer({ + name: 'dual', + url: 'http://a.test', + endpoints: [ + { url: 'http://a.test', priority: 0 }, + { url: 'http://b.test', priority: 1 }, + ], + }) + serverStore.setLockedEndpoint(server.id, 'http://b.test') + expect(serverStore.getLockedEndpointUrl(server.id)).toBe('http://b.test') + + expect(serverStore.removeServer(server.id)).toBe(true) + // 服务器已删除 → 运行时状态不应残留(读取返回空语义) + expect(serverStore.getServer(server.id)).toBeNull() + expect(serverStore.getLockedEndpointUrl(server.id)).toBeNull() + }) +}) + +describe('endpoint-switch 的门控语义', () => { + it('换地址不影响数据主体:两种绑定都返回 false', async () => { + const { affectsBoundServer } = await import('./serverChangeScope') + + // 跟随 active:不触发「清空 → 重拉」 + expect(affectsBoundServer(undefined, 'local', 'endpoint-switch', 'local')).toBe(false) + // 固定绑定同一台:同样不重置数据(旧地址可能仍可达,重置只会闪) + expect(affectsBoundServer('local', 'local', 'endpoint-switch', 'local')).toBe(false) + }) + + it('对比:server-runtime-updated 在固定绑定时仍需重置(旧端口已死)', async () => { + const { affectsBoundServer } = await import('./serverChangeScope') + + expect(affectsBoundServer('local', 'local', 'server-runtime-updated', 'local')).toBe(true) + }) +}) diff --git a/src/store/serverStore.ts b/src/store/serverStore.ts index 38fd5cd41..23d6c6a94 100644 --- a/src/store/serverStore.ts +++ b/src/store/serverStore.ts @@ -28,13 +28,34 @@ export interface ServerAuth { password: string // 密码 } +/** + * 服务器地址(Issue #183:同一台服务器可有多个入口)。 + * + * 典型场景:`opencode serve` 同时有内网直连和公网隧道两个入口。 + * `priority` 越小越优先(内网 0,公网 1)——这是**主备**语义,不是负载均衡: + * 高优先级可达就不去比延迟,只有同类地址之间才看 latency。 + */ +export interface ServerEndpoint { + /** 归一化后的服务器地址(不含尾部斜杠) */ + url: string + /** 优先级,越小越优先;同优先级之间才按延迟比较 */ + priority: number + /** 用户可读标签(如「内网」「公网」),仅展示 */ + label?: string +} + /** * 服务器配置 */ export interface ServerConfig { id: string // 唯一标识 name: string // 显示名称 - url: string // 服务器 URL (不含尾部斜杠) + url: string // 主地址 (不含尾部斜杠);等价 endpoints 中优先级最高者 + /** + * 多地址列表(可选)。缺省表示单地址服务器,行为与旧版完全一致。 + * 存在时 `url` 仍是主地址,`getServerBaseUrl` 会优先返回当前生效地址。 + */ + endpoints?: ServerEndpoint[] isDefault?: boolean // 是否为默认服务器 auth?: ServerAuth // 认证信息 (可选) } @@ -64,12 +85,69 @@ interface ServerClockCalibration { } type Listener = () => void -export type ServerChangeReason = 'server-switch' | 'local-runtime-url' | 'server-runtime-updated' +export type ServerChangeReason = + | 'server-switch' + | 'local-runtime-url' + | 'server-runtime-updated' + /** + * 同一台服务器换入口地址(Issue #183:内网 ↔ 公网切换)。 + * + * 与 server-switch 的区别:数据主体(会话/消息/布局)**不变**, + * 只是 baseUrl 换了。因此消费方不该走「清空 → 重拉」, + * 而应交由 SSE 重连后的 onReconnected 做补偿刷新。 + */ + | 'endpoint-switch' function isRecord(value: unknown): value is Record { return !!value && typeof value === 'object' && !Array.isArray(value) } +/** + * 归一化单条地址:去尾部斜杠。非字符串 / 空串返回 undefined。 + */ +function normalizeEndpointUrl(value: unknown): string | undefined { + if (typeof value !== 'string') return undefined + const trimmed = value.trim() + if (!trimmed) return undefined + return trimmed.replace(/\/+$/, '') +} + +/** + * 解析并归一化服务器的多地址列表(持久化与备份导入共用)。 + * + * - 丢弃非法项(非对象 / url 非字符串) + * - 按 url 去重(保留首次出现的优先级) + * - 按 priority 升序稳定排序 + * - 空结果返回 undefined(表示退回单地址语义) + */ +export function normalizeEndpoints(raw: unknown): ServerEndpoint[] | undefined { + if (!Array.isArray(raw)) return undefined + + const seen = new Set() + const parsed: ServerEndpoint[] = [] + for (const item of raw) { + if (!isRecord(item)) continue + const url = normalizeEndpointUrl(item.url) + if (!url || seen.has(url)) continue + seen.add(url) + const priority = typeof item.priority === 'number' && Number.isFinite(item.priority) ? item.priority : 0 + const label = typeof item.label === 'string' && item.label.trim() ? item.label.trim() : undefined + parsed.push({ url, priority, ...(label ? { label } : {}) }) + } + + if (parsed.length === 0) return undefined + // 稳定排序:priority 相同的保持录入顺序 + return parsed.sort((a, b) => a.priority - b.priority) +} + +/** + * 取「优先级最高的地址」,即地址列表的主地址。 + * 无 endpoints 时返回 undefined(调用方退回 `server.url`)。 + */ +export function primaryEndpointUrl(endpoints: ServerEndpoint[] | undefined): string | undefined { + return endpoints?.[0]?.url +} + /** * 把「监听所有接口」的绑定地址归一化成可连接的地址。 * @@ -178,6 +256,37 @@ function isSameServerAuth(a: ServerAuth | undefined, b: ServerAuth | undefined): return a?.username === b?.username && a?.password === b?.password } +/** 多地址列表是否等价(顺序敏感——priority 排序后顺序即语义) */ +function isSameEndpoints(a: ServerEndpoint[] | undefined, b: ServerEndpoint[] | undefined): boolean { + if (a === b) return true + if (!a || !b) return false + if (a.length !== b.length) return false + return a.every((endpoint, index) => { + const other = b[index] + return endpoint.url === other.url && endpoint.priority === other.priority && endpoint.label === other.label + }) +} + +/** + * 多地址的运行时状态(**不持久化**)。 + * + * 持久层只存「用户配了哪些地址」;「此刻在用哪个」是运行时事实, + * 每次启动都该按网络环境重新探测/回退,存下来反而会让下次启动落在死地址上。 + */ +export interface EndpointRuntime { + /** 当前生效地址;null 表示尚未选定,getter 退化为 server.url */ + activeUrl: string | null + /** 用户手动锁定的地址;非 null 时自动探测完全让位 */ + lockedUrl: string | null + /** 上次自动/手动切地址的单调时刻(performance.now()),升级滞回用 */ + lastSwitchAt: number +} + +/** 空的运行时状态(新服务器 / 未初始化)。集中构造,避免漏字段 */ +function emptyEndpointRuntime(): EndpointRuntime { + return { activeUrl: null, lockedUrl: null, lastSwitchAt: 0 } +} + /** * Server Store * 管理多个 OpenCode 后端服务器配置 @@ -192,6 +301,8 @@ class ServerStore { private lastClockCalibrationAt = new Map() private listeners: Set = new Set() private localServerUrlOverride: string | null = null + /** 多地址运行时状态(按 serverId);见 EndpointRuntime 注释 */ + private endpointRuntime = new Map() // 上次关闭时用户停留的 WSL 服务器 id(wslStore 就绪后据此恢复 active) private bootIntentServerId: string | null = null // 启动默认服务器偏好(内存缓存,随 notify 快照供 React 订阅) @@ -204,6 +315,8 @@ class ServerStore { private _serversSnapshot: ServerConfig[] = [] private _activeServerSnapshot: ServerConfig | null = null private _healthMapSnapshot: Map = new Map() + /** 多地址运行时状态快照(生效地址 / 锁定地址) */ + private _endpointStateSnapshot: Map = new Map() // 默认本地服务器 ID private readonly DEFAULT_SERVER_ID = LOCAL_SERVER_ID @@ -229,9 +342,11 @@ class ServerStore { // 遗留的 wsl: 条目,避免老用户下次启动先落在死地址上 const stored = localStorage.getItem(STORAGE_KEY) if (stored) { - this.servers = (JSON.parse(stored) as ServerConfig[]).filter( - server => typeof server?.id === 'string' && !server.id.startsWith(WSL_SERVER_PREFIX), - ) + this.servers = (JSON.parse(stored) as ServerConfig[]) + .filter(server => typeof server?.id === 'string' && !server.id.startsWith(WSL_SERVER_PREFIX)) + // endpoints 归一化:旧数据没有该字段(→ undefined,保持单地址语义), + // 手改 / 历史脏值则在此清洗,不让非法地址流进运行时 + .map(server => ({ ...server, endpoints: normalizeEndpoints(server.endpoints) })) } // 如果没有服务器,添加默认的本地服务器 @@ -339,6 +454,11 @@ class ServerStore { this._serversSnapshot = this.servers.map(server => this.withRuntimeServerUrl(server)) this._activeServerSnapshot = this._serversSnapshot.find(s => s.id === this.activeServerId) ?? null this._healthMapSnapshot = new Map(this.healthMap) + // 运行时地址状态(生效/锁定)也要有快照:UI 靠它决定「使用中」「已锁定」标记。 + // 复制成新 Map,保证 useSyncExternalStore 能看出变化 + this._endpointStateSnapshot = new Map( + this.servers.map(server => [server.id, this.endpointRuntime.get(server.id) ?? emptyEndpointRuntime()]), + ) } private withRuntimeServerUrl(server: ServerConfig): ServerConfig { @@ -379,11 +499,36 @@ class ServerStore { } /** - * 获取指定服务器(含 runtime URL override)的 base URL + * 获取指定服务器(含 runtime URL override)的 base URL。 + * + * 多地址服务器返回**当前生效地址**(`activeUrl`),未选定时退回主地址 + * `server.url`。SDK / http 层的 baseUrl 全部经此读取,因此切换地址 + * 不需要改动 sdk.ts。 */ getServerBaseUrl(serverId: string): string { + return this.getActiveEndpointUrl(serverId) + } + + /** 读取多地址运行时状态(不存在时返回空对象,不创建) */ + getEndpointRuntime(serverId: string): Readonly { + return this.endpointRuntime.get(serverId) ?? emptyEndpointRuntime() + } + + /** 当前生效地址(含单地址服务器与 local runtime override 的退化) */ + getActiveEndpointUrl(serverId: string): string { const server = this.servers.find(s => s.id === serverId) - return server ? this.withRuntimeServerUrl(server).url : API_BASE_URL + if (!server) return API_BASE_URL + const active = this.endpointRuntime.get(serverId)?.activeUrl + if (active) return active + // 单地址服务器:local 由运行时注入真实回环地址(见 withRuntimeServerUrl), + // 其余服务器取 endpoints 主地址(无 endpoints 时即 url 本身) + const runtimeUrl = this.withRuntimeServerUrl(server).url + return primaryEndpointUrl(server.endpoints) ?? runtimeUrl + } + + /** 已锁定的地址;null 表示未锁定(自动模式) */ + getLockedEndpointUrl(serverId: string): string | null { + return this.endpointRuntime.get(serverId)?.lockedUrl ?? null } /** @@ -408,6 +553,10 @@ class ServerStore { * - 用户手动添加的服务器:按 URL 的 host 判(`localhost` / `127.0.0.1` / * `[::1]`)。 * + * 多地址服务器(Issue #183)判的是**当前生效地址**,不是配置里的主地址: + * 同一台服务器走内网 IP 时不同机、走回环隧道时可能同机,取决于此刻连的是 + * 哪个入口。用主地址会把「已降级到公网」误判成同机。 + * * ⚠️ 已知边界:容器端口转发到回环(Docker `-p 127.0.0.1:4096`)会被判成同机, * 但服务端进程在容器里读不到宿主路径。调用方需要能容忍这一点(失败时退化 * 为上传/引用,不要让它变成"消息发不出去")。 @@ -416,8 +565,10 @@ class ServerStore { const id = serverId ?? this.getActiveServerId() if (id === this.DEFAULT_SERVER_ID) return true if (id.startsWith(WSL_SERVER_PREFIX)) return false + // 未知 id 按非同机处理(宁可上传,别拿本机路径去引用) + if (!this.getServer(id)) return false - return isLocalServerHost(this.getServer(id)?.url) + return isLocalServerHost(this.getServerBaseUrl(id)) } /** @@ -429,11 +580,13 @@ class ServerStore { } /** - * 获取当前 API Base URL + * 获取当前 API Base URL。 + * + * 走 getServerBaseUrl(= 当前生效地址),多地址服务器才能拿到实际在用的入口; + * 单地址 / local runtime override 的行为不变。 */ getActiveBaseUrl(): string { - const server = this.getActiveServer() - return server?.url ?? API_BASE_URL + return this.getServerBaseUrl(this.getActiveServerId()) } /** @@ -466,6 +619,16 @@ class ServerStore { return this._healthMapSnapshot } + /** + * 多地址运行时状态快照(按 serverId)。 + * + * 只读快照:UI 用它渲染「使用中 / 已锁定」;业务判断一律走 + * getServerBaseUrl / getActiveEndpointUrl,避免读到过期副本。 + */ + getEndpointStates(): Map> { + return this._endpointStateSnapshot + } + getActiveCalibratedNow(): number | undefined { const calibration = this.clockCalibrationMap.get(this.getActiveServerId()) if (!calibration) return undefined @@ -523,6 +686,7 @@ class ServerStore { ...config, id, url: config.url.replace(/\/+$/, ''), // 移除尾部斜杠 + endpoints: normalizeEndpoints(config.endpoints), } this.servers.push(server) this.saveToStorage() @@ -538,6 +702,7 @@ class ServerStore { const server: ServerConfig = { ...config, url: config.url.replace(/\/+$/, ''), // 移除尾部斜杠 + endpoints: normalizeEndpoints(config.endpoints), } const index = this.servers.findIndex(s => s.id === server.id) const previous = index === -1 ? undefined : this.servers[index] @@ -547,19 +712,28 @@ class ServerStore { previous && previous.name === server.name && previous.url === server.url && - isSameServerAuth(previous.auth, server.auth) + isSameServerAuth(previous.auth, server.auth) && + isSameEndpoints(previous.endpoints, server.endpoints) ) { return previous } // 端点/凭据是否变化。新增时 previous 为空,「可用端点从无到有」 // 对消费方与变更等价(WSL 就绪注册是典型场景) - const runtimeChanged = !previous || previous.url !== server.url || !isSameServerAuth(previous.auth, server.auth) + const runtimeChanged = + !previous || + previous.url !== server.url || + !isSameServerAuth(previous.auth, server.auth) || + !isSameEndpoints(previous.endpoints, server.endpoints) if (index === -1) { this.servers.push(server) } else { this.servers[index] = server } this.saveToStorage() + // 地址集变了:已选/已锁的地址可能已被删掉,必须回收, + // 否则 getServerBaseUrl 会一直返回一个不存在的地址。 + // 必须在 notify 之前——notify 负责重建 UI 快照。 + this.reconcileEndpointRuntime(server.id) this.notify() // 端点变化无条件广播(不限定 active):SSE/SDK 消费方建连时现读 serverStore, // 收到信号按 serverId 定向重建即拿到新值。active 与否只决定「谁正在用」, @@ -578,20 +752,124 @@ class ServerStore { if (index === -1) return false const server = this.servers[index] + const nextEndpoints = updates.endpoints !== undefined ? normalizeEndpoints(updates.endpoints) : server.endpoints this.servers[index] = { ...server, ...updates, id: server.id, // 确保 id 不被覆盖 url: updates.url ? updates.url.replace(/\/+$/, '') : server.url, + endpoints: nextEndpoints, } if (id === this.DEFAULT_SERVER_ID && updates.url) { this.localServerUrlOverride = null } + // 地址集变了:已有的生效地址 / 锁定地址可能已不存在,必须回收, + // 否则 getServerBaseUrl 会一直返回一个用户已经删掉的地址。 + this.reconcileEndpointRuntime(id) this.saveToStorage() this.notify() return true } + /** + * 回收失效的运行时地址。 + * + * `activeUrl` / `lockedUrl` 必须仍在当前地址集内,否则置空 + * (置空后 getter 退回主地址 `server.url`)。 + */ + private reconcileEndpointRuntime(serverId: string): void { + const server = this.servers.find(s => s.id === serverId) + const runtime = this.endpointRuntime.get(serverId) + if (!server || !runtime) return + + const known = new Set([ + ...(server.endpoints ?? []).map(endpoint => endpoint.url), + server.url, + ]) + const activeUrl = runtime.activeUrl && known.has(runtime.activeUrl) ? runtime.activeUrl : null + const lockedUrl = runtime.lockedUrl && known.has(runtime.lockedUrl) ? runtime.lockedUrl : null + if (activeUrl === runtime.activeUrl && lockedUrl === runtime.lockedUrl) return + this.endpointRuntime.set(serverId, { ...runtime, activeUrl, lockedUrl }) + } + + /** + * 切换生效地址(Issue #183)。 + * + * 地址必须属于该服务器的 endpoints(或等于 `server.url`)。切换后: + * - `getServerBaseUrl` 立即返回新地址 → SDK/http 自动指向新入口 + * - 广播 `endpoint-switch`(不是 server-switch),消费方据此重连 SSE + * 但不重置会话/消息(数据主体按 serverId 分片,未变) + */ + setActiveEndpoint(serverId: string, url: string): boolean { + const server = this.servers.find(s => s.id === serverId) + if (!server) return false + + const normalized = normalizeEndpointUrl(url) + if (!normalized) return false + const known = new Set([ + ...(server.endpoints ?? []).map(endpoint => endpoint.url), + server.url, + ]) + if (!known.has(normalized)) return false + + const runtime = this.endpointRuntime.get(serverId) ?? emptyEndpointRuntime() + if (runtime.activeUrl === normalized) return false + + // 记录切换时刻:自动升级要等滞回窗口(见 endpointProbe) + this.endpointRuntime.set(serverId, { + ...runtime, + activeUrl: normalized, + lastSwitchAt: performance.now(), + }) + this.notify() + this.notifyServerChange(serverId, 'endpoint-switch') + return true + } + + /** + * 锁定 / 解锁自动切换。 + * + * 传入地址即锁定到该地址(同时把它设为生效地址);传 null 解锁, + * 恢复自动探测。锁定期间探测模块必须完全让位(不得改动 activeUrl)。 + */ + setLockedEndpoint(serverId: string, url: string | null): boolean { + const server = this.servers.find(s => s.id === serverId) + if (!server) return false + + const runtime = this.endpointRuntime.get(serverId) ?? emptyEndpointRuntime() + + if (url === null) { + if (runtime.lockedUrl === null) return false + // 解锁即重新交给自动探测:滞回窗口从此刻起算,避免刚解锁就立刻被降级 + this.endpointRuntime.set(serverId, { ...runtime, lockedUrl: null, lastSwitchAt: performance.now() }) + this.notify() + return true + } + + const normalized = normalizeEndpointUrl(url) + if (!normalized) return false + const known = new Set([ + ...(server.endpoints ?? []).map(endpoint => endpoint.url), + server.url, + ]) + if (!known.has(normalized)) return false + if (runtime.lockedUrl === normalized && runtime.activeUrl === normalized) return false + + this.endpointRuntime.set(serverId, { + activeUrl: normalized, + lockedUrl: normalized, + lastSwitchAt: performance.now(), + }) + this.notify() + this.notifyServerChange(serverId, 'endpoint-switch') + return true + } + + /** 清理运行时状态(删除服务器时调用,避免 Map 只增不减) */ + private clearEndpointRuntime(serverId: string): void { + this.endpointRuntime.delete(serverId) + } + setLocalServerRuntimeUrl(url: string): boolean { if (!this.servers.some(s => s.id === this.DEFAULT_SERVER_ID)) return false @@ -621,6 +899,7 @@ class ServerStore { this.healthMap.delete(id) this.healthCheckSeqMap.delete(id) this.clockCalibrationMap.delete(id) + this.clearEndpointRuntime(id) // 默认服务器偏好指向被删服务器时必须一并清除(只增不减的隐患):否则下次启动仍会拿一个 // 已不存在的 id 当默认目标。仅限非 WSL:WSL 的 removeServer 常因瞬时未就绪(starting/stopped) @@ -843,6 +1122,43 @@ class ServerStore { async checkAllHealth(): Promise { await Promise.all(this.servers.map(s => this.checkHealth(s.id))) } + + /** + * 探测单个地址是否可达(Issue #183 多地址探测用)。 + * + * 与 checkHealth 的区别:**不写 healthMap、不通知订阅方**。它是 per-endpoint + * 的事实采集,读写它的只有探测循环;把结果塞进 per-server 的 healthMap 会污染 + * 服务器卡片上的健康灯。探测端点用 GET /api/info(无副作用,且能同时验证 + * 服务端身份——返回 401 说明地址可达但凭据不对,也算「可达」)。 + * + * @returns 可达时带延迟;不可达返回 null(超时/网络错误/非 JSON 响应) + */ + async probeEndpoint(url: string, auth: ServerAuth | undefined, timeoutMs = 4000): Promise { + const target = `${url.replace(/\/+$/, '')}/api/info` + const controller = new AbortController() + const timeoutId = setTimeout(() => controller.abort(), timeoutMs) + const startTime = Date.now() + + try { + const headers: Record = {} + if (auth?.password) { + headers['Authorization'] = makeBasicAuthHeader(auth) + } + const f = await getUnifiedFetch() + const response = await f(target, { method: 'GET', signal: controller.signal, headers }) + const latency = Date.now() - startTime + // 401 = 地址通、凭据待补,对「能不能连上」而言仍算可达 + if (response.status === 401) return latency + if (!response.ok) return null + // 服务器会对未知路径回退 SPA HTML,必须是 JSON 才算真服务端 + const contentType = response.headers.get('content-type')?.toLowerCase() ?? '' + return contentType.includes('application/json') ? latency : null + } catch { + return null + } finally { + clearTimeout(timeoutId) + } + } } // 单例导出 @@ -866,6 +1182,7 @@ function normalizeServerBackup(raw: unknown): ServerSettingsBackup { id: item.id, name: item.name, url: item.url.replace(/\/+$/, ''), + endpoints: normalizeEndpoints(item.endpoints), isDefault: item.isDefault === true, auth: item.auth && @@ -918,6 +1235,7 @@ export function exportServerSettingsBackup(): ServerSettingsBackup { .map(server => ({ ...server, auth: server.auth ? { ...server.auth } : undefined, + endpoints: server.endpoints ? server.endpoints.map(endpoint => ({ ...endpoint })) : undefined, })), activeServerId: serverStore.getActiveServerId(), defaultServerId: serverStore.getDefaultServerId(), diff --git a/src/utils/pairing.test.ts b/src/utils/pairing.test.ts index 11f78c05a..1254805d8 100644 --- a/src/utils/pairing.test.ts +++ b/src/utils/pairing.test.ts @@ -103,7 +103,13 @@ describe('redeemPairingLink', () => { const result = await redeemPairingLink({ urls: ['http://server'], code: 'abc' }) - expect(result).toEqual({ type: 'paired', url: 'http://server', token: 'secret-token' }) + // urls 回传完整地址集(Issue #183:兑换后要保存全部地址) + expect(result).toEqual({ + type: 'paired', + url: 'http://server', + urls: ['http://server'], + token: 'secret-token', + }) const [requestUrl, init] = fetchMock.mock.calls[0] as unknown as [string, RequestInit] expect(requestUrl).toBe('http://server/auth/connect/abc') expect((init.headers as Record).Accept).toBe('application/json') @@ -150,7 +156,12 @@ describe('redeemPairingLink', () => { await new Promise(resolve => setTimeout(resolve, 20)) resolveFirst(jsonResponse(200, { token: 'token-from-first' })) - await expect(pending).resolves.toEqual({ type: 'paired', url: 'http://first', token: 'token-from-first' }) + await expect(pending).resolves.toEqual({ + type: 'paired', + url: 'http://first', + urls: ['http://first', 'http://second'], + token: 'token-from-first', + }) }) it('首选地址不可达 → 用竞速赢家的地址', async () => { @@ -165,6 +176,7 @@ describe('redeemPairingLink', () => { await expect(redeemPairingLink({ urls: ['http://first', 'http://second'], code: 'abc' })).resolves.toEqual({ type: 'paired', url: 'http://second', + urls: ['http://first', 'http://second'], token: 'token-from-second', }) }) diff --git a/src/utils/pairing.ts b/src/utils/pairing.ts index 228f7c4aa..3bae03984 100644 --- a/src/utils/pairing.ts +++ b/src/utils/pairing.ts @@ -20,7 +20,19 @@ export interface PairingLink { } export type RedeemResult = - | { type: 'paired'; url: string; token: string } + | { + type: 'paired' + /** 兑换实际使用的地址(竞速赢家 / 首选地址) */ + url: string + /** + * QR 载荷里的**全部**地址(归一化去重后,保持原顺序)。 + * + * 兑换只证明 code 有效、token 可用;token 在服务器所有地址上通用, + * 因此这里把完整地址集交给调用方保存为多地址(Issue #183)。 + */ + urls: string[] + token: string + } | { type: 'expired' } | { type: 'unreachable' } @@ -140,7 +152,7 @@ export async function redeemPairingLink(link: PairingLink): Promise Date: Tue, 20 Oct 2026 10:32:24 +0800 Subject: [PATCH 06/67] =?UTF-8?q?test(e2e):=20=E7=9C=9F=E5=AE=9E=E6=9C=8D?= =?UTF-8?q?=E5=8A=A1=E7=AB=AF=E4=B8=8A=E7=9A=84=E5=A4=9A=E5=9C=B0=E5=9D=80?= =?UTF-8?q?=E6=8E=A2=E6=B5=8B=E3=80=81=E5=88=87=E6=8D=A2=E4=B8=8E=E5=BB=B6?= =?UTF-8?q?=E8=BF=9F=E9=AA=8C=E8=AF=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 三个默认跳过的验证脚本,需要 VITE_OPENCODE_LIVE_E2E=1 且本机跑着 v2 服务端才执行,不影响常规测试套件。 - endpoint-probe:可达返回延迟、401 仍算可达(地址通、只是凭据不对)、 死端口返回 null、探测不污染 per-server 健康灯。 - endpoint-switch:死地址自动降级 → SDK/http 真的连到新地址并拉到数据 → 锁定后探测让位 → 解锁恢复自动模式。 - endpoint-latency:主地址不可达时首次探测即切到备用,且耗时不拖到探测超时。 --- src/test/endpoint-latency.live.test.ts | 54 ++++++++++++++++++++++ src/test/endpoint-probe.live.test.ts | 59 ++++++++++++++++++++++++ src/test/endpoint-switch.live.test.ts | 62 ++++++++++++++++++++++++++ 3 files changed, 175 insertions(+) create mode 100644 src/test/endpoint-latency.live.test.ts create mode 100644 src/test/endpoint-probe.live.test.ts create mode 100644 src/test/endpoint-switch.live.test.ts diff --git a/src/test/endpoint-latency.live.test.ts b/src/test/endpoint-latency.live.test.ts new file mode 100644 index 000000000..d79fd4106 --- /dev/null +++ b/src/test/endpoint-latency.live.test.ts @@ -0,0 +1,54 @@ +// 真实服务端上的切换延迟验证(默认跳过)。 +// +// 场景:主地址是一个**必然拒绝连接**的端口(模拟换了网络后旧入口不可达), +// 备用地址是真实服务端。验证两轮探测内就切走,且切换后 SDK 真能拉到数据。 +// +// OPENCODE_PASSWORD=test123 opencode serve --port 4199 --hostname 0.0.0.0 +// VITE_OPENCODE_LIVE_E2E=1 npx vitest run src/test/endpoint-latency.live.test.ts +import { describe, it, expect } from 'vitest' +import { serverStore } from '../store/serverStore' +import { probeServerOnce, resetAllProbeStates } from '../store/endpointProbe' +import { getLocationInfo } from '../api/global' + +const LIVE = import.meta.env.VITE_OPENCODE_LIVE_E2E === '1' +const LIVE_URL = 'http://127.0.0.1:4199' +/** 没有进程监听的端口:连接会被立即拒绝(等价于「这条入口已经不可达」) */ +const DEAD_URL = 'http://127.0.0.1:4298' +const AUTH = { username: 'opencode', password: 'test123' } +const SERVER_ID = 'latency-live' + +describe.skipIf(!LIVE)('切换延迟与端到端恢复', () => { + it('主地址不可达 → 首次探测即切到备用(启动场景)', async () => { + resetAllProbeStates() + const server = serverStore.upsertServer({ + id: SERVER_ID, + name: 'latency', + url: DEAD_URL, + endpoints: [ + { url: DEAD_URL, priority: 0 }, + { url: LIVE_URL, priority: 1 }, + ], + auth: AUTH, + }) + serverStore.setActiveServer(server.id) + + const startedAt = Date.now() + await probeServerOnce(server.id) + const elapsed = Date.now() - startedAt + + // 首次选择不等失败阈值:主地址探一次不通就直接用备用 + expect(serverStore.getServerBaseUrl(server.id)).toBe(LIVE_URL) + // 连接拒绝是快速的,不该拖到探测超时(4s) + expect(elapsed).toBeLessThan(5_000) + }, 30000) + + it('主地址不可达且已在备用 → 保持,不乱切', async () => { + await probeServerOnce(SERVER_ID) + expect(serverStore.getServerBaseUrl(SERVER_ID)).toBe(LIVE_URL) + }, 30000) + + it('切到备用后 SDK 立刻能拉到数据', async () => { + const loc = await getLocationInfo(undefined, SERVER_ID) + expect(loc.directory).toBeTruthy() + }, 30000) +}) diff --git a/src/test/endpoint-probe.live.test.ts b/src/test/endpoint-probe.live.test.ts new file mode 100644 index 000000000..740ffcd55 --- /dev/null +++ b/src/test/endpoint-probe.live.test.ts @@ -0,0 +1,59 @@ +// 多地址探测的真实服务端验证(默认跳过,不提交为常规套件)。 +// 需要本机跑着 v2 服务端: +// OPENCODE_PASSWORD=test123 opencode serve --port 4199 --hostname 0.0.0.0 +// 然后: +// VITE_OPENCODE_LIVE_E2E=1 npx vitest run src/test/endpoint-probe.live.test.ts +import { describe, it, expect } from 'vitest' +import { serverStore } from '../store/serverStore' +import { probeServerOnce, getProbeState, resetAllProbeStates } from '../store/endpointProbe' + +const LIVE = import.meta.env.VITE_OPENCODE_LIVE_E2E === '1' +const LIVE_URL = 'http://127.0.0.1:4199' +/** 关掉的端口,用来模拟不可达地址 */ +const DEAD_URL = 'http://127.0.0.1:4198' +const AUTH = { username: 'opencode', password: 'test123' } + +describe.skipIf(!LIVE)('endpoint probe against a live server', () => { + it('可达地址返回延迟', async () => { + const latency = await serverStore.probeEndpoint(LIVE_URL, AUTH) + expect(typeof latency).toBe('number') + expect(latency).toBeGreaterThanOrEqual(0) + }, 15000) + + it('凭据错误仍算可达(401 = 地址通,只是认证不过)', async () => { + const latency = await serverStore.probeEndpoint(LIVE_URL, { username: 'opencode', password: 'wrong' }) + expect(typeof latency).toBe('number') + }, 15000) + + it('死端口返回 null', async () => { + expect(await serverStore.probeEndpoint(DEAD_URL, AUTH)).toBeNull() + }, 15000) + + it('探测不污染 per-server 健康状态', async () => { + serverStore.upsertServer({ id: 'probe-live', name: 'probe', url: LIVE_URL, auth: AUTH }) + const before = serverStore.getHealth('probe-live') + await serverStore.probeEndpoint(LIVE_URL, AUTH) + expect(serverStore.getHealth('probe-live')).toBe(before) + }, 15000) + + it('内网地址死、公网(回环)活 → 自动降级到可达地址', async () => { + resetAllProbeStates() + serverStore.removeServer('probe-live') + + const server = serverStore.upsertServer({ + id: 'probe-switch', + name: 'dual live', + url: DEAD_URL, + endpoints: [ + { url: DEAD_URL, priority: 0 }, + { url: LIVE_URL, priority: 1 }, + ], + auth: AUTH, + }) + + await probeServerOnce(server.id) + expect(serverStore.getServerBaseUrl(server.id)).toBe(LIVE_URL) + expect(getProbeState(server.id, DEAD_URL)?.reachable).toBe(false) + expect(getProbeState(server.id, LIVE_URL)?.reachable).toBe(true) + }, 30000) +}) diff --git a/src/test/endpoint-switch.live.test.ts b/src/test/endpoint-switch.live.test.ts new file mode 100644 index 000000000..52e0d5d75 --- /dev/null +++ b/src/test/endpoint-switch.live.test.ts @@ -0,0 +1,62 @@ +// 真实服务端上的完整切换链验证(默认跳过): +// 死地址 + 活地址 → 自动降级 → SDK 指向新地址 → 能真正拉到数据。 +// +// OPENCODE_PASSWORD=test123 opencode serve --port 4199 --hostname 0.0.0.0 +// VITE_OPENCODE_LIVE_E2E=1 npx vitest run src/test/endpoint-switch.live.test.ts +import { describe, it, expect, beforeAll } from 'vitest' +import { serverStore } from '../store/serverStore' +import { probeServerOnce, resetAllProbeStates } from '../store/endpointProbe' +import { getSessions } from '../api/session' +import { getLocationInfo } from '../api/global' + +const LIVE = import.meta.env.VITE_OPENCODE_LIVE_E2E === '1' +const LIVE_URL = 'http://127.0.0.1:4199' +const DEAD_URL = 'http://127.0.0.1:4198' +const AUTH = { username: 'opencode', password: 'test123' } +const SERVER_ID = 'switch-live' + +describe.skipIf(!LIVE)('endpoint switch against a live server', () => { + beforeAll(() => { + resetAllProbeStates() + serverStore.upsertServer({ + id: SERVER_ID, + name: 'dual live', + url: DEAD_URL, + endpoints: [ + { url: DEAD_URL, priority: 0 }, + { url: LIVE_URL, priority: 1 }, + ], + auth: AUTH, + }) + serverStore.setActiveServer(SERVER_ID) + }) + + it('死的内网地址 → 自动降级到可达地址', async () => { + await probeServerOnce(SERVER_ID) + expect(serverStore.getServerBaseUrl(SERVER_ID)).toBe(LIVE_URL) + expect(serverStore.getActiveBaseUrl()).toBe(LIVE_URL) + }, 30000) + + it('降级后 SDK / http 层真的连到新地址,能拉到数据', async () => { + const loc = await getLocationInfo(undefined, SERVER_ID) + expect(loc.directory).toBeTruthy() + + const sessions = await getSessions({ limit: 3 }, SERVER_ID) + expect(Array.isArray(sessions)).toBe(true) + }, 30000) + + it('锁定后探测让位,生效地址不变', async () => { + serverStore.setLockedEndpoint(SERVER_ID, LIVE_URL) + resetAllProbeStates() + + // 即便主地址(死的)被判可达,锁定也不让它切 + await probeServerOnce(SERVER_ID) + expect(serverStore.getServerBaseUrl(SERVER_ID)).toBe(LIVE_URL) + expect(serverStore.getLockedEndpointUrl(SERVER_ID)).toBe(LIVE_URL) + }, 30000) + + it('解锁后恢复自动模式', async () => { + serverStore.setLockedEndpoint(SERVER_ID, null) + expect(serverStore.getLockedEndpointUrl(SERVER_ID)).toBeNull() + }) +}) From 0ccecccfac24f332008ca09316250dd60c813724 Mon Sep 17 00:00:00 2001 From: lehhair Date: Tue, 20 Oct 2026 10:43:51 +0800 Subject: [PATCH 07/67] =?UTF-8?q?feat(settings):=20=E5=9C=B0=E5=9D=80?= =?UTF-8?q?=E5=88=97=E8=A1=A8=E5=8F=AF=E6=89=8B=E5=8A=A8=E5=A2=9E=E5=88=A0?= =?UTF-8?q?=E6=8E=92=E5=BA=8F=EF=BC=8C=E5=A4=9A=E5=9C=B0=E5=9D=80=E4=B8=8D?= =?UTF-8?q?=E5=86=8D=E5=8F=AA=E8=83=BD=E9=9D=A0=E9=87=8D=E6=96=B0=E9=85=8D?= =?UTF-8?q?=E5=AF=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 上一版多地址只做了「配对回填」:地址从 QR 载荷来,用户想加第三个入口 只能重新扫码。等于「支持多地址」只做了一半。 - 新增 EndpointListEditor:主地址固定第一行(等价于上方 URL 字段), 备用地址可增删、上下移动。顺序即优先级,不让用户手填 priority 数字。 - 添加 / 编辑表单都接入,配对回填与手动编辑共用同一套结构。 - 顺带修正 updateServer 的清空语义:原来用 `updates.endpoints !== undefined` 判断「本次有没有改」,导致传 undefined 表示清空时被当成「没改」, 地址永远删不掉。改用 hasOwnProperty——显式传 undefined 才代表清空。 --- .../components/ServersSettings.test.tsx | 96 ++++++++++ .../settings/components/ServersSettings.tsx | 179 +++++++++++++++--- src/locales/en/settings.json | 10 +- src/locales/zh-CN/settings.json | 10 +- src/store/serverEndpoints.test.ts | 19 ++ src/store/serverStore.ts | 8 +- 6 files changed, 294 insertions(+), 28 deletions(-) diff --git a/src/features/settings/components/ServersSettings.test.tsx b/src/features/settings/components/ServersSettings.test.tsx index bee8f955a..1b5986720 100644 --- a/src/features/settings/components/ServersSettings.test.tsx +++ b/src/features/settings/components/ServersSettings.test.tsx @@ -111,4 +111,100 @@ describe('ServersSettings', () => { fireEvent.click(lockButton!) expect(setLockedEndpointMock).toHaveBeenCalledWith('dual', 'http://192.168.1.5:4096') }) + + /** + * 地址编辑 UI(Issue #183)。此前地址只能由配对回填,用户没法手动增删, + * 想加第三个入口只能重新扫码 —— 这等于「支持多地址」只做了一半。 + */ + it('编辑表单可增删地址,顺序即优先级', async () => { + const updateServerMock = vi.fn() + const dualServer = { + id: 'dual', + name: 'Dual', + url: 'http://lan.test', + endpoints: [ + { url: 'http://lan.test', priority: 0 }, + { url: 'https://wan.test', priority: 1 }, + ], + } + useServerStoreMock.mockReturnValue({ + servers: [dualServer], + activeServer: dualServer, + addServer: vi.fn(), + removeServer: vi.fn(), + updateServer: updateServerMock, + setActiveServer: setActiveServerMock, + setActiveEndpoint: setActiveEndpointMock, + setLockedEndpoint: setLockedEndpointMock, + checkHealth: checkHealthMock, + checkAllHealth: vi.fn(), + getHealth: vi.fn(() => null), + endpointStates: new Map(), + }) + + render() + + // 进编辑 + fireEvent.click(screen.getByTitle('servers.editServer')) + await waitFor(() => expect(screen.getByText('servers.endpointsLabel')).toBeTruthy()) + + // 已有的备用地址出现在输入框里 + const wanInput = screen.getByDisplayValue('https://wan.test') + expect(wanInput).toBeTruthy() + + // 再加一个 + fireEvent.click(screen.getByText('servers.endpointAdd')) + const inputs = screen.getAllByLabelText(/servers\.endpointNth/) + fireEvent.change(inputs[inputs.length - 1]!, { target: { value: 'https://tailscale.test' } }) + + fireEvent.click(screen.getByText('common:save')) + + await waitFor(() => expect(updateServerMock).toHaveBeenCalled()) + const [, updates] = updateServerMock.mock.calls[0]! + expect(updates.endpoints).toEqual([ + { url: 'http://lan.test', priority: 0 }, + { url: 'https://wan.test', priority: 1 }, + { url: 'https://tailscale.test', priority: 1 }, + ]) + }) + + it('删光备用地址后 endpoints 传 undefined(清空而非保持原值)', async () => { + const updateServerMock = vi.fn() + const dualServer = { + id: 'dual', + name: 'Dual', + url: 'http://lan.test', + endpoints: [ + { url: 'http://lan.test', priority: 0 }, + { url: 'https://wan.test', priority: 1 }, + ], + } + useServerStoreMock.mockReturnValue({ + servers: [dualServer], + activeServer: dualServer, + addServer: vi.fn(), + removeServer: vi.fn(), + updateServer: updateServerMock, + setActiveServer: setActiveServerMock, + setActiveEndpoint: setActiveEndpointMock, + setLockedEndpoint: setLockedEndpointMock, + checkHealth: checkHealthMock, + checkAllHealth: vi.fn(), + getHealth: vi.fn(() => null), + endpointStates: new Map(), + }) + + render() + fireEvent.click(screen.getByTitle('servers.editServer')) + await waitFor(() => expect(screen.getByText('servers.endpointsLabel')).toBeTruthy()) + + fireEvent.click(screen.getByTitle('servers.endpointRemove')) + fireEvent.click(screen.getByText('common:save')) + + await waitFor(() => expect(updateServerMock).toHaveBeenCalled()) + const [, updates] = updateServerMock.mock.calls[0]! + // 必须显式传 undefined:store 用 hasOwnProperty 判断才会真的清空 + expect('endpoints' in updates).toBe(true) + expect(updates.endpoints).toBeUndefined() + }) }) diff --git a/src/features/settings/components/ServersSettings.tsx b/src/features/settings/components/ServersSettings.tsx index 72af18cfa..3271f5c77 100644 --- a/src/features/settings/components/ServersSettings.tsx +++ b/src/features/settings/components/ServersSettings.tsx @@ -4,7 +4,7 @@ import { Button } from '../../../components/ui/Button' import { ConfirmDialog } from '../../../components/ui/ConfirmDialog' import { DropdownMenu } from '../../../components/ui/DropdownMenu' import { MenuItem } from '../../../components/ui/MenuItem' -import { TrashIcon, KeyIcon, PencilIcon, RetryIcon, PlugIcon, CircleIcon, QrCodeIcon, CheckIcon, PinIcon } from '../../../components/Icons' +import { TrashIcon, KeyIcon, PencilIcon, RetryIcon, PlugIcon, CircleIcon, QrCodeIcon, CheckIcon, PinIcon, PlusIcon, ArrowUpIcon, ArrowDownIcon } from '../../../components/Icons' import { useServerStore, useRouter } from '../../../hooks' import { messageStore } from '../../../store' import { useMultiServerStore, multiServerStore } from '../../../store/multiServerStore' @@ -38,24 +38,35 @@ function isHttpsIpUrl(url: string): boolean { } /** - * 把「配对拿到的地址集 + 用户填的主地址」合成 endpoints(Issue #183)。 - * - * 规则: - * - 主地址排第一(priority 0)——它是用户当前选中的入口,也是 QR 首选地址 - * - 其余地址 priority 1(收进同一个服务器条目里备用) - * - 主地址不在地址集里(用户手改过)→ 只有它自己,退回单地址语义 - * - 只有一个地址 → 返回 undefined,不写 endpoints(保持旧行为) + * 表单里编辑中的地址项。`id` 只是 React key,不落库—— + * 用下标当 key 在删除中间行时会让输入框内容错位。 + */ +interface EditableEndpoint { + id: number + url: string +} + +let editableEndpointSeq = 0 + +function toEditable(urls: string[]): EditableEndpoint[] { + return urls.map(url => ({ id: ++editableEndpointSeq, url })) +} + +/** + * 把表单里的地址列表 + 主地址合成为落库的 endpoints。 * - * 保持 QR 原始顺序:官方特意保留 `urls[0]`(用户挑选的顺序有信息量), - * 因此除主地址外不做重排。 + * 与 `buildEndpoints` 的区别:那个用于**配对回填**(主地址固定排第一), + * 这个用于**手动编辑**(用户排的顺序就是优先级顺序)。 + * 主地址始终排第一:`server.url` 与 endpoints[0] 必须一致, + * 否则「主地址」和「生效地址」会指向两条不同的记录。 */ -function buildEndpoints(primaryUrl: string, pairedUrls: string[]): ServerEndpoint[] | undefined { +function mergeEditableEndpoints(primaryUrl: string, editable: EditableEndpoint[]): ServerEndpoint[] | undefined { const primary = primaryUrl.trim().replace(/\/+$/, '') if (!primary) return undefined const ordered: string[] = [primary] - for (const candidate of pairedUrls) { - const normalized = candidate.trim().replace(/\/+$/, '') + for (const item of editable) { + const normalized = item.url.trim().replace(/\/+$/, '') if (normalized && !ordered.includes(normalized)) ordered.push(normalized) } @@ -63,6 +74,115 @@ function buildEndpoints(primaryUrl: string, pairedUrls: string[]): ServerEndpoin return ordered.map((url, index) => ({ url, priority: index === 0 ? 0 : 1 })) } +/** + * 地址列表编辑器(Issue #183)。 + * + * 顺序即优先级:第一行是主地址(等价于表单上方的 URL 字段),往下依次备用。 + * 只暴露「顺序」而不暴露 priority 数字——对用户来说「哪个优先」就是排第几, + * 让人手填优先级数字只会增加误操作。 + */ +function EndpointListEditor({ + primaryUrl, + items, + onChange, +}: { + primaryUrl: string + items: EditableEndpoint[] + onChange: (next: EditableEndpoint[]) => void +}) { + const { t } = useTranslation(['settings', 'common']) + const inputCls = settingsFieldClass + + const update = (id: number, url: string) => { + onChange(items.map(item => (item.id === id ? { ...item, url } : item))) + } + const remove = (id: number) => { + onChange(items.filter(item => item.id !== id)) + } + const move = (index: number, delta: -1 | 1) => { + const target = index + delta + if (target < 0 || target >= items.length) return + const next = [...items] + ;[next[index], next[target]] = [next[target], next[index]] + onChange(next) + } + + return ( +
+
+ + +
+ + {/* 主地址固定第一行、不可删不可移:它就是上面 URL 字段的值 */} +
+ 1 + + {primaryUrl || '—'} + + {t('servers.endpointPrimary')} +
+ + {items.map((item, index) => ( +
+ {index + 2} + update(item.id, e.target.value)} + placeholder={t('servers.urlPlaceholder')} + className={`${inputCls} min-w-0 flex-1 font-mono`} + aria-label={t('servers.endpointNth', { index: index + 2 })} + /> + + + +
+ ))} + +

{t('servers.endpointOrderHint')}

+
+ ) +} + // ============================================ // Server Item // ============================================ @@ -321,11 +441,12 @@ function EditServerForm({ const [name, setName] = useState(server.name) const [url, setUrl] = useState(server.url) /** - * 配对拿到的全部地址(Issue #183)。与 `url`(主地址)分开存: - * 用户手改 url 不会动这个集合,保存时按「url 优先 + 集合去重」合成 endpoints。 + * 备用地址列表(Issue #183)。与 `url`(主地址)分开存:主地址由上面那个 + * URL 字段维护,这里有顺序的就是备用地址,顺序即优先级。 + * 配对回填时整组替换,手动编辑时增删移。 */ - const [pairedUrls, setPairedUrls] = useState(() => - (server.endpoints ?? []).map(endpoint => endpoint.url), + const [extraEndpoints, setExtraEndpoints] = useState(() => + toEditable((server.endpoints ?? []).slice(1).map(endpoint => endpoint.url)), ) const [username, setUsername] = useState(server.auth?.username || '') const [password, setPassword] = useState(server.auth?.password || '') @@ -336,8 +457,11 @@ function EditServerForm({ // 与添加表单同一条配对链:重新扫码 / 粘贴 pair 链接兑换后回填地址与凭据, // 保存时才落库——适合换了端口 / 重装了服务端后原地更新连接配置 const applyPairing = useCallback((pairedUrl: string, token: string, urls: string[]) => { - setUrl(pairedUrl) - setPairedUrls(urls) + // 配对拿到的地址集里,第一个是首选主地址,其余收进备用列表 + const ordered = [pairedUrl, ...urls].map(item => item.trim().replace(/\/+$/, '')).filter(Boolean) + const unique = [...new Set(ordered)] + setUrl(unique[0] ?? pairedUrl) + setExtraEndpoints(toEditable(unique.slice(1))) setUsername('opencode') setPassword(token) setShowAuth(true) @@ -378,7 +502,7 @@ function EditServerForm({ url: url.trim(), username: password.trim() ? username.trim() || 'opencode' : undefined, password: password.trim() || undefined, - endpoints: buildEndpoints(url, pairedUrls), + endpoints: mergeEditableEndpoints(url, extraEndpoints), }) } @@ -476,6 +600,8 @@ function EditServerForm({ )} + + {error &&

{error}

}
- {/* 主地址固定第一行、不可删不可移:它就是上面 URL 字段的值 */} -
- 1 - - {primaryUrl || '—'} - - {t('servers.endpointPrimary')} -
- {items.map((item, index) => (
- {index + 2} + + {index + 1} + update(item.id, e.target.value)} + onChange={e => { + const value = e.target.value + // 配对链接粘到地址框 → 交给配对流程,不当作普通地址 + if (onPairLinkPasted?.(value)) return + update(item.id, value) + }} placeholder={t('servers.urlPlaceholder')} className={`${inputCls} min-w-0 flex-1 font-mono`} - aria-label={t('servers.endpointNth', { index: index + 2 })} + aria-label={t('servers.endpointNth', { index: index + 1 })} /> @@ -439,29 +454,32 @@ function EditServerForm({ }) { const { t } = useTranslation(['settings', 'common']) const [name, setName] = useState(server.name) - const [url, setUrl] = useState(server.url) /** - * 备用地址列表(Issue #183)。与 `url`(主地址)分开存:主地址由上面那个 - * URL 字段维护,这里有顺序的就是备用地址,顺序即优先级。 - * 配对回填时整组替换,手动编辑时增删移。 + * 地址列表(Issue #183)——**唯一的地址数据源**。 + * + * 不再有单独的 URL 输入框:那会变成「同一个值两个入口,一个能改一个不能」。 + * 第一行即主地址(保存时同时写入 `server.url`),顺序即优先级。 */ - const [extraEndpoints, setExtraEndpoints] = useState(() => - toEditable((server.endpoints ?? []).slice(1).map(endpoint => endpoint.url)), + const [endpoints, setEndpoints] = useState(() => + toEditable( + server.endpoints?.length ? server.endpoints.map(endpoint => endpoint.url) : [server.url], + ), ) const [username, setUsername] = useState(server.auth?.username || '') const [password, setPassword] = useState(server.auth?.password || '') const [showAuth, setShowAuth] = useState(!!server.auth?.password) const [error, setError] = useState('') - const showHttpsIpWarning = isHttpsIpUrl(url) + // 主地址 = 列表第一个有效项(校验与 URL 警告都看它) + const primaryUrl = collectEndpointUrls(endpoints)[0] ?? '' + const showHttpsIpWarning = isHttpsIpUrl(primaryUrl) // 与添加表单同一条配对链:重新扫码 / 粘贴 pair 链接兑换后回填地址与凭据, // 保存时才落库——适合换了端口 / 重装了服务端后原地更新连接配置 const applyPairing = useCallback((pairedUrl: string, token: string, urls: string[]) => { - // 配对拿到的地址集里,第一个是首选主地址,其余收进备用列表 + // 配对拿到的地址集整组替换列表,第一个即主地址 const ordered = [pairedUrl, ...urls].map(item => item.trim().replace(/\/+$/, '')).filter(Boolean) const unique = [...new Set(ordered)] - setUrl(unique[0] ?? pairedUrl) - setExtraEndpoints(toEditable(unique.slice(1))) + setEndpoints(toEditable(unique.length > 0 ? unique : [pairedUrl])) setUsername('opencode') setPassword(token) setShowAuth(true) @@ -487,22 +505,26 @@ function EditServerForm({ setError(t('servers.nameRequired')) return } - if (!url.trim()) { + const urls = collectEndpointUrls(endpoints) + if (urls.length === 0) { setError(t('servers.urlRequired')) return } - try { - new URL(url) - } catch { - setError(t('servers.invalidUrl')) - return + for (const candidate of urls) { + try { + new URL(candidate) + } catch { + setError(t('servers.invalidUrl')) + return + } } onSave({ name: trimmedName, - url: url.trim(), + // 主地址写 url:旧逻辑、SDK 兜底、单地址界面都读它 + url: urls[0]!, username: password.trim() ? username.trim() || 'opencode' : undefined, password: password.trim() || undefined, - endpoints: mergeEditableEndpoints(url, extraEndpoints), + endpoints: toServerEndpoints(urls), }) } @@ -534,25 +556,15 @@ function EditServerForm({ autoFocus />
-
- - { - const value = e.target.value - // 粘贴到 URL 框的 pair 链接转到配对流程(官方连接对话框同款识别) - if (parsePairingLink(value) || isLegacyPairingLink(value)) { - handlePairLinkChange(value) - return - } - setUrl(value) - setError('') - }} - placeholder={t('servers.urlPlaceholder')} - className={`${inputCls} font-mono`} - /> -
+ { + if (!parsePairingLink(value) && !isLegacyPairingLink(value)) return false + handlePairLinkChange(value) + return true + }} + /> - - - ) - })} +
e.stopPropagation()}> + + + {showEndpoints && ( +
+ {server.endpoints.map(endpoint => { + const isCurrent = effectiveEndpointUrl(server, endpointState) === endpoint.url + const locked = endpointState.lockedUrl === endpoint.url + return ( +
+ + +
+ ) + })} +
+ )}
)} diff --git a/src/locales/en/settings.json b/src/locales/en/settings.json index 60c987580..10fe2db27 100644 --- a/src/locales/en/settings.json +++ b/src/locales/en/settings.json @@ -161,7 +161,9 @@ "endpointMoveUp": "Move up", "endpointMoveDown": "Move down", "endpointRemove": "Remove address", - "endpointOrderHint": "Order is priority: earlier addresses are preferred, falling back to later ones when unreachable. The first is the primary address." + "endpointOrderHint": "Order is priority: earlier addresses are preferred, falling back to later ones when unreachable. The first is the primary address.", + "endpointCount": "{{count}} addresses", + "endpointToggle": "Show {{count}} addresses" }, "chat": { "pathsFormatting": "Paths & Formatting", diff --git a/src/locales/zh-CN/settings.json b/src/locales/zh-CN/settings.json index 94a0ba098..147560702 100644 --- a/src/locales/zh-CN/settings.json +++ b/src/locales/zh-CN/settings.json @@ -161,7 +161,9 @@ "endpointMoveUp": "上移", "endpointMoveDown": "下移", "endpointRemove": "删除地址", - "endpointOrderHint": "顺序即优先级:优先用靠前的地址,连不上时自动退到后面的。第一行是主地址。" + "endpointOrderHint": "顺序即优先级:优先用靠前的地址,连不上时自动退到后面的。第一行是主地址。", + "endpointCount": "{{count}} 个地址", + "endpointToggle": "展开 {{count}} 个地址" }, "chat": { "pathsFormatting": "路径和格式", From e846d75191c24e36e2c8f1dc9f875a50dfa4f78a Mon Sep 17 00:00:00 2001 From: lehhair Date: Tue, 20 Oct 2026 11:58:42 +0800 Subject: [PATCH 11/67] =?UTF-8?q?fix(server):=20=E5=81=A5=E5=BA=B7?= =?UTF-8?q?=E6=A3=80=E6=9F=A5=E6=8E=A2=E5=BD=93=E5=89=8D=E7=94=9F=E6=95=88?= =?UTF-8?q?=E5=9C=B0=E5=9D=80=EF=BC=8C=E4=B8=8D=E5=86=8D=E7=9B=AF=E7=9D=80?= =?UTF-8?q?=E5=88=97=E8=A1=A8=E7=AC=AC=E4=B8=80=E8=A1=8C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 主地址排第一、备用(隧道)排第二时,用户手动选或自动降级到隧道后, 实际请求全走 getServerBaseUrl(生效地址),健康灯却去打 server.url (第一行的镜像)。主地址死了、备用活着 → 面板红叉,实际用得好好的。 反过来把隧道排第一,健康灯刚好打到活的地址,就显示绿色。 - checkHealth 改用 getActiveEndpointUrl - endpoint-switch 时补一次健康检查,否则切完还挂着旧入口的红叉 - ChatPane 连接报错里的 URL 也改生效地址,免得指着一个没在用的地址 - 补测试:主地址死、备用可达时健康灯为绿色,且请求真打在备用地址上 --- src/features/chat/ChatPane.tsx | 4 +++- src/main.tsx | 2 ++ src/store/serverStore.test.ts | 32 ++++++++++++++++++++++++++++++++ src/store/serverStore.ts | 7 ++++++- 4 files changed, 43 insertions(+), 2 deletions(-) diff --git a/src/features/chat/ChatPane.tsx b/src/features/chat/ChatPane.tsx index ab4b1a9a5..d3d04ae32 100644 --- a/src/features/chat/ChatPane.tsx +++ b/src/features/chat/ChatPane.tsx @@ -428,7 +428,9 @@ export const ChatPane = memo(function ChatPane({ const lines = [ `Server: ${activeServer.name}`, - `URL: ${activeServer.url}`, + // 用生效地址而不是 activeServer.url:后者只是地址列表第一行的镜像, + // 降级到备用入口时会把报错指向一个当前根本没在用的地址 + `URL: ${serverStore.getActiveBaseUrl()}`, `Status: ${activeServerHealth.status}`, activeServerHealth.error ? `Error: ${activeServerHealth.error}` : '', activeServerHealth.status === 'error' || activeServerHealth.status === 'offline' diff --git a/src/main.tsx b/src/main.tsx index 45db9d07a..41d1aeabf 100644 --- a/src/main.tsx +++ b/src/main.tsx @@ -81,6 +81,8 @@ serverStore.onServerChange((serverId, reason) => { // 非 active 的订阅连接同样挂在旧地址上,不重连就会一直连着死地址。 // reason 'network' 让重连成功后走补偿拉取,而不是按'换服务器'跳过。 reconnectServerSSE(serverId, { reason: 'network' }) + // 健康灯探的是生效地址,换了地址就得重测,否则会一直挂着旧入口的红叉 + void serverStore.checkHealth(serverId) return } diff --git a/src/store/serverStore.test.ts b/src/store/serverStore.test.ts index c3b762335..12d426fcb 100644 --- a/src/store/serverStore.test.ts +++ b/src/store/serverStore.test.ts @@ -592,6 +592,38 @@ describe('serverStore health check', () => { expect(staleHealth.status).toBe('error') expect(serverStore.getHealth('local')?.status).toBe('online') }) + + /** + * 健康灯探的必须是**当前生效地址**。 + * + * 之前的 bug:checkHealth 打 `server.url`(地址列表第一行的镜像)。 + * 多地址服务器降到备用入口后,请求全走 getServerBaseUrl,健康灯却还在 + * 敲那个已经死掉的主地址 —— 面板显示红叉,实际用得好好的。 + */ + it('探当前生效地址,而不是地址列表第一行', async () => { + const { serverStore } = await import('./serverStore') + const server = serverStore.addServer({ + name: 'dual', + url: 'http://dead.test', + endpoints: [ + { url: 'http://dead.test', priority: 0 }, + { url: 'https://live.test', priority: 1 }, + ], + }) + // 切到备用地址(等价于探测降级 / 用户手动选) + serverStore.setActiveEndpoint(server.id, 'https://live.test') + + vi.mocked(fetch).mockResolvedValueOnce( + jsonResponse({ version: '2.0.14', pid: 1234, urls: [], paths: { tmp: '/tmp' } }), + ) + + const health = await serverStore.checkHealth(server.id) + + expect(health.status).toBe('online') + // 确认请求真的打在备用地址上 + const requestedUrl = vi.mocked(fetch).mock.calls.at(-1)?.[0] + expect(String(requestedUrl)).toBe('https://live.test/api/info') + }) }) // ============================================ diff --git a/src/store/serverStore.ts b/src/store/serverStore.ts index f9c990883..c2c47a28a 100644 --- a/src/store/serverStore.ts +++ b/src/store/serverStore.ts @@ -1024,7 +1024,12 @@ class ServerStore { // v2 没有 v1 的 /global/health;官方客户端用 server.info() // (GET /api/info,返回 { version, pid, urls, paths })做健康探测。 // v2 服务器会对未知路径回退到 SPA HTML,因此打到 v1 路径会 200 + text/html。 - const healthUrl = `${server.url}/api/info` + // + // 必须探**当前生效地址**而非 `server.url`(后者只是第一行的镜像): + // 多地址服务器切到备用入口后,实际请求全走 getServerBaseUrl, + // 健康灯却去敲主地址,主地址死、备用活着就会显示红叉—— + // 面板说连不上,实际用得好好的。 + const healthUrl = `${this.getActiveEndpointUrl(serverId)}/api/info` const commitHealth = (health: ServerHealth) => { if (this.healthCheckSeqMap.get(serverId) === checkSeq) { From 6e31eb0132c75f94bd324b9e8ffb55b2868df72d Mon Sep 17 00:00:00 2001 From: lehhair Date: Tue, 20 Oct 2026 12:05:23 +0800 Subject: [PATCH 12/67] chore: bump version to 0.7.21 --- CHANGELOG.md | 5 +++++ package-lock.json | 4 ++-- package.json | 2 +- src-tauri/Cargo.lock | 2 +- src-tauri/Cargo.toml | 2 +- src-tauri/tauri.conf.json | 2 +- 6 files changed, 11 insertions(+), 6 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 6ce5ef804..76e649bba 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,10 @@ # Changelog +## [v0.7.21] - 2026-10-20 + +- fix(server): 健康检查探当前生效地址,不再盯着列表第一行 (e846d751) +- fix(settings): 地址列表默认收起,多入口不再把卡片撑成半屏 (46c1b259) + ## [v0.7.20] - 2026-10-20 - refactor(settings): 地址列表成为唯一数据源,去掉重复的 URL 输入框 (82481049) diff --git a/package-lock.json b/package-lock.json index 2027154cf..f29c50f05 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "opencodeui", - "version": "0.7.20", + "version": "0.7.21", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "opencodeui", - "version": "0.7.20", + "version": "0.7.21", "hasInstallScript": true, "license": "GPL-3.0-only", "dependencies": { diff --git a/package.json b/package.json index 2e6e7db0a..0aaeaba1b 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "opencodeui", - "version": "0.7.20", + "version": "0.7.21", "description": "A third-party web frontend for OpenCode", "license": "GPL-3.0-only", "type": "module", diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lock index 4911fa921..29c9524ad 100644 --- a/src-tauri/Cargo.lock +++ b/src-tauri/Cargo.lock @@ -2725,7 +2725,7 @@ dependencies = [ [[package]] name = "opencodeui" -version = "0.7.20" +version = "0.7.21" dependencies = [ "futures-util", "log", diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml index 450dd7393..68187492b 100644 --- a/src-tauri/Cargo.toml +++ b/src-tauri/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "opencodeui" -version = "0.7.20" +version = "0.7.21" description = "OpenCode UI - Tauri Mobile App" authors = ["lehhair"] license = "GPL-3.0-only" diff --git a/src-tauri/tauri.conf.json b/src-tauri/tauri.conf.json index 1ecc5a3a0..1968bd5e8 100644 --- a/src-tauri/tauri.conf.json +++ b/src-tauri/tauri.conf.json @@ -1,7 +1,7 @@ { "$schema": "../node_modules/@tauri-apps/cli/config.schema.json", "productName": "OpenCode", - "version": "0.7.20", + "version": "0.7.21", "identifier": "com.opencodeui.app", "build": { "frontendDist": "../dist", From 1c78fed7af92a2ef9944af98ce1ca228d098877f Mon Sep 17 00:00:00 2001 From: AAEE86 Date: Wed, 21 Oct 2026 10:01:50 +0800 Subject: [PATCH 13/67] =?UTF-8?q?fix(api):=20=E7=9B=B8=E5=AF=B9=20baseUrl?= =?UTF-8?q?=20=E8=A1=A5=E5=85=A8=E4=B8=BA=E7=BB=9D=E5=AF=B9=E5=9C=B0?= =?UTF-8?q?=E5=9D=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit standalone/Docker 镜像把 VITE_API_BASE_URL 设为同源前缀 `/api`, 而 @opencode/client 内部用 `new URL(options.baseUrl)` 构造请求地址, 只接受绝对 URL。于是所有 SDK 请求在发出前就抛 Invalid URL; 健康检查用原生 fetch 支持相对路径,仍显示在线,表现为 「服务器在线但会话/模型/消息/终端全部不可用」。 在 http.ts 增加 toAbsoluteBaseUrl,getApiBaseUrl 与 SDK 客户端 统一按当前页面 origin 补全,保留反代下 `/api` 前缀部署方式。 补充相对地址、协议相对地址与绝对地址的单测。 --- src/api/http.test.ts | 31 ++++++++++++++++++++++++++++++- src/api/http.ts | 27 ++++++++++++++++++++++++++- src/api/sdk.test.ts | 13 +++++++++++++ src/api/sdk.ts | 17 +++++++++++++++-- 4 files changed, 84 insertions(+), 4 deletions(-) diff --git a/src/api/http.test.ts b/src/api/http.test.ts index 99ee10bea..11bba7418 100644 --- a/src/api/http.test.ts +++ b/src/api/http.test.ts @@ -1,5 +1,34 @@ import { describe, expect, it } from 'vitest' -import { buildQueryString } from './http' +import { buildQueryString, toAbsoluteBaseUrl } from './http' + +// ============================================ +// toAbsoluteBaseUrl 测试 +// ============================================ + +describe('toAbsoluteBaseUrl', () => { + it('resolves a same-origin prefix against the page origin', () => { + expect(toAbsoluteBaseUrl('/api')).toBe(`${window.location.origin}/api`) + }) + + it('strips trailing slashes from a resolved relative URL', () => { + expect(toAbsoluteBaseUrl('/api/')).toBe(`${window.location.origin}/api`) + }) + + it('resolves a protocol-relative URL against the page protocol', () => { + expect(toAbsoluteBaseUrl('//example.com/api')).toBe(`${window.location.protocol}//example.com/api`) + }) + + it('leaves absolute URLs unchanged', () => { + expect(toAbsoluteBaseUrl('http://127.0.0.1:4096')).toBe('http://127.0.0.1:4096') + expect(toAbsoluteBaseUrl('https://opencode.example.com:51133/api')).toBe( + 'https://opencode.example.com:51133/api', + ) + }) + + it('returns an empty value unchanged', () => { + expect(toAbsoluteBaseUrl('')).toBe('') + }) +}) // ============================================ // buildQueryString 测试 diff --git a/src/api/http.ts b/src/api/http.ts index dd04413e5..0deefff8c 100644 --- a/src/api/http.ts +++ b/src/api/http.ts @@ -5,13 +5,38 @@ import { serverStore, makeBasicAuthHeader } from '../store/serverStore' +/** + * 把相对 API 地址补成绝对地址。 + * + * `@opencode/client` 内部用 `new URL(options.baseUrl)` 构造请求地址, + * 只接受绝对 URL。Docker / standalone 镜像把 `VITE_API_BASE_URL` 设为 + * 同源前缀 `/api`,原样交给 SDK 会在**发请求前**抛 `Invalid URL`: + * 健康检查走原生 fetch(支持相对路径)显示在线,但会话、模型、消息、 + * 终端等所有 SDK 请求全部失败。 + * + * 这里按当前页面 origin 补全,既保留反代下的 `/api` 前缀部署方式, + * 也兼容 Tauri / 桌面端直接配置绝对地址的场景。 + */ +export function toAbsoluteBaseUrl(baseUrl: string): string { + if (!baseUrl) return baseUrl + // 已是绝对 URL(带 scheme)就原样返回,不去尾部斜杠,避免改掉用户配置 + if (/^[a-z][a-z\d+.-]*:\/\//i.test(baseUrl)) return baseUrl + if (typeof window === 'undefined') return baseUrl + // file:// 等非标准页面的 origin 是字符串 'null',不能作为 URL base + const origin = window.location.origin + if (!origin || origin === 'null') return baseUrl + return new URL(baseUrl, origin).toString().replace(/\/+$/, '') +} + /** * 获取 API Base URL * 优先使用 serverStore 中的活动服务器,回退到常量 + * 返回值保证是绝对地址(SDK / PTY 都要求完整 URL) * @param serverId 指定服务器(缺省用活动服务器) */ export function getApiBaseUrl(serverId?: string): string { - return serverId ? serverStore.getServerBaseUrl(serverId) : serverStore.getActiveBaseUrl() + const raw = serverId ? serverStore.getServerBaseUrl(serverId) : serverStore.getActiveBaseUrl() + return toAbsoluteBaseUrl(raw) } /** diff --git a/src/api/sdk.test.ts b/src/api/sdk.test.ts index 6f8d2132a..be11ad516 100644 --- a/src/api/sdk.test.ts +++ b/src/api/sdk.test.ts @@ -62,6 +62,19 @@ describe('v2 client request lifecycle', () => { expect(client.__options.baseUrl).toBe('http://127.0.0.1:4096') }) + it('resolves a relative base URL before handing it to the SDK', async () => { + // 回归:standalone 镜像把 VITE_API_BASE_URL 设成 `/api`,SDK 内部 + // `new URL('/api')` 会抛 Invalid URL。必须按页面 origin 补全。 + getActiveBaseUrlMock.mockReturnValue('/api') + + const { getSDKClient } = await import('./sdk') + const client = getSDKClient() as unknown as MockClient + + expect(client.__options.baseUrl).toBe(`${window.location.origin}/api`) + // 缓存 key 也用补全后的地址,重复调用必须命中同一实例 + expect(getSDKClient()).toBe(client) + }) + it('aborts in-flight requests when the server endpoint changes', async () => { const { abortInFlightApiRequests, getSDKClient } = await import('./sdk') const client = getSDKClient() as unknown as MockClient diff --git a/src/api/sdk.ts b/src/api/sdk.ts index a8c921e4f..56fe50599 100644 --- a/src/api/sdk.ts +++ b/src/api/sdk.ts @@ -14,6 +14,7 @@ import { OpenCode } from '@opencode/client/promise' import type { OpenCodeClient } from '@opencode/client/promise' import { serverStore, makeBasicAuthHeader } from '../store/serverStore' import { isTauri } from '../utils/tauri' +import { toAbsoluteBaseUrl } from './http' /** v2 客户端实例(内部 API 层的唯一形状) */ export type ServerApi = OpenCodeClient @@ -151,8 +152,20 @@ interface CachedClientEntry { const _cachedClients = new Map() +/** + * 读取当前服务器的 baseUrl,并补成 SDK 要求的绝对地址。 + * + * standalone 部署的 `VITE_API_BASE_URL=/api` 是相对前缀,直接用会被 + * `new URL('/api')` 判为 Invalid URL;缓存 key 也必须用补全后的值, + * 否则相对/绝对两种写法会各建一份客户端。 + */ +function resolveClientBaseUrl(serverId?: string): string { + const raw = serverId ? serverStore.getServerBaseUrl(serverId) : serverStore.getActiveBaseUrl() + return toAbsoluteBaseUrl(raw) +} + function buildCacheKey(serverId?: string): string { - const baseUrl = serverId ? serverStore.getServerBaseUrl(serverId) : serverStore.getActiveBaseUrl() + const baseUrl = resolveClientBaseUrl(serverId) const auth = serverId ? serverStore.getServerAuth(serverId) : serverStore.getActiveAuth() const authPart = auth?.password ? `${auth.username}:${auth.password}` : '' return `${baseUrl}|${authPart}` @@ -179,7 +192,7 @@ export function getSDKClient(serverId?: string): ServerApi { return cached.client } - const baseUrl = serverId ? serverStore.getServerBaseUrl(serverId) : serverStore.getActiveBaseUrl() + const baseUrl = resolveClientBaseUrl(serverId) const headers = buildHeaders(serverId) const generation = _apiRequestGeneration From c8f8bfe600abe8f36748967e681e497326378f9e Mon Sep 17 00:00:00 2001 From: lehhair Date: Fri, 23 Oct 2026 10:08:25 +0800 Subject: [PATCH 14/67] =?UTF-8?q?perf(session):=20=E8=BF=9B=E4=BC=9A?= =?UTF-8?q?=E8=AF=9D=E5=A4=8D=E7=94=A8=E5=88=97=E8=A1=A8=E5=85=83=E4=BF=A1?= =?UTF-8?q?=E6=81=AF=E5=B9=B6=E9=A2=84=E5=8F=96=E9=A6=96=E5=B1=8F=EF=BC=8C?= =?UTF-8?q?=E6=81=A2=E5=A4=8D=E5=8A=A8=E4=BD=9C=E8=AE=A9=E5=87=BA=E9=A6=96?= =?UTF-8?q?=E5=B1=8F=E8=B7=AF=E5=BE=84?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 进入会话过去会重发 session.get,并在首屏消息落地前同步发起子会话查询、 全量权限/表单拉取和 task 卡片绑定校验(最多 12 次 message.list),和首屏 请求抢同源连接槽。 - 点击列表时把完整 SessionInfo 交给 sessionInfoCache,进会话不再 session.get;getSession/updateSession 回填,rename 就地更新, move/delete 立即失效 - 点击时预取首屏消息,会话页取走同一个 in-flight 请求;已有可渲染缓存的 会话不预取,失败的预取回退为正常请求 - 子会话/权限/表单恢复到首屏落地后执行;/children 改用「已确认」标记, 每会话只问一次,重连时作废补漏 - task 卡片绑定校验移到空闲调度,不再挡在首屏前 - 首屏已挂载时不再等元信息回读,避免整页空白 / 重新建 virtualizer --- src/App.tsx | 29 ++++++- src/api/messagePrefetch.test.ts | 96 +++++++++++++++++++++ src/api/messagePrefetch.ts | 100 ++++++++++++++++++++++ src/api/session.ts | 14 ++- src/features/chat/ChatPane.tsx | 6 +- src/hooks/useChatSession.ts | 116 +++++++++++++++++-------- src/hooks/useGlobalEvents.ts | 9 ++ src/hooks/useSessionManager.test.tsx | 123 +++++++++++++++++++++++++++ src/hooks/useSessionManager.ts | 79 ++++++++++++++--- src/store/childSessionStore.test.ts | 34 ++++++++ src/store/childSessionStore.ts | 27 ++++++ src/store/messageStore.ts | 12 +++ src/store/sessionInfoCache.test.ts | 72 ++++++++++++++++ src/store/sessionInfoCache.ts | 110 ++++++++++++++++++++++++ src/utils/scheduleIdle.ts | 63 ++++++++++++++ src/utils/sessionLifecycle.ts | 4 + 16 files changed, 837 insertions(+), 57 deletions(-) create mode 100644 src/api/messagePrefetch.test.ts create mode 100644 src/api/messagePrefetch.ts create mode 100644 src/store/sessionInfoCache.test.ts create mode 100644 src/store/sessionInfoCache.ts create mode 100644 src/utils/scheduleIdle.ts diff --git a/src/App.tsx b/src/App.tsx index b74d445f9..b47317e4d 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -39,6 +39,9 @@ import { multiServerStore } from './store/multiServerStore' import { serverStore } from './store/serverStore' import { initNotificationSound } from './utils/notificationSoundBridge' import { createPtySession } from './api/pty' +import { prefetchSessionMessages } from './api/messagePrefetch' +import { isCompleteSessionInfo, sessionInfoCache } from './store/sessionInfoCache' +import { INITIAL_MESSAGE_LIMIT } from './constants' import type { TerminalTab } from './store/layoutStore' import type { SettingsTab } from './features/settings/SettingsDialog' import { isTauri, isTauriMobile } from './utils/tauri' @@ -221,7 +224,15 @@ function App() { (session: { id: string; serverId?: string; directory?: string; location?: { directory?: string } }) => { const paneId = paneLayout.focusedPaneId ?? paneLayoutStore.getFocusedPaneId() if (!paneId) return - const sessionKey = makeSessionKey(session.serverId ?? serverStore.getActiveServerId(), session.id) + const serverId = session.serverId ?? serverStore.getActiveServerId() + const sessionKey = makeSessionKey(serverId, session.id) + + // 点击即出发:把列表里已有的元信息留给会话页(省掉 session.get), + // 同时预取首屏消息。两者都只是写缓存 / 发请求,不等待结果, + // 页面照常立刻导航(官方 home/sessions/controller.tsx:348 同款时机)。 + if (isCompleteSessionInfo(session)) sessionInfoCache.remember(serverId, session) + prefetchSessionMessages(serverId, session.id, INITIAL_MESSAGE_LIMIT) + // v2 的目录在 location.directory;扁平 directory 只有命令面板等少数路径会带 navigatePaneToSession(paneId, sessionKey, sessionRouteDirectory(session)) }, @@ -229,7 +240,9 @@ function App() { ) // 命令面板混合搜索的会话/文件数据源(官方 palette.ts 同款: - // 命令之外还能搜到会话与文件) + // 命令之外还能搜到会话与文件)。 + // 面板只读 id/title/directory,所以这里只挑这三个字段;点击时再按 id + // 从 allSessions 取回完整记录(见 handlePaletteOpenSession)。 const { sessions: allSessions } = useSessionContext() const paletteSessions = useMemo( () => @@ -240,6 +253,16 @@ function App() { })), [allSessions], ) + + // 面板只回传 id + directory(它并不关心完整记录),这里按 id 补回列表里的 + // 完整 SessionInfo:元信息交接缓存与目录解析都依赖完整字段。 + const handlePaletteOpenSession = useCallback( + (session: { id: string; directory?: string }) => { + const full = allSessions.find(item => item.id === session.id) + handleSelectSession(full ?? session) + }, + [allSessions, handleSelectSession], + ) const handlePaletteOpenFile = useCallback( (path: string) => { const name = path.split(/[\\/]/).pop() ?? path @@ -1085,7 +1108,7 @@ function App() { commands={commands} directory={focusedDirectory || currentDirectory || undefined} sessions={paletteSessions} - onOpenSession={handleSelectSession} + onOpenSession={handlePaletteOpenSession} onOpenFile={handlePaletteOpenFile} /> diff --git a/src/api/messagePrefetch.test.ts b/src/api/messagePrefetch.test.ts new file mode 100644 index 000000000..d0539838e --- /dev/null +++ b/src/api/messagePrefetch.test.ts @@ -0,0 +1,96 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest' +import { messageStore } from '../store/messageStore' +import { makeSessionKey } from '../utils/sessionKey' + +const { getSessionMessagesPageMock } = vi.hoisted(() => ({ getSessionMessagesPageMock: vi.fn() })) + +vi.mock('./message', () => ({ + getSessionMessagesPage: (...args: unknown[]) => getSessionMessagesPageMock(...args), +})) + +const { + clearSessionMessagesPrefetch, + prefetchSessionMessages, + takeSessionMessagesPrefetch, +} = await import('./messagePrefetch') + +const SERVER = 'local' +const SESSION = 'ses_a' +const LIMIT = 20 + +const emptyPage = { messages: [], nextCursor: null } + +describe('messagePrefetch', () => { + beforeEach(() => { + clearSessionMessagesPrefetch() + getSessionMessagesPageMock.mockReset() + getSessionMessagesPageMock.mockResolvedValue(emptyPage) + }) + + it('预取后会话页取走同一个请求,不会重发', async () => { + prefetchSessionMessages(SERVER, SESSION, LIMIT) + const taken = takeSessionMessagesPrefetch(SERVER, SESSION, LIMIT) + + expect(taken).toBeDefined() + await expect(taken).resolves.toEqual(emptyPage) + expect(getSessionMessagesPageMock).toHaveBeenCalledTimes(1) + expect(getSessionMessagesPageMock).toHaveBeenCalledWith(SESSION, { limit: LIMIT }, SERVER) + }) + + it('一次性:取走后再次获取为 undefined(由调用方正常请求)', () => { + prefetchSessionMessages(SERVER, SESSION, LIMIT) + takeSessionMessagesPrefetch(SERVER, SESSION, LIMIT) + expect(takeSessionMessagesPrefetch(SERVER, SESSION, LIMIT)).toBeUndefined() + }) + + it('重复预取复用同一个请求(连点列表不会打两次)', async () => { + prefetchSessionMessages(SERVER, SESSION, LIMIT) + prefetchSessionMessages(SERVER, SESSION, LIMIT) + + await takeSessionMessagesPrefetch(SERVER, SESSION, LIMIT) + expect(getSessionMessagesPageMock).toHaveBeenCalledTimes(1) + }) + + it('未预取时返回 undefined', () => { + expect(takeSessionMessagesPrefetch(SERVER, SESSION, LIMIT)).toBeUndefined() + }) + + it('按服务器与会话隔离', () => { + prefetchSessionMessages(SERVER, SESSION, LIMIT) + expect(takeSessionMessagesPrefetch('remote', SESSION, LIMIT)).toBeUndefined() + expect(takeSessionMessagesPrefetch(SERVER, 'ses_other', LIMIT)).toBeUndefined() + }) + + it('会话已有可渲染缓存时不预取(切过去根本不会请求)', () => { + messageStore.setMessages(makeSessionKey(SERVER, SESSION), [], { directory: '/workspace/demo' }) + messageStore.setMessages( + makeSessionKey(SERVER, SESSION), + [{ id: 'msg-1', type: 'user', text: 'hi', time: { created: 1 } }] as never, + { directory: '/workspace/demo' }, + ) + + prefetchSessionMessages(SERVER, SESSION, LIMIT) + + expect(getSessionMessagesPageMock).not.toHaveBeenCalled() + messageStore.clearSession(makeSessionKey(SERVER, SESSION)) + }) + + it('请求失败会清理槽位,且不产生 unhandled rejection', async () => { + getSessionMessagesPageMock.mockRejectedValueOnce(new Error('boom')) + prefetchSessionMessages(SERVER, SESSION, LIMIT) + + // 没人取走:等待微任务让 catch 跑道 + await Promise.resolve() + await Promise.resolve() + + expect(takeSessionMessagesPrefetch(SERVER, SESSION, LIMIT)).toBeUndefined() + }) + + it('取走失败请求时调用方仍能拿到真实错误', async () => { + const failure = new Error('boom') + getSessionMessagesPageMock.mockRejectedValueOnce(failure) + prefetchSessionMessages(SERVER, SESSION, LIMIT) + + await expect(takeSessionMessagesPrefetch(SERVER, SESSION, LIMIT)).rejects.toBe(failure) + }) +}) diff --git a/src/api/messagePrefetch.ts b/src/api/messagePrefetch.ts new file mode 100644 index 000000000..ff53320d1 --- /dev/null +++ b/src/api/messagePrefetch.ts @@ -0,0 +1,100 @@ +// ============================================ +// 会话首屏消息预取 +// +// 点击列表项到 ChatPane 的 effect 真正执行之间,隔着一次 React 提交。 +// 官方 app 在点击回调里就发出 `message.sync`(home/sessions/controller.tsx:348), +// 这里做同一件事:导航入口先发请求,会话页再「取走」这个 in-flight promise。 +// +// 复用而不是并行重发:会话页拿到的是同一个请求,不会因为预取而多打一次。 +// 未被取走的预取在 TTL 后自然失效;promise 上的 catch 保证不会产生 +// unhandled rejection(调用方 await 时仍能拿到真实错误)。 +// +// TTL 取「点击 → effect 执行」这个量级(10s),而不是元信息缓存的 30s: +// 这里存的是会话内容,宁可偶尔多打一次请求,也不要让用户看到十秒前 +// 的转写(期间可能正在流式输出)。 +// ============================================ + +import { getSessionMessagesPage } from './message' +import { messageStore } from '../store/messageStore' +import { makeSessionKey, splitSessionKey } from '../utils/sessionKey' + +type MessagePage = Awaited> + +const TTL_MS = 10_000 +const MAX_INFLIGHT = 32 + +interface Entry { + promise: Promise + startedAt: number +} + +const inflight = new Map() + +/** + * 归一化会话标识:导航入口传原始 id(列表项的 session.id), + * 会话页传复合 key(serverId::sessionId),两者必须落到同一个槽位。 + */ +function normalizeTarget(serverId: string, sessionId: string): { serverId: string; sessionId: string } { + return sessionId.includes('::') ? splitSessionKey(sessionId) : { serverId, sessionId } +} + +function cacheKey(serverId: string, sessionId: string, limit: number): string { + const target = normalizeTarget(serverId, sessionId) + return `${target.serverId}\0${target.sessionId}\0${limit}` +} + +function prune(now: number): void { + for (const [key, entry] of inflight) { + if (now - entry.startedAt > TTL_MS) inflight.delete(key) + } + // 极端情况下(一直被导航打断)按插入顺序丢最早的一批 + while (inflight.size > MAX_INFLIGHT) { + const oldest = inflight.keys().next().value + if (oldest === undefined) break + inflight.delete(oldest) + } +} + +/** + * 预取会话首屏消息;重复调用复用同一个请求。 + * + * 已经有可用缓存视图(切过去不会再请求)时直接跳过:白白发一次请求, + * 而且 request 的结果没人取,只会在槽位里留到过期。 + */ +export function prefetchSessionMessages(serverId: string, sessionId: string, limit: number): void { + const target = normalizeTarget(serverId, sessionId) + // 已有可用缓存视图时,会话页根本不会再请求:预取纯属浪费 + if (messageStore.hasRenderableCache(makeSessionKey(target.serverId, target.sessionId))) return + const key = cacheKey(serverId, sessionId, limit) + if (inflight.has(key)) return + + prune(Date.now()) + const promise = getSessionMessagesPage(sessionId, { limit }, serverId) + // 失败时清理槽位,并吞掉「没人取走」场景下的 rejection + promise.catch(() => { + if (inflight.get(key)?.promise === promise) inflight.delete(key) + }) + inflight.set(key, { promise, startedAt: Date.now() }) +} + +/** + * 取走预取结果(一次性)。过期则视为未命中,由调用方重新请求。 + * 返回 undefined 表示没有可用的预取。 + */ +export function takeSessionMessagesPrefetch( + serverId: string, + sessionId: string, + limit: number, +): Promise | undefined { + const key = cacheKey(serverId, sessionId, limit) + const entry = inflight.get(key) + if (!entry) return undefined + inflight.delete(key) + if (Date.now() - entry.startedAt > TTL_MS) return undefined + return entry.promise +} + +/** 测试用:清空预取槽位 */ +export function clearSessionMessagesPrefetch(): void { + inflight.clear() +} diff --git a/src/api/session.ts b/src/api/session.ts index 3e12a27d2..4b38eea72 100644 --- a/src/api/session.ts +++ b/src/api/session.ts @@ -27,6 +27,7 @@ import { inboxStore } from '../store/inboxStore' import { normalizeFileDiffs } from '../types/api/file' import type { FileDiff, Session, SessionListParams, SessionRevert, SessionStatusMap } from './types' import type { SessionTransferData, SessionInboxInfo } from '@opencode/client/promise' +import { sessionInfoCache } from '../store/sessionInfoCache' // ============================================ // 会话状态 @@ -120,7 +121,10 @@ export async function getSessionChildren( export async function getSession(sessionId: string, _directory?: string, serverId?: string): Promise { const target = resolveSessionTarget(sessionId, serverId) const sdk = getSDKClient(target.serverId) - return await sdk.session.get({ sessionID: target.sessionId }) + const session = await sdk.session.get({ sessionID: target.sessionId }) + // 权威读顺手刷新交接缓存:从任何路径回读到的最新元信息都能被下一次进入命中 + sessionInfoCache.remember(target.serverId, session) + return session } /** @@ -177,7 +181,9 @@ export async function updateSession( title: params.title, }) // v2 的 update 返回 void,回读一次保证调用点拿到最新会话 - return await sdk.session.get({ sessionID: target.sessionId }) + const session = await sdk.session.get({ sessionID: target.sessionId }) + sessionInfoCache.remember(target.serverId, session) + return session } /** 删除会话(v1 的 delete → v2 的 remove) */ @@ -185,6 +191,8 @@ export async function deleteSession(sessionId: string, _directory?: string, serv const target = resolveSessionTarget(sessionId, serverId) const sdk = getSDKClient(target.serverId) await sdk.session.remove({ sessionID: target.sessionId }) + // 删掉的会话不该在 TTL 内还命中交接缓存 + sessionInfoCache.forget(target.serverId, sessionId) return true } @@ -198,6 +206,8 @@ export async function moveSession(sessionId: string, directory: string, serverId const target = resolveSessionTarget(sessionId, serverId) const sdk = getSDKClient(target.serverId) await sdk.session.move({ sessionID: target.sessionId, directory }) + // 目录归属变了:交接缓存里的 location 立刻作废,避免进会话用错目录 + sessionInfoCache.forget(target.serverId, sessionId) } /** diff --git a/src/features/chat/ChatPane.tsx b/src/features/chat/ChatPane.tsx index d3d04ae32..65f668ebd 100644 --- a/src/features/chat/ChatPane.tsx +++ b/src/features/chat/ChatPane.tsx @@ -403,7 +403,11 @@ export const ChatPane = memo(function ChatPane({ const renderedLoadState = loadState === 'loaded' && isRenderingDeferredMessages ? 'loading' : loadState // 对齐 oc:session 消息 ready 后再 mount ChatArea,避免空 virtualizer 先建再跳 const messagesReady = !routeSessionId || loadState === 'loaded' || loadState === 'error' - const chatAreaMountKey = messagesReady ? (routeSessionId ?? 'home') : null + // 已有可显示消息就先挂出来(官方 createTimelineModel 的 ready 同款: + // 任意一条非 pending 消息即视为可渲染,enrich 之后补)。 + // 缓存命中 / SSE 先到 / 重连刷新时,没必要为了一次元信息回读让整页空白。 + const hasRenderableMessages = renderedMessages.length > 0 + const chatAreaMountKey = messagesReady || hasRenderableMessages ? (routeSessionId ?? 'home') : null const inputDisabled = !!routeSessionId && loadState === 'error' && messages.length === 0 const chatPageViewModel = useChatPageViewModel(projectedMessages) diff --git a/src/hooks/useChatSession.ts b/src/hooks/useChatSession.ts index d531debb0..37a53ca96 100644 --- a/src/hooks/useChatSession.ts +++ b/src/hooks/useChatSession.ts @@ -65,6 +65,7 @@ import type { APIError } from '../types/api/common' import { clipboardErrorHandler, copyTextToClipboard, createErrorHandler } from '../utils' import { saveData } from '../utils/downloadUtils' import { clearSessionRuntimeState } from '../utils/sessionLifecycle' +import { scheduleIdle } from '../utils/scheduleIdle' import { serverStorage } from '../utils/perServerStorage' import { makeSessionKey, sessionKeyToServerId, splitSessionKey } from '../utils/sessionKey' import { sweepTaskChildBindings, verifyTaskChildBindings } from '../utils/taskChildBinding' @@ -600,6 +601,9 @@ export function useChatSession({ }, onReconnected: (_reason: 'network' | 'server-switch') => { messageStore.markAllSessionsStale() + // 断连期间新建的子会话没收到 session.created:作废「已确认」标记, + // 让首屏落地后的关系恢复重新问一次(每个会话也只多一次) + childSessionStore.resetChildrenScans() // SSE 重连后重新加载当前会话,补齐断连期间可能丢失的消息 if (routeSessionId) { @@ -668,13 +672,15 @@ export function useChatSession({ // No-op: parts are always in memory now }, []) - // Preload @ root directory and / commands for current session directory + // Preload @ root directory and / commands for current session directory. + // 依赖只跟目录/服务器走:同目录切会话不该重发这两次请求 + //(缓存 TTL 只有 10s,挂在 routeSessionId 上等于每次切会话都打穿)。 useEffect(() => { - if (!routeSessionId || !effectiveDirectory) return + if (!effectiveDirectory) return prefetchRootDirectory(effectiveDirectory, paneServerId).catch(() => {}) prefetchCommands(effectiveDirectory, paneServerId).catch(() => {}) - }, [routeSessionId, effectiveDirectory, paneServerId]) + }, [effectiveDirectory, paneServerId]) // agents 列表加载后,校验当前选中的 agent 是否存在于列表中 // 选择值统一为 agent **id**(v2 API 用 id);历史存储的显示名会被归一化成 id @@ -702,29 +708,55 @@ export function useChatSession({ return () => cancelAnimationFrame(frameId) }, [agents, selectedAgent, setSelectedAgent]) - // Load child sessions and pending permissions on session change - // 页面刷新时 childSessionStore 是空的,需要先从 API 恢复子 session 关系 - // 然后再加载权限请求(包括子 session 的权限) - // 切换 session 时同样要清空旧 session 的 pending 权限/问题,否则 A 会话的请求会残留在 B 会话 + // ============================================ + // 会话切换:先清掉旧会话残留,恢复动作延后到首屏消息落地 + // ============================================ + // + // 这里原来在切会话时同步发起 getSessionChildren + 全量权限 + 全量表单 + + // task 卡片绑定校验(内部最多 12 次 message.list)。这些请求会和首屏 + // getSession / message.list 抢同源连接槽,直接把「进入会话」拖慢。 + // + // 现在分两段: + // 1. 立即清空上一个会话的待处理请求(纯内存操作,防串台) + // 2. 首屏消息落地(loaded / error)后再恢复关系与权限,绑定校验放到空闲时 + // + // 功能不减:刷新后子会话关系、权限弹窗、task 卡片绑定照样恢复,只是 + // 不再挡在首屏前面。官方同样把子会话 sync 留在真正需要时 + //(app/src/session/timeline/controller.tsx:301)。 useEffect(() => { resetPendingRequests() - if (!routeSessionId) { - return - } + }, [routeSessionId, resetPendingRequests]) - let cancelled = false + useEffect(() => { + if (!routeSessionId) return - async function loadChildSessionsAndPermissions() { - // Step 1: 恢复子 session 关系(如果 store 中还没有) - const existingChildren = childSessionStore.getChildSessionIds(routeSessionId!) - if (existingChildren.length === 0) { + // 首屏还没落地:先让消息占满带宽(idle / loading 直接返回)。 + if (loadState !== 'loaded' && loadState !== 'error') return + + let cancelled = false + let cancelBindingScan: (() => void) | null = null + + async function restoreSessionRelations() { + const sessionKey = routeSessionId! + const knownChildren = childSessionStore.getChildSessionIds(sessionKey) + // 子会话关系只能靠 REST 问清楚(列表和事件都不保证覆盖历史子会话)。 + // 但每个会话问一次就够:问过之后要么 store 里已有子会话,要么确认没有; + // 之后新建的子会话会由 session.created 直接注册进来。 + // + // 早先的做法是靠「消息里有没有 task 卡片 + 有没有更多历史」推断, + // 那是有概率漏判的(导入的会话树、卡片在未加载的历史页)。 + // 记住「问过了」既省掉重复请求,又不依赖推断。 + const shouldQueryChildren = knownChildren.length === 0 && !childSessionStore.hasScannedChildren(sessionKey) + + if (shouldQueryChildren) { try { - const children = await getSessionChildren(routeSessionId!, effectiveDirectory, paneServerId) + const children = await getSessionChildren(sessionKey, effectiveDirectory, paneServerId) if (cancelled) return - // 注册所有子 session 到 store for (const child of children) { childSessionStore.registerChildSession(child, paneServerId) } + // 请求成功才落「已确认」:失败(离线、瞬时 5xx)下次进入还会再问 + childSessionStore.markChildrenScanned(sessionKey) // 父子关系刚由 REST 建立:此前因「不知道子会话归属」而只弹了 toast、 // 被缓存下来的权限/表单请求,现在补投进 pane(否则要刷新页面才挂上) flushPendingRequests() @@ -733,32 +765,17 @@ export function useChatSession({ } } - // 刷新/重进后运行中的 task 卡片 metadata 里没有 sessionID(progress 不落库): - // 先一对一同步直绑,剩下的用 input.prompt 与子 session 首条用户消息 - // 逐字比对精确绑定(在线时由 tool.progress 的 metadata.sessionID 精确下发, - // 这里是离线恢复通道——绝不用 agent/title 做概率性配对,会挂错会话) - sweepTaskChildBindings(paneServerId, routeSessionId!) - await verifyTaskChildBindings(paneServerId, routeSessionId!, async childKey => { - try { - const messages = await getSessionMessages(childKey, undefined, undefined, paneServerId) - const firstUser = messages.find(m => m.type === 'user') - return firstUser?.type === 'user' ? firstUser.text : undefined - } catch { - return undefined - } - }) - if (cancelled) return - // Step 2: 获取完整的 session family(主 session + 所有子孙) - const family = new Set(childSessionStore.getSessionAndDescendants(routeSessionId!)) + // 完整的 session family(主 session + 所有子孙) + const family = new Set(childSessionStore.getSessionAndDescendants(sessionKey)) // family 是复合 key;API 返回的 sessionID 是原始 id,兼容两种形式比较 const familyRaw = new Set([...family].map(k => splitSessionKey(k).sessionId)) const matchesFamily = (rawSessionId: string) => familyRaw.has(rawSessionId) || familyRaw.has(splitSessionKey(rawSessionId).sessionId) - // Step 3: 获取所有待处理请求,然后用 family 过滤 - // GET /permission 和 GET /question 返回全量数据,不传 sessionId 避免 N 次重复请求 + // 待处理请求:GET /permission 和 GET /question 返回全量数据, + // 不传 sessionId 避免 N 次重复请求 const [allPerms, allQuestions] = await Promise.all([ getPendingPermissions(undefined, effectiveDirectory, paneServerId).catch(() => []), getPendingForms(undefined, effectiveDirectory, paneServerId).catch(() => []), @@ -788,15 +805,40 @@ export function useChatSession({ } return Array.from(merged.values()) }) + + if (cancelled) return + + // 刷新/重进后运行中的 task 卡片 metadata 里没有 sessionID(progress 不落库): + // 先一对一同步直绑,剩下的用 input.prompt 与子 session 首条用户消息 + // 逐字比对精确绑定(在线时由 tool.progress 的 metadata.sessionID 精确下发, + // 这里是离线恢复通道——绝不用 agent/title 做概率性配对,会挂错会话)。 + // + // 这一步最多发 12 次 message.list,纯恢复性质:放到空闲时,别和用户 + // 紧接着的操作抢连接。 + cancelBindingScan = scheduleIdle(() => { + if (cancelled) return + sweepTaskChildBindings(paneServerId, sessionKey) + void verifyTaskChildBindings(paneServerId, sessionKey, async childKey => { + try { + const childMessages = await getSessionMessages(childKey, undefined, undefined, paneServerId) + const firstUser = childMessages.find(m => m.type === 'user') + return firstUser?.type === 'user' ? firstUser.text : undefined + } catch { + return undefined + } + }) + }) } - loadChildSessionsAndPermissions() + void restoreSessionRelations() return () => { cancelled = true + cancelBindingScan?.() } }, [ routeSessionId, + loadState, effectiveDirectory, paneServerId, resetPendingRequests, diff --git a/src/hooks/useGlobalEvents.ts b/src/hooks/useGlobalEvents.ts index ab492c6a8..e8d95571e 100644 --- a/src/hooks/useGlobalEvents.ts +++ b/src/hooks/useGlobalEvents.ts @@ -15,6 +15,7 @@ import { inboxStore } from '../store/inboxStore' import { usageExceededStore } from '../store/usageExceededStore' import { shellInventoryStore } from '../store/shellInventoryStore' import { activeSessionStore } from '../store/activeSessionStore' +import { sessionInfoCache } from '../store/sessionInfoCache' import { notificationStore } from '../store/notificationStore' import { soundStore } from '../store/soundStore' import { playNotificationSoundDeduped } from '../utils/notificationSoundBridge' @@ -1144,11 +1145,19 @@ export function useGlobalEvents(directories?: string[]) { onSessionRenamed: data => { const scopedId = scope(data.sessionID) activeSessionStore.setSessionMeta(scopedId, data.title, undefined) + // 交接缓存里的标题同步更新:否则 TTL 内从列表点进去会显示旧标题 + if (data.title) sessionInfoCache.update(serverId, data.sessionID, { title: data.title }) if (data.title && messageStore.getSessionState(scopedId)) { messageStore.updateSessionMetadata(scopedId, { title: data.title }) } }, + onSessionMoved: data => { + // 目录归属变了:交接缓存里的 location 立刻作废, + // 否则 TTL 内进会话会带着旧目录(undo / 媒体路径都会用错) + sessionInfoCache.forget(serverId, data.sessionID) + }, + onSessionDeleted: data => { const scopedId = scope(data.sessionID) const removedSessionIds = childSessionStore.getSessionAndDescendants(scopedId) diff --git a/src/hooks/useSessionManager.test.tsx b/src/hooks/useSessionManager.test.tsx index d3ad7e7f3..f43d9cb36 100644 --- a/src/hooks/useSessionManager.test.tsx +++ b/src/hooks/useSessionManager.test.tsx @@ -1,12 +1,14 @@ import { renderHook, waitFor } from '@testing-library/react' import { beforeEach, describe, expect, it, vi } from 'vitest' import { useSessionManager } from './useSessionManager' +import { sessionInfoCache } from '../store/sessionInfoCache' const { getSessionMock, getSessionMessagesPageMock, messageStoreMock, sessionErrorHandlerMock } = vi.hoisted(() => ({ getSessionMock: vi.fn(), getSessionMessagesPageMock: vi.fn(), messageStoreMock: { getSessionState: vi.fn(), + hasRenderableCache: vi.fn(() => false), setLoadState: vi.fn(), setLoadError: vi.fn(), setMessages: vi.fn(), @@ -25,6 +27,12 @@ vi.mock('../api', () => ({ extractUserMessageContent: vi.fn(), })) +// messagePrefetch 直接依赖 ./message(绕过 api 桶),两处必须指向同一个 mock, +// 否则「复用预取」的断言会看到两个互不相干的函数 +vi.mock('../api/message', () => ({ + getSessionMessagesPage: (...args: unknown[]) => getSessionMessagesPageMock(...args), +})) + vi.mock('../store', () => ({ messageStore: messageStoreMock, })) @@ -45,6 +53,7 @@ describe('useSessionManager', () => { messageStoreMock.prependMessages.mockReset() messageStoreMock.setRevertState.mockReset() sessionErrorHandlerMock.mockReset() + sessionInfoCache.clear() messageStoreMock.getSessionState.mockReturnValue(null) getSessionMock.mockResolvedValue({ id: 'session-1', directory: '/workspace/demo' }) @@ -144,4 +153,118 @@ describe('useSessionManager', () => { expect(getSessionMessagesPageMock).not.toHaveBeenCalled() }) + + it('列表交接命中:进入会话不再发 session.get', async () => { + sessionInfoCache.remember('local', { + id: 'session-1', + title: '来自列表', + location: { directory: '/workspace/demo' }, + time: { created: 1, updated: 2 }, + } as never) + + renderHook(() => useSessionManager({ sessionId: 'local::session-1', directory: '/workspace/demo' })) + + await waitFor(() => { + expect(messageStoreMock.setMessages).toHaveBeenCalled() + }) + + expect(getSessionMock).not.toHaveBeenCalled() + expect(messageStoreMock.setMessages).toHaveBeenCalledWith( + 'local::session-1', + [], + expect.objectContaining({ title: '来自列表', directory: '/workspace/demo' }), + ) + }) + + it('交接缓存命中被 force(重连恢复)显式跳过,仍回读服务端', async () => { + sessionInfoCache.remember('local', { + id: 'session-1', + title: '旧标题', + location: { directory: '/workspace/demo' }, + time: { created: 1, updated: 2 }, + } as never) + + const { result } = renderHook(() => + useSessionManager({ sessionId: 'local::session-1', directory: '/workspace/demo' }), + ) + + // 首次进入命中缓存,不发请求 + await waitFor(() => { + expect(messageStoreMock.setMessages).toHaveBeenCalled() + }) + getSessionMock.mockClear() + + await result.current.loadSession('local::session-1', { force: true }) + + expect(getSessionMock).toHaveBeenCalledWith('local::session-1', '/workspace/demo', 'local') + }) + + it('交接缓存命中时,本地已有的回退边界不能被旧快照抹掉', async () => { + sessionInfoCache.remember('local', { + id: 'session-1', + title: '来自列表', + location: { directory: '/workspace/demo' }, + time: { created: 1, updated: 2 }, + } as never) + // 本端刚 undo 过,列表快照还没有 revert 字段 + messageStoreMock.getSessionState.mockReturnValue({ + messages: [], + loadState: 'idle', + isStale: false, + revertState: { messageId: 'msg_revert', history: [] }, + }) + + renderHook(() => useSessionManager({ sessionId: 'local::session-1', directory: '/workspace/demo' })) + + await waitFor(() => { + expect(messageStoreMock.setMessages).toHaveBeenCalled() + }) + + expect(messageStoreMock.setMessages).toHaveBeenCalledWith( + 'local::session-1', + [], + expect.objectContaining({ revertState: { messageID: 'msg_revert' } }), + ) + }) + + it('服务端回读的 revert 优先于本地(权威数据覆盖)', async () => { + getSessionMock.mockResolvedValue({ + id: 'session-1', + location: { directory: '/workspace/demo' }, + revert: { messageID: 'msg_server' }, + }) + // 缓存未命中,走服务端;本地还留着旧边界 + messageStoreMock.getSessionState.mockReturnValue({ + messages: [], + loadState: 'idle', + isStale: false, + revertState: { messageId: 'msg_local', history: [] }, + }) + + renderHook(() => useSessionManager({ sessionId: 'local::session-1', directory: '/workspace/demo' })) + + await waitFor(() => { + expect(messageStoreMock.setMessages).toHaveBeenCalled() + }) + + expect(messageStoreMock.setMessages).toHaveBeenCalledWith( + 'local::session-1', + [], + expect.objectContaining({ revertState: { messageID: 'msg_server' } }), + ) + }) + + it('导航入口已预取消息时复用同一请求,不重复拉首屏', async () => { + const { prefetchSessionMessages } = await import('../api/messagePrefetch') + prefetchSessionMessages('local', 'session-1', 50) + + renderHook(() => useSessionManager({ sessionId: 'local::session-1', directory: '/workspace/demo' })) + + await waitFor(() => { + expect(messageStoreMock.setMessages).toHaveBeenCalled() + }) + + // 预取过一次就够:加载路径取走它,而不是再发一次 + expect(getSessionMessagesPageMock).toHaveBeenCalledTimes(1) + }) }) diff --git a/src/hooks/useSessionManager.ts b/src/hooks/useSessionManager.ts index 06eda114a..e51f1ef84 100644 --- a/src/hooks/useSessionManager.ts +++ b/src/hooks/useSessionManager.ts @@ -11,15 +11,18 @@ import { useCallback, useEffect, useRef } from 'react' import { logger } from '../utils/logger' import { messageStore, type RevertState } from '../store' import { LOCAL_SERVER_ID } from '../store/serverStore' +import { sessionInfoCache } from '../store/sessionInfoCache' import { useServiceStore } from '../store/serviceStore' import { sessionKeyToServerId } from '../utils/sessionKey' import { getSessionMessagesPage, getSession, revertMessage, unrevertSession } from '../api' +import { takeSessionMessagesPrefetch } from '../api/messagePrefetch' import { sessionErrorHandler } from '../utils' import { isSessionNotFoundError } from '../utils/sessionErrors' import { INITIAL_MESSAGE_LIMIT, HISTORY_LOAD_BATCH_SIZE } from '../constants' import { isUserMessage } from '../types/api/message' import type { APIError } from '../types/api/common' import type { SessionMessageInfo } from '../types/api/message' +import type { Session as ApiSession } from '../types/api/session' /** * 首屏窗口是否从半截回合开始(官方 leadingTurnNeedsParent 同款, @@ -41,6 +44,32 @@ const LEADING_TURN_PAGE_DELAY = 200 const REVERT_BOUNDARY_PAGE_LIMIT = 50 const pause = (ms: number) => new Promise(resolve => setTimeout(resolve, ms)) +/** + * 会话元信息通道:列表点击时留下的 SessionInfo 优先。 + * + * 列表返回的本来就是完整 SessionInfo,再从列表点进来时没必要重复 + * `session.get`(官方 data.session.remember 同款)。force(重连恢复) + * 与未命中(深链、刷新)照常请求。 + * + * `fresh` 表示这份元信息是刚从服务端读回来的(权威)。缓存命中的那份 + * 只是点击前的列表快照,某些字段(revert)可能已经落后于本端操作。 + */ +interface LoadedSessionInfo { + info: ApiSession + fresh: boolean +} + +function loadSessionInfo( + sessionId: string, + directory: string | undefined, + serverId: string, + force: boolean, +): Promise { + const cached = force ? undefined : sessionInfoCache.get(serverId, sessionId) + if (cached) return Promise.resolve({ info: cached, fresh: false }) + return getSession(sessionId, directory, serverId).then(info => ({ info, fresh: true })) +} + /** * 会话加载失败 → v2 的结构化错误(`{ type, message, status?, response? }`)。 * @@ -160,14 +189,17 @@ export function useSessionManager({ // 异步加载 session 元数据(不阻塞) const dir = directoryRef.current const serverId = sessionKeyToServerId(sid) + // 导航入口若已预取首屏,这里同样取走同一个请求,而不是再发一次 + const prefetched = force ? undefined : takeSessionMessagesPrefetch(serverId, sid, INITIAL_MESSAGE_LIMIT) Promise.all([ - getSession(sid, dir, serverId).catch(() => null), - getSessionMessagesPage(sid, { limit: INITIAL_MESSAGE_LIMIT }, serverId) + loadSessionInfo(sid, dir, serverId, false).catch(() => null), + (prefetched ?? getSessionMessagesPage(sid, { limit: INITIAL_MESSAGE_LIMIT }, serverId)) .then(page => ({ ok: true as const, page })) .catch(() => ({ ok: false as const, page: null })), ]) - .then(([sessionInfo, messagesResult]) => { + .then(([sessionInfoResult, messagesResult]) => { if (isStale()) return + const sessionInfo = sessionInfoResult?.info messageStore.updateSessionMetadata(sid, { ...(messagesResult.ok && messagesResult.page @@ -192,15 +224,37 @@ export function useSessionManager({ messageStore.setLoadState(sid, 'loading') try { - // 并行加载 session 信息和消息(传递 directory) + // 并行加载 session 信息和消息(传递 directory)。 + // 消息若在导航入口已预取(prefetchSessionMessages),这里直接取走同一个 + // in-flight 请求;元信息若刚由列表写入缓存,也不再发 session.get。 const serverId = sessionKeyToServerId(sid) - const [sessionInfo, firstPage] = await Promise.all([ - getSession(sid, dir, serverId).catch(() => null), - getSessionMessagesPage(sid, { limit: INITIAL_MESSAGE_LIMIT }, serverId), + const prefetchedMessages = force ? undefined : takeSessionMessagesPrefetch(serverId, sid, INITIAL_MESSAGE_LIMIT) + const [sessionInfoResult, firstPage] = await Promise.all([ + loadSessionInfo(sid, dir, serverId, force).catch(() => null), + // 预取失败不该让整个进入失败(真实请求还没试过):取到的预取出错就重发一次 + (prefetchedMessages ?? getSessionMessagesPage(sid, { limit: INITIAL_MESSAGE_LIMIT }, serverId)).catch( + error => { + if (!prefetchedMessages) throw error + return getSessionMessagesPage(sid, { limit: INITIAL_MESSAGE_LIMIT }, serverId) + }, + ), ]) if (isStale()) return + const sessionInfo = sessionInfoResult?.info + // revert 边界的取舍: + // - 刚从服务端读回(fresh)→ 无条件采信 + // - 命中交接缓存:缓存是点击前的列表快照,可能比本端操作旧(刚 undo 变出来会被 + // 抹掉,刚 redo 掉的又会被复活)。本端已有该会话状态时以本地为准, + // 没有(首次进入这条会话)才用缓存兜底,至少能恢复撤销后的可见性。 + const localState = messageStore.getSessionState(sid) + const revertState = sessionInfoResult?.fresh + ? (sessionInfo?.revert ?? null) + : localState + ? (localState.revertState ? { messageID: localState.revertState.messageId } : null) + : (sessionInfo?.revert ?? null) + const apiMessages = firstPage.messages const nextCursor = firstPage.nextCursor @@ -238,7 +292,7 @@ export function useSessionManager({ historyCursor: nextCursor, // 服务端把回退边界持久化在 Session.Info.revert(schema session.ts), // 刷新后据此重建 redo 历史,否则刷新就像没 undo 过。 - revertState: sessionInfo?.revert ?? null, + revertState, // 会话级 agent/model 的 durable 来源(官方 selection.tsx 同款): // 新鲜客户端没有 live SSE 历史时,composer 从这里恢复 agent: sessionInfo?.agent, @@ -262,7 +316,7 @@ export function useSessionManager({ // deep undo:回退边界不在首屏时(undo 的消息很深),往回翻页把边界补进内存, // 重建逐条 redo 历史 + 预填内容。边界一加载 rebuildRevertHistory 就返回 true 提前终止; // 正常情况下同一页里边界之前的消息也一并带出来,当前(撤销后的)视图就有了。 - if (sessionInfo?.revert?.messageID) { + if (revertState?.messageID) { for (let pages = 0; pages < REVERT_BOUNDARY_PAGE_LIMIT; pages++) { if (messageStore.rebuildRevertHistory(sid)) break const state = messageStore.getSessionState(sid) @@ -435,13 +489,10 @@ export function useSessionManager({ useEffect(() => { if (!sessionId) return - const cached = messageStore.getSessionState(sessionId) - const canUseCached = !!cached && cached.loadState === 'loaded' && !cached.isStale && cached.messages.length > 0 - - if (canUseCached) { + if (messageStore.hasRenderableCache(sessionId)) { logger.log('[SessionManager] switch:use-cached', { sessionId, - cachedCount: cached.messages.length, + cachedCount: messageStore.getSessionState(sessionId)?.messages.length ?? 0, }) return } diff --git a/src/store/childSessionStore.test.ts b/src/store/childSessionStore.test.ts index b629d0581..02a7f7cbe 100644 --- a/src/store/childSessionStore.test.ts +++ b/src/store/childSessionStore.test.ts @@ -51,3 +51,37 @@ describe('工具卡片 ↔ 子 session 绑定', () => { expect(childSessionStore.getBoundChildForToolPart('local', 'call_a')).toBeUndefined() }) }) + +describe('子会话「已确认」标记', () => { + it('标记之后不再重复问服务端', () => { + expect(childSessionStore.hasScannedChildren('local::ses_parent')).toBe(false) + childSessionStore.markChildrenScanned('local::ses_parent') + expect(childSessionStore.hasScannedChildren('local::ses_parent')).toBe(true) + }) + + it('removeSession 丢掉标记(会话没了,下次重建要重新确认)', () => { + childSessionStore.markChildrenScanned('local::ses_parent') + childSessionStore.removeSession('local::ses_parent') + expect(childSessionStore.hasScannedChildren('local::ses_parent')).toBe(false) + }) + + it('clearChildren 丢掉标记(子会话记录被清空需要重新问)', () => { + childSessionStore.markChildrenScanned('local::ses_parent') + childSessionStore.clearChildren('local::ses_parent') + expect(childSessionStore.hasScannedChildren('local::ses_parent')).toBe(false) + }) + + it('resetChildrenScans 只清标记(重连补拉断连期间新建的子会话)', () => { + childSessionStore.markChildrenScanned('local::ses_a') + childSessionStore.markChildrenScanned('local::ses_b') + childSessionStore.resetChildrenScans() + expect(childSessionStore.hasScannedChildren('local::ses_a')).toBe(false) + expect(childSessionStore.hasScannedChildren('local::ses_b')).toBe(false) + }) + + it('clearAll 清空标记(切换服务器)', () => { + childSessionStore.markChildrenScanned('local::ses_parent') + childSessionStore.clearAll() + expect(childSessionStore.hasScannedChildren('local::ses_parent')).toBe(false) + }) +}) diff --git a/src/store/childSessionStore.ts b/src/store/childSessionStore.ts index fc7c424ef..dc6da2a55 100644 --- a/src/store/childSessionStore.ts +++ b/src/store/childSessionStore.ts @@ -44,6 +44,10 @@ class ChildSessionStore { private toolBindings = new Map() // 反向索引:childSessionKey -> partKey(一个子 session 只属于一张卡片) private toolBindingsByChild = new Map() + // 已经问过服务端「这个父会话有哪些子会话」的 parent key。 + // 查询只能靠 REST(列表/事件都不保证覆盖历史子会话),所以每个会话只问一次: + // 之后要么 store 里已有子会话,要么已确认没有。会话创建时照样会注册进来。 + private childrenScanned = new Set() private subscribers = new Set() private version = 0 @@ -152,6 +156,25 @@ class ChildSessionStore { return this.sessionInfo.get(sessionId) } + /** 标记「已向服务端确认过该父会话的子会话列表」 */ + markChildrenScanned(parentId: string) { + this.childrenScanned.add(parentId) + } + + /** 是否已经确认过该父会话的子会话列表(确认过就不会再重复请求) */ + hasScannedChildren(parentId: string): boolean { + return this.childrenScanned.has(parentId) + } + + /** + * 丢弃「已确认」标记(重连后调用): + * 断连期间新建的子会话没有走过 session.created,只有重新问一次才能补齐。 + */ + resetChildrenScans() { + if (this.childrenScanned.size === 0) return + this.childrenScanned.clear() + } + getVersion = (): number => this.version // ============================================ @@ -231,6 +254,7 @@ class ChildSessionStore { this.sessionInfo.clear() this.toolBindings.clear() this.toolBindingsByChild.clear() + this.childrenScanned.clear() this.notify() } @@ -249,6 +273,8 @@ class ChildSessionStore { this.childrenByParent.delete(parentId) this.notify() } + // 记录被清掉 = 需要重新向服务端确认 + this.childrenScanned.delete(parentId) } removeSession(sessionId: string) { @@ -267,6 +293,7 @@ class ChildSessionStore { if (this.childrenByParent.delete(id)) changed = true if (this.sessionInfo.delete(id)) changed = true + if (this.childrenScanned.delete(id)) changed = true if (this.dropToolBinding(id)) changed = true } diff --git a/src/store/messageStore.ts b/src/store/messageStore.ts index d8ede5a37..ebed2e386 100644 --- a/src/store/messageStore.ts +++ b/src/store/messageStore.ts @@ -418,6 +418,18 @@ class MessageStore { return this.sessions.get(sessionId) } + /** + * 会话是否已有可直接渲染的缓存视图。 + * + * 「切过去不用再拉」和「点击时不必预取」是同一个判断,放在这里做唯一定义, + * 免得两处口径漂移(改阈值只改一处)。 + */ + hasRenderableCache(sessionId: string | null): boolean { + if (!sessionId) return false + const cached = this.sessions.get(sessionId) + return !!cached && cached.loadState === 'loaded' && !cached.isStale && cached.messages.length > 0 + } + /** 可见消息:undo 生效后,撤销点及其之后的消息不再展示 */ getVisibleMessages(sessionId: string | null): SessionMessageInfo[] { if (!sessionId) return [] diff --git a/src/store/sessionInfoCache.test.ts b/src/store/sessionInfoCache.test.ts new file mode 100644 index 000000000..7201eac4d --- /dev/null +++ b/src/store/sessionInfoCache.test.ts @@ -0,0 +1,72 @@ +import { describe, expect, it } from 'vitest' +import { isCompleteSessionInfo, sessionInfoCache } from './sessionInfoCache' +import type { Session } from '../types/api/session' + +const SERVER = 'local' + +function session(id: string, patch: Partial = {}): Session { + return { + id, + title: `title-${id}`, + location: { directory: '/workspace/demo' }, + time: { created: 1, updated: 2 }, + ...patch, + } as Session +} + +describe('sessionInfoCache', () => { + it('remember 之后可以命中(列表 → 会话页的交接)', () => { + sessionInfoCache.remember(SERVER, session('ses_a')) + expect(sessionInfoCache.get(SERVER, 'ses_a')?.title).toBe('title-ses_a') + sessionInfoCache.forget(SERVER, 'ses_a') + }) + + it('按服务器隔离:同 id 不同服务器不串数据', () => { + sessionInfoCache.remember(SERVER, session('ses_shared', { title: 'local-title' })) + sessionInfoCache.remember('remote', session('ses_shared', { title: 'remote-title' })) + + expect(sessionInfoCache.get(SERVER, 'ses_shared')?.title).toBe('local-title') + expect(sessionInfoCache.get('remote', 'ses_shared')?.title).toBe('remote-title') + + sessionInfoCache.clear() + }) + + it('未命中返回 undefined(深链、刷新走正常请求)', () => { + sessionInfoCache.clear() + expect(sessionInfoCache.get(SERVER, 'ses_missing')).toBeUndefined() + }) + + it('forget 之后不再命中(删除会话)', () => { + sessionInfoCache.remember(SERVER, session('ses_gone')) + sessionInfoCache.forget(SERVER, 'ses_gone') + expect(sessionInfoCache.get(SERVER, 'ses_gone')).toBeUndefined() + }) + + it('update 就地刷新标题(重命名后 TTL 内不再显示旧标题)', () => { + sessionInfoCache.remember(SERVER, session('ses_rename')) + sessionInfoCache.update(SERVER, 'ses_rename', { title: '新标题' }) + expect(sessionInfoCache.get(SERVER, 'ses_rename')?.title).toBe('新标题') + // 其余字段保持不变,不能因为 patch 把对象弄残 + expect(sessionInfoCache.get(SERVER, 'ses_rename')?.location?.directory).toBe('/workspace/demo') + sessionInfoCache.forget(SERVER, 'ses_rename') + }) + + it('update 命中不存在的条目时什么都不做(不凭空造数据)', () => { + sessionInfoCache.clear() + sessionInfoCache.update(SERVER, 'ses_absent', { title: 'x' }) + expect(sessionInfoCache.get(SERVER, 'ses_absent')).toBeUndefined() + }) +}) + +describe('isCompleteSessionInfo', () => { + it('完整 SessionInfo 通过', () => { + expect(isCompleteSessionInfo(session('ses_full'))).toBe(true) + }) + + it('半截对象(缺 time / location)拒绝写入缓存', () => { + expect(isCompleteSessionInfo({ id: 'ses_partial', location: { directory: '/x' } })).toBe(false) + expect(isCompleteSessionInfo({ id: 'ses_partial' })).toBe(false) + expect(isCompleteSessionInfo(null)).toBe(false) + expect(isCompleteSessionInfo(undefined)).toBe(false) + }) +}) diff --git a/src/store/sessionInfoCache.ts b/src/store/sessionInfoCache.ts new file mode 100644 index 000000000..53d354285 --- /dev/null +++ b/src/store/sessionInfoCache.ts @@ -0,0 +1,110 @@ +// ============================================ +// SessionInfoCache — 列表到会话页的元信息交接 +// +// 列表(session.list)返回的本来就是完整 `SessionInfo`,但会话页过去还要 +// 再发一次 `session.get` 才拿得到标题 / 目录 / agent / model / revert。 +// 官方 app 的做法是点击时 `data.session.remember(session)`,进会话不再请求。 +// +// 这里保存同一份交接数据,带短 TTL: +// - 命中 → 进入会话少一个请求,且不占同源连接槽 +// - 过期 / 未命中(深链、刷新)→ 照常走 session.get +// +// TTL 内服务端状态可能已变(重命名、revert),所以只用于「刚从列表点进来」 +// 这一条路径;重连刷新(force)显式跳过缓存。 +// ============================================ + +import type { Session } from '../types/api/session' +import { splitSessionKey } from '../utils/sessionKey' + +/** 交接数据的可信窗口:列表刚拉到的数据足够新鲜 */ +const TTL_MS = 30_000 +/** 上限按「一个服务器常见会话数量」取,超出按 LRU 淘汰 */ +const MAX_ENTRIES = 300 + +interface Entry { + session: Session + storedAt: number +} + +class SessionInfoCache { + private entries = new Map() + + /** + * 归一化会话标识:调用方可能传原始 id(列表项)或复合 key(路由/pane), + * 两种形式落到同一个条目上。 + */ + private normalize(serverId: string, sessionId: string): { serverId: string; sessionId: string } { + if (!sessionId.includes('::')) return { serverId, sessionId } + const parsed = splitSessionKey(sessionId) + return { serverId: parsed.serverId, sessionId: parsed.sessionId } + } + + private key(serverId: string, sessionId: string): string { + const target = this.normalize(serverId, sessionId) + return `${target.serverId}\0${target.sessionId}` + } + + remember(serverId: string, session: Session): void { + const key = this.key(serverId, session.id) + // delete + set:维持 Map 的插入顺序即 LRU 顺序 + this.entries.delete(key) + if (this.entries.size >= MAX_ENTRIES) { + const oldest = this.entries.keys().next().value + if (oldest !== undefined) this.entries.delete(oldest) + } + this.entries.set(key, { session, storedAt: Date.now() }) + } + + get(serverId: string, sessionId: string): Session | undefined { + const key = this.key(serverId, sessionId) + const entry = this.entries.get(key) + if (!entry) return undefined + if (Date.now() - entry.storedAt > TTL_MS) { + this.entries.delete(key) + return undefined + } + // 命中即最近使用:delete + set 保持 Map 的插入顺序等于 LRU 顺序 + this.entries.delete(key) + this.entries.set(key, entry) + return entry.session + } + + forget(serverId: string, sessionId: string): void { + this.entries.delete(this.key(serverId, sessionId)) + } + + /** + * 就地更新已缓存的条目(重命名等局部变更)。 + * 没有条目时什么都不做——交给下一次 getSession 回填。 + */ + update(serverId: string, sessionId: string, patch: Partial): void { + const key = this.key(serverId, sessionId) + const entry = this.entries.get(key) + if (!entry) return + entry.session = { ...entry.session, ...patch } + } + + clear(): void { + this.entries.clear() + } +} + +export const sessionInfoCache = new SessionInfoCache() + +/** + * 列表项是否已经是完整可用的 `SessionInfo`。 + * + * 缓存只接受完整对象:半截对象(只有 id + location)写进去会让会话页 + * 拿不到标题/时间/agent,比不发缓存更糟。列表与命令面板给的都是完整 + * 记录,守卫只是把这条边界写死。 + */ +export function isCompleteSessionInfo(value: unknown): value is Session { + const candidate = value as Partial | undefined + return ( + !!candidate && + typeof candidate.id === 'string' && + typeof candidate.location?.directory === 'string' && + typeof candidate.time?.updated === 'number' + ) +} + diff --git a/src/utils/scheduleIdle.ts b/src/utils/scheduleIdle.ts new file mode 100644 index 000000000..79a6d8d04 --- /dev/null +++ b/src/utils/scheduleIdle.ts @@ -0,0 +1,63 @@ +// ============================================ +// 空闲调度 +// +// 会话切换时有些恢复动作(子会话关系、task 卡片绑定校验、权限补拉) +// 功能上必需,但不该和首屏消息抢同源连接。等到浏览器空闲再跑, +// 并用 timeout 兜底:后台标签页里 requestIdleCallback 可能长期不触发。 +// ============================================ + +interface IdleDeadlineLike { + didTimeout: boolean + timeRemaining: () => number +} + +type RequestIdleCallback = (callback: (deadline: IdleDeadlineLike) => void, options?: { timeout?: number }) => number +type CancelIdleCallback = (handle: number) => void + +interface IdleWindow { + requestIdleCallback?: RequestIdleCallback + cancelIdleCallback?: CancelIdleCallback +} + +/** + * 在空闲时执行一次任务,返回取消函数。 + * + * 任务最多执行一次;取消后不会再执行。没有 requestIdleCallback 的环境 + * (测试 / 旧内核)退化为定时器,保证任务一定有机会执行。 + */ +export function scheduleIdle(task: () => void, timeoutMs = 500): () => void { + let done = false + let idleHandle: number | null = null + let timer: ReturnType | null = null + + const idleWindow = typeof window === 'undefined' ? undefined : (window as unknown as IdleWindow) + + const clear = () => { + if (idleHandle !== null && idleWindow?.cancelIdleCallback) { + idleWindow.cancelIdleCallback(idleHandle) + } + idleHandle = null + if (timer !== null) { + clearTimeout(timer) + timer = null + } + } + + const run = () => { + if (done) return + done = true + clear() + task() + } + + if (idleWindow?.requestIdleCallback) { + idleHandle = idleWindow.requestIdleCallback(run, { timeout: timeoutMs }) + } + // rIC 迟迟不派发(后台标签页)时由定时器接管 + timer = setTimeout(run, timeoutMs) + + return () => { + done = true + clear() + } +} diff --git a/src/utils/sessionLifecycle.ts b/src/utils/sessionLifecycle.ts index a28204cc7..53bfd8d95 100644 --- a/src/utils/sessionLifecycle.ts +++ b/src/utils/sessionLifecycle.ts @@ -2,6 +2,8 @@ import { activeSessionStore } from '../store/activeSessionStore' import { childSessionStore } from '../store/childSessionStore' import { inboxStore } from '../store/inboxStore' import { messageStore } from '../store/messageStore' +import { sessionInfoCache } from '../store/sessionInfoCache' +import { splitSessionKey } from './sessionKey' export function clearSessionRuntimeState(sessionId: string) { const sessionIds = childSessionStore.getSessionAndDescendants(sessionId) @@ -10,6 +12,8 @@ export function clearSessionRuntimeState(sessionId: string) { messageStore.clearSession(id) inboxStore.clearSession(id) activeSessionStore.removeSession(id) + // 列表交接缓存同样要清:否则删掉的会话还能在 TTL 内命中旧元信息 + sessionInfoCache.forget(splitSessionKey(id).serverId, id) } childSessionStore.removeSession(sessionId) From ddec0aadb9f05d5218a2b540acef8a8a19110524 Mon Sep 17 00:00:00 2001 From: lehhair Date: Fri, 23 Oct 2026 12:16:54 +0800 Subject: [PATCH 15/67] =?UTF-8?q?perf(session-list):=20=E6=AF=8F=E5=8F=B0?= =?UTF-8?q?=E6=9C=8D=E5=8A=A1=E5=99=A8=E4=B8=80=E4=BB=BD=E4=BC=9A=E8=AF=9D?= =?UTF-8?q?=E7=B4=A2=E5=BC=95=EF=BC=8C=E5=88=87=E7=9B=AE=E5=BD=95=E4=B8=8D?= =?UTF-8?q?=E5=86=8D=E5=8F=91=E8=AF=B7=E6=B1=82?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 侧栏列表过去按目录各拉各的:文件夹模式下每个文件夹一次 session.list, 切目录、切回来、重连都重新请求;翻页靠 limit 递增重拉整表,越翻越慢。 改成和官方 home 一致的「服务器级根会话索引」(sessionIndexStore): - getSessions 拆出保留游标的 listSessionsPage,索引按 cursor 翻页, 首轮最多自动翻两页(limit 500),大库才需要「显示更多」 - 索引 30s 内复用,并发 ensure 共享同一个请求;重连直接重拉, 旧数据保留到新数据到达,列表不再闪空态 - SSE 增量(创建 / fork / 改名 / 删除 / 移动)由索引统一处理, 列表层不再各订一份;刷新期间的增量排队重放,不会被整页覆盖 - SessionProvider / useSessions 改成按目录过滤 + 本地切片, 文件夹模式的多个目录共享一次请求 - 搜索改为本地标题 / id 匹配,不再每次按键打服务端 --- src/api/session.ts | 29 +- src/contexts/SessionContext.test.tsx | 377 ++++++++----------- src/contexts/SessionContext.tsx | 298 ++++------------ src/hooks/useSessions.test.tsx | 516 ++++++++------------------- src/hooks/useSessions.ts | 420 +++++----------------- src/store/sessionIndexStore.test.ts | 264 ++++++++++++++ src/store/sessionIndexStore.ts | 398 +++++++++++++++++++++ 7 files changed, 1137 insertions(+), 1165 deletions(-) create mode 100644 src/store/sessionIndexStore.test.ts create mode 100644 src/store/sessionIndexStore.ts diff --git a/src/api/session.ts b/src/api/session.ts index 4b38eea72..4f0de83d5 100644 --- a/src/api/session.ts +++ b/src/api/session.ts @@ -81,12 +81,22 @@ export async function getSessionDiff(sessionId: string, serverId?: string): Prom // 会话 CRUD // ============================================ +/** 一页会话列表;`next` 是下一页游标(null = 到底) */ +export interface SessionListPage { + data: Session[] + next: string | null +} + /** - * 获取会话列表。 + * 获取一页会话列表,保留服务端游标。 * - * v2 返回 `{ data, cursor }`;调用点普遍期望数组,这里返回 `data`。 + * 翻页(loadMore)走这里:cursor 分页只取新增的一页,不必把整张表 + * 重新拉一遍(旧实现靠 limit 递增重拉,越翻越慢)。 */ -export async function getSessions(params: SessionListParams = {}, serverId?: string): Promise { +export async function listSessionsPage( + params: SessionListParams = {}, + serverId?: string, +): Promise { const sdk = getSDKClient(serverId) const { directory, parentID, search, limit, order, cursor, project, subpath } = params const result = await sdk.session.list({ @@ -99,7 +109,18 @@ export async function getSessions(params: SessionListParams = {}, serverId?: str project, subpath, }) - return result.data + return { data: result.data, next: result.cursor?.next ?? null } +} + +/** + * 获取会话列表(数组形态)。 + * + * 只要第一页的调用点(搜索、e2e)继续用它;需要翻页的列表走 + * `listSessionsPage` 或 `sessionIndexStore`。 + */ +export async function getSessions(params: SessionListParams = {}, serverId?: string): Promise { + const page = await listSessionsPage(params, serverId) + return page.data } /** diff --git a/src/contexts/SessionContext.test.tsx b/src/contexts/SessionContext.test.tsx index c6a71e8bd..ea8dabde0 100644 --- a/src/contexts/SessionContext.test.tsx +++ b/src/contexts/SessionContext.test.tsx @@ -1,88 +1,103 @@ import { act, render } from '@testing-library/react' import { useContext, useEffect, type ContextType } from 'react' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import type { EventCallbacks } from '../types/api/event' +import { beforeEach, describe, expect, it, vi } from 'vitest' import { SessionContext } from './SessionContext.shared' import { SessionProvider } from './SessionContext' -import type { ServerChangeReason } from '../store/serverStore' - -function createDeferred() { - let resolve!: (value: T) => void - const promise = new Promise(res => { - resolve = res - }) - return { promise, resolve } -} - -const { - getSessionsMock, - createSessionMock, - deleteSessionMock, - subscribeToEventsMock, - clearChildrenMock, - clearFollowupQueueMock, - clearSessionRuntimeStateMock, - sessionErrorHandlerMock, - autoDetectPathStyleMock, - onServerChangeMock, -} = vi.hoisted(() => ({ - getSessionsMock: vi.fn(), - createSessionMock: vi.fn(), - deleteSessionMock: vi.fn(), - subscribeToEventsMock: vi.fn(), - clearChildrenMock: vi.fn(), - clearFollowupQueueMock: vi.fn(), - clearSessionRuntimeStateMock: vi.fn(), - sessionErrorHandlerMock: vi.fn(), - autoDetectPathStyleMock: vi.fn(), - onServerChangeMock: vi.fn(), -})) -let latestEventCallbacks: Partial = {} -let latestContext: ContextType = null -let latestServerChange: ((serverId: string, reason: ServerChangeReason) => void) | undefined +import type { Session } from '../types/api/session' + +const { storeMock, createSessionMock, deleteSessionMock, clearSessionRuntimeStateMock, unpinMock } = vi.hoisted(() => { + const listeners = new Set<() => void>() + let snapshot: { + sessions: Session[] + hasMore: boolean + ready: boolean + loading: boolean + error: Error | null + } = { sessions: [], hasMore: false, ready: false, loading: false, error: null } + + const storeMock = { + subscribe: (listener: () => void) => { + listeners.add(listener) + return () => listeners.delete(listener) + }, + getSnapshot: () => snapshot, + ensure: vi.fn(() => Promise.resolve()), + loadMore: vi.fn(() => Promise.resolve()), + remove: vi.fn(), + patch: vi.fn(), + upsert: vi.fn(), + reset: vi.fn(), + setSnapshotForTest: (next: Partial) => { + snapshot = { ...snapshot, ...next } + for (const listener of listeners) listener() + }, + resetSnapshotForTest: () => { + snapshot = { sessions: [], hasMore: false, ready: false, loading: false, error: null } + for (const listener of listeners) listener() + }, + } + + return { + storeMock, + createSessionMock: vi.fn(), + deleteSessionMock: vi.fn(), + clearSessionRuntimeStateMock: vi.fn(), + unpinMock: vi.fn(), + } +}) vi.mock('../api', () => ({ - getSessions: (...args: unknown[]) => getSessionsMock(...args), createSession: (...args: unknown[]) => createSessionMock(...args), deleteSession: (...args: unknown[]) => deleteSessionMock(...args), - subscribeToEvents: (...args: unknown[]) => subscribeToEventsMock(...args), })) -vi.mock('./useDirectory', () => ({ - useDirectory: () => ({ currentDirectory: '/workspace/demo' }), +vi.mock('../store/sessionIndexStore', () => ({ + sessionIndexStore: storeMock, })) -vi.mock('../store/childSessionStore', () => ({ - childSessionStore: { - clearChildren: clearChildrenMock, - }, +vi.mock('./useDirectory', () => ({ + useDirectory: () => ({ currentDirectory: '/workspace/demo' }), })) -vi.mock('../store/inboxStore', () => ({ - inboxStore: { - clearSession: clearFollowupQueueMock, +vi.mock('../store/pinnedSessionsStore', () => ({ + pinnedSessionsStore: { + unpin: (...args: unknown[]) => unpinMock(...args), }, })) -// v2 删除了 todoStore(连同整块 todo UI),这里不再 mock vi.mock('../store/serverStore', () => ({ serverStore: { - onServerChange: (...args: unknown[]) => onServerChangeMock(...args), + subscribe: () => () => {}, getActiveServerId: () => 'local', }, })) vi.mock('../utils', () => ({ - sessionErrorHandler: (...args: unknown[]) => sessionErrorHandlerMock(...args), - normalizeToForwardSlash: (value?: string) => value, - isSameDirectory: (left?: string, right?: string) => left === right, - autoDetectPathStyle: (...args: unknown[]) => autoDetectPathStyleMock(...args), + normalizeToForwardSlash: (value?: string) => value?.replace(/\\/g, '/'), + isSameDirectory: (left?: string, right?: string) => { + const normalize = (value?: string) => value?.replace(/[\\/]+$/, '') + return normalize(left) === normalize(right) + }, })) vi.mock('../utils/sessionLifecycle', () => ({ clearSessionRuntimeState: (...args: unknown[]) => clearSessionRuntimeStateMock(...args), })) +function makeSession(id: string, directory = '/workspace/demo', updated = 2): Session { + return { + id, + projectID: 'project-1', + location: { directory }, + title: `Session ${id}`, + cost: 0, + tokens: { input: 0, output: 0, reasoning: 0, cache: { read: 0, write: 0 } }, + time: { created: 1, updated }, + } as Session +} + +let latestContext: ContextType = null + function SessionContextProbe() { const context = useContext(SessionContext) @@ -93,225 +108,127 @@ function SessionContextProbe() { return null } +function renderProvider() { + return render( + + + , + ) +} + describe('SessionProvider', () => { beforeEach(() => { - vi.useFakeTimers() latestContext = null - latestEventCallbacks = {} - getSessionsMock.mockReset() + storeMock.ensure.mockClear() + storeMock.loadMore.mockClear() + storeMock.remove.mockClear() + storeMock.patch.mockClear() + storeMock.upsert.mockClear() createSessionMock.mockReset() deleteSessionMock.mockReset() - subscribeToEventsMock.mockReset() - clearChildrenMock.mockReset() - clearFollowupQueueMock.mockReset() clearSessionRuntimeStateMock.mockReset() - sessionErrorHandlerMock.mockReset() - autoDetectPathStyleMock.mockReset() - onServerChangeMock.mockReset() - latestServerChange = undefined - subscribeToEventsMock.mockImplementation((callbacks: EventCallbacks) => { - latestEventCallbacks = callbacks - return vi.fn() - }) - onServerChangeMock.mockImplementation(listener => { - latestServerChange = listener as (serverId: string, reason: ServerChangeReason) => void - return vi.fn() - }) - }) - - afterEach(() => { - vi.useRealTimers() + unpinMock.mockReset() + storeMock.resetSnapshotForTest() }) - it('queues a reconnect refresh while the latest request is still pending', async () => { - const firstRequest = createDeferred>() - const secondRequest = createDeferred>() - const thirdRequest = createDeferred>() - - getSessionsMock - .mockImplementationOnce(() => firstRequest.promise) - .mockImplementationOnce(() => secondRequest.promise) - .mockImplementationOnce(() => thirdRequest.promise) - - render( - - - , - ) - - await act(async () => { - vi.runAllTimers() - await Promise.resolve() - }) - - expect(latestContext).not.toBeNull() - - act(() => { - latestContext!.setSearch('branch') + it('从共享索引按当前目录过滤(不再自己发请求)', async () => { + storeMock.setSnapshotForTest({ + ready: true, + sessions: [ + makeSession('ses_a', '/workspace/demo'), + makeSession('ses_b', '/workspace/other'), + makeSession('ses_c', '/workspace/demo/'), + ], }) - await act(async () => { - vi.advanceTimersByTime(300) - await Promise.resolve() - }) - - await act(async () => { - firstRequest.resolve([{ id: 'session-1', directory: '/workspace/demo' }]) - await Promise.resolve() - await Promise.resolve() - }) + renderProvider() - await act(async () => { - latestEventCallbacks.onReconnected?.('network') - await Promise.resolve() - }) - - expect(getSessionsMock).toHaveBeenCalledTimes(2) - - await act(async () => { - secondRequest.resolve([{ id: 'session-2', directory: '/workspace/demo' }]) - await Promise.resolve() - await Promise.resolve() - }) - - expect(getSessionsMock).toHaveBeenCalledTimes(3) - - await act(async () => { - thirdRequest.resolve([{ id: 'session-3', directory: '/workspace/demo' }]) - await Promise.resolve() - await Promise.resolve() - }) - - expect(latestContext?.sessions.map(session => session.id)).toEqual(['session-3']) + expect(storeMock.ensure).toHaveBeenCalledWith('local') + expect(latestContext?.sessions.map(session => session.id)).toEqual(['ses_a', 'ses_c']) + expect(latestContext?.isLoading).toBe(false) }) - it('retries the initial session list fetch after a startup failure', async () => { - getSessionsMock - .mockRejectedValueOnce(new Error('service not ready')) - .mockResolvedValueOnce([{ id: 'session-1', directory: '/workspace/demo' }]) - - render( - - - , - ) + it('首帧还没拉到数据时显示 loading,失败后不再转圈', () => { + renderProvider() + expect(latestContext?.isLoading).toBe(true) - await act(async () => { - vi.runOnlyPendingTimers() - await Promise.resolve() - await Promise.resolve() - }) - - expect(getSessionsMock).toHaveBeenCalledTimes(1) - - await act(async () => { - vi.advanceTimersByTime(500) - await Promise.resolve() - await Promise.resolve() + act(() => { + storeMock.setSnapshotForTest({ ready: false, error: new Error('down') }) }) - - expect(getSessionsMock).toHaveBeenCalledTimes(2) - expect(latestContext?.sessions.map(session => session.id)).toEqual(['session-1']) + expect(latestContext?.isLoading).toBe(false) }) - it('removes deleted sessions from context and clears runtime state', async () => { - getSessionsMock.mockResolvedValue([ - { id: 'session-1', directory: '/workspace/demo' }, - { id: 'session-2', directory: '/workspace/demo' }, - ]) - - render( - - - , - ) - - await act(async () => { - vi.runAllTimers() - await Promise.resolve() - await Promise.resolve() + it('搜索在本地过滤标题 / id,不触发任何请求', () => { + storeMock.setSnapshotForTest({ + ready: true, + sessions: [makeSession('ses_a', '/workspace/demo'), makeSession('ses_b', '/workspace/demo')], }) - expect(latestContext?.sessions.map(session => session.id)).toEqual(['session-1', 'session-2']) + renderProvider() + const ensureCalls = storeMock.ensure.mock.calls.length act(() => { - latestEventCallbacks.onSessionDeleted?.({ sessionID: 'session-1' }) + latestContext?.setSearch('ses_b') }) - expect(clearSessionRuntimeStateMock).toHaveBeenCalledWith('session-1') - expect(latestContext?.sessions.map(session => session.id)).toEqual(['session-2']) + expect(latestContext?.sessions.map(session => session.id)).toEqual(['ses_b']) + expect(storeMock.ensure).toHaveBeenCalledTimes(ensureCalls) }) - it('refetches on server endpoint changes even while the old request is in flight', async () => { - const staleRequest = createDeferred>() - const freshRequest = createDeferred>() - - getSessionsMock - .mockImplementationOnce(() => staleRequest.promise) - .mockImplementationOnce(() => freshRequest.promise) + it('本地已拉到的会话先切片露出,见底后才向服务端续页', async () => { + const many = Array.from({ length: 40 }, (_, index) => makeSession(`ses_${index}`, '/workspace/demo')) + storeMock.setSnapshotForTest({ ready: true, sessions: many, hasMore: false }) - render( - - - , - ) + renderProvider() + expect(latestContext?.sessions).toHaveLength(30) + expect(latestContext?.hasMore).toBe(true) await act(async () => { - vi.runAllTimers() - await Promise.resolve() + await latestContext!.loadMore() }) - expect(getSessionsMock).toHaveBeenCalledTimes(1) + expect(storeMock.loadMore).not.toHaveBeenCalled() + expect(latestContext?.sessions).toHaveLength(40) + expect(latestContext?.hasMore).toBe(false) - await act(async () => { - // active 服务器自身端点变化(serverId = active)才应触发重拉 - latestServerChange?.('local', 'server-runtime-updated') - await Promise.resolve() + act(() => { + storeMock.setSnapshotForTest({ ready: true, sessions: many, hasMore: true }) }) - - expect(getSessionsMock).toHaveBeenCalledTimes(2) - await act(async () => { - freshRequest.resolve([{ id: 'fresh', directory: '/workspace/demo' }]) - await Promise.resolve() - await Promise.resolve() + await latestContext!.loadMore() }) - expect(latestContext?.sessions.map(session => session.id)).toEqual(['fresh']) + expect(storeMock.loadMore).toHaveBeenCalledWith('local') + }) - await act(async () => { - staleRequest.resolve([{ id: 'stale', directory: '/workspace/demo' }]) - await Promise.resolve() - await Promise.resolve() + it('切换目录不重新拉索引', () => { + storeMock.setSnapshotForTest({ ready: true, sessions: [makeSession('ses_a', '/workspace/demo')] }) + renderProvider() + + act(() => { + storeMock.setSnapshotForTest({ + ready: true, + sessions: [makeSession('ses_a', '/workspace/demo'), makeSession('ses_b', '/workspace/other')], + }) }) - expect(latestContext?.sessions.map(session => session.id)).toEqual(['fresh']) + expect(storeMock.ensure).toHaveBeenCalledTimes(1) + expect(latestContext?.sessions.map(session => session.id)).toEqual(['ses_a']) }) - it('keeps the session list untouched when a non-active server endpoint changes', async () => { - getSessionsMock.mockResolvedValue([{ id: 'session-1', directory: '/workspace/demo' }]) - - render( - - - , - ) - - await act(async () => { - vi.runAllTimers() - await Promise.resolve() - }) + it('删除会话:调 API、清运行时状态、清索引', async () => { + storeMock.setSnapshotForTest({ ready: true, sessions: [makeSession('ses_a', '/workspace/demo')] }) + deleteSessionMock.mockResolvedValue(true) - expect(getSessionsMock).toHaveBeenCalledTimes(1) - expect(latestContext?.sessions.map(session => session.id)).toEqual(['session-1']) + renderProvider() - // 非 active 服务器(remote)端点变化:与 active 会话列表无关,不得清空/重拉 await act(async () => { - latestServerChange?.('remote', 'server-runtime-updated') - await Promise.resolve() + await latestContext!.deleteSession('ses_a') }) - expect(getSessionsMock).toHaveBeenCalledTimes(1) - expect(latestContext?.sessions.map(session => session.id)).toEqual(['session-1']) + expect(deleteSessionMock).toHaveBeenCalledWith('ses_a', '/workspace/demo') + expect(unpinMock).toHaveBeenCalledWith('ses_a') + expect(clearSessionRuntimeStateMock).toHaveBeenCalledWith('ses_a') + expect(storeMock.remove).toHaveBeenCalledWith('local', 'ses_a') }) }) diff --git a/src/contexts/SessionContext.tsx b/src/contexts/SessionContext.tsx index 7d724c0b6..2616e862e 100644 --- a/src/contexts/SessionContext.tsx +++ b/src/contexts/SessionContext.tsx @@ -1,255 +1,104 @@ -import { useState, useCallback, useEffect, useRef, useMemo, type ReactNode } from 'react' -import { - getSessions, - getSession, - createSession as apiCreateSession, - deleteSession as apiDeleteSession, - subscribeToEvents, - type ApiSession, - type SessionListParams, -} from '../api' -import { affectsBoundServer } from '../store/serverChangeScope' +import { useState, useCallback, useEffect, useMemo, useSyncExternalStore, type ReactNode } from 'react' +import { createSession as apiCreateSession, deleteSession as apiDeleteSession } from '../api' import { serverStore } from '../store/serverStore' import { pinnedSessionsStore } from '../store/pinnedSessionsStore' +import { sessionIndexStore } from '../store/sessionIndexStore' import { useDirectory } from './useDirectory' -import { sessionErrorHandler, normalizeToForwardSlash, isSameDirectory, autoDetectPathStyle } from '../utils' +import { isSameDirectory, normalizeToForwardSlash } from '../utils' import { clearSessionRuntimeState } from '../utils/sessionLifecycle' import { SessionContext, type SessionContextValue } from './SessionContext.shared' +/** 列表首屏条数;「显示更多」每次多露出这么多 */ +const LIST_PAGE_SIZE = 30 + +/** 稳定引用:useSyncExternalStore 每次渲染拿到同一个 subscribe,避免反复解绑 */ +const subscribeServerStore = serverStore.subscribe.bind(serverStore) +const getActiveServerId = () => serverStore.getActiveServerId() + +/** + * 会话列表数据源。 + * + * 列表本身来自 `sessionIndexStore`(每个服务器一份根会话索引,30s 内复用), + * 这里只做三件事:按当前目录过滤、按搜索词过滤、按需要切片。 + * + * 好处是切目录/切回来不再发请求,文件夹模式的各个目录也共享同一份索引; + * 搜索是本地标题匹配(官方 home 的会话搜索同款),不再每个按键打一次服务端。 + */ export function SessionProvider({ children }: { children: ReactNode }) { const { currentDirectory } = useDirectory() + const serverId = useSyncExternalStore(subscribeServerStore, getActiveServerId, getActiveServerId) - const [sessions, setSessions] = useState([]) - const [isLoading, setIsLoading] = useState(true) - const [isLoadingMore, setIsLoadingMore] = useState(false) - const [hasMore, setHasMore] = useState(true) - const [search, setSearch] = useState('') - - const requestIdRef = useRef(0) - const searchTimerRef = useRef(null) - const currentDirectoryRef = useRef(currentDirectory) - const searchRef = useRef(search) - const isLoadingMoreRef = useRef(false) // 防止并发 loadMore - const isFetchingRef = useRef(false) // 防止 onReconnected 密集触发时重复请求 - const queuedReconnectRefreshRef = useRef(false) - const retryTimerRef = useRef(null) - const fetchSessionsRef = useRef< - (params?: SessionListParams & { append?: boolean; retryAttempt?: number }) => Promise - >(() => Promise.resolve()) - const currentLimitRef = useRef(30) // 当前 limit,loadMore 时递增 - - // 保持 ref 同步 - useEffect(() => { - currentDirectoryRef.current = currentDirectory - }, [currentDirectory]) - - useEffect(() => { - searchRef.current = search - }, [search]) - - // 核心获取逻辑 - // 注意:directory 传给 getSessions 时使用正斜杠格式 - // http 层的 fetchWithBothSlashesAndMerge 会处理两种斜杠格式的兼容 - const fetchSessions = useCallback( - async (params: SessionListParams & { append?: boolean; retryAttempt?: number } = {}) => { - const { append = false, retryAttempt = 0, ...queryParams } = params - const requestId = ++requestIdRef.current - isFetchingRef.current = true - - if (append) { - setIsLoadingMore(true) - } else { - setIsLoading(true) - } - - try { - // 使用正斜杠格式传给 API(http 层会处理兼容) - const targetDir = normalizeToForwardSlash(currentDirectory) || undefined - - const data = await getSessions({ - // v2 没有 roots 开关:根会话用 parentID: null 表达 - parentID: null, - limit: currentLimitRef.current, - directory: targetDir, - search: search || undefined, - ...queryParams, - }) - - if (requestId !== requestIdRef.current) return - - // 自动检测路径风格(从后端返回的 directory 字段) - if (data.length > 0 && data[0].location?.directory) { - autoDetectPathStyle(data[0].location?.directory) - } - - if (append) { - // 去重:过滤掉已存在的 session - setSessions(prev => { - const existingIds = new Set(prev.map(s => s.id)) - const newSessions = data.filter(s => !existingIds.has(s.id)) - return [...prev, ...newSessions] - }) - } else { - setSessions(data) - } - setHasMore(data.length >= currentLimitRef.current) - } catch (e) { - if (requestId === requestIdRef.current && !append) { - if (retryAttempt < 3) { - if (retryTimerRef.current) clearTimeout(retryTimerRef.current) - retryTimerRef.current = window.setTimeout(() => { - if (requestId !== requestIdRef.current) return - void fetchSessions({ ...queryParams, retryAttempt: retryAttempt + 1 }) - }, [500, 1500, 3000][retryAttempt]) - } else { - setSessions([]) - setHasMore(false) - } - } - sessionErrorHandler('fetch sessions', e) - } finally { - if (requestId === requestIdRef.current) { - isFetchingRef.current = false - setIsLoading(false) - setIsLoadingMore(false) - if (queuedReconnectRefreshRef.current) { - queuedReconnectRefreshRef.current = false - setSessions([]) - void fetchSessionsRef.current({ search: searchRef.current || undefined }) - } - } - } - }, - [currentDirectory, search], + const snapshot = useSyncExternalStore( + sessionIndexStore.subscribe, + () => sessionIndexStore.getSnapshot(serverId), + () => sessionIndexStore.getSnapshot(serverId), ) - // 保持 fetchSessions ref 同步(用于 SSE onReconnected 回调) - fetchSessionsRef.current = fetchSessions - - const matchesCurrentDirectory = useCallback((session: ApiSession) => { - return !currentDirectoryRef.current || isSameDirectory(currentDirectoryRef.current, session.location?.directory) - }, []) + const [search, setSearch] = useState('') + const [limit, setLimit] = useState(LIST_PAGE_SIZE) + const [isLoadingMore, setIsLoadingMore] = useState(false) - // 监听 directory 和 search 变化 + // 挂载 / 切服务器:确保索引可用(30s 内命中则不请求) useEffect(() => { - if (searchTimerRef.current) clearTimeout(searchTimerRef.current) - - // 切换目录或搜索时重置 limit - currentLimitRef.current = 30 - - searchTimerRef.current = window.setTimeout( - () => { - fetchSessions() - }, - search ? 300 : 0, - ) + void sessionIndexStore.ensure(serverId) + }, [serverId]) - return () => { - if (searchTimerRef.current) clearTimeout(searchTimerRef.current) - if (retryTimerRef.current) clearTimeout(retryTimerRef.current) - } - }, [fetchSessions, search, currentDirectory]) - - // 订阅 SSE 事件,实时更新 session 列表 + // 换目录或改搜索词:重新从第一页开始露出 useEffect(() => { - const unsubscribe = subscribeToEvents({ - onSessionCreated: data => { - // 忽略子 session(有 parentID 的是子 agent 创建的) - if (data.parentID) return - - // v2 的 session.created 负载是**创建记录**(以 sessionID 为键、带 slug/version), - // 不是 SessionInfo,因此回读一次拿到完整会话再入列表。 - void getSession(data.sessionID, normalizeToForwardSlash(currentDirectory) || undefined, data.location?.directory) - .then(session => { - if (!session || !matchesCurrentDirectory(session)) return - - // 搜索态下交给服务端重新给出结果,避免本地过滤和服务端逻辑不一致 - if (searchRef.current) { - fetchSessionsRef.current() - return - } - - setSessions(prev => { - if (prev.some(s => s.id === session.id)) return prev - return [session, ...prev] - }) - }) - .catch(() => { - // 回读失败时退回整表刷新,保证列表不落后 - fetchSessionsRef.current() - }) - }, - onSessionRenamed: data => { - // v2 把 v1 的 session.updated 收敛成 session.renamed(只有标题变化) - setSessions(prev => { - const index = prev.findIndex(s => s.id === data.sessionID) - if (index === -1) return prev - const next = [...prev] - next[index] = { ...next[index], title: data.title } - return next - }) - }, - onSessionDeleted: data => { - // v2 的 session.deleted 负载是 { sessionID }(v1 直接是字符串) - clearSessionRuntimeState(data.sessionID) - setSessions(prev => prev.filter(s => s.id !== data.sessionID)) - }, - onReconnected: reason => { - if (reason === 'server-switch') return - if (isFetchingRef.current) { - queuedReconnectRefreshRef.current = true - return - } - setSessions([]) - fetchSessionsRef.current() - }, + setLimit(LIST_PAGE_SIZE) + }, [currentDirectory, search]) + + const directorySessions = useMemo(() => { + if (!currentDirectory) return snapshot.sessions + return snapshot.sessions.filter(session => isSameDirectory(currentDirectory, session.location?.directory)) + }, [snapshot.sessions, currentDirectory]) + + const filteredSessions = useMemo(() => { + const term = search.trim().toLowerCase() + if (!term) return directorySessions + return directorySessions.filter(session => { + const title = (session.title ?? '').toLowerCase() + return title.includes(term) || session.id.toLowerCase().includes(term) }) + }, [directorySessions, search]) - return unsubscribe - }, [matchesCurrentDirectory]) - - useEffect(() => { - return serverStore.onServerChange((serverId, reason) => { - // 会话列表跟随 active server:非 active 服务器端点变化(WSL 重启)不影响本列表, - // 避免无关事件触发「清空 → 重拉」的可见闪烁;只有 active 数据源真的变了才重置 - if (!affectsBoundServer(undefined, serverId, reason, serverStore.getActiveServerId())) return - currentLimitRef.current = 30 - setSessions([]) - void fetchSessionsRef.current() - }) - }, []) + const sessions = useMemo(() => filteredSessions.slice(0, limit), [filteredSessions, limit]) + const searching = search.trim().length > 0 + const hasMore = filteredSessions.length > limit || (!searching && snapshot.hasMore) + // 首帧还没发起请求时也别显示空态;请求失败后交给空态/重试入口 + const isLoading = !snapshot.ready && !snapshot.error - // Actions - const refresh = useCallback(() => fetchSessions(), [fetchSessions]) + const refresh = useCallback(async () => { + await sessionIndexStore.ensure(serverId, { force: true }) + }, [serverId]) const loadMore = useCallback(async () => { - // 使用 ref 检查,防止并发请求 - if (isLoadingMoreRef.current || !hasMore || sessions.length === 0) return - isLoadingMoreRef.current = true - + if (isLoadingMore || !hasMore) return + setIsLoadingMore(true) try { - // 跟官方 webui 一样,递增 limit 重新请求整个列表 - currentLimitRef.current += 15 - setIsLoadingMore(true) - await fetchSessions() + // 本地还有没露出的先露出;本地见底了再向服务端要下一页 + if (filteredSessions.length > limit) { + setLimit(current => current + LIST_PAGE_SIZE) + return + } + if (snapshot.hasMore) { + await sessionIndexStore.loadMore(serverId) + setLimit(current => current + LIST_PAGE_SIZE) + } } finally { - isLoadingMoreRef.current = false setIsLoadingMore(false) } - }, [hasMore, sessions, fetchSessions]) + }, [isLoadingMore, hasMore, filteredSessions.length, limit, snapshot.hasMore, serverId]) const createSession = useCallback( async (title?: string) => { - // 使用正斜杠格式传给后端 const targetDir = normalizeToForwardSlash(currentDirectory) || undefined - - const newSession = await apiCreateSession({ - title, - directory: targetDir, - }) + const newSession = await apiCreateSession({ title, directory: targetDir }) + // 直接进索引,不等 SSE(新建会话已经是完整元信息) + if (!newSession.parentID) sessionIndexStore.upsert(serverId, newSession) return newSession }, - [currentDirectory], + [currentDirectory, serverId], ) const deleteSession = useCallback( @@ -258,12 +107,11 @@ export function SessionProvider({ children }: { children: ReactNode }) { await apiDeleteSession(id, targetDir) pinnedSessionsStore.unpin(id) clearSessionRuntimeState(id) - setSessions(prev => prev.filter(s => s.id !== id)) + sessionIndexStore.remove(serverId, id) }, - [currentDirectory], + [currentDirectory, serverId], ) - // 稳定化 Provider value,避免每次渲染创建新对象导致子组件不必要重渲染 const value = useMemo( () => ({ sessions, diff --git a/src/hooks/useSessions.test.tsx b/src/hooks/useSessions.test.tsx index 56f9fc053..02bfaf9c3 100644 --- a/src/hooks/useSessions.test.tsx +++ b/src/hooks/useSessions.test.tsx @@ -1,54 +1,77 @@ import { act, renderHook } from '@testing-library/react' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import type { EventCallbacks } from '../types/api/event' -import type { ServerChangeReason } from '../store/serverStore' +import { beforeEach, describe, expect, it, vi } from 'vitest' import { useSessions } from './useSessions' +import type { Session } from '../types/api/session' + +const { storeMock, createSessionMock, deleteSessionMock, unpinMock } = vi.hoisted(() => { + const listeners = new Set<() => void>() + let snapshot: { + sessions: Session[] + hasMore: boolean + ready: boolean + loading: boolean + error: Error | null + } = { sessions: [], hasMore: false, ready: false, loading: false, error: null } + + const storeMock = { + subscribe: (listener: () => void) => { + listeners.add(listener) + return () => listeners.delete(listener) + }, + getSnapshot: () => snapshot, + ensure: vi.fn<(serverId: string, options?: { force?: boolean }) => Promise>(() => Promise.resolve()), + loadMore: vi.fn(() => Promise.resolve()), + remove: vi.fn(), + patch: vi.fn(), + upsert: vi.fn(), + setSnapshotForTest: (next: Partial) => { + snapshot = { ...snapshot, ...next } + for (const listener of listeners) listener() + }, + resetSnapshotForTest: () => { + snapshot = { sessions: [], hasMore: false, ready: false, loading: false, error: null } + for (const listener of listeners) listener() + }, + } -function createDeferred() { - let resolve!: (value: T) => void - const promise = new Promise(res => { - resolve = res - }) - return { promise, resolve } -} - -// eslint-disable-next-line @typescript-eslint/no-explicit-any -type AnyFn = (...args: any[]) => any -const { - getSessionsMock, - getSessionMock, - createSessionMock, - deleteSessionMock, - subscribeToEventsMock, - onServerChangeMock, -} = vi.hoisted(() => ({ - getSessionsMock: vi.fn(), - getSessionMock: vi.fn(), - createSessionMock: vi.fn(), - deleteSessionMock: vi.fn(), - subscribeToEventsMock: vi.fn(), - onServerChangeMock: vi.fn(() => () => {}), -})) -let latestEventCallbacks: Partial = {} -let latestServerChange: ((serverId: string, reason: ServerChangeReason) => void) | undefined + return { + storeMock, + createSessionMock: vi.fn(), + deleteSessionMock: vi.fn(), + unpinMock: vi.fn(), + } +}) vi.mock('../api', () => ({ - getSessions: (...args: unknown[]) => getSessionsMock(...args), - getSession: (...args: unknown[]) => getSessionMock(...args), createSession: (...args: unknown[]) => createSessionMock(...args), deleteSession: (...args: unknown[]) => deleteSessionMock(...args), - subscribeToEvents: (...args: unknown[]) => subscribeToEventsMock(...args), +})) + +vi.mock('../store/sessionIndexStore', () => ({ + sessionIndexStore: storeMock, +})) + +vi.mock('../store/pinnedSessionsStore', () => ({ + pinnedSessionsStore: { + unpin: (...args: unknown[]) => unpinMock(...args), + }, })) vi.mock('../store/serverStore', () => ({ serverStore: { - onServerChange: (...args: unknown[]) => onServerChangeMock(...args), + subscribe: () => () => {}, getActiveServerId: () => 'local', }, })) -/** v2 的 SessionInfo:目录在 location.directory,且 cost/tokens 必填 */ -function makeSession(id: string, directory = '/workspace/demo') { +vi.mock('../utils', () => ({ + isSameDirectory: (left?: string, right?: string) => { + const normalize = (value?: string) => value?.replace(/[\\/]+$/, '') + return normalize(left) === normalize(right) + }, +})) + +function makeSession(id: string, directory = '/workspace/demo', updated = 2): Session { return { id, projectID: 'project-1', @@ -56,415 +79,160 @@ function makeSession(id: string, directory = '/workspace/demo') { title: `Session ${id}`, cost: 0, tokens: { input: 0, output: 0, reasoning: 0, cache: { read: 0, write: 0 } }, - time: { - created: 1, - updated: 2, - }, - } -} - -/** - * v2 的 session.created 负载是**创建记录**(以 sessionID 为键、带 slug/version), - * 不是 SessionInfo——hook 收到后会回读 getSession 再入列表。 - * - * 回读时要还原该会话真实所属目录,否则「属于别的目录」的会话会被误收进列表, - * 因此这里记录每个 id 的目录供 getSession mock 查询。 - */ -const createdDirectories = new Map() - -function makeCreatedPayload(id: string, directory = '/workspace/demo', parentID?: string) { - createdDirectories.set(id, directory) - return { - sessionID: id, - projectID: 'project-1', - location: { directory }, - slug: id, - title: `Session ${id}`, - version: '1', - ...(parentID ? { parentID } : {}), - } -} - -/** - * session.forked 负载(session-event.ts:187):sessionID 是新会话,parentID 是「fork 自 - * 哪个会话」(不是 subagent 标记),boundary 是 fork 边界。 - */ -function makeForkedPayload(id: string, directory = '/workspace/demo', parentID = 'parent-1') { - createdDirectories.set(id, directory) - return { - sessionID: id, - parentID, - boundary: { type: 'through', messageID: 'msg-1' }, - } + time: { created: 1, updated }, + } as Session } describe('useSessions', () => { beforeEach(() => { - vi.useFakeTimers() - createdDirectories.clear() - getSessionsMock.mockReset() - getSessionMock.mockReset() - getSessionMock.mockImplementation((id: string) => - Promise.resolve(makeSession(id, createdDirectories.get(id) ?? '/workspace/demo')), - ) + storeMock.ensure.mockClear() + storeMock.loadMore.mockClear() + storeMock.remove.mockClear() + storeMock.patch.mockClear() + storeMock.upsert.mockClear() createSessionMock.mockReset() deleteSessionMock.mockReset() - subscribeToEventsMock.mockReset() - onServerChangeMock.mockReset() - getSessionsMock.mockResolvedValue([]) - createSessionMock.mockResolvedValue(makeSession('new')) - deleteSessionMock.mockResolvedValue(true) - latestEventCallbacks = {} - latestServerChange = undefined - subscribeToEventsMock.mockImplementation((callbacks: EventCallbacks) => { - latestEventCallbacks = callbacks - return vi.fn() - }) - onServerChangeMock.mockImplementation((listener: (serverId: string, reason: ServerChangeReason) => void) => { - latestServerChange = listener - return vi.fn() - }) + unpinMock.mockReset() + storeMock.resetSnapshotForTest() }) - afterEach(() => { - vi.useRealTimers() - }) - - it('waits for enabled before fetching', async () => { + it('enabled 为 false 时不拉索引', () => { const { rerender } = renderHook(({ enabled }) => useSessions({ directory: '/workspace/demo', enabled }), { initialProps: { enabled: false }, }) - expect(getSessionsMock).not.toHaveBeenCalled() + expect(storeMock.ensure).not.toHaveBeenCalled() rerender({ enabled: true }) - - await act(async () => { - vi.runAllTimers() - await Promise.resolve() - }) - - expect(getSessionsMock).toHaveBeenCalledWith( - { - // v2 的根会话过滤用 parentID: null - parentID: null, - limit: 20, - directory: '/workspace/demo', - }, - undefined, - ) + expect(storeMock.ensure).toHaveBeenCalledWith('local') }) - it('passes the scoped directory when removing a session', async () => { - getSessionsMock.mockResolvedValue([makeSession('session-1')]) - - const { result } = renderHook(() => useSessions({ directory: '/workspace/demo' })) - - await act(async () => { - vi.runAllTimers() - await Promise.resolve() + it('按目录从共享索引过滤,php 风格尾斜杠不影响匹配', () => { + storeMock.setSnapshotForTest({ + ready: true, + sessions: [ + makeSession('ses_a', '/workspace/demo'), + makeSession('ses_b', '/workspace/demo/'), + makeSession('ses_c', '/workspace/other'), + ], }) - expect(result.current.sessions).toHaveLength(1) + const { result } = renderHook(() => useSessions({ directory: '/workspace/demo', pageSize: 5 })) - await act(async () => { - await result.current.remove('session-1') - }) - - expect(deleteSessionMock).toHaveBeenCalledWith('session-1', '/workspace/demo', undefined) + expect(result.current.sessions.map(session => session.id)).toEqual(['ses_a', 'ses_b']) + expect(result.current.isLoading).toBe(false) }) - it('adds matching sessions from realtime events immediately', async () => { - const { result } = renderHook(() => useSessions({ directory: '/workspace/demo' })) - - await act(async () => { - vi.runAllTimers() - await Promise.resolve() - }) + it('同一台服务器的多个目录共享一次索引请求(每个 hook 只调用 ensure,不再各自发请求)', () => { + const first = renderHook(() => useSessions({ directory: '/workspace/a' })) + const second = renderHook(() => useSessions({ directory: '/workspace/b' })) - await act(async () => { - latestEventCallbacks.onSessionCreated?.(makeCreatedPayload('session-1') as never) - latestEventCallbacks.onSessionCreated?.(makeCreatedPayload('session-ignored', '/workspace/other') as never) - latestEventCallbacks.onSessionCreated?.(makeCreatedPayload('session-child', '/workspace/demo', 'parent-1') as never) - }) - - expect(result.current.sessions.map(session => session.id)).toEqual(['session-1']) + expect(first.result.current.isLoading).toBe(true) + expect(second.result.current.isLoading).toBe(true) + expect(storeMock.ensure).toHaveBeenCalledTimes(2) + // 请求去重在 store 里:两次 ensure 指向同一个 serverId 的同一个入口 + expect(storeMock.ensure.mock.calls.every(call => call[0] === 'local')).toBe(true) }) - it('adds forked sessions from session.forked events(fork 负载也带 parentID,但那是 fork 来源不是 subagent,不能跳过)', async () => { - const { result } = renderHook(() => useSessions({ directory: '/workspace/demo' })) - - await act(async () => { - vi.runAllTimers() - await Promise.resolve() + it('pageSize 本地切片,loadMore 先露出本地数据', async () => { + storeMock.setSnapshotForTest({ + ready: true, + sessions: Array.from({ length: 8 }, (_, index) => makeSession(`ses_${index}`)), }) - await act(async () => { - latestEventCallbacks.onSessionForked?.(makeForkedPayload('session-fork') as never) - latestEventCallbacks.onSessionForked?.(makeForkedPayload('session-fork-other', '/workspace/other') as never) - }) - - expect(result.current.sessions.map(session => session.id)).toEqual(['session-fork']) - }) - - it('queues a reconnect refresh while a newer request is still in flight', async () => { - const firstRequest = createDeferred[]>() - const secondRequest = createDeferred[]>() - const thirdRequest = createDeferred[]>() - - getSessionsMock - .mockImplementationOnce(() => firstRequest.promise) - .mockImplementationOnce(() => secondRequest.promise) - .mockImplementationOnce(() => thirdRequest.promise) - - const { result } = renderHook(() => useSessions({ directory: '/workspace/demo' })) + const { result } = renderHook(() => useSessions({ directory: '/workspace/demo', pageSize: 5 })) + expect(result.current.sessions).toHaveLength(5) + expect(result.current.hasMore).toBe(true) await act(async () => { - vi.runAllTimers() - await Promise.resolve() - }) - - act(() => { - result.current.setSearch('branch') + await result.current.loadMore() }) - await act(async () => { - vi.advanceTimersByTime(300) - await Promise.resolve() - }) - - await act(async () => { - firstRequest.resolve([makeSession('session-1')]) - await Promise.resolve() - await Promise.resolve() - }) - - await act(async () => { - latestEventCallbacks.onReconnected?.('network') - await Promise.resolve() - }) - - expect(getSessionsMock).toHaveBeenCalledTimes(2) - - await act(async () => { - secondRequest.resolve([makeSession('session-2')]) - await Promise.resolve() - await Promise.resolve() - }) - - expect(getSessionsMock).toHaveBeenCalledTimes(3) - - await act(async () => { - thirdRequest.resolve([makeSession('session-3')]) - await Promise.resolve() - await Promise.resolve() - }) - - expect(result.current.sessions.map(session => session.id)).toEqual(['session-3']) + expect(result.current.sessions).toHaveLength(8) + expect(storeMock.loadMore).not.toHaveBeenCalled() + expect(result.current.hasMore).toBe(false) }) - it('retries the initial fetch after a startup failure', async () => { - getSessionsMock - .mockRejectedValueOnce(new Error('service not ready')) - .mockResolvedValueOnce([makeSession('session-1')]) + it('本地见底且服务端还有下一页时才续页', async () => { + storeMock.setSnapshotForTest({ ready: true, sessions: [makeSession('ses_0')], hasMore: true }) - const { result } = renderHook(() => useSessions({ directory: '/workspace/demo' })) + const { result } = renderHook(() => useSessions({ directory: '/workspace/demo', pageSize: 5 })) await act(async () => { - vi.runOnlyPendingTimers() - await Promise.resolve() - await Promise.resolve() + await result.current.loadMore() }) - expect(getSessionsMock).toHaveBeenCalledTimes(1) - - await act(async () => { - vi.advanceTimersByTime(500) - await Promise.resolve() - await Promise.resolve() - }) - - expect(getSessionsMock).toHaveBeenCalledTimes(2) - expect(result.current.sessions.map(session => session.id)).toEqual(['session-1']) + expect(storeMock.loadMore).toHaveBeenCalledWith('local') }) - it('refetches on server endpoint changes even while the old request is in flight', async () => { - const staleRequest = createDeferred[]>() - const freshRequest = createDeferred[]>() - - getSessionsMock - .mockImplementationOnce(() => staleRequest.promise) - .mockImplementationOnce(() => freshRequest.promise) - - const { result } = renderHook(() => useSessions({ directory: '/workspace/demo' })) - - await act(async () => { - vi.runAllTimers() - await Promise.resolve() - }) + it('删除会话传对目录,并同步清掉索引条目', async () => { + deleteSessionMock.mockResolvedValue(true) + storeMock.setSnapshotForTest({ ready: true, sessions: [makeSession('ses_a')] }) - expect(getSessionsMock).toHaveBeenCalledTimes(1) + const { result } = renderHook(() => useSessions({ directory: '/workspace/demo', serverId: 'remote' })) await act(async () => { - // active 服务器自身端点变化(serverId = active)才应触发重拉 - latestServerChange?.('local', 'server-runtime-updated') - await Promise.resolve() + await result.current.remove('ses_a') }) - expect(getSessionsMock).toHaveBeenCalledTimes(2) + expect(deleteSessionMock).toHaveBeenCalledWith('ses_a', '/workspace/demo', 'remote') + expect(unpinMock).toHaveBeenCalledWith('ses_a') + expect(storeMock.remove).toHaveBeenCalledWith('remote', 'ses_a') + }) - await act(async () => { - freshRequest.resolve([makeSession('fresh')]) - await Promise.resolve() - await Promise.resolve() + it('搜索在本地过滤标题,不产生额外请求', () => { + storeMock.setSnapshotForTest({ + ready: true, + sessions: [makeSession('ses_a'), makeSession('ses_b')], }) - expect(result.current.sessions.map(session => session.id)).toEqual(['fresh']) + const { result } = renderHook(() => useSessions({ directory: '/workspace/demo' })) + const ensureCalls = storeMock.ensure.mock.calls.length - await act(async () => { - staleRequest.resolve([makeSession('stale')]) - await Promise.resolve() - await Promise.resolve() + act(() => { + result.current.setSearch('ses_b') }) - expect(result.current.sessions.map(session => session.id)).toEqual(['fresh']) + expect(result.current.sessions.map(session => session.id)).toEqual(['ses_b']) + expect(storeMock.ensure).toHaveBeenCalledTimes(ensureCalls) }) - it('refetches only for active-server events, ignoring non-active runtime updates', async () => { - getSessionsMock.mockResolvedValue([makeSession('session-1')]) + it('新建会话直接写进索引(不等 SSE)', async () => { + const created = makeSession('ses_new', '/workspace/git', 100) + createSessionMock.mockResolvedValue(created) - renderHook(() => useSessions({ directory: '/workspace/demo' })) + const { result } = renderHook(() => useSessions({ directory: '/workspace/git' })) await act(async () => { - vi.runAllTimers() - await Promise.resolve() + await result.current.create('hello') }) - expect(getSessionsMock).toHaveBeenCalledTimes(1) - - // 非 active 服务器(remote)端点变化:与当前列表无关,不得清空/重拉 - await act(async () => { - latestServerChange?.('remote', 'server-runtime-updated') - await Promise.resolve() - }) - expect(getSessionsMock).toHaveBeenCalledTimes(1) - - // active(getActiveServerId mock = 'local')自身端点变化:数据源地址变了,需要重拉 - await act(async () => { - latestServerChange?.('local', 'server-runtime-updated') - await Promise.resolve() - }) - expect(getSessionsMock).toHaveBeenCalledTimes(2) - - // 真实切换:事件里的 serverId 即新 active,照常重拉 - await act(async () => { - latestServerChange?.('remote', 'server-switch') - await Promise.resolve() - }) - expect(getSessionsMock).toHaveBeenCalledTimes(3) + expect(createSessionMock).toHaveBeenCalledWith({ title: 'hello', directory: '/workspace/git' }, undefined) + expect(storeMock.upsert).toHaveBeenCalledWith('local', created) }) - it('keeps loading during retry backoff and lands error only at terminal failure', async () => { - getSessionsMock.mockRejectedValue(new Error('service not ready')) + it('索引错误原样透出,refresh 走 force', async () => { + const error = new Error('down') + storeMock.setSnapshotForTest({ ready: false, error }) const { result } = renderHook(() => useSessions({ directory: '/workspace/demo' })) - - // 首次失败:进入重试等待期,必须仍是 loading(空列表 + 非 loading 会闪现空态文案) - await act(async () => { - vi.runOnlyPendingTimers() - await Promise.resolve() - await Promise.resolve() - }) - - expect(getSessionsMock).toHaveBeenCalledTimes(1) - expect(result.current.isLoading).toBe(true) - expect(result.current.error).toBeNull() - - // 前两次退避到期后仍在加载(等待第三次重试),第三次退避会耗尽重试 - for (const backoff of [500, 1500]) { - await act(async () => { - vi.advanceTimersByTime(backoff) - await Promise.resolve() - await Promise.resolve() - await Promise.resolve() - }) - expect(result.current.isLoading).toBe(true) - } - - // 第三次退避到期 → 第四次尝试 → 耗尽 → 终态 - await act(async () => { - vi.advanceTimersByTime(3000) - await Promise.resolve() - await Promise.resolve() - await Promise.resolve() - }) - - expect(getSessionsMock).toHaveBeenCalledTimes(4) + expect(result.current.error).toBe(error) expect(result.current.isLoading).toBe(false) - expect(result.current.error).not.toBeNull() - expect(result.current.sessions).toEqual([]) - // 重试耗尽(500+1500+3000 后第四次尝试):终态 = 非 loading + error,而非「没有对话」 await act(async () => { - vi.advanceTimersByTime(3000) - await Promise.resolve() - await Promise.resolve() + await result.current.refresh() }) - expect(getSessionsMock).toHaveBeenCalledTimes(4) - expect(result.current.isLoading).toBe(false) - expect(result.current.error).not.toBeNull() - expect(result.current.sessions).toEqual([]) + expect(storeMock.ensure).toHaveBeenLastCalledWith('local', { force: true }) }) - it('lands success after a retry and clears error', async () => { - getSessionsMock - .mockRejectedValueOnce(new Error('service not ready')) - .mockResolvedValueOnce([makeSession('session-1')]) - + it('patchLocalSession 写到共享索引', () => { const { result } = renderHook(() => useSessions({ directory: '/workspace/demo' })) - await act(async () => { - vi.runOnlyPendingTimers() - await Promise.resolve() - await Promise.resolve() - }) - - await act(async () => { - vi.advanceTimersByTime(500) - await Promise.resolve() - await Promise.resolve() - }) - - expect(result.current.sessions.map(session => session.id)).toEqual(['session-1']) - expect(result.current.isLoading).toBe(false) - expect(result.current.error).toBeNull() - }) - - it('cancels the pending retry backoff when unmounted', async () => { - getSessionsMock.mockRejectedValueOnce(new Error('service not ready')) - getSessionsMock.mockResolvedValue([]) - - const { unmount } = renderHook(() => useSessions({ directory: '/workspace/demo' })) - - // 首次失败 → 停在 500ms 退避等待中 - await act(async () => { - vi.runOnlyPendingTimers() - await Promise.resolve() - await Promise.resolve() - }) - expect(getSessionsMock).toHaveBeenCalledTimes(1) - - unmount() - - // 推过整个退避表:卸载必须中断重试,否则陈旧 timer 会在组件消失后再发最多 3 次请求 - await act(async () => { - vi.advanceTimersByTime(6000) - await Promise.resolve() - await Promise.resolve() - await Promise.resolve() + act(() => { + result.current.patchLocalSession('ses_a', { title: 'new' }) }) - expect(getSessionsMock).toHaveBeenCalledTimes(1) + expect(storeMock.patch).toHaveBeenCalledWith('local', 'ses_a', { title: 'new' }) }) }) diff --git a/src/hooks/useSessions.ts b/src/hooks/useSessions.ts index 0a91c18b7..50f703561 100644 --- a/src/hooks/useSessions.ts +++ b/src/hooks/useSessions.ts @@ -1,30 +1,19 @@ -import { useState, useEffect, useCallback, useRef } from 'react' -import { - getSessions, - getSession, - createSession, - deleteSession, - subscribeToEvents, - subscribeToServerEvents, - type ApiSession, - type SessionListParams, -} from '../api' -import { affectsBoundServer } from '../store/serverChangeScope' +import { useState, useEffect, useCallback, useMemo, useSyncExternalStore } from 'react' +import { createSession, deleteSession, type ApiSession } from '../api' import { serverStore } from '../store/serverStore' import { pinnedSessionsStore } from '../store/pinnedSessionsStore' -import { autoDetectPathStyle, isSameDirectory } from '../utils' +import { sessionIndexStore } from '../store/sessionIndexStore' +import { isSameDirectory } from '../utils' -// 会话列表加载失败的重试退避(毫秒)。退避间隔内仍算「加载中」, -// 不落空态——消费方据此区分「还在加载」与「确实没有对话」 -const SESSION_RETRY_DELAYS_MS = [500, 1500, 3000] +/** 稳定引用:useSyncExternalStore 每次渲染拿到同一个 subscribe,避免反复解绑 */ +const subscribeServerStore = serverStore.subscribe.bind(serverStore) +const getActiveServerId = () => serverStore.getActiveServerId() interface UseSessionsOptions { - /** 每页数量 */ + /** 每页数量(本地切片,不触发网络请求) */ pageSize?: number /** 初始搜索词 */ initialSearch?: string - /** 只加载根会话 */ - rootsOnly?: boolean /** 按目录过滤 */ directory?: string /** 延迟启用,用于懒加载 */ @@ -56,359 +45,126 @@ interface UseSessionsResult { removeLocalSession: (sessionId: string) => void } +/** + * 目录级会话列表(侧栏文件夹模式 / 多服务器模式)。 + * + * 数据来自 `sessionIndexStore` 的服务器级索引:同一台服务器上无论展开 + * 多少个文件夹,都只共享一次 `session.list`,目录过滤和分页切片都在本地。 + * 过去每个文件夹(pageSize=5)各发一次请求,文件夹一多就把队列打满。 + */ export function useSessions(options: UseSessionsOptions = {}): UseSessionsResult { - const { pageSize = 20, initialSearch = '', rootsOnly = true, directory, enabled = true, serverId } = options + const { pageSize = 20, initialSearch = '', directory, enabled = true, serverId } = options // 标准化 directory 路径 (移除末尾斜杠,统一正斜杠) const normalizedDirectory = directory ? directory.replace(/\\/g, '/').replace(/\/$/, '') : undefined - - const [sessions, setSessions] = useState([]) - const [isLoading, setIsLoading] = useState(enabled) - const [isLoadingMore, setIsLoadingMore] = useState(false) - const [error, setError] = useState(null) - const [hasMore, setHasMore] = useState(true) - const [search, setSearch] = useState(initialSearch) - - // 用于跟踪最后一次请求,避免竞态条件 - const requestIdRef = useRef(0) - // 防抖 timer - const searchTimerRef = useRef(null) - // 当前 limit,loadMore 时递增(与 SessionContext 保持一致) - const currentLimitRef = useRef(pageSize) - const searchRef = useRef(search) - // enabled 实时值:重试循环等待期间读取(懒加载闸门关闭时中断在途重试) - const enabledRef = useRef(enabled) - // 防止 onReconnected 密集触发时重复请求 - const isFetchingRef = useRef(false) - const queuedReconnectRefreshRef = useRef(false) - const fetchSessionsRef = useRef<(params?: SessionListParams & { append?: boolean }) => Promise>( - () => Promise.resolve(), + // 固定服务器直接用;没传时跟随活动服务器(切服务器要换索引) + const activeServerId = useSyncExternalStore( + subscribeServerStore, + getActiveServerId, + getActiveServerId, ) - // 重试退避的在途句柄:unmount 时清 timer 并唤醒循环,防止组件消失后仍继续发请求 - const pendingRetryRef = useRef<{ cancel: () => void } | null>(null) - // 卸载标记:重试循环与 finally 的后续动作据此整体退出(React 卸载后不应再有网络/状态动作) - const unmountedRef = useRef(false) + const serverKey = serverId ?? activeServerId - // unmount 中断在途重试(对齐旧实现 retryTimerRef 的清理语义) - useEffect(() => { - unmountedRef.current = false - return () => { - unmountedRef.current = true - pendingRetryRef.current?.cancel() - } - }, []) - - useEffect(() => { - enabledRef.current = enabled - }, [enabled]) - - useEffect(() => { - searchRef.current = search - }, [search]) - - const matchesDirectory = useCallback( - (session: ApiSession) => !normalizedDirectory || isSameDirectory(normalizedDirectory, session.location?.directory), - [normalizedDirectory], + const snapshot = useSyncExternalStore( + sessionIndexStore.subscribe, + () => sessionIndexStore.getSnapshot(serverKey), + () => sessionIndexStore.getSnapshot(serverKey), ) - // 获取会话列表 - // append 仅用于控制 loading 状态:true 时用 isLoadingMore,false 时用 isLoading - // 数据始终全量替换(递增 limit 策略) - // 重试为显式循环而非 setTimeout 自调用:loading 的生命周期 = 循环的生命周期, - // 重试空档不再以「空列表 + 非 loading」示人(空态文案闪现的根因) - const fetchSessions = useCallback( - async (params: SessionListParams & { append?: boolean } = {}) => { - if (!enabled) return - - const { append = false, ...queryParams } = params - const requestId = ++requestIdRef.current - isFetchingRef.current = true - - if (append) { - setIsLoadingMore(true) - } else { - setIsLoading(true) - setError(null) - } - - try { - for (let retryAttempt = 0; ; retryAttempt++) { - try { - const data = await getSessions( - { - // v2 没有 roots 开关:只要根会话时传 parentID: null - ...(rootsOnly ? { parentID: null } : {}), - limit: currentLimitRef.current, - directory: normalizedDirectory, - ...queryParams, - }, - serverId, - ) - - // 已被更新的请求覆盖:静默退出,不碰任何状态 - if (requestId !== requestIdRef.current) return - - if (data.length > 0 && data[0].location?.directory) { - // 按服务器记录路径风格(多服务器连不同操作系统时互不干扰) - autoDetectPathStyle(data[0].location?.directory, serverId) - } - - setSessions(data) - setHasMore(data.length >= currentLimitRef.current) - setError(null) - return - } catch (e) { - // 已被更新的请求覆盖:静默退出,状态恢复交给新请求的 finally - if (requestId !== requestIdRef.current) return - const exhausted = retryAttempt >= SESSION_RETRY_DELAYS_MS.length - if (append || exhausted) { - // 失败终态:error 落定后退出,finally 统一恢复 loading - setError(e instanceof Error ? e : new Error('Failed to fetch sessions')) - return - } - // 重试未耗尽 = 仍在加载:loading 不落地,按退避表等待后进入下一轮。 - // 等待做成「可取消」:unmount 的 cleanup 会清 timer 并立即 resolve, - // 循环经下面的 unmounted 检查正常退出,不会再发重试请求 - await new Promise(resolve => { - const timer = window.setTimeout(() => { - pendingRetryRef.current = null - resolve() - }, SESSION_RETRY_DELAYS_MS[retryAttempt]) - pendingRetryRef.current = { - cancel: () => { - window.clearTimeout(timer) - pendingRetryRef.current = null - resolve() - }, - } - }) - // 等待期间可能被新请求覆盖、组件已禁用(懒加载闸门回退)或已卸载 - if (unmountedRef.current || requestId !== requestIdRef.current || !enabledRef.current) return - } - } - } finally { - // 卸载后状态与排队动作整体跳过:退避 promise 被 cancel 唤醒时 finally 也会执行 - if (!unmountedRef.current && requestId === requestIdRef.current) { - isFetchingRef.current = false - setIsLoading(false) - setIsLoadingMore(false) - if (queuedReconnectRefreshRef.current) { - queuedReconnectRefreshRef.current = false - setSessions([]) - void fetchSessionsRef.current({ search: searchRef.current || undefined }) - } - } - } - }, - [rootsOnly, normalizedDirectory, enabled, serverId], - ) - - fetchSessionsRef.current = fetchSessions + const [search, setSearch] = useState(initialSearch) + const [limit, setLimit] = useState(pageSize) + const [isLoadingMore, setIsLoadingMore] = useState(false) - // 初始加载和搜索变化时重新加载 + // 目录/搜索/分页大小变化:回到第一页 useEffect(() => { - if (!enabled) { - setIsLoading(false) - setIsLoadingMore(false) - return - } - - // 搜索或 enabled 变化时重置 limit - currentLimitRef.current = pageSize - - // 防抖处理搜索 - if (searchTimerRef.current) { - clearTimeout(searchTimerRef.current) - } - - searchTimerRef.current = window.setTimeout( - () => { - fetchSessions({ search: search || undefined }) - }, - search ? 300 : 0, - ) // 有搜索词时延迟 300ms,无搜索词时立即执行 - - return () => { - if (searchTimerRef.current) { - clearTimeout(searchTimerRef.current) - } - } - }, [search, fetchSessions, enabled, pageSize]) + setLimit(pageSize) + }, [normalizedDirectory, search, pageSize, serverKey]) + // 懒加载:只有 enabled 的文件夹才触发索引拉取(同一服务器仍然只拉一次) useEffect(() => { if (!enabled) return - - const subscribe = serverId - ? (cb: Parameters[1]) => subscribeToServerEvents(serverId, cb) - : subscribeToEvents - - // 回读完整会话并插到列表头部(session.created / session.forked 的负载都不是完整 - // SessionInfo,都得回读一次)。去重靠 setSessions 里的 some 判断。 - const prependSessionById = (sessionID: string) => { - void getSession(sessionID, undefined, serverId) - .then(session => { - if (!session || !matchesDirectory(session)) return - - if (searchRef.current) { - void fetchSessionsRef.current({ search: searchRef.current || undefined }) - return - } - - setSessions(prev => { - if (prev.some(item => item.id === session.id)) return prev - return [session, ...prev] - }) - }) - .catch(() => { - // 回读失败退回整表刷新 - void fetchSessionsRef.current({ search: searchRef.current || undefined }) - }) - } - - const unsubscribe = subscribe({ - onSessionCreated: data => { - // subagent 子会话(Task 工具 spawn,parentID 非空)不进主列表 - if (data.parentID) return - prependSessionById(data.sessionID) - }, - // fork 出来的是用户可见的新顶层会话,必须进列表:DB 里 parent_id=null(来源记在 - // fork 字段,不是 subagent),且服务端 fork 只发 session.forked 不发 session.created, - // 所以走 onSessionCreated 永远接不到。负载里的 parentID 是「fork 自哪个会话」, - // 不是 subagent 标记,不能据此跳过。 - onSessionForked: data => { - prependSessionById(data.sessionID) - }, - onSessionRenamed: data => { - // v2 把 v1 的 session.updated 收敛成 session.renamed(只有标题变化) - setSessions(prev => { - const index = prev.findIndex(item => item.id === data.sessionID) - if (index === -1) return prev - const next = [...prev] - next[index] = { ...next[index], title: data.title } - return next - }) - }, - onSessionDeleted: data => { - // v2 的 session.deleted 负载是 { sessionID } - setSessions(prev => prev.filter(item => item.id !== data.sessionID)) - }, - onSessionMoved: data => { - // v2 session.move 后目录归属变化:回读一次,匹配本列表目录则加入/更新,否则移除 - void getSession(data.sessionID, undefined, serverId) - .then(session => { - if (!session) return - setSessions(prev => { - const index = prev.findIndex(item => item.id === data.sessionID) - if (matchesDirectory(session)) { - if (index === -1) return [session, ...prev] - const next = [...prev] - next[index] = session - return next - } - return index === -1 ? prev : prev.filter(item => item.id !== data.sessionID) - }) - }) - .catch(() => { - // 回读失败退回整表刷新 - void fetchSessionsRef.current({ search: searchRef.current || undefined }) - }) - }, - onReconnected: reason => { - if (reason === 'server-switch') return - if (isFetchingRef.current) { - queuedReconnectRefreshRef.current = true - return - } - setSessions([]) - void fetchSessionsRef.current({ search: searchRef.current || undefined }) - }, + void sessionIndexStore.ensure(serverKey) + }, [enabled, serverKey]) + + const directorySessions = useMemo(() => { + if (!normalizedDirectory) return snapshot.sessions + return snapshot.sessions.filter(session => isSameDirectory(normalizedDirectory, session.location?.directory)) + }, [snapshot.sessions, normalizedDirectory]) + + const filteredSessions = useMemo(() => { + const term = search.trim().toLowerCase() + if (!term) return directorySessions + return directorySessions.filter(session => { + const title = (session.title ?? '').toLowerCase() + return title.includes(term) || session.id.toLowerCase().includes(term) }) + }, [directorySessions, search]) - return unsubscribe - }, [enabled, matchesDirectory, pageSize, serverId]) + const sessions = useMemo(() => filteredSessions.slice(0, limit), [filteredSessions, limit]) + const searching = search.trim().length > 0 + const hasMore = filteredSessions.length > limit || (!searching && snapshot.hasMore) + const isLoading = !enabled ? false : !snapshot.ready && !snapshot.error - useEffect(() => { - if (!enabled) return - - // 固定服务器订阅(多服务器模式):不随 active server 切换刷新 - if (serverId) return - - return serverStore.onServerChange((changedServerId, reason) => { - // 本实例跟随 active server:非 active 服务器端点变化(WSL 重启)与列表无关, - // 不该触发「清空 → 重拉」;仅 active 换了或变的这台就是 active 时才重置 - if (!affectsBoundServer(undefined, changedServerId, reason, serverStore.getActiveServerId())) return - currentLimitRef.current = pageSize - setSessions([]) - void fetchSessionsRef.current({ search: searchRef.current || undefined }) - }) - }, [enabled, pageSize, serverId]) - - // 加载更多:递增 limit 重新拉取完整列表(与 SessionContext 一致) const loadMore = useCallback(async () => { - if (!enabled || isLoadingMore || !hasMore || sessions.length === 0) return - - currentLimitRef.current += pageSize - await fetchSessions({ - search: search || undefined, - append: true, - }) - }, [sessions, search, hasMore, isLoadingMore, fetchSessions, enabled, pageSize]) + if (!enabled || isLoadingMore || !hasMore) return + setIsLoadingMore(true) + try { + if (filteredSessions.length > limit) { + setLimit(current => current + pageSize) + return + } + if (snapshot.hasMore) { + await sessionIndexStore.loadMore(serverKey) + setLimit(current => current + pageSize) + } + } finally { + setIsLoadingMore(false) + } + }, [enabled, isLoadingMore, hasMore, filteredSessions.length, limit, pageSize, snapshot.hasMore, serverKey]) - // 刷新 const refresh = useCallback(async () => { if (!enabled) return - await fetchSessions({ search: search || undefined }) - }, [search, fetchSessions, enabled]) + await sessionIndexStore.ensure(serverKey, { force: true }) + }, [enabled, serverKey]) - // 创建新会话 const create = useCallback( async (title?: string) => { - // 创建时也要传 directory - const newSession = await createSession( - { - title, - directory: normalizedDirectory, - }, - serverId, - ) - - if (searchRef.current) { - void fetchSessionsRef.current({ search: searchRef.current || undefined }) - } else { - setSessions(prev => { - if (prev.some(session => session.id === newSession.id)) return prev - return [newSession, ...prev] - }) - } - + const newSession = await createSession({ title, directory: normalizedDirectory }, serverId) + // 不等 SSE:新建的会话已经是完整元信息,直接进索引 + if (!newSession.parentID) sessionIndexStore.upsert(serverKey, newSession) return newSession }, - [normalizedDirectory, serverId], + [normalizedDirectory, serverId, serverKey], ) - // 删除会话 const remove = useCallback( async (sessionId: string) => { await deleteSession(sessionId, normalizedDirectory, serverId) pinnedSessionsStore.unpin(sessionId) - setSessions(prev => prev.filter(s => s.id !== sessionId)) + sessionIndexStore.remove(serverKey, sessionId) }, - [normalizedDirectory, serverId], + [normalizedDirectory, serverId, serverKey], ) - const patchLocalSession = useCallback((sessionId: string, patch: Partial) => { - setSessions(prev => prev.map(session => (session.id === sessionId ? { ...session, ...patch } : session))) - }, []) + const patchLocalSession = useCallback( + (sessionId: string, patch: Partial) => { + sessionIndexStore.patch(serverKey, sessionId, patch) + }, + [serverKey], + ) - const removeLocalSession = useCallback((sessionId: string) => { - setSessions(prev => prev.filter(session => session.id !== sessionId)) - }, []) + const removeLocalSession = useCallback( + (sessionId: string) => { + sessionIndexStore.remove(serverKey, sessionId) + }, + [serverKey], + ) return { sessions, isLoading, isLoadingMore, - error, + error: snapshot.error, hasMore, search, setSearch, diff --git a/src/store/sessionIndexStore.test.ts b/src/store/sessionIndexStore.test.ts new file mode 100644 index 000000000..615683eb7 --- /dev/null +++ b/src/store/sessionIndexStore.test.ts @@ -0,0 +1,264 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import type { EventCallbacks } from '../types/api/event' +import type { Session } from '../types/api/session' + +const { listSessionsPageMock, getSessionMock, subscribeMock } = vi.hoisted(() => ({ + listSessionsPageMock: vi.fn(), + getSessionMock: vi.fn(), + subscribeMock: vi.fn(), +})) + +vi.mock('../api/session', () => ({ + listSessionsPage: (...args: unknown[]) => listSessionsPageMock(...args), + getSession: (...args: unknown[]) => getSessionMock(...args), +})) + +vi.mock('../api/events', () => ({ + subscribeToServerEvents: (...args: unknown[]) => subscribeMock(...args), +})) + +vi.mock('../utils/directoryUtils', () => ({ + autoDetectPathStyle: vi.fn(), +})) + +const { sessionIndexStore } = await import('./sessionIndexStore') + +const SERVER = 'local' + +function session(id: string, patch: Partial = {}): Session { + return { + id, + projectID: 'project-1', + location: { directory: '/workspace/demo' }, + title: `Session ${id}`, + cost: 0, + tokens: { input: 0, output: 0, reasoning: 0, cache: { read: 0, write: 0 } }, + time: { created: 1, updated: 2 }, + ...patch, + } as Session +} + +function page(data: Session[], next: string | null = null) { + return { data, next } +} + +let eventCallbacks: Partial = {} + +describe('sessionIndexStore', () => { + beforeEach(() => { + sessionIndexStore.reset() + listSessionsPageMock.mockReset() + getSessionMock.mockReset() + subscribeMock.mockReset() + eventCallbacks = {} + subscribeMock.mockImplementation((_serverId: string, callbacks: EventCallbacks) => { + eventCallbacks = callbacks + return vi.fn() + }) + }) + + afterEach(() => { + sessionIndexStore.reset() + vi.useRealTimers() + }) + + it('首屏只拉根会话,按更新时间倒序(子会话与归档不进索引)', async () => { + listSessionsPageMock.mockResolvedValue( + page([ + session('ses_old', { time: { created: 1, updated: 10 } }), + session('ses_new', { time: { created: 1, updated: 99 } }), + session('ses_child', { parentID: 'ses_new' }), + session('ses_archived', { time: { created: 1, updated: 50, archived: 60 } }), + ]), + ) + + await sessionIndexStore.ensure(SERVER) + + expect(listSessionsPageMock).toHaveBeenCalledWith({ parentID: null, order: 'desc', limit: 500 }, SERVER) + expect(sessionIndexStore.getSnapshot(SERVER).sessions.map(item => item.id)).toEqual(['ses_new', 'ses_old']) + expect(sessionIndexStore.getSnapshot(SERVER).ready).toBe(true) + }) + + it('30s 内重复 ensure 不重复请求(切目录/重挂载零请求)', async () => { + listSessionsPageMock.mockResolvedValue(page([session('ses_a')])) + + await sessionIndexStore.ensure(SERVER) + await sessionIndexStore.ensure(SERVER) + + expect(listSessionsPageMock).toHaveBeenCalledTimes(1) + }) + + it('force 跳过 TTL 重新拉,旧数据在新数据到达前保留', async () => { + listSessionsPageMock.mockResolvedValueOnce(page([session('ses_a')])) + await sessionIndexStore.ensure(SERVER) + + const next = page([session('ses_b')]) + listSessionsPageMock.mockResolvedValueOnce(next) + const refreshing = sessionIndexStore.ensure(SERVER, { force: true }) + + // 刷新期间仍是旧快照,不闪空态 + expect(sessionIndexStore.getSnapshot(SERVER).sessions.map(item => item.id)).toEqual(['ses_a']) + await refreshing + + expect(listSessionsPageMock).toHaveBeenCalledTimes(2) + expect(sessionIndexStore.getSnapshot(SERVER).sessions.map(item => item.id)).toEqual(['ses_b']) + }) + + it('cursor 续页只追加新的一页,到底后 hasMore=false', async () => { + // 首轮自动翻两页(page1 → page2),第三页留给「显示更多」 + listSessionsPageMock + .mockResolvedValueOnce(page([session('ses_1')], 'cursor-2')) + .mockResolvedValueOnce(page([session('ses_2')], 'cursor-3')) + await sessionIndexStore.ensure(SERVER) + expect(listSessionsPageMock).toHaveBeenCalledTimes(2) + expect(sessionIndexStore.getSnapshot(SERVER).hasMore).toBe(true) + + listSessionsPageMock.mockResolvedValueOnce(page([session('ses_3')])) + await sessionIndexStore.loadMore(SERVER) + + expect(listSessionsPageMock).toHaveBeenLastCalledWith( + { parentID: null, order: 'desc', limit: 500, cursor: 'cursor-3' }, + SERVER, + ) + expect(sessionIndexStore.getSnapshot(SERVER).sessions.map(item => item.id)).toEqual([ + 'ses_1', + 'ses_2', + 'ses_3', + ]) + expect(sessionIndexStore.getSnapshot(SERVER).hasMore).toBe(false) + }) + + it('续页去重(游标重复时不会出现重复行)', async () => { + listSessionsPageMock + .mockResolvedValueOnce(page([session('ses_1')], 'cursor-2')) + .mockResolvedValueOnce(page([session('ses_1'), session('ses_2')], 'cursor-3')) + await sessionIndexStore.ensure(SERVER) + + listSessionsPageMock.mockResolvedValueOnce(page([session('ses_2')], null)) + await sessionIndexStore.loadMore(SERVER) + + expect(sessionIndexStore.getSnapshot(SERVER).sessions.map(item => item.id).sort()).toEqual(['ses_1', 'ses_2']) + }) + + it('首屏失败按退避重试,最终成功不落 error', async () => { + vi.useFakeTimers() + listSessionsPageMock + .mockRejectedValueOnce(new Error('offline')) + .mockRejectedValueOnce(new Error('offline')) + .mockResolvedValueOnce(page([session('ses_a')])) + + const request = sessionIndexStore.ensure(SERVER) + await vi.advanceTimersByTimeAsync(500) + await vi.advanceTimersByTimeAsync(1500) + await request + + expect(listSessionsPageMock).toHaveBeenCalledTimes(3) + expect(sessionIndexStore.getSnapshot(SERVER).error).toBeNull() + expect(sessionIndexStore.getSnapshot(SERVER).sessions).toHaveLength(1) + }) + + it('重试耗尽后 error 落定,ready 仍为 false(消费方显示失败态)', async () => { + vi.useFakeTimers() + listSessionsPageMock.mockRejectedValue(new Error('offline')) + + const request = sessionIndexStore.ensure(SERVER) + await vi.advanceTimersByTimeAsync(500) + await vi.advanceTimersByTimeAsync(1500) + await vi.advanceTimersByTimeAsync(3000) + await request + + expect(listSessionsPageMock).toHaveBeenCalledTimes(4) + expect(sessionIndexStore.getSnapshot(SERVER).error).toBeInstanceOf(Error) + expect(sessionIndexStore.getSnapshot(SERVER).ready).toBe(false) + }) + + it('事件增量:改名就地更新、删除移除、根会话创建回读后插入', async () => { + listSessionsPageMock.mockResolvedValue(page([session('ses_a')])) + await sessionIndexStore.ensure(SERVER) + + eventCallbacks.onSessionRenamed?.({ sessionID: 'ses_a', title: '新标题' } as never) + expect(sessionIndexStore.getSnapshot(SERVER).sessions[0].title).toBe('新标题') + + getSessionMock.mockResolvedValue(session('ses_new', { time: { created: 1, updated: 100 } })) + eventCallbacks.onSessionCreated?.({ sessionID: 'ses_new', location: { directory: '/workspace/demo' } } as never) + await vi.waitFor(() => { + expect(sessionIndexStore.getSnapshot(SERVER).sessions[0].id).toBe('ses_new') + }) + + expect(getSessionMock).toHaveBeenCalledWith('ses_new', undefined, SERVER) + + eventCallbacks.onSessionDeleted?.({ sessionID: 'ses_new' } as never) + expect(sessionIndexStore.getSnapshot(SERVER).sessions.map(item => item.id)).toEqual(['ses_a']) + }) + + it('子会话创建不触发根索引回读', async () => { + listSessionsPageMock.mockResolvedValue(page([session('ses_a')])) + await sessionIndexStore.ensure(SERVER) + + eventCallbacks.onSessionCreated?.({ sessionID: 'ses_child', parentID: 'ses_a' } as never) + await Promise.resolve() + + expect(getSessionMock).not.toHaveBeenCalled() + }) + + it('重连标脏并强制重拉,期间旧数据保留', async () => { + listSessionsPageMock.mockResolvedValueOnce(page([session('ses_a')])) + await sessionIndexStore.ensure(SERVER) + listSessionsPageMock.mockResolvedValueOnce(page([session('ses_b')])) + + eventCallbacks.onReconnected?.('network') + expect(sessionIndexStore.getSnapshot(SERVER).sessions.map(item => item.id)).toEqual(['ses_a']) + await vi.waitFor(() => { + expect(sessionIndexStore.getSnapshot(SERVER).sessions.map(item => item.id)).toEqual(['ses_b']) + }) + + expect(listSessionsPageMock).toHaveBeenCalledTimes(2) + }) + + it('刷新期间到达的新会话不会被整页替换覆盖', async () => { + listSessionsPageMock.mockResolvedValueOnce(page([session('ses_a')])) + await sessionIndexStore.ensure(SERVER) + + let resolveRefresh!: (value: { data: Session[]; next: string | null }) => void + listSessionsPageMock.mockImplementationOnce( + () => + new Promise(resolve => { + resolveRefresh = resolve + }), + ) + const refreshing = sessionIndexStore.ensure(SERVER, { force: true }) + + // 刷新还在飞:新建的会话先排队 + sessionIndexStore.upsert(SERVER, session('ses_new', { time: { created: 1, updated: 999 } })) + resolveRefresh(page([session('ses_a')])) + await refreshing + + expect(sessionIndexStore.getSnapshot(SERVER).sessions.map(item => item.id)).toEqual(['ses_new', 'ses_a']) + }) + + it('并发 ensure 共享同一个请求(多个文件夹同时展开只打一次)', async () => { + let resolvePage!: (value: { data: Session[]; next: string | null }) => void + listSessionsPageMock.mockImplementation( + () => + new Promise(resolve => { + resolvePage = resolve + }), + ) + + const first = sessionIndexStore.ensure(SERVER) + const second = sessionIndexStore.ensure(SERVER) + resolvePage(page([session('ses_a')])) + await Promise.all([first, second]) + + expect(listSessionsPageMock).toHaveBeenCalledTimes(1) + expect(sessionIndexStore.getSnapshot(SERVER).sessions).toHaveLength(1) + }) + + it('同一服务器只建一次事件订阅', async () => { + listSessionsPageMock.mockResolvedValue(page([])) + await sessionIndexStore.ensure(SERVER) + await sessionIndexStore.ensure(SERVER, { force: true }) + + expect(subscribeMock).toHaveBeenCalledTimes(1) + }) +}) diff --git a/src/store/sessionIndexStore.ts b/src/store/sessionIndexStore.ts new file mode 100644 index 000000000..a80f56f13 --- /dev/null +++ b/src/store/sessionIndexStore.ts @@ -0,0 +1,398 @@ +// ============================================ +// SessionIndexStore — 每个服务器一份根会话索引 +// +// 侧栏的会话列表过去按「目录」各拉各的:文件夹模式下一个文件夹一次 +// `session.list`,切目录/切服务器再各拉一次。同一台服务器上的会话被 +// 重复请求了 N 遍,目录切换也永远要等一次网络往返。 +// +// 官方 app 的做法是拉一份「根会话索引」(`loadHomeSessionIndex`), +// 在本地按目录分组、按时间切片(home/sessions/index.ts)。这里做同一件事: +// +// - `ensure(serverId)` 拉首页(limit 500,首轮最多自动翻两页),30s 内复用 +// - 各列表从 `getSnapshot(serverId)` 里按目录过滤、按需切片,零额外请求 +// - SSE 增量(新增/重命名/删除/移动)直接写进索引,所有列表同步更新 +// - 重连直接重拉第一页,旧数据保留到新数据到达,列表不会闪一下空态 +// +// 索引只存根会话(parentID 为空、未归档):子会话由 childSessionStore +// 管理,不属于侧栏列表。 +// ============================================ + +import { getSession, listSessionsPage } from '../api/session' +import { subscribeToServerEvents } from '../api/events' +import { autoDetectPathStyle } from '../utils/directoryUtils' +import type { Session } from '../types/api/session' + +/** 与官方 home 列表的 staleTime 对齐:30s 内重复挂载不再请求 */ +const TTL_MS = 30_000 +/** 单页条数:常规服务器一页拉完,大库再按 cursor 续页 */ +const PAGE_LIMIT = 500 +/** 首轮最多自动翻几页:保证「别的目录把前 500 条占满」时当前目录仍有数据 */ +const AUTO_PAGES = 2 +/** 兜底上限:极端情况下也不无限翻页 */ +const MAX_SESSIONS = 2_000 +/** 首屏失败的重试退避(启动可能早于本地服务端就绪) */ +const RETRY_DELAYS_MS = [500, 1_500, 3_000] + +export interface SessionIndexSnapshot { + /** 根会话,按更新时间倒序 */ + sessions: Session[] + /** 服务端还有下一页没拉 */ + hasMore: boolean + /** 至少成功拉过一页(空列表也算 ready) */ + ready: boolean + loading: boolean + error: Error | null +} + +const EMPTY_SNAPSHOT: SessionIndexSnapshot = Object.freeze({ + sessions: [], + hasMore: false, + ready: false, + loading: false, + error: null, +}) + +interface Entry { + sessions: Session[] + cursor: string | null + exhausted: boolean + ready: boolean + fetchedAt: number + loading: Promise | null + error: Error | null + /** 拉取期间收到的增量(整页替换后重放,避免刚创建的会话被覆盖掉) */ + pending: Mutation[] + snapshot: SessionIndexSnapshot +} + +type Mutation = + | { type: 'upsert'; session: Session } + | { type: 'patch'; sessionId: string; patch: Partial } + | { type: 'remove'; sessionId: string } + +type Listener = () => void + +function updatedAt(session: Session): number { + return session.time?.updated ?? session.time?.created ?? 0 +} + +/** 根会话、未归档才进索引 */ +function isIndexable(session: Session): boolean { + return !session.parentID && typeof session.time?.archived !== 'number' +} + +function sortSessions(sessions: Session[]): Session[] { + return [...sessions].sort((a, b) => { + const diff = updatedAt(b) - updatedAt(a) + if (diff !== 0) return diff + return a.id < b.id ? -1 : a.id > b.id ? 1 : 0 + }) +} + +/** 按 id 去重(同 id 后出现的为准),再统一排序 */ +function normalize(sessions: Session[]): Session[] { + const byId = new Map() + for (const session of sessions) { + if (!isIndexable(session)) continue + byId.set(session.id, session) + } + return sortSessions([...byId.values()]) +} + +class SessionIndexStore { + private entries = new Map() + private listeners = new Set() + private subscriptions = new Map void>() + /** 单会话回读去重:多个列表同时收到 created/移动事件只打一次 getSession */ + private refreshing = new Map>() + + // ============================================ + // 订阅(useSyncExternalStore) + // ============================================ + + subscribe = (listener: Listener): (() => void) => { + this.listeners.add(listener) + return () => { + this.listeners.delete(listener) + } + } + + getSnapshot = (serverId: string): SessionIndexSnapshot => { + return this.entries.get(serverId)?.snapshot ?? EMPTY_SNAPSHOT + } + + // ============================================ + // 拉取 + // ============================================ + + /** + * 确保索引可用。30s 内命中缓存直接返回;并发调用共享同一个请求。 + */ + ensure(serverId: string, options: { force?: boolean } = {}): Promise { + this.ensureSubscription(serverId) + const entry = this.entries.get(serverId) + if (entry?.loading) return entry.loading + if (!options.force && entry?.ready && Date.now() - entry.fetchedAt < TTL_MS) { + return Promise.resolve() + } + return this.fetchPage(serverId, null) + } + + /** 翻下一页(列表滚到底时调用) */ + loadMore(serverId: string): Promise { + this.ensureSubscription(serverId) + const entry = this.entries.get(serverId) + if (!entry) return this.ensure(serverId) + if (entry.loading) return entry.loading + if (entry.exhausted || !entry.cursor) return Promise.resolve() + return this.fetchPage(serverId, entry.cursor) + } + + // ============================================ + // 增量更新(事件 / 单会话回读) + // ============================================ + + /** 回读单个会话并写回索引(created / forked / moved) */ + refreshSession(serverId: string, sessionId: string): Promise { + const key = `${serverId}\0${sessionId}` + const existing = this.refreshing.get(key) + if (existing) return existing + + const request = getSession(sessionId, undefined, serverId) + .then(session => { + this.upsert(serverId, session) + }) + .catch(() => { + // 回读失败:整页重拉一次兜底(和旧实现「回读失败退回整表刷新」一致) + void this.ensure(serverId, { force: true }) + }) + .finally(() => { + this.refreshing.delete(key) + }) + + this.refreshing.set(key, request) + return request + } + + upsert(serverId: string, session: Session): void { + this.mutate(serverId, { type: 'upsert', session }) + } + + patch(serverId: string, sessionId: string, patch: Partial): void { + this.mutate(serverId, { type: 'patch', sessionId, patch }) + } + + remove(serverId: string, sessionId: string): void { + this.mutate(serverId, { type: 'remove', sessionId }) + } + + /** 测试用:清空全部索引与订阅 */ + reset(): void { + for (const unsubscribe of this.subscriptions.values()) unsubscribe() + this.subscriptions.clear() + this.refreshing.clear() + this.entries.clear() + this.notify() + } + + // ============================================ + // 内部 + // ============================================ + + private mutableEntry(serverId: string): Entry { + const existing = this.entries.get(serverId) + if (existing) return existing + const entry: Entry = { + sessions: [], + cursor: null, + exhausted: true, + ready: false, + fetchedAt: 0, + loading: null, + error: null, + pending: [], + snapshot: EMPTY_SNAPSHOT, + } + this.entries.set(serverId, entry) + return entry + } + + /** + * 增量入口:拉取进行中先排队,等整页落地后重放。 + * 否则「刷新第一页」会用旧快照覆盖掉刚创建的会话。 + */ + private mutate(serverId: string, mutation: Mutation): void { + const entry = this.entries.get(serverId) + // 索引还没加载过:没有可改的东西,等 ensure 拉回来自然包含 + if (!entry) return + if (entry.loading) { + entry.pending.push(mutation) + return + } + this.applyMutation(entry, mutation) + this.commit(entry) + } + + private applyMutation(entry: Entry, mutation: Mutation): void { + if (mutation.type === 'upsert') { + const { session } = mutation + const rest = entry.sessions.filter(item => item.id !== session.id) + if (isIndexable(session)) rest.push(session) + entry.sessions = normalize(rest) + return + } + + if (mutation.type === 'patch') { + const index = entry.sessions.findIndex(session => session.id === mutation.sessionId) + if (index === -1) return + const next = [...entry.sessions] + next[index] = { ...next[index], ...mutation.patch } + entry.sessions = normalize(next) + return + } + + const next = entry.sessions.filter(session => session.id !== mutation.sessionId) + if (next.length !== entry.sessions.length) entry.sessions = next + } + + private fetchPage(serverId: string, cursor: string | null): Promise { + const entry = this.mutableEntry(serverId) + // 已有数据时刷新不清空:stale-while-revalidate + const request = (async () => { + // 只有首屏值得重试(启动早于服务端就绪是常态); + // 续页失败就让用户再点一次「显示更多」,别在后台反复打 + const delays = cursor ? [] : RETRY_DELAYS_MS + // 首屏自动续页:一次多拉几页,避免别的目录把第一页占满 + const maxPages = cursor ? 1 : AUTO_PAGES + + for (let attempt = 0; ; attempt++) { + try { + let nextCursor = cursor + let collected: Session[] = cursor ? [...entry.sessions] : [] + let pages = 0 + let sampleDirectory: string | undefined + + for (;;) { + const page = await listSessionsPage( + { + parentID: null, + order: 'desc', + limit: PAGE_LIMIT, + ...(nextCursor ? { cursor: nextCursor } : {}), + }, + serverId, + ) + // 期间被 reset / 重新 ensure 顶掉:丢弃这次结果 + if (this.entries.get(serverId) !== entry) return + sampleDirectory ??= page.data[0]?.location?.directory + collected = [...collected, ...page.data] + nextCursor = page.next + pages += 1 + + // 首屏第一页先落地:大库要翻第二页时,用户不必等第二页回来才看到列表 + if (!cursor && pages === 1) { + entry.sessions = normalize(collected) + entry.cursor = nextCursor + entry.exhausted = !nextCursor + entry.ready = true + entry.error = null + entry.fetchedAt = Date.now() + if (sampleDirectory) autoDetectPathStyle(sampleDirectory, serverId) + this.commit(entry) + } + + if (!nextCursor || pages >= maxPages || collected.length >= MAX_SESSIONS) break + } + + entry.sessions = normalize(collected) + entry.cursor = nextCursor + entry.exhausted = !nextCursor || entry.sessions.length >= MAX_SESSIONS + entry.ready = true + entry.error = null + entry.fetchedAt = Date.now() + // 拉取期间排队的增量现在重放(整页替换会覆盖它们) + for (const mutation of entry.pending) this.applyMutation(entry, mutation) + entry.pending = [] + return + } catch (error) { + if (this.entries.get(serverId) !== entry) return + if (attempt >= delays.length) { + // 失败也要把排队增量落下来,别把用户刚做的操作丢了 + for (const mutation of entry.pending) this.applyMutation(entry, mutation) + entry.pending = [] + entry.error = error instanceof Error ? error : new Error('Failed to fetch sessions') + return + } + await new Promise(resolve => { + setTimeout(resolve, delays[attempt]) + }) + if (this.entries.get(serverId) !== entry) return + } + } + })() + + entry.loading = request + this.commit(entry) + void request.finally(() => { + if (entry.loading === request) entry.loading = null + this.commit(entry) + }) + return request + } + + private commit(entry: Entry): void { + entry.snapshot = { + sessions: entry.sessions, + hasMore: !entry.exhausted, + ready: entry.ready, + loading: entry.loading !== null, + error: entry.error, + } + this.notify() + } + + private notify(): void { + for (const listener of this.listeners) listener() + } + + /** + * 索引自己的事件订阅:列表层不再各订一份,新增/改名/删除只处理一次。 + * 连接是引用计数的,同一服务器已有订阅时不会新建传输。 + */ + private ensureSubscription(serverId: string): void { + if (this.subscriptions.has(serverId)) return + const unsubscribe = subscribeToServerEvents(serverId, { + onSessionCreated: data => { + // 子会话不进根索引;父会话的关系由 childSessionStore 处理 + if (data.parentID) return + void this.refreshSession(serverId, data.sessionID) + }, + onSessionForked: data => { + void this.refreshSession(serverId, data.sessionID) + }, + onSessionRenamed: data => { + this.patch(serverId, data.sessionID, { title: data.title }) + }, + onSessionDeleted: data => { + this.remove(serverId, data.sessionID) + }, + onSessionMoved: data => { + // 目录变了:回读后按新 location 落到对应目录 + void this.refreshSession(serverId, data.sessionID) + }, + onServerConnected: () => { + // 首次连上(本地 serve 刚拉起)时补一次:启动期的重试可能已经耗尽 + const entry = this.entries.get(serverId) + if (!entry?.ready || entry.error) void this.ensure(serverId) + }, + onReconnected: reason => { + if (reason === 'server-switch') return + // 断连期间的新增/删除都丢了:直接重拉第一页,旧数据保留到新数据到达 + void this.ensure(serverId, { force: true }) + }, + }) + this.subscriptions.set(serverId, unsubscribe) + } +} + +export const sessionIndexStore = new SessionIndexStore() From eeeee4f9617356a05ab874f4844f4edc8e723ef9 Mon Sep 17 00:00:00 2001 From: lehhair Date: Fri, 23 Oct 2026 12:31:46 +0800 Subject: [PATCH 16/67] =?UTF-8?q?fix(session-list):=20=E5=B1=95=E5=BC=80?= =?UTF-8?q?=E9=87=8F=E8=B7=9F=E9=9A=8F=E7=9B=AE=E5=BD=95=EF=BC=8C=E5=88=87?= =?UTF-8?q?=E8=B5=B0=E5=86=8D=E5=88=87=E5=9B=9E=E6=9D=A5=E4=B8=8D=E8=B7=B3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 「显示更多」过去是一个全局 limit,切目录那一帧会先用旧展开量渲染新目录, 再被 effect 收回第一页,看起来先多出一截又消失。 把展开量绑定到「服务器 + 目录 + 搜索词」,切过去直接用第一页, 不再需要重置 effect。 --- src/contexts/SessionContext.tsx | 21 ++++++++++++--------- src/hooks/useSessions.test.tsx | 27 +++++++++++++++++++++++++++ src/hooks/useSessions.ts | 18 ++++++++++-------- 3 files changed, 49 insertions(+), 17 deletions(-) diff --git a/src/contexts/SessionContext.tsx b/src/contexts/SessionContext.tsx index 2616e862e..c2254d7a1 100644 --- a/src/contexts/SessionContext.tsx +++ b/src/contexts/SessionContext.tsx @@ -35,19 +35,22 @@ export function SessionProvider({ children }: { children: ReactNode }) { ) const [search, setSearch] = useState('') - const [limit, setLimit] = useState(LIST_PAGE_SIZE) const [isLoadingMore, setIsLoadingMore] = useState(false) + // 「显示更多」的展开量跟目录/搜索词绑定:切过去时从第一页开始,不会把 + // 上一个目录的展开量短暂套到新目录上(会出现多显示一截再收回的跳动) + const listKey = `${currentDirectory ?? ''}\0${search}` + const [slice, setSlice] = useState({ key: listKey, limit: LIST_PAGE_SIZE }) + const limit = slice.key === listKey ? slice.limit : LIST_PAGE_SIZE + + const grow = useCallback(() => { + setSlice({ key: listKey, limit: limit + LIST_PAGE_SIZE }) + }, [listKey, limit]) // 挂载 / 切服务器:确保索引可用(30s 内命中则不请求) useEffect(() => { void sessionIndexStore.ensure(serverId) }, [serverId]) - // 换目录或改搜索词:重新从第一页开始露出 - useEffect(() => { - setLimit(LIST_PAGE_SIZE) - }, [currentDirectory, search]) - const directorySessions = useMemo(() => { if (!currentDirectory) return snapshot.sessions return snapshot.sessions.filter(session => isSameDirectory(currentDirectory, session.location?.directory)) @@ -78,17 +81,17 @@ export function SessionProvider({ children }: { children: ReactNode }) { try { // 本地还有没露出的先露出;本地见底了再向服务端要下一页 if (filteredSessions.length > limit) { - setLimit(current => current + LIST_PAGE_SIZE) + grow() return } if (snapshot.hasMore) { await sessionIndexStore.loadMore(serverId) - setLimit(current => current + LIST_PAGE_SIZE) + grow() } } finally { setIsLoadingMore(false) } - }, [isLoadingMore, hasMore, filteredSessions.length, limit, snapshot.hasMore, serverId]) + }, [isLoadingMore, hasMore, filteredSessions.length, limit, grow, snapshot.hasMore, serverId]) const createSession = useCallback( async (title?: string) => { diff --git a/src/hooks/useSessions.test.tsx b/src/hooks/useSessions.test.tsx index 02bfaf9c3..079e14a95 100644 --- a/src/hooks/useSessions.test.tsx +++ b/src/hooks/useSessions.test.tsx @@ -211,6 +211,33 @@ describe('useSessions', () => { expect(storeMock.upsert).toHaveBeenCalledWith('local', created) }) + it('切换目录后展开量回到第一页,不把上一个目录的「显示更多」带过去', async () => { + storeMock.setSnapshotForTest({ + ready: true, + sessions: Array.from({ length: 8 }, (_, index) => makeSession(`a_${index}`, '/workspace/a')), + }) + + const { result, rerender } = renderHook(({ directory }) => useSessions({ directory, pageSize: 5 }), { + initialProps: { directory: '/workspace/a' }, + }) + + await act(async () => { + await result.current.loadMore() + }) + expect(result.current.sessions).toHaveLength(8) + + storeMock.setSnapshotForTest({ + ready: true, + sessions: [ + ...Array.from({ length: 8 }, (_, index) => makeSession(`a_${index}`, '/workspace/a')), + ...Array.from({ length: 8 }, (_, index) => makeSession(`b_${index}`, '/workspace/b')), + ], + }) + rerender({ directory: '/workspace/b' }) + + expect(result.current.sessions).toHaveLength(5) + }) + it('索引错误原样透出,refresh 走 force', async () => { const error = new Error('down') storeMock.setSnapshotForTest({ ready: false, error }) diff --git a/src/hooks/useSessions.ts b/src/hooks/useSessions.ts index 50f703561..1fc7c891c 100644 --- a/src/hooks/useSessions.ts +++ b/src/hooks/useSessions.ts @@ -72,13 +72,15 @@ export function useSessions(options: UseSessionsOptions = {}): UseSessionsResult ) const [search, setSearch] = useState(initialSearch) - const [limit, setLimit] = useState(pageSize) const [isLoadingMore, setIsLoadingMore] = useState(false) + // 展开量跟「服务器 + 目录 + 搜索词」绑定:切走后不把旧展开量带过去 + const listKey = `${serverKey}\0${normalizedDirectory ?? ''}\0${search}\0${pageSize}` + const [slice, setSlice] = useState({ key: listKey, limit: pageSize }) + const limit = slice.key === listKey ? slice.limit : pageSize - // 目录/搜索/分页大小变化:回到第一页 - useEffect(() => { - setLimit(pageSize) - }, [normalizedDirectory, search, pageSize, serverKey]) + const grow = useCallback(() => { + setSlice({ key: listKey, limit: limit + pageSize }) + }, [listKey, limit, pageSize]) // 懒加载:只有 enabled 的文件夹才触发索引拉取(同一服务器仍然只拉一次) useEffect(() => { @@ -110,17 +112,17 @@ export function useSessions(options: UseSessionsOptions = {}): UseSessionsResult setIsLoadingMore(true) try { if (filteredSessions.length > limit) { - setLimit(current => current + pageSize) + grow() return } if (snapshot.hasMore) { await sessionIndexStore.loadMore(serverKey) - setLimit(current => current + pageSize) + grow() } } finally { setIsLoadingMore(false) } - }, [enabled, isLoadingMore, hasMore, filteredSessions.length, limit, pageSize, snapshot.hasMore, serverKey]) + }, [enabled, isLoadingMore, hasMore, filteredSessions.length, limit, grow, snapshot.hasMore, serverKey]) const refresh = useCallback(async () => { if (!enabled) return From 4b9c41195cde8ed7205c82a49857498287978b4a Mon Sep 17 00:00:00 2001 From: lehhair Date: Fri, 23 Oct 2026 12:44:28 +0800 Subject: [PATCH 17/67] =?UTF-8?q?fix(session-list):=20=E5=BD=93=E5=89=8D?= =?UTF-8?q?=E7=9B=AE=E5=BD=95=E8=A2=AB=E6=8C=A4=E5=87=BA=E7=B4=A2=E5=BC=95?= =?UTF-8?q?=E6=97=B6=E6=8C=89=E7=9B=AE=E5=BD=95=E8=A1=A5=E6=8B=89=E4=B8=80?= =?UTF-8?q?=E6=AC=A1?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 索引只保证最近若干页。某个项目的会话如果都比这些页旧,切过去就是空的, 只能靠反复点「显示更多」碰运气。 现在列表发现「当前目录一条都没有 + 服务端还有页」时,按目录单独问一次 (limit 100),结果并进索引;同一目录 30s 内只补一次,并发调用合并。 这同时兜住服务端在缺省目录时只返回默认 location 的实现差异。 --- src/contexts/SessionContext.test.tsx | 33 +++++++++++++++++ src/contexts/SessionContext.tsx | 9 +++++ src/hooks/useSessions.test.tsx | 14 ++++++++ src/hooks/useSessions.ts | 8 +++++ src/store/sessionIndexStore.test.ts | 45 +++++++++++++++++++++++ src/store/sessionIndexStore.ts | 53 ++++++++++++++++++++++++++++ 6 files changed, 162 insertions(+) diff --git a/src/contexts/SessionContext.test.tsx b/src/contexts/SessionContext.test.tsx index ea8dabde0..41e53de8d 100644 --- a/src/contexts/SessionContext.test.tsx +++ b/src/contexts/SessionContext.test.tsx @@ -22,6 +22,7 @@ const { storeMock, createSessionMock, deleteSessionMock, clearSessionRuntimeStat }, getSnapshot: () => snapshot, ensure: vi.fn(() => Promise.resolve()), + ensureDirectory: vi.fn(() => Promise.resolve()), loadMore: vi.fn(() => Promise.resolve()), remove: vi.fn(), patch: vi.fn(), @@ -120,6 +121,7 @@ describe('SessionProvider', () => { beforeEach(() => { latestContext = null storeMock.ensure.mockClear() + storeMock.ensureDirectory.mockClear() storeMock.loadMore.mockClear() storeMock.remove.mockClear() storeMock.patch.mockClear() @@ -216,6 +218,37 @@ describe('SessionProvider', () => { expect(latestContext?.sessions.map(session => session.id)).toEqual(['ses_a']) }) + it('当前目录在索引里为空且服务端还有页时,按目录兜底补拉', () => { + storeMock.setSnapshotForTest({ + ready: true, + hasMore: true, + sessions: [makeSession('ses_other', '/workspace/other')], + }) + + renderProvider() + + expect(storeMock.ensureDirectory).toHaveBeenCalledWith('local', '/workspace/demo') + }) + + it('索引已到底或目录本身有数据时不补拉', () => { + storeMock.setSnapshotForTest({ + ready: true, + hasMore: false, + sessions: [makeSession('ses_other', '/workspace/other')], + }) + renderProvider() + expect(storeMock.ensureDirectory).not.toHaveBeenCalled() + + act(() => { + storeMock.setSnapshotForTest({ + ready: true, + hasMore: true, + sessions: [makeSession('ses_a', '/workspace/demo')], + }) + }) + expect(storeMock.ensureDirectory).not.toHaveBeenCalled() + }) + it('删除会话:调 API、清运行时状态、清索引', async () => { storeMock.setSnapshotForTest({ ready: true, sessions: [makeSession('ses_a', '/workspace/demo')] }) deleteSessionMock.mockResolvedValue(true) diff --git a/src/contexts/SessionContext.tsx b/src/contexts/SessionContext.tsx index c2254d7a1..1b8c3a5ea 100644 --- a/src/contexts/SessionContext.tsx +++ b/src/contexts/SessionContext.tsx @@ -56,6 +56,15 @@ export function SessionProvider({ children }: { children: ReactNode }) { return snapshot.sessions.filter(session => isSameDirectory(currentDirectory, session.location?.directory)) }, [snapshot.sessions, currentDirectory]) + // 当前目录在索引里一条都没有、而服务端还有没拉到的页:按目录兜底补一次。 + // 索引只保证最近若干页,旧项目可能整段被挤出;补拉后就有数据了。 + const needsDirectoryFetch = + !!currentDirectory && snapshot.ready && snapshot.hasMore && directorySessions.length === 0 + useEffect(() => { + if (!needsDirectoryFetch || !currentDirectory) return + void sessionIndexStore.ensureDirectory(serverId, currentDirectory) + }, [needsDirectoryFetch, currentDirectory, serverId]) + const filteredSessions = useMemo(() => { const term = search.trim().toLowerCase() if (!term) return directorySessions diff --git a/src/hooks/useSessions.test.tsx b/src/hooks/useSessions.test.tsx index 079e14a95..6b19e198a 100644 --- a/src/hooks/useSessions.test.tsx +++ b/src/hooks/useSessions.test.tsx @@ -20,6 +20,7 @@ const { storeMock, createSessionMock, deleteSessionMock, unpinMock } = vi.hoiste }, getSnapshot: () => snapshot, ensure: vi.fn<(serverId: string, options?: { force?: boolean }) => Promise>(() => Promise.resolve()), + ensureDirectory: vi.fn<(serverId: string, directory: string) => Promise>(() => Promise.resolve()), loadMore: vi.fn(() => Promise.resolve()), remove: vi.fn(), patch: vi.fn(), @@ -86,6 +87,7 @@ function makeSession(id: string, directory = '/workspace/demo', updated = 2): Se describe('useSessions', () => { beforeEach(() => { storeMock.ensure.mockClear() + storeMock.ensureDirectory.mockClear() storeMock.loadMore.mockClear() storeMock.remove.mockClear() storeMock.patch.mockClear() @@ -107,6 +109,18 @@ describe('useSessions', () => { expect(storeMock.ensure).toHaveBeenCalledWith('local') }) + it('目录在索引里为空且服务端还有页时,按目录补拉一次', () => { + storeMock.setSnapshotForTest({ + ready: true, + hasMore: true, + sessions: [makeSession('ses_other', '/workspace/other')], + }) + + renderHook(() => useSessions({ directory: '/workspace/demo' })) + + expect(storeMock.ensureDirectory).toHaveBeenCalledWith('local', '/workspace/demo') + }) + it('按目录从共享索引过滤,php 风格尾斜杠不影响匹配', () => { storeMock.setSnapshotForTest({ ready: true, diff --git a/src/hooks/useSessions.ts b/src/hooks/useSessions.ts index 1fc7c891c..36bb6aa97 100644 --- a/src/hooks/useSessions.ts +++ b/src/hooks/useSessions.ts @@ -93,6 +93,14 @@ export function useSessions(options: UseSessionsOptions = {}): UseSessionsResult return snapshot.sessions.filter(session => isSameDirectory(normalizedDirectory, session.location?.directory)) }, [snapshot.sessions, normalizedDirectory]) + // 当前目录在索引里一条都没有、而服务端还有没拉到的页:按目录兜底补一次 + const needsDirectoryFetch = + enabled && !!normalizedDirectory && snapshot.ready && snapshot.hasMore && directorySessions.length === 0 + useEffect(() => { + if (!needsDirectoryFetch || !normalizedDirectory) return + void sessionIndexStore.ensureDirectory(serverKey, normalizedDirectory) + }, [needsDirectoryFetch, normalizedDirectory, serverKey]) + const filteredSessions = useMemo(() => { const term = search.trim().toLowerCase() if (!term) return directorySessions diff --git a/src/store/sessionIndexStore.test.ts b/src/store/sessionIndexStore.test.ts index 615683eb7..dbda681af 100644 --- a/src/store/sessionIndexStore.test.ts +++ b/src/store/sessionIndexStore.test.ts @@ -261,4 +261,49 @@ describe('sessionIndexStore', () => { expect(subscribeMock).toHaveBeenCalledTimes(1) }) + + it('目录兜底补拉:把被挤出全局索引的目录并回来,30s 内不重复补', async () => { + listSessionsPageMock.mockResolvedValueOnce(page([session('ses_recent')])) + await sessionIndexStore.ensure(SERVER) + + listSessionsPageMock.mockResolvedValueOnce(page([session('ses_old')])) + await sessionIndexStore.ensureDirectory(SERVER, '/workspace/demo') + + expect(listSessionsPageMock).toHaveBeenLastCalledWith( + { directory: '/workspace/demo', parentID: null, order: 'desc', limit: 100 }, + SERVER, + ) + expect(sessionIndexStore.getSnapshot(SERVER).sessions.map(item => item.id).sort()).toEqual([ + 'ses_old', + 'ses_recent', + ]) + + // TTL 内再挂载一次(切目录来回)不再请求 + await sessionIndexStore.ensureDirectory(SERVER, '/workspace/demo') + expect(listSessionsPageMock).toHaveBeenCalledTimes(2) + }) + + it('目录补拉与首屏并发时共享请求,目录之间互不影响', async () => { + let resolveFirst!: (value: { data: Session[]; next: string | null }) => void + listSessionsPageMock.mockImplementationOnce( + () => + new Promise(resolve => { + resolveFirst = resolve + }), + ) + const first = sessionIndexStore.ensure(SERVER) + + listSessionsPageMock.mockResolvedValueOnce(page([session('ses_old')])) + const dirA = sessionIndexStore.ensureDirectory(SERVER, '/workspace/a') + const dirB = sessionIndexStore.ensureDirectory(SERVER, '/workspace/a') + resolveFirst(page([session('ses_recent')])) + await Promise.all([first, dirA, dirB]) + + // 首屏一页 + 目录一页(同一个目录的并发调用合并) + expect(listSessionsPageMock).toHaveBeenCalledTimes(2) + expect(sessionIndexStore.getSnapshot(SERVER).sessions.map(item => item.id).sort()).toEqual([ + 'ses_old', + 'ses_recent', + ]) + }) }) diff --git a/src/store/sessionIndexStore.ts b/src/store/sessionIndexStore.ts index a80f56f13..6c0ff7801 100644 --- a/src/store/sessionIndexStore.ts +++ b/src/store/sessionIndexStore.ts @@ -30,6 +30,8 @@ const PAGE_LIMIT = 500 const AUTO_PAGES = 2 /** 兜底上限:极端情况下也不无限翻页 */ const MAX_SESSIONS = 2_000 +/** 目录级补拉的条数:只用来把「被挤出全局索引」的那个目录补出来 */ +const DIRECTORY_LIMIT = 100 /** 首屏失败的重试退避(启动可能早于本地服务端就绪) */ const RETRY_DELAYS_MS = [500, 1_500, 3_000] @@ -81,6 +83,11 @@ function isIndexable(session: Session): boolean { return !session.parentID && typeof session.time?.archived !== 'number' } +/** 目录键:分隔符与末尾斜杠归一化,避免同一目录重复补拉 */ +function normalizeDirectoryKey(directory: string): string { + return directory.replace(/\\/g, '/').replace(/\/+$/, '') +} + function sortSessions(sessions: Session[]): Session[] { return [...sessions].sort((a, b) => { const diff = updatedAt(b) - updatedAt(a) @@ -105,6 +112,10 @@ class SessionIndexStore { private subscriptions = new Map void>() /** 单会话回读去重:多个列表同时收到 created/移动事件只打一次 getSession */ private refreshing = new Map>() + /** 目录级补拉的 TTL(key = serverId\0directory) */ + private directoryFetchedAt = new Map() + /** 目录级补拉去重(同一目录并发只打一次) */ + private directoryLoading = new Map>() // ============================================ // 订阅(useSyncExternalStore) @@ -148,6 +159,46 @@ class SessionIndexStore { return this.fetchPage(serverId, entry.cursor) } + /** + * 目录兜底补拉。 + * + * 全局索引只保证最近若干页;某个项目的会话如果都比这些页旧,切过去会是空的。 + * 这时按目录单独问一次(最多 DIRECTORY_LIMIT 条),结果直接并进索引。 + * + * 顺带兜住「服务端在缺省目录时只返回默认 location」的实现差异:真有这种 + * 服务端,每个目录第一次挂载都会走这里,列表仍然是对的。 + */ + ensureDirectory(serverId: string, directory: string): Promise { + this.ensureSubscription(serverId) + const dir = normalizeDirectoryKey(directory) + if (!dir) return Promise.resolve() + + const key = `${serverId}\0${dir}` + const loading = this.directoryLoading.get(key) + if (loading) return loading + const fetchedAt = this.directoryFetchedAt.get(key) + if (fetchedAt !== undefined && Date.now() - fetchedAt < TTL_MS) return Promise.resolve() + + const request = (async () => { + try { + const page = await listSessionsPage( + { directory: dir, parentID: null, order: 'desc', limit: DIRECTORY_LIMIT }, + serverId, + ) + // 走 mutate 而不是直接改:整页刷新在飞时先排队,落地后重放 + for (const session of page.data) this.mutate(serverId, { type: 'upsert', session }) + this.directoryFetchedAt.set(key, Date.now()) + } catch { + // 补拉失败不记 TTL:下次挂载还有机会再试 + } finally { + this.directoryLoading.delete(key) + } + })() + + this.directoryLoading.set(key, request) + return request + } + // ============================================ // 增量更新(事件 / 单会话回读) // ============================================ @@ -191,6 +242,8 @@ class SessionIndexStore { for (const unsubscribe of this.subscriptions.values()) unsubscribe() this.subscriptions.clear() this.refreshing.clear() + this.directoryFetchedAt.clear() + this.directoryLoading.clear() this.entries.clear() this.notify() } From a5fee5579a42b7914bdd59fb6691f4c8aedf3020 Mon Sep 17 00:00:00 2001 From: lehhair Date: Fri, 23 Oct 2026 12:46:20 +0800 Subject: [PATCH 18/67] =?UTF-8?q?perf(session-list):=20=E9=A6=96=E5=B1=8F?= =?UTF-8?q?=E5=8F=AA=E6=8B=89=E4=B8=80=E9=A1=B5=20200=20=E6=9D=A1=EF=BC=8C?= =?UTF-8?q?=E4=B8=8D=E5=86=8D=E8=87=AA=E5=8A=A8=E7=BB=AD=E9=A1=B5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 首屏过去最多拉两页 × 500 条,公网/慢链路上光列表就要等两份大响应, 而用户第一眼只看到 30 条。 现在首屏只拉一页 200 条;目录被挤出索引由 ensureDirectory 兜底, 更旧的会话靠「显示更多」按 cursor 续。少了自动续页,也少了一次 「必须等第二页回来」的等待。 --- src/store/sessionIndexStore.test.ts | 28 +++++------ src/store/sessionIndexStore.ts | 74 +++++++++++------------------ 2 files changed, 39 insertions(+), 63 deletions(-) diff --git a/src/store/sessionIndexStore.test.ts b/src/store/sessionIndexStore.test.ts index dbda681af..d53666e0d 100644 --- a/src/store/sessionIndexStore.test.ts +++ b/src/store/sessionIndexStore.test.ts @@ -74,7 +74,7 @@ describe('sessionIndexStore', () => { await sessionIndexStore.ensure(SERVER) - expect(listSessionsPageMock).toHaveBeenCalledWith({ parentID: null, order: 'desc', limit: 500 }, SERVER) + expect(listSessionsPageMock).toHaveBeenCalledWith({ parentID: null, order: 'desc', limit: 200 }, SERVER) expect(sessionIndexStore.getSnapshot(SERVER).sessions.map(item => item.id)).toEqual(['ses_new', 'ses_old']) expect(sessionIndexStore.getSnapshot(SERVER).ready).toBe(true) }) @@ -104,36 +104,30 @@ describe('sessionIndexStore', () => { expect(sessionIndexStore.getSnapshot(SERVER).sessions.map(item => item.id)).toEqual(['ses_b']) }) - it('cursor 续页只追加新的一页,到底后 hasMore=false', async () => { - // 首轮自动翻两页(page1 → page2),第三页留给「显示更多」 - listSessionsPageMock - .mockResolvedValueOnce(page([session('ses_1')], 'cursor-2')) - .mockResolvedValueOnce(page([session('ses_2')], 'cursor-3')) + it('首屏只拉一页,更多靠「显示更多」按 cursor 续页', async () => { + listSessionsPageMock.mockResolvedValueOnce(page([session('ses_1')], 'cursor-2')) await sessionIndexStore.ensure(SERVER) - expect(listSessionsPageMock).toHaveBeenCalledTimes(2) + expect(listSessionsPageMock).toHaveBeenCalledTimes(1) expect(sessionIndexStore.getSnapshot(SERVER).hasMore).toBe(true) - listSessionsPageMock.mockResolvedValueOnce(page([session('ses_3')])) + listSessionsPageMock.mockResolvedValueOnce(page([session('ses_2')])) await sessionIndexStore.loadMore(SERVER) expect(listSessionsPageMock).toHaveBeenLastCalledWith( - { parentID: null, order: 'desc', limit: 500, cursor: 'cursor-3' }, + { parentID: null, order: 'desc', limit: 200, cursor: 'cursor-2' }, SERVER, ) - expect(sessionIndexStore.getSnapshot(SERVER).sessions.map(item => item.id)).toEqual([ - 'ses_1', - 'ses_2', - 'ses_3', - ]) + expect(sessionIndexStore.getSnapshot(SERVER).sessions.map(item => item.id)).toEqual(['ses_1', 'ses_2']) expect(sessionIndexStore.getSnapshot(SERVER).hasMore).toBe(false) }) it('续页去重(游标重复时不会出现重复行)', async () => { - listSessionsPageMock - .mockResolvedValueOnce(page([session('ses_1')], 'cursor-2')) - .mockResolvedValueOnce(page([session('ses_1'), session('ses_2')], 'cursor-3')) + listSessionsPageMock.mockResolvedValueOnce(page([session('ses_1')], 'cursor-2')) await sessionIndexStore.ensure(SERVER) + listSessionsPageMock.mockResolvedValueOnce(page([session('ses_1'), session('ses_2')], 'cursor-3')) + await sessionIndexStore.loadMore(SERVER) + listSessionsPageMock.mockResolvedValueOnce(page([session('ses_2')], null)) await sessionIndexStore.loadMore(SERVER) diff --git a/src/store/sessionIndexStore.ts b/src/store/sessionIndexStore.ts index 6c0ff7801..0b197a5f7 100644 --- a/src/store/sessionIndexStore.ts +++ b/src/store/sessionIndexStore.ts @@ -8,13 +8,17 @@ // 官方 app 的做法是拉一份「根会话索引」(`loadHomeSessionIndex`), // 在本地按目录分组、按时间切片(home/sessions/index.ts)。这里做同一件事: // -// - `ensure(serverId)` 拉首页(limit 500,首轮最多自动翻两页),30s 内复用 +// - `ensure(serverId)` 拉首页(limit 200),30s 内复用 // - 各列表从 `getSnapshot(serverId)` 里按目录过滤、按需切片,零额外请求 +// - 某个目录被挤出索引时 `ensureDirectory` 按目录补一次(见下) // - SSE 增量(新增/重命名/删除/移动)直接写进索引,所有列表同步更新 // - 重连直接重拉第一页,旧数据保留到新数据到达,列表不会闪一下空态 // // 索引只存根会话(parentID 为空、未归档):子会话由 childSessionStore // 管理,不属于侧栏列表。 +// +// 不传 `directory` 表示「全服务器」:上游 `session.list` 的 `ListAllInput` +// 就是不带 location 的那支(packages/core/src/session/store.ts)。 // ============================================ import { getSession, listSessionsPage } from '../api/session' @@ -24,10 +28,8 @@ import type { Session } from '../types/api/session' /** 与官方 home 列表的 staleTime 对齐:30s 内重复挂载不再请求 */ const TTL_MS = 30_000 -/** 单页条数:常规服务器一页拉完,大库再按 cursor 续页 */ -const PAGE_LIMIT = 500 -/** 首轮最多自动翻几页:保证「别的目录把前 500 条占满」时当前目录仍有数据 */ -const AUTO_PAGES = 2 +/** 单页条数:首屏一页就要出内容,大库靠 cursor 续页 / 目录补拉 */ +const PAGE_LIMIT = 200 /** 兜底上限:极端情况下也不无限翻页 */ const MAX_SESSIONS = 2_000 /** 目录级补拉的条数:只用来把「被挤出全局索引」的那个目录补出来 */ @@ -315,57 +317,36 @@ class SessionIndexStore { // 只有首屏值得重试(启动早于服务端就绪是常态); // 续页失败就让用户再点一次「显示更多」,别在后台反复打 const delays = cursor ? [] : RETRY_DELAYS_MS - // 首屏自动续页:一次多拉几页,避免别的目录把第一页占满 - const maxPages = cursor ? 1 : AUTO_PAGES for (let attempt = 0; ; attempt++) { try { - let nextCursor = cursor - let collected: Session[] = cursor ? [...entry.sessions] : [] - let pages = 0 - let sampleDirectory: string | undefined - - for (;;) { - const page = await listSessionsPage( - { - parentID: null, - order: 'desc', - limit: PAGE_LIMIT, - ...(nextCursor ? { cursor: nextCursor } : {}), - }, - serverId, - ) - // 期间被 reset / 重新 ensure 顶掉:丢弃这次结果 - if (this.entries.get(serverId) !== entry) return - sampleDirectory ??= page.data[0]?.location?.directory - collected = [...collected, ...page.data] - nextCursor = page.next - pages += 1 - - // 首屏第一页先落地:大库要翻第二页时,用户不必等第二页回来才看到列表 - if (!cursor && pages === 1) { - entry.sessions = normalize(collected) - entry.cursor = nextCursor - entry.exhausted = !nextCursor - entry.ready = true - entry.error = null - entry.fetchedAt = Date.now() - if (sampleDirectory) autoDetectPathStyle(sampleDirectory, serverId) - this.commit(entry) - } - - if (!nextCursor || pages >= maxPages || collected.length >= MAX_SESSIONS) break - } + const page = await listSessionsPage( + { + parentID: null, + order: 'desc', + limit: PAGE_LIMIT, + ...(cursor ? { cursor } : {}), + }, + serverId, + ) + // 期间被 reset / 重新 ensure 顶掉:丢弃这次结果 + if (this.entries.get(serverId) !== entry) return - entry.sessions = normalize(collected) - entry.cursor = nextCursor - entry.exhausted = !nextCursor || entry.sessions.length >= MAX_SESSIONS + // 首屏整页替换,续页追加;normalize 按 id 去重并统一排序 + entry.sessions = normalize([...(cursor ? entry.sessions : []), ...page.data]) + entry.cursor = page.next + entry.exhausted = !page.next || entry.sessions.length >= MAX_SESSIONS entry.ready = true entry.error = null entry.fetchedAt = Date.now() + + const sampleDirectory = page.data[0]?.location?.directory + if (!cursor && sampleDirectory) autoDetectPathStyle(sampleDirectory, serverId) + // 拉取期间排队的增量现在重放(整页替换会覆盖它们) for (const mutation of entry.pending) this.applyMutation(entry, mutation) entry.pending = [] + this.commit(entry) return } catch (error) { if (this.entries.get(serverId) !== entry) return @@ -374,6 +355,7 @@ class SessionIndexStore { for (const mutation of entry.pending) this.applyMutation(entry, mutation) entry.pending = [] entry.error = error instanceof Error ? error : new Error('Failed to fetch sessions') + this.commit(entry) return } await new Promise(resolve => { From ff89068cbda07ffd55923806ede4931fda17f1a1 Mon Sep 17 00:00:00 2001 From: lehhair Date: Fri, 23 Oct 2026 12:48:22 +0800 Subject: [PATCH 19/67] =?UTF-8?q?fix(session-list):=20=E7=BF=BB=E9=A1=B5?= =?UTF-8?q?=E4=BB=A5=E5=BD=93=E5=89=8D=E7=9B=AE=E5=BD=95=E4=B8=BA=E5=87=86?= =?UTF-8?q?=EF=BC=8C=E5=8E=BB=E6=8E=89=202000=20=E6=9D=A1=E7=A1=AC?= =?UTF-8?q?=E4=B8=8A=E9=99=90?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 索引过去到 2000 条就假装到底,更旧的会话没有入口;而且服务端翻页是 全局的,点一次「显示更多」可能一条都不属于当前目录,看起来像没反应。 现在 hasMore 只看服务端游标,点多少翻多少;每次点击最多连翻三页, 直到当前目录出现新行或服务端到底。当前目录为空时另由 ensureDirectory 按目录补拉。 --- src/contexts/SessionContext.test.tsx | 30 +++++++++++++++++++++++++++- src/contexts/SessionContext.tsx | 24 +++++++++++++++++++--- src/hooks/useSessions.ts | 25 ++++++++++++++++++++--- src/store/sessionIndexStore.test.ts | 18 +++++++++++++++++ src/store/sessionIndexStore.ts | 5 ++--- 5 files changed, 92 insertions(+), 10 deletions(-) diff --git a/src/contexts/SessionContext.test.tsx b/src/contexts/SessionContext.test.tsx index 41e53de8d..1fd897622 100644 --- a/src/contexts/SessionContext.test.tsx +++ b/src/contexts/SessionContext.test.tsx @@ -122,7 +122,8 @@ describe('SessionProvider', () => { latestContext = null storeMock.ensure.mockClear() storeMock.ensureDirectory.mockClear() - storeMock.loadMore.mockClear() + storeMock.loadMore.mockReset() + storeMock.loadMore.mockImplementation(() => Promise.resolve()) storeMock.remove.mockClear() storeMock.patch.mockClear() storeMock.upsert.mockClear() @@ -203,6 +204,33 @@ describe('SessionProvider', () => { expect(storeMock.loadMore).toHaveBeenCalledWith('local') }) + it('「显示更多」连翻到当前目录出现新行就停', async () => { + storeMock.setSnapshotForTest({ + ready: true, + hasMore: true, + sessions: [makeSession('ses_other', '/workspace/other')], + }) + renderProvider() + + let pages = 0 + storeMock.loadMore.mockImplementation(async () => { + pages += 1 + if (pages < 2) return + storeMock.setSnapshotForTest({ + ready: true, + hasMore: true, + sessions: [makeSession('ses_other', '/workspace/other'), makeSession('ses_b', '/workspace/demo')], + }) + }) + + await act(async () => { + await latestContext!.loadMore() + }) + + expect(storeMock.loadMore).toHaveBeenCalledTimes(2) + expect(latestContext?.sessions.map(session => session.id)).toEqual(['ses_b']) + }) + it('切换目录不重新拉索引', () => { storeMock.setSnapshotForTest({ ready: true, sessions: [makeSession('ses_a', '/workspace/demo')] }) renderProvider() diff --git a/src/contexts/SessionContext.tsx b/src/contexts/SessionContext.tsx index 1b8c3a5ea..23096099c 100644 --- a/src/contexts/SessionContext.tsx +++ b/src/contexts/SessionContext.tsx @@ -93,14 +93,32 @@ export function SessionProvider({ children }: { children: ReactNode }) { grow() return } - if (snapshot.hasMore) { + if (!snapshot.hasMore) return + // 服务端翻页是全局的:某一页可能一条都不属于当前目录。 + // 以「当前目录有没有变多」为准,最多连翻三页,别让点击看起来没反应。 + const before = filteredSessions.length + for (let page = 0; page < 3; page++) { await sessionIndexStore.loadMore(serverId) - grow() + const latest = sessionIndexStore.getSnapshot(serverId) + const inDirectory = currentDirectory + ? latest.sessions.filter(item => isSameDirectory(currentDirectory, item.location?.directory)).length + : latest.sessions.length + if (inDirectory > before || !latest.hasMore) break } + grow() } finally { setIsLoadingMore(false) } - }, [isLoadingMore, hasMore, filteredSessions.length, limit, grow, snapshot.hasMore, serverId]) + }, [ + isLoadingMore, + hasMore, + filteredSessions.length, + limit, + grow, + snapshot.hasMore, + serverId, + currentDirectory, + ]) const createSession = useCallback( async (title?: string) => { diff --git a/src/hooks/useSessions.ts b/src/hooks/useSessions.ts index 36bb6aa97..5e2bc406f 100644 --- a/src/hooks/useSessions.ts +++ b/src/hooks/useSessions.ts @@ -123,14 +123,33 @@ export function useSessions(options: UseSessionsOptions = {}): UseSessionsResult grow() return } - if (snapshot.hasMore) { + if (!snapshot.hasMore) return + // 服务端翻页是全局的:某一页可能一条都不属于当前目录。 + // 以「当前目录有没有变多」为准,最多连翻三页,别让点击看起来没反应。 + const before = filteredSessions.length + for (let page = 0; page < 3; page++) { await sessionIndexStore.loadMore(serverKey) - grow() + const latest = sessionIndexStore.getSnapshot(serverKey) + const inDirectory = normalizedDirectory + ? latest.sessions.filter(item => isSameDirectory(normalizedDirectory, item.location?.directory)).length + : latest.sessions.length + if (inDirectory > before || !latest.hasMore) break } + grow() } finally { setIsLoadingMore(false) } - }, [enabled, isLoadingMore, hasMore, filteredSessions.length, limit, grow, snapshot.hasMore, serverKey]) + }, [ + enabled, + isLoadingMore, + hasMore, + filteredSessions.length, + limit, + grow, + snapshot.hasMore, + serverKey, + normalizedDirectory, + ]) const refresh = useCallback(async () => { if (!enabled) return diff --git a/src/store/sessionIndexStore.test.ts b/src/store/sessionIndexStore.test.ts index d53666e0d..daff05ea0 100644 --- a/src/store/sessionIndexStore.test.ts +++ b/src/store/sessionIndexStore.test.ts @@ -104,6 +104,24 @@ describe('sessionIndexStore', () => { expect(sessionIndexStore.getSnapshot(SERVER).sessions.map(item => item.id)).toEqual(['ses_b']) }) + it('手动翻页不受条数上限截断(hasMore 只看服务端游标)', async () => { + let pageIndex = 0 + listSessionsPageMock.mockImplementation(async () => { + const base = pageIndex * 200 + pageIndex += 1 + const rows = Array.from({ length: 200 }, (_, offset) => + session(`ses_${base + offset}`, { time: { created: 1, updated: 100_000 - (base + offset) } }), + ) + return page(rows, `cursor-${pageIndex}`) + }) + + await sessionIndexStore.ensure(SERVER) + for (let index = 0; index < 10; index++) await sessionIndexStore.loadMore(SERVER) + + expect(sessionIndexStore.getSnapshot(SERVER).sessions).toHaveLength(2_200) + expect(sessionIndexStore.getSnapshot(SERVER).hasMore).toBe(true) + }) + it('首屏只拉一页,更多靠「显示更多」按 cursor 续页', async () => { listSessionsPageMock.mockResolvedValueOnce(page([session('ses_1')], 'cursor-2')) await sessionIndexStore.ensure(SERVER) diff --git a/src/store/sessionIndexStore.ts b/src/store/sessionIndexStore.ts index 0b197a5f7..4a86a3dc6 100644 --- a/src/store/sessionIndexStore.ts +++ b/src/store/sessionIndexStore.ts @@ -30,8 +30,6 @@ import type { Session } from '../types/api/session' const TTL_MS = 30_000 /** 单页条数:首屏一页就要出内容,大库靠 cursor 续页 / 目录补拉 */ const PAGE_LIMIT = 200 -/** 兜底上限:极端情况下也不无限翻页 */ -const MAX_SESSIONS = 2_000 /** 目录级补拉的条数:只用来把「被挤出全局索引」的那个目录补出来 */ const DIRECTORY_LIMIT = 100 /** 首屏失败的重试退避(启动可能早于本地服务端就绪) */ @@ -335,7 +333,8 @@ class SessionIndexStore { // 首屏整页替换,续页追加;normalize 按 id 去重并统一排序 entry.sessions = normalize([...(cursor ? entry.sessions : []), ...page.data]) entry.cursor = page.next - entry.exhausted = !page.next || entry.sessions.length >= MAX_SESSIONS + // 到底只看服务端游标:不加本地条数上限,用户点多少就能翻多少 + entry.exhausted = !page.next entry.ready = true entry.error = null entry.fetchedAt = Date.now() From 6ec8625e307dc4cb1752f06cad4d681a5e9195ae Mon Sep 17 00:00:00 2001 From: lehhair Date: Fri, 23 Oct 2026 12:50:49 +0800 Subject: [PATCH 20/67] =?UTF-8?q?fix(session-list):=20=E6=9C=8D=E5=8A=A1?= =?UTF-8?q?=E5=99=A8=E8=A2=AB=E5=88=A0=E9=99=A4=E6=97=B6=E9=87=8A=E6=94=BE?= =?UTF-8?q?=E7=B4=A2=E5=BC=95=E4=B8=8E=E4=BA=8B=E4=BB=B6=E8=AE=A2=E9=98=85?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 索引和 SSE 订阅之前只增不减:删掉的服务器会一直留着一份会话列表和 一条连接,直到应用退出。 现在索引订阅 serverStore,发现「上次见过、这次不见」的服务器 id 就 释放对应条目、订阅和目录补拉缓存。WSL 例外:它在 starting/stopped 期间会被临时移出列表,同一个 id 稍后回来,丢掉索引没人会重新 ensure, 会留下一个空列表。 --- src/store/sessionIndexStore.test.ts | 27 +++++++++++++++++++ src/store/sessionIndexStore.ts | 42 +++++++++++++++++++++++++++++ 2 files changed, 69 insertions(+) diff --git a/src/store/sessionIndexStore.test.ts b/src/store/sessionIndexStore.test.ts index daff05ea0..3efcf8b8e 100644 --- a/src/store/sessionIndexStore.test.ts +++ b/src/store/sessionIndexStore.test.ts @@ -22,6 +22,7 @@ vi.mock('../utils/directoryUtils', () => ({ })) const { sessionIndexStore } = await import('./sessionIndexStore') +const { serverStore } = await import('./serverStore') const SERVER = 'local' @@ -274,6 +275,32 @@ describe('sessionIndexStore', () => { expect(subscribeMock).toHaveBeenCalledTimes(1) }) + it('服务器被删除时释放索引与事件订阅', async () => { + const server = serverStore.addServer({ name: 'remote', url: 'http://remote.test' }) + listSessionsPageMock.mockResolvedValue(page([session('ses_a')])) + await sessionIndexStore.ensure(server.id) + + expect(sessionIndexStore.getSnapshot(server.id).sessions).toHaveLength(1) + const unsubscribe = subscribeMock.mock.results[0]?.value as ReturnType + + serverStore.removeServer(server.id) + + expect(unsubscribe).toHaveBeenCalled() + expect(sessionIndexStore.getSnapshot(server.id).sessions).toHaveLength(0) + expect(sessionIndexStore.getSnapshot(server.id).ready).toBe(false) + }) + + it('WSL 服务器临时移出列表时不丢索引(同一个 id 稍后会回来)', async () => { + const id = 'wsl:ubuntu' + serverStore.upsertServer({ id, name: 'Ubuntu', url: 'http://127.0.0.1:9999' }) + listSessionsPageMock.mockResolvedValue(page([session('ses_w')])) + await sessionIndexStore.ensure(id) + + serverStore.removeServer(id) + + expect(sessionIndexStore.getSnapshot(id).sessions).toHaveLength(1) + }) + it('目录兜底补拉:把被挤出全局索引的目录并回来,30s 内不重复补', async () => { listSessionsPageMock.mockResolvedValueOnce(page([session('ses_recent')])) await sessionIndexStore.ensure(SERVER) diff --git a/src/store/sessionIndexStore.ts b/src/store/sessionIndexStore.ts index 4a86a3dc6..1a03a4d9f 100644 --- a/src/store/sessionIndexStore.ts +++ b/src/store/sessionIndexStore.ts @@ -24,6 +24,7 @@ import { getSession, listSessionsPage } from '../api/session' import { subscribeToServerEvents } from '../api/events' import { autoDetectPathStyle } from '../utils/directoryUtils' +import { serverStore, WSL_SERVER_PREFIX } from './serverStore' import type { Session } from '../types/api/session' /** 与官方 home 列表的 staleTime 对齐:30s 内重复挂载不再请求 */ @@ -116,6 +117,47 @@ class SessionIndexStore { private directoryFetchedAt = new Map() /** 目录级补拉去重(同一目录并发只打一次) */ private directoryLoading = new Map>() + /** 上一次看到的服务器集合:用来发现「哪台被删了」 */ + private knownServerIds: Set + + constructor() { + this.knownServerIds = new Set(serverStore.getServers().map(server => server.id)) + serverStore.subscribe(this.handleServerStoreChange) + } + + /** + * 服务器被删除时释放对应索引和 SSE 订阅。 + * + * 不能只增不减:删掉的服务器会一直留着一条连接和一份会话列表, + * 直到应用退出。这里只处理「上次见过、这次不见了」的 id,新增不受影响。 + * + * WSL 例外:`wsl:` 服务器在 starting/stopped 期间会被临时移出列表, + * 稍后带着同一个 id 回来。这时丢掉索引没人会重新 ensure(hook 的 + * serverKey 没变),列表会一直空着,所以宁可留着内存。 + */ + private handleServerStoreChange = (): void => { + const current = new Set(serverStore.getServers().map(server => server.id)) + for (const serverId of this.knownServerIds) { + if (current.has(serverId) || serverId.startsWith(WSL_SERVER_PREFIX)) continue + this.forget(serverId) + } + this.knownServerIds = current + } + + /** 丢弃某台服务器的全部内存状态(下次 ensure 重新拉) */ + forget(serverId: string): void { + this.subscriptions.get(serverId)?.() + this.subscriptions.delete(serverId) + this.entries.delete(serverId) + // 键都是 `${serverId}\0...` 形式,按前缀一起清 + const prefix = `${serverId}\0` + for (const map of [this.refreshing, this.directoryFetchedAt, this.directoryLoading]) { + for (const key of map.keys()) { + if (key.startsWith(prefix)) map.delete(key) + } + } + this.notify() + } // ============================================ // 订阅(useSyncExternalStore) From 58282d64b7b3884587a29d057e86e0a19e6c4a15 Mon Sep 17 00:00:00 2001 From: lehhair Date: Fri, 23 Oct 2026 12:52:12 +0800 Subject: [PATCH 21/67] =?UTF-8?q?fix(session-list):=20=E9=87=8D=E8=BF=9E?= =?UTF-8?q?=E6=92=9E=E4=B8=8A=E5=9C=A8=E9=80=94=E6=8B=89=E5=8F=96=E6=97=B6?= =?UTF-8?q?=EF=BC=8C=E8=90=BD=E5=9C=B0=E5=90=8E=E5=86=8D=E8=A1=A5=E4=B8=80?= =?UTF-8?q?=E6=AC=A1?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 断连补偿走 ensure(force),但过去碰上正在飞的请求就直接返回那个请求: 它取的是断连前的数据,断连期间的新增/删除照样丢,要等下一次重连才补。 现在标记 refreshQueued,等在途请求落地后再拉一次第一页;重复的 force 只排一次,不会叠出第三个请求。 --- src/store/sessionIndexStore.test.ts | 22 ++++++++++++++++++++++ src/store/sessionIndexStore.ts | 19 ++++++++++++++++++- 2 files changed, 40 insertions(+), 1 deletion(-) diff --git a/src/store/sessionIndexStore.test.ts b/src/store/sessionIndexStore.test.ts index 3efcf8b8e..7419fedfb 100644 --- a/src/store/sessionIndexStore.test.ts +++ b/src/store/sessionIndexStore.test.ts @@ -275,6 +275,28 @@ describe('sessionIndexStore', () => { expect(subscribeMock).toHaveBeenCalledTimes(1) }) + it('重连撞上在途拉取时,等它落地后再补一次强制刷新', async () => { + let resolveFirst!: (value: { data: Session[]; next: string | null }) => void + listSessionsPageMock.mockImplementationOnce( + () => + new Promise(resolve => { + resolveFirst = resolve + }), + ) + const first = sessionIndexStore.ensure(SERVER) + + listSessionsPageMock.mockResolvedValueOnce(page([session('ses_b')])) + const forced = sessionIndexStore.ensure(SERVER, { force: true }) + // 在途请求没回来之前不能抢跑 + expect(listSessionsPageMock).toHaveBeenCalledTimes(1) + + resolveFirst(page([session('ses_a')])) + await Promise.all([first, forced]) + + expect(listSessionsPageMock).toHaveBeenCalledTimes(2) + expect(sessionIndexStore.getSnapshot(SERVER).sessions.map(item => item.id)).toEqual(['ses_b']) + }) + it('服务器被删除时释放索引与事件订阅', async () => { const server = serverStore.addServer({ name: 'remote', url: 'http://remote.test' }) listSessionsPageMock.mockResolvedValue(page([session('ses_a')])) diff --git a/src/store/sessionIndexStore.ts b/src/store/sessionIndexStore.ts index 1a03a4d9f..6f2462c47 100644 --- a/src/store/sessionIndexStore.ts +++ b/src/store/sessionIndexStore.ts @@ -65,6 +65,8 @@ interface Entry { error: Error | null /** 拉取期间收到的增量(整页替换后重放,避免刚创建的会话被覆盖掉) */ pending: Mutation[] + /** 在途请求落地后是否还要补一次强制刷新(重连撞上请求时用) */ + refreshQueued: boolean snapshot: SessionIndexSnapshot } @@ -184,7 +186,21 @@ class SessionIndexStore { ensure(serverId: string, options: { force?: boolean } = {}): Promise { this.ensureSubscription(serverId) const entry = this.entries.get(serverId) - if (entry?.loading) return entry.loading + + if (entry?.loading) { + // 重连补偿可能正好撞上在途请求:光等它拿不到断连后的新数据, + // 但要等它落地后再拉一次,否则两个全量请求会互相覆盖 + if (!options.force || entry.refreshQueued) return entry.loading + entry.refreshQueued = true + return entry.loading.then(() => { + entry.refreshQueued = false + if (this.entries.get(serverId) !== entry) return + // 期间又起了一次拉取:等它,不叠第三个 + if (entry.loading) return entry.loading + return this.fetchPage(serverId, null) + }) + } + if (!options.force && entry?.ready && Date.now() - entry.fetchedAt < TTL_MS) { return Promise.resolve() } @@ -306,6 +322,7 @@ class SessionIndexStore { loading: null, error: null, pending: [], + refreshQueued: false, snapshot: EMPTY_SNAPSHOT, } this.entries.set(serverId, entry) From a60ff2a5c589269db9a52edb3c0d86d37e1d7e99 Mon Sep 17 00:00:00 2001 From: lehhair Date: Fri, 23 Oct 2026 12:54:57 +0800 Subject: [PATCH 22/67] =?UTF-8?q?fix(session-list):=20=E7=B4=A2=E5=BC=95?= =?UTF-8?q?=E6=B2=A1=E8=A6=86=E7=9B=96=E7=9A=84=E6=97=A7=E4=BC=9A=E8=AF=9D?= =?UTF-8?q?=E4=B9=9F=E8=83=BD=E6=90=9C=E5=88=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 本地搜索只看得见索引里的最近一页,比这更旧的会话搜不到;过去直接把 search 交给服务端,反而没有这个问题。 现在索引不完整时(还有下一页),本地结果先出,再按目录去服务端补一次 (去抖 300ms、limit 50),只并本地没有的那部分。上游 search 只匹配 标题,本地是标题 + id 的超集,所以补回的结果按同样条件再筛一遍, 上一次搜索的旧结果不会串到新词下面。索引已经完整时不发请求。 --- src/contexts/SessionContext.test.tsx | 137 ++++++++++++++++++--------- src/contexts/SessionContext.tsx | 66 ++++++++++++- 2 files changed, 155 insertions(+), 48 deletions(-) diff --git a/src/contexts/SessionContext.test.tsx b/src/contexts/SessionContext.test.tsx index 1fd897622..3bd58d3bc 100644 --- a/src/contexts/SessionContext.test.tsx +++ b/src/contexts/SessionContext.test.tsx @@ -1,55 +1,58 @@ import { act, render } from '@testing-library/react' import { useContext, useEffect, type ContextType } from 'react' -import { beforeEach, describe, expect, it, vi } from 'vitest' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { SessionContext } from './SessionContext.shared' import { SessionProvider } from './SessionContext' import type { Session } from '../types/api/session' -const { storeMock, createSessionMock, deleteSessionMock, clearSessionRuntimeStateMock, unpinMock } = vi.hoisted(() => { - const listeners = new Set<() => void>() - let snapshot: { - sessions: Session[] - hasMore: boolean - ready: boolean - loading: boolean - error: Error | null - } = { sessions: [], hasMore: false, ready: false, loading: false, error: null } - - const storeMock = { - subscribe: (listener: () => void) => { - listeners.add(listener) - return () => listeners.delete(listener) - }, - getSnapshot: () => snapshot, - ensure: vi.fn(() => Promise.resolve()), - ensureDirectory: vi.fn(() => Promise.resolve()), - loadMore: vi.fn(() => Promise.resolve()), - remove: vi.fn(), - patch: vi.fn(), - upsert: vi.fn(), - reset: vi.fn(), - setSnapshotForTest: (next: Partial) => { - snapshot = { ...snapshot, ...next } - for (const listener of listeners) listener() - }, - resetSnapshotForTest: () => { - snapshot = { sessions: [], hasMore: false, ready: false, loading: false, error: null } - for (const listener of listeners) listener() - }, - } - - return { - storeMock, - createSessionMock: vi.fn(), - deleteSessionMock: vi.fn(), - clearSessionRuntimeStateMock: vi.fn(), - unpinMock: vi.fn(), - } -}) +const { storeMock, createSessionMock, deleteSessionMock, getSessionsMock, clearSessionRuntimeStateMock, unpinMock } = + vi.hoisted(() => { + const listeners = new Set<() => void>() + let snapshot: { + sessions: Session[] + hasMore: boolean + ready: boolean + loading: boolean + error: Error | null + } = { sessions: [], hasMore: false, ready: false, loading: false, error: null } + + const storeMock = { + subscribe: (listener: () => void) => { + listeners.add(listener) + return () => listeners.delete(listener) + }, + getSnapshot: () => snapshot, + ensure: vi.fn(() => Promise.resolve()), + ensureDirectory: vi.fn(() => Promise.resolve()), + loadMore: vi.fn(() => Promise.resolve()), + remove: vi.fn(), + patch: vi.fn(), + upsert: vi.fn(), + reset: vi.fn(), + setSnapshotForTest: (next: Partial) => { + snapshot = { ...snapshot, ...next } + for (const listener of listeners) listener() + }, + resetSnapshotForTest: () => { + snapshot = { sessions: [], hasMore: false, ready: false, loading: false, error: null } + for (const listener of listeners) listener() + }, + } + + return { + storeMock, + createSessionMock: vi.fn(), + deleteSessionMock: vi.fn(), + getSessionsMock: vi.fn(), + clearSessionRuntimeStateMock: vi.fn(), + unpinMock: vi.fn(), + } + }) vi.mock('../api', () => ({ createSession: (...args: unknown[]) => createSessionMock(...args), deleteSession: (...args: unknown[]) => deleteSessionMock(...args), + getSessions: (...args: unknown[]) => getSessionsMock(...args), })) vi.mock('../store/sessionIndexStore', () => ({ @@ -129,11 +132,17 @@ describe('SessionProvider', () => { storeMock.upsert.mockClear() createSessionMock.mockReset() deleteSessionMock.mockReset() + getSessionsMock.mockReset() + getSessionsMock.mockResolvedValue([]) clearSessionRuntimeStateMock.mockReset() unpinMock.mockReset() storeMock.resetSnapshotForTest() }) + afterEach(() => { + vi.useRealTimers() + }) + it('从共享索引按当前目录过滤(不再自己发请求)', async () => { storeMock.setSnapshotForTest({ ready: true, @@ -161,7 +170,7 @@ describe('SessionProvider', () => { expect(latestContext?.isLoading).toBe(false) }) - it('搜索在本地过滤标题 / id,不触发任何请求', () => { + it('搜索在本地过滤标题 / id,索引完整时不发请求', () => { storeMock.setSnapshotForTest({ ready: true, sessions: [makeSession('ses_a', '/workspace/demo'), makeSession('ses_b', '/workspace/demo')], @@ -176,6 +185,48 @@ describe('SessionProvider', () => { expect(latestContext?.sessions.map(session => session.id)).toEqual(['ses_b']) expect(storeMock.ensure).toHaveBeenCalledTimes(ensureCalls) + expect(getSessionsMock).not.toHaveBeenCalled() + }) + + it('索引没覆盖全部会话时,本地搜不到的再向服务端补一次', async () => { + vi.useFakeTimers() + storeMock.setSnapshotForTest({ ready: true, hasMore: true, sessions: [makeSession('ses_a')] }) + getSessionsMock.mockResolvedValue([makeSession('ses_old', '/workspace/demo', 99)]) + + renderProvider() + act(() => { + latestContext?.setSearch('old') + }) + expect(latestContext?.sessions).toEqual([]) + + await act(async () => { + await vi.advanceTimersByTimeAsync(300) + }) + + expect(getSessionsMock).toHaveBeenCalledWith( + { parentID: null, search: 'old', limit: 50, directory: '/workspace/demo' }, + 'local', + ) + expect(latestContext?.sessions.map(session => session.id)).toEqual(['ses_old']) + }) + + it('服务端补回的结果按当前目录收口', async () => { + vi.useFakeTimers() + storeMock.setSnapshotForTest({ ready: true, hasMore: true, sessions: [makeSession('ses_a')] }) + getSessionsMock.mockResolvedValue([ + makeSession('ses_old', '/workspace/demo', 99), + makeSession('ses_elsewhere', '/workspace/other', 100), + ]) + + renderProvider() + act(() => { + latestContext?.setSearch('old') + }) + await act(async () => { + await vi.advanceTimersByTimeAsync(300) + }) + + expect(latestContext?.sessions.map(session => session.id)).toEqual(['ses_old']) }) it('本地已拉到的会话先切片露出,见底后才向服务端续页', async () => { diff --git a/src/contexts/SessionContext.tsx b/src/contexts/SessionContext.tsx index 23096099c..292b75f39 100644 --- a/src/contexts/SessionContext.tsx +++ b/src/contexts/SessionContext.tsx @@ -1,5 +1,9 @@ import { useState, useCallback, useEffect, useMemo, useSyncExternalStore, type ReactNode } from 'react' -import { createSession as apiCreateSession, deleteSession as apiDeleteSession } from '../api' +import { + createSession as apiCreateSession, + deleteSession as apiDeleteSession, + getSessions, +} from '../api' import { serverStore } from '../store/serverStore' import { pinnedSessionsStore } from '../store/pinnedSessionsStore' import { sessionIndexStore } from '../store/sessionIndexStore' @@ -7,6 +11,7 @@ import { useDirectory } from './useDirectory' import { isSameDirectory, normalizeToForwardSlash } from '../utils' import { clearSessionRuntimeState } from '../utils/sessionLifecycle' import { SessionContext, type SessionContextValue } from './SessionContext.shared' +import type { Session } from '../types/api/session' /** 列表首屏条数;「显示更多」每次多露出这么多 */ const LIST_PAGE_SIZE = 30 @@ -21,8 +26,11 @@ const getActiveServerId = () => serverStore.getActiveServerId() * 列表本身来自 `sessionIndexStore`(每个服务器一份根会话索引,30s 内复用), * 这里只做三件事:按当前目录过滤、按搜索词过滤、按需要切片。 * - * 好处是切目录/切回来不再发请求,文件夹模式的各个目录也共享同一份索引; - * 搜索是本地标题匹配(官方 home 的会话搜索同款),不再每个按键打一次服务端。 + * 好处是切目录/切回来不再发请求,文件夹模式的各个目录也共享同一份索引。 + * + * 搜索先走本地(标题 / id)。但索引只有最近一页,旧会话可能不在里面: + * 这时再按目录去服务端搜一次补上(去抖 300ms),只补本地没有的那部分。 + * 索引已经完整时纯本地,不按键打服务端。 */ export function SessionProvider({ children }: { children: ReactNode }) { const { currentDirectory } = useDirectory() @@ -36,6 +44,8 @@ export function SessionProvider({ children }: { children: ReactNode }) { const [search, setSearch] = useState('') const [isLoadingMore, setIsLoadingMore] = useState(false) + /** 索引没覆盖到的旧会话(服务端按标题搜出来的补充结果) */ + const [remoteSessions, setRemoteSessions] = useState([]) // 「显示更多」的展开量跟目录/搜索词绑定:切过去时从第一页开始,不会把 // 上一个目录的展开量短暂套到新目录上(会出现多显示一截再收回的跳动) const listKey = `${currentDirectory ?? ''}\0${search}` @@ -65,14 +75,60 @@ export function SessionProvider({ children }: { children: ReactNode }) { void sessionIndexStore.ensureDirectory(serverId, currentDirectory) }, [needsDirectoryFetch, currentDirectory, serverId]) + // 索引只覆盖最近一页:本地搜不到的旧会话再问一次服务端(去抖 300ms)。 + // 上游 search 只匹配标题,本地是「标题 + id」的超集,所以服务端结果 + // 按同样的条件再筛一遍,避免上一次搜索的旧结果串到新词下面。 + useEffect(() => { + const term = search.trim() + if (!term || !snapshot.hasMore) { + setRemoteSessions(previous => (previous.length === 0 ? previous : [])) + return + } + let cancelled = false + const timer = window.setTimeout(() => { + const directory = normalizeToForwardSlash(currentDirectory) || undefined + void getSessions( + { parentID: null, search: term, limit: 50, ...(directory ? { directory } : {}) }, + serverId, + ) + .then(data => { + if (!cancelled) setRemoteSessions(data) + }) + .catch(() => { + if (!cancelled) setRemoteSessions([]) + }) + }, 300) + return () => { + cancelled = true + window.clearTimeout(timer) + } + }, [search, snapshot.hasMore, currentDirectory, serverId]) + const filteredSessions = useMemo(() => { const term = search.trim().toLowerCase() if (!term) return directorySessions - return directorySessions.filter(session => { + + const matches = (session: Session) => { const title = (session.title ?? '').toLowerCase() return title.includes(term) || session.id.toLowerCase().includes(term) + } + + const local = directorySessions.filter(matches) + if (remoteSessions.length === 0) return local + + // 服务端补来的结果可能包含别处的目录(缺省目录时是全服务器),按当前目录收口 + const byId = new Map(local.map(session => [session.id, session])) + for (const session of remoteSessions) { + if (!matches(session)) continue + if (currentDirectory && !isSameDirectory(currentDirectory, session.location?.directory)) continue + if (!byId.has(session.id)) byId.set(session.id, session) + } + return [...byId.values()].sort((a, b) => { + const left = a.time?.updated ?? a.time?.created ?? 0 + const right = b.time?.updated ?? b.time?.created ?? 0 + return right - left }) - }, [directorySessions, search]) + }, [directorySessions, search, remoteSessions, currentDirectory]) const sessions = useMemo(() => filteredSessions.slice(0, limit), [filteredSessions, limit]) const searching = search.trim().length > 0 From 9ae6b1e7feddc4a82f57846ecee2d368f925dfba Mon Sep 17 00:00:00 2001 From: lehhair Date: Fri, 23 Oct 2026 12:57:48 +0800 Subject: [PATCH 23/67] =?UTF-8?q?docs(session-list):=20=E8=AE=B0=E5=BD=95?= =?UTF-8?q?=20session.list=20=E7=9A=84=E5=AE=9E=E6=B5=8B=E8=AF=AD=E4=B9=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 拿 v2.0.29 起了一台真服务端核对(200 条样本): 不传 directory 确实返回全服务器多目录的会话;不传 parentID 会把子会话 一起带回来,只有 parentID: null 才是纯根会话;cursor 续页无重复。 把这三条写进索引头部,避免以后把 parentID: null 当成冗余参数删掉, 或者误以为缺省目录只给默认 location。 --- src/store/sessionIndexStore.ts | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/src/store/sessionIndexStore.ts b/src/store/sessionIndexStore.ts index 6f2462c47..d08873223 100644 --- a/src/store/sessionIndexStore.ts +++ b/src/store/sessionIndexStore.ts @@ -19,6 +19,12 @@ // // 不传 `directory` 表示「全服务器」:上游 `session.list` 的 `ListAllInput` // 就是不带 location 的那支(packages/core/src/session/store.ts)。 +// +// 实测(v2.0.29,200 条样本): +// - 不传 `directory` 返回全服务器、多目录的会话,不是只给默认 location +// - 不传 `parentID` 会把子会话一起带回来;`parentID: null` 才只要根会话 +// - `cursor.next` 直接续页,跨页无重复 +// 所以下面每处 list 都显式带 `parentID: null`,别省。 // ============================================ import { getSession, listSessionsPage } from '../api/session' From 1414f17a99f647d3b4009337441b6fe55f7c6e5f Mon Sep 17 00:00:00 2001 From: lehhair Date: Fri, 23 Oct 2026 13:05:33 +0800 Subject: [PATCH 24/67] =?UTF-8?q?fix(session-list):=20=E6=90=9C=E7=B4=A2?= =?UTF-8?q?=E8=A1=A5=E5=85=A8=E7=BB=93=E6=9E=9C=E8=B7=9F=E6=9C=8D=E5=8A=A1?= =?UTF-8?q?=E5=99=A8=E7=BB=91=E5=AE=9A=EF=BC=8C=E5=88=87=E6=9C=8D=E5=8A=A1?= =?UTF-8?q?=E5=99=A8=E4=B8=8D=E4=B8=B2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 补充结果只按目录收口,切到另一台服务器后、新结果回来前的那 300ms 里, 旧服务器的会话会挂在同一个目录名下显示出来。 把结果和 serverId 存成一份,读取时对不上就当作空。 --- src/contexts/SessionContext.tsx | 18 +++++++++++++----- 1 file changed, 13 insertions(+), 5 deletions(-) diff --git a/src/contexts/SessionContext.tsx b/src/contexts/SessionContext.tsx index 292b75f39..6178430de 100644 --- a/src/contexts/SessionContext.tsx +++ b/src/contexts/SessionContext.tsx @@ -44,8 +44,12 @@ export function SessionProvider({ children }: { children: ReactNode }) { const [search, setSearch] = useState('') const [isLoadingMore, setIsLoadingMore] = useState(false) - /** 索引没覆盖到的旧会话(服务端按标题搜出来的补充结果) */ - const [remoteSessions, setRemoteSessions] = useState([]) + /** 索引没覆盖到的旧会话(服务端按标题搜出来的补充结果);跟 serverId 绑死,切服务器不串 */ + const [remoteResults, setRemoteResults] = useState<{ serverId: string; sessions: Session[] }>({ + serverId, + sessions: [], + }) + const remoteSessions = remoteResults.serverId === serverId ? remoteResults.sessions : [] // 「显示更多」的展开量跟目录/搜索词绑定:切过去时从第一页开始,不会把 // 上一个目录的展开量短暂套到新目录上(会出现多显示一截再收回的跳动) const listKey = `${currentDirectory ?? ''}\0${search}` @@ -81,7 +85,11 @@ export function SessionProvider({ children }: { children: ReactNode }) { useEffect(() => { const term = search.trim() if (!term || !snapshot.hasMore) { - setRemoteSessions(previous => (previous.length === 0 ? previous : [])) + setRemoteResults(previous => + previous.sessions.length === 0 && previous.serverId === serverId + ? previous + : { serverId, sessions: [] }, + ) return } let cancelled = false @@ -92,10 +100,10 @@ export function SessionProvider({ children }: { children: ReactNode }) { serverId, ) .then(data => { - if (!cancelled) setRemoteSessions(data) + if (!cancelled) setRemoteResults({ serverId, sessions: data }) }) .catch(() => { - if (!cancelled) setRemoteSessions([]) + if (!cancelled) setRemoteResults({ serverId, sessions: [] }) }) }, 300) return () => { From 73874945b5fb870e8a955aa399532856d4f7cc85 Mon Sep 17 00:00:00 2001 From: lehhair Date: Fri, 23 Oct 2026 13:51:36 +0800 Subject: [PATCH 25/67] =?UTF-8?q?refactor(session-list):=20=E6=90=9C?= =?UTF-8?q?=E7=B4=A2=E6=94=B9=E5=AE=98=E6=96=B9=E5=8F=A3=E5=BE=84=EF=BC=8C?= =?UTF-8?q?=E6=9C=AC=E5=9C=B0=E5=8C=B9=E9=85=8D=20+=20=E4=BC=9A=E8=AF=9D?= =?UTF-8?q?=20ID=20=E5=9B=9E=E8=AF=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 官方 home 的搜索只看索引里的标题;输入像完整 ID 时直接 session.get 回读那一条,不打服务端标题搜索。这里照做: - 删掉「本地搜不到再按目录查服务端」的补全(300ms 防抖 + limit 50) - 输入长度 > 20 且 ses_ 开头时回读一次,不在索引/当前目录也放到最前 - 多服务器搜索补上 parentID: null,和官方命令面板一致(只列根会话) --- src/contexts/SessionContext.test.tsx | 62 ++++----------- src/contexts/SessionContext.tsx | 86 ++++++++------------- src/features/chat/sidebar/SearchResults.tsx | 4 +- 3 files changed, 49 insertions(+), 103 deletions(-) diff --git a/src/contexts/SessionContext.test.tsx b/src/contexts/SessionContext.test.tsx index 3bd58d3bc..ed346181c 100644 --- a/src/contexts/SessionContext.test.tsx +++ b/src/contexts/SessionContext.test.tsx @@ -1,11 +1,11 @@ import { act, render } from '@testing-library/react' import { useContext, useEffect, type ContextType } from 'react' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { beforeEach, describe, expect, it, vi } from 'vitest' import { SessionContext } from './SessionContext.shared' import { SessionProvider } from './SessionContext' import type { Session } from '../types/api/session' -const { storeMock, createSessionMock, deleteSessionMock, getSessionsMock, clearSessionRuntimeStateMock, unpinMock } = +const { storeMock, createSessionMock, deleteSessionMock, getSessionMock, clearSessionRuntimeStateMock, unpinMock } = vi.hoisted(() => { const listeners = new Set<() => void>() let snapshot: { @@ -43,7 +43,7 @@ const { storeMock, createSessionMock, deleteSessionMock, getSessionsMock, clearS storeMock, createSessionMock: vi.fn(), deleteSessionMock: vi.fn(), - getSessionsMock: vi.fn(), + getSessionMock: vi.fn(), clearSessionRuntimeStateMock: vi.fn(), unpinMock: vi.fn(), } @@ -52,7 +52,7 @@ const { storeMock, createSessionMock, deleteSessionMock, getSessionsMock, clearS vi.mock('../api', () => ({ createSession: (...args: unknown[]) => createSessionMock(...args), deleteSession: (...args: unknown[]) => deleteSessionMock(...args), - getSessions: (...args: unknown[]) => getSessionsMock(...args), + getSession: (...args: unknown[]) => getSessionMock(...args), })) vi.mock('../store/sessionIndexStore', () => ({ @@ -132,17 +132,13 @@ describe('SessionProvider', () => { storeMock.upsert.mockClear() createSessionMock.mockReset() deleteSessionMock.mockReset() - getSessionsMock.mockReset() - getSessionsMock.mockResolvedValue([]) + getSessionMock.mockReset() + getSessionMock.mockRejectedValue(new Error('not found')) clearSessionRuntimeStateMock.mockReset() unpinMock.mockReset() storeMock.resetSnapshotForTest() }) - afterEach(() => { - vi.useRealTimers() - }) - it('从共享索引按当前目录过滤(不再自己发请求)', async () => { storeMock.setSnapshotForTest({ ready: true, @@ -170,7 +166,7 @@ describe('SessionProvider', () => { expect(latestContext?.isLoading).toBe(false) }) - it('搜索在本地过滤标题 / id,索引完整时不发请求', () => { + it('搜索在本地过滤标题 / id,不发请求', () => { storeMock.setSnapshotForTest({ ready: true, sessions: [makeSession('ses_a', '/workspace/demo'), makeSession('ses_b', '/workspace/demo')], @@ -185,48 +181,22 @@ describe('SessionProvider', () => { expect(latestContext?.sessions.map(session => session.id)).toEqual(['ses_b']) expect(storeMock.ensure).toHaveBeenCalledTimes(ensureCalls) - expect(getSessionsMock).not.toHaveBeenCalled() - }) - - it('索引没覆盖全部会话时,本地搜不到的再向服务端补一次', async () => { - vi.useFakeTimers() - storeMock.setSnapshotForTest({ ready: true, hasMore: true, sessions: [makeSession('ses_a')] }) - getSessionsMock.mockResolvedValue([makeSession('ses_old', '/workspace/demo', 99)]) - - renderProvider() - act(() => { - latestContext?.setSearch('old') - }) - expect(latestContext?.sessions).toEqual([]) - - await act(async () => { - await vi.advanceTimersByTimeAsync(300) - }) - - expect(getSessionsMock).toHaveBeenCalledWith( - { parentID: null, search: 'old', limit: 50, directory: '/workspace/demo' }, - 'local', - ) - expect(latestContext?.sessions.map(session => session.id)).toEqual(['ses_old']) + expect(getSessionMock).not.toHaveBeenCalled() }) - it('服务端补回的结果按当前目录收口', async () => { - vi.useFakeTimers() - storeMock.setSnapshotForTest({ ready: true, hasMore: true, sessions: [makeSession('ses_a')] }) - getSessionsMock.mockResolvedValue([ - makeSession('ses_old', '/workspace/demo', 99), - makeSession('ses_elsewhere', '/workspace/other', 100), - ]) + it('输入完整会话 ID 时直接回读(官方 home 的 lookup 口径)', async () => { + const id = `ses_${'a'.repeat(24)}` + storeMock.setSnapshotForTest({ ready: true, sessions: [] }) + getSessionMock.mockResolvedValue(makeSession(id, '/workspace/other')) renderProvider() - act(() => { - latestContext?.setSearch('old') - }) await act(async () => { - await vi.advanceTimersByTimeAsync(300) + latestContext?.setSearch(id) }) - expect(latestContext?.sessions.map(session => session.id)).toEqual(['ses_old']) + expect(getSessionMock).toHaveBeenCalledWith(id, undefined, 'local') + // 不在索引 / 当前目录里也要露出来:用户是拿着 ID 找的 + expect(latestContext?.sessions.map(session => session.id)).toEqual([id]) }) it('本地已拉到的会话先切片露出,见底后才向服务端续页', async () => { diff --git a/src/contexts/SessionContext.tsx b/src/contexts/SessionContext.tsx index 6178430de..c099651b4 100644 --- a/src/contexts/SessionContext.tsx +++ b/src/contexts/SessionContext.tsx @@ -2,7 +2,7 @@ import { useState, useCallback, useEffect, useMemo, useSyncExternalStore, type R import { createSession as apiCreateSession, deleteSession as apiDeleteSession, - getSessions, + getSession, } from '../api' import { serverStore } from '../store/serverStore' import { pinnedSessionsStore } from '../store/pinnedSessionsStore' @@ -28,9 +28,8 @@ const getActiveServerId = () => serverStore.getActiveServerId() * * 好处是切目录/切回来不再发请求,文件夹模式的各个目录也共享同一份索引。 * - * 搜索先走本地(标题 / id)。但索引只有最近一页,旧会话可能不在里面: - * 这时再按目录去服务端搜一次补上(去抖 300ms),只补本地没有的那部分。 - * 索引已经完整时纯本地,不按键打服务端。 + * 搜索走官方 home 的口径:只在索引里按标题匹配;输入看起来是会话 ID + * (长度 > 20 且 `ses_` 开头)时直接回读那一条,补上索引可能没有的会话。 */ export function SessionProvider({ children }: { children: ReactNode }) { const { currentDirectory } = useDirectory() @@ -44,12 +43,8 @@ export function SessionProvider({ children }: { children: ReactNode }) { const [search, setSearch] = useState('') const [isLoadingMore, setIsLoadingMore] = useState(false) - /** 索引没覆盖到的旧会话(服务端按标题搜出来的补充结果);跟 serverId 绑死,切服务器不串 */ - const [remoteResults, setRemoteResults] = useState<{ serverId: string; sessions: Session[] }>({ - serverId, - sessions: [], - }) - const remoteSessions = remoteResults.serverId === serverId ? remoteResults.sessions : [] + /** 输入完整会话 ID 时回读到的会话(官方 home 的 exact lookup) */ + const [lookedUp, setLookedUp] = useState<{ serverId: string; session: Session } | null>(null) // 「显示更多」的展开量跟目录/搜索词绑定:切过去时从第一页开始,不会把 // 上一个目录的展开量短暂套到新目录上(会出现多显示一截再收回的跳动) const listKey = `${currentDirectory ?? ''}\0${search}` @@ -79,64 +74,45 @@ export function SessionProvider({ children }: { children: ReactNode }) { void sessionIndexStore.ensureDirectory(serverId, currentDirectory) }, [needsDirectoryFetch, currentDirectory, serverId]) - // 索引只覆盖最近一页:本地搜不到的旧会话再问一次服务端(去抖 300ms)。 - // 上游 search 只匹配标题,本地是「标题 + id」的超集,所以服务端结果 - // 按同样的条件再筛一遍,避免上一次搜索的旧结果串到新词下面。 + // 官方 home 的搜索口径:本地标题匹配 + 会话 ID 精确回读。 + // 不做服务端标题搜索,也不按键打接口;只有输入像完整 ID 时才 lookup 一次。 + const searchTerm = search.trim() + const looksLikeSessionID = searchTerm.length > 20 && searchTerm.startsWith('ses_') useEffect(() => { - const term = search.trim() - if (!term || !snapshot.hasMore) { - setRemoteResults(previous => - previous.sessions.length === 0 && previous.serverId === serverId - ? previous - : { serverId, sessions: [] }, - ) + if (!looksLikeSessionID) { + setLookedUp(previous => (previous === null ? previous : null)) return } let cancelled = false - const timer = window.setTimeout(() => { - const directory = normalizeToForwardSlash(currentDirectory) || undefined - void getSessions( - { parentID: null, search: term, limit: 50, ...(directory ? { directory } : {}) }, - serverId, - ) - .then(data => { - if (!cancelled) setRemoteResults({ serverId, sessions: data }) - }) - .catch(() => { - if (!cancelled) setRemoteResults({ serverId, sessions: [] }) - }) - }, 300) + void getSession(searchTerm, undefined, serverId) + .then(session => { + if (!cancelled) setLookedUp({ serverId, session }) + }) + .catch(() => { + if (!cancelled) setLookedUp(null) + }) return () => { cancelled = true - window.clearTimeout(timer) } - }, [search, snapshot.hasMore, currentDirectory, serverId]) + }, [searchTerm, looksLikeSessionID, serverId]) const filteredSessions = useMemo(() => { - const term = search.trim().toLowerCase() - if (!term) return directorySessions + const value = search.trim().toLowerCase() + if (!value) return directorySessions - const matches = (session: Session) => { + const local = directorySessions.filter(session => { const title = (session.title ?? '').toLowerCase() - return title.includes(term) || session.id.toLowerCase().includes(term) - } - - const local = directorySessions.filter(matches) - if (remoteSessions.length === 0) return local + return title.includes(value) || session.id.toLowerCase().includes(value) + }) - // 服务端补来的结果可能包含别处的目录(缺省目录时是全服务器),按当前目录收口 - const byId = new Map(local.map(session => [session.id, session])) - for (const session of remoteSessions) { - if (!matches(session)) continue - if (currentDirectory && !isSameDirectory(currentDirectory, session.location?.directory)) continue - if (!byId.has(session.id)) byId.set(session.id, session) + // 官方 home:ID 回读到的会话即使不在索引/当前目录里也放到最前面, + // 用户是拿着完整 ID 来找的。归档会话不进列表。 + const exact = lookedUp?.serverId === serverId ? lookedUp.session : undefined + if (!exact || typeof exact.time?.archived === 'number' || local.some(item => item.id === exact.id)) { + return local } - return [...byId.values()].sort((a, b) => { - const left = a.time?.updated ?? a.time?.created ?? 0 - const right = b.time?.updated ?? b.time?.created ?? 0 - return right - left - }) - }, [directorySessions, search, remoteSessions, currentDirectory]) + return [exact, ...local] + }, [directorySessions, search, lookedUp, serverId]) const sessions = useMemo(() => filteredSessions.slice(0, limit), [filteredSessions, limit]) const searching = search.trim().length > 0 diff --git a/src/features/chat/sidebar/SearchResults.tsx b/src/features/chat/sidebar/SearchResults.tsx index 33d9c0a44..a588c3b9f 100644 --- a/src/features/chat/sidebar/SearchResults.tsx +++ b/src/features/chat/sidebar/SearchResults.tsx @@ -119,8 +119,8 @@ function ServerSearchGroup({ } const timer = window.setTimeout(() => { setIsLoadingSessions(true) - // v2 没有 roots 开关:只要根会话时传 parentID: null;这里要全部会话故省略 - getSessions({ search, limit: 50 }, serverId) + // 官方命令面板同款:只要根会话(parentID: null),limit 50 + getSessions({ parentID: null, search, limit: 50 }, serverId) .then(data => { if (requestId === requestIdRef.current) setSessions(data) }) From 9e20a5eac59bf72767267e0c310d45926232595f Mon Sep 17 00:00:00 2001 From: lehhair Date: Fri, 23 Oct 2026 13:51:36 +0800 Subject: [PATCH 26/67] =?UTF-8?q?perf(session-list):=20=E7=9B=AE=E5=BD=95?= =?UTF-8?q?=E8=A1=A5=E6=8B=89=E6=8C=89=E5=AE=98=E6=96=B9=E9=A1=B5=E5=A4=A7?= =?UTF-8?q?=E5=B0=8F=E4=B8=80=E6=AC=A1=E6=8B=BF=E6=BB=A1?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 目录兜底从 100 条改成官方 home 的会话页大小 5000 (HOME_V2_SESSION_PAGE_LIMIT):一个目录再深也是一次请求,不用反复 点「显示更多」去翻全局页。 顺带把排序注释写明:只看 time.updated,流式输出不置顶, 和官方 retainHomeSessions 一致。 --- src/store/sessionIndexStore.test.ts | 3 ++- src/store/sessionIndexStore.ts | 8 ++++++-- 2 files changed, 8 insertions(+), 3 deletions(-) diff --git a/src/store/sessionIndexStore.test.ts b/src/store/sessionIndexStore.test.ts index 7419fedfb..cde8e3cbf 100644 --- a/src/store/sessionIndexStore.test.ts +++ b/src/store/sessionIndexStore.test.ts @@ -330,8 +330,9 @@ describe('sessionIndexStore', () => { listSessionsPageMock.mockResolvedValueOnce(page([session('ses_old')])) await sessionIndexStore.ensureDirectory(SERVER, '/workspace/demo') + // 一次拿满官方 home 的页大小,目录多深都能露出来 expect(listSessionsPageMock).toHaveBeenLastCalledWith( - { directory: '/workspace/demo', parentID: null, order: 'desc', limit: 100 }, + { directory: '/workspace/demo', parentID: null, order: 'desc', limit: 5_000 }, SERVER, ) expect(sessionIndexStore.getSnapshot(SERVER).sessions.map(item => item.id).sort()).toEqual([ diff --git a/src/store/sessionIndexStore.ts b/src/store/sessionIndexStore.ts index d08873223..bd2c0923c 100644 --- a/src/store/sessionIndexStore.ts +++ b/src/store/sessionIndexStore.ts @@ -9,6 +9,8 @@ // 在本地按目录分组、按时间切片(home/sessions/index.ts)。这里做同一件事: // // - `ensure(serverId)` 拉首页(limit 200),30s 内复用 +// 官方 home 一次拉 5000(HOME_V2_SESSION_PAGE_LIMIT);这里为了首屏更快 +// 只拉一页,目录覆盖交给 ensureDirectory(一次也拿满 5000) // - 各列表从 `getSnapshot(serverId)` 里按目录过滤、按需切片,零额外请求 // - 某个目录被挤出索引时 `ensureDirectory` 按目录补一次(见下) // - SSE 增量(新增/重命名/删除/移动)直接写进索引,所有列表同步更新 @@ -37,8 +39,8 @@ import type { Session } from '../types/api/session' const TTL_MS = 30_000 /** 单页条数:首屏一页就要出内容,大库靠 cursor 续页 / 目录补拉 */ const PAGE_LIMIT = 200 -/** 目录级补拉的条数:只用来把「被挤出全局索引」的那个目录补出来 */ -const DIRECTORY_LIMIT = 100 +/** 目录级补拉的条数:对齐官方 home 的会话页大小(HOME_V2_SESSION_PAGE_LIMIT) */ +const DIRECTORY_LIMIT = 5_000 /** 首屏失败的重试退避(启动可能早于本地服务端就绪) */ const RETRY_DELAYS_MS = [500, 1_500, 3_000] @@ -99,6 +101,8 @@ function normalizeDirectoryKey(directory: string): string { function sortSessions(sessions: Session[]): Session[] { return [...sessions].sort((a, b) => { + // 与官方 home 的 retainHomeSessions 同款排序:只看 time.updated, + // 流式输出期间服务端不改这个时间,所以行不会立刻跳到顶部。 const diff = updatedAt(b) - updatedAt(a) if (diff !== 0) return diff return a.id < b.id ? -1 : a.id > b.id ? 1 : 0 From f84901647081cf5e847c592fc6ed2863bff0b573 Mon Sep 17 00:00:00 2001 From: lehhair Date: Fri, 23 Oct 2026 14:18:49 +0800 Subject: [PATCH 27/67] =?UTF-8?q?fix(events):=20=E5=88=87=E5=9B=9E?= =?UTF-8?q?=E5=89=8D=E5=8F=B0=E5=A4=8D=E6=A0=B8=E5=8D=8A=E5=BC=80=E8=BF=9E?= =?UTF-8?q?=E6=8E=A5=EF=BC=8C=E7=9F=AD=E6=97=B6=E5=88=87=E5=B1=8F=E4=BF=9D?= =?UTF-8?q?=E6=8C=81=E6=87=92=E8=BF=9E=E6=8E=A5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 后台期间 JS 定时器会被冻结,看门狗不会 tick;切回前台时若连接已是半开, 状态还停在 connected,用户要等最多 45s 才看到界面恢复。 回到前台先留 2s 让恢复后缓冲的事件/心跳落地,再按静默时长复核: - 静默不足一个心跳(20s):保持懒连接,不重连 - 静默超过阈值:主动掐断并走重连补偿(与 online 共用同一套逻辑) 顺带把半开连接的 5s 强制复位抽成 dropSilentConnection,并补上代次校验, 避免兜底定时器误伤已经重建的新连接。 Issue #184 --- src/api/events.test.ts | 87 +++++++++++++++++++++++++++++ src/api/events.ts | 121 +++++++++++++++++++++++++++++------------ 2 files changed, 173 insertions(+), 35 deletions(-) diff --git a/src/api/events.test.ts b/src/api/events.test.ts index 6234597c3..51e65a4ba 100644 --- a/src/api/events.test.ts +++ b/src/api/events.test.ts @@ -69,6 +69,11 @@ function v2Event(type: string, data: unknown) { return { id: `evt-${type}`, created: Date.now(), type, data } } +/** jsdom 不提供真实的可见性切换:临时覆盖 document.visibilityState 再派发事件 */ +function setDocumentVisibility(state: 'visible' | 'hidden') { + Object.defineProperty(document, 'visibilityState', { configurable: true, get: () => state }) +} + describe('v2 event dispatch', () => { beforeEach(() => { vi.resetModules() @@ -363,6 +368,88 @@ describe('v2 event dispatch', () => { } }) + /** + * 切后台再切回来(Issue #184):后台期间 JS 定时器被冻结,看门狗不 tick, + * 半开连接的状态会一直停在 connected。回到前台必须主动复核一次静默时长, + * 否则用户要等最多 45s 才看到刷新。 + * + * 但复核不能见 connected 就重连:短时间切屏、连接还活着的时候应该保持 + * 懒连接,所以静默不足一个心跳阈值时什么都不做。 + */ + it('keeps the connection when the app returns quickly from background', async () => { + vi.useFakeTimers() + try { + const harnesses: Array> = [] + subscribeMock.mockImplementation(() => { + const harness = createEventStream() + harnesses.push(harness) + return harness.stream + }) + + const { subscribeToServerEvents, getServerConnectionInfo } = await import('./events') + const unsubscribe = subscribeToServerEvents('test-server', {}) + await Promise.resolve() + + harnesses[0].emit(v2Event('session.idle', { sessionID: 's1' })) + await vi.advanceTimersByTimeAsync(0) + expect(getServerConnectionInfo('test-server').state).toBe('connected') + + // 短暂切屏:累计静默远小于一个心跳阈值 + await vi.advanceTimersByTimeAsync(5_000) + setDocumentVisibility('hidden') + document.dispatchEvent(new Event('visibilitychange')) + setDocumentVisibility('visible') + document.dispatchEvent(new Event('visibilitychange')) + await vi.advanceTimersByTimeAsync(5_000) + + expect(subscribeMock.mock.calls.length).toBe(1) + expect(getServerConnectionInfo('test-server').state).toBe('connected') + unsubscribe() + } finally { + setDocumentVisibility('visible') + vi.useRealTimers() + } + }) + + it('reconnects on returning from a long background instead of waiting for the watchdog', async () => { + vi.useFakeTimers() + try { + const harnesses: Array> = [] + subscribeMock.mockImplementation(() => { + const harness = createEventStream() + harnesses.push(harness) + return harness.stream + }) + + const { subscribeToServerEvents, getServerConnectionInfo } = await import('./events') + const unsubscribe = subscribeToServerEvents('test-server', {}) + await Promise.resolve() + + harnesses[0].emit(v2Event('session.idle', { sessionID: 's1' })) + await vi.advanceTimersByTimeAsync(0) + expect(getServerConnectionInfo('test-server').state).toBe('connected') + + // 后台期间心跳停了,但还没到看门狗阈值(45s)——确保救场的不是看门狗 + await vi.advanceTimersByTimeAsync(25_000) + expect(getServerConnectionInfo('test-server').state).toBe('connected') + + setDocumentVisibility('hidden') + document.dispatchEvent(new Event('visibilitychange')) + setDocumentVisibility('visible') + document.dispatchEvent(new Event('visibilitychange')) + + // 复核窗口 + 半开连接复位兜底 + 退避重连 + await vi.advanceTimersByTimeAsync(3_000) + await vi.advanceTimersByTimeAsync(6_000) + + expect(subscribeMock.mock.calls.length).toBeGreaterThanOrEqual(2) + unsubscribe() + } finally { + setDocumentVisibility('visible') + vi.useRealTimers() + } + }) + /** * 端点变更重连必须广播 onReconnected:否则订阅者不做补偿拉取, * WSL 端口变化等场景下状态/权限/消息全部陈旧。 diff --git a/src/api/events.ts b/src/api/events.ts index 072c3fe76..df1b09e0d 100644 --- a/src/api/events.ts +++ b/src/api/events.ts @@ -81,6 +81,8 @@ const endpointReconnectFlags = new Map() let lifecycleListenersRegistered = false let isInBackground = false let keepaliveTimer: ReturnType | null = null +/** 切回前台后的静默复核定时器(见 RESUME_PROBE_DELAY_MS) */ +let resumeProbeTimer: ReturnType | null = null // ============================================ // 常量 @@ -116,6 +118,13 @@ const CONNECT_STALL_TIMEOUT = 15_000 * 刚收到心跳就被误判。 */ const ONLINE_RESUME_SILENCE_MS = 20_000 +/** + * 切回前台后的静默复核延迟(Issue #184)。 + * + * 后台期间 JS 定时器会被冻结,回到前台时「静默时长」天然偏大,不能立刻 + * 据此判死连接——先留一小段时间让恢复后缓冲的事件/心跳落地,再复核。 + */ +const RESUME_PROBE_DELAY_MS = 2_000 const DEFAULT_CONNECTION_INFO: ConnectionInfo = { state: 'disconnected', @@ -703,6 +712,65 @@ function disconnectServerConnection(conn: ServerConnection): void { // 生命周期 / keepalive // ============================================ +/** + * 掐断半开连接,交给重连循环。 + * + * abort 后底层 fetch 通常会让 for-await 退出;但挂起的读可能不认 abort, + * isConnecting 会卡在 true 吞掉所有重连入口。5s 后仍卡在同一代次就作废 + * 本代次强制复位(与看门狗的同款兜底)。 + */ +function dropSilentConnection(conn: ServerConnection): void { + conn.watchdogDrop = true + conn.controller?.abort() + const generation = conn.generation + setTimeout(() => { + if (generation !== conn.generation) return + if (!conn.isConnecting) return + conn.generation += 1 + conn.isConnecting = false + conn.watchdogDrop = false + conn.connectStartedAt = 0 + updateConnectionState(conn.serverId, { state: 'disconnected' }) + scheduleReconnect(conn) + }, 5_000) +} + +/** + * 连接自愈:网络恢复(online)与切回前台(visibilitychange)共用。 + * + * - 没连上:立刻建连,不等退避定时器; + * - 状态还是 connected 但已静默超过一个心跳:说明是半开连接,主动掐断重连。 + * + * 状态停在 connected 不等于连着:断网时 TCP 常常是半开的——流既不报错也 + * 不结束,状态就一直挂着,只能等看门狗 45s 才发现。网络恢复 / 回到前台 + * 都是外部事实,此时按「静默超过一个心跳就判可疑」主动校准,而不是相信 + * state === 'connected'。阈值取得比看门狗短得多:断网期间心跳必然收不到, + * 恢复后按心跳间隔算早该有几个了。 + * + * 静默不足阈值的直接放过——短时间切屏、网络没变时保持懒连接(Issue #184)。 + */ +function revalidateConnections(): void { + for (const conn of connections.values()) { + if (conn.subscribers.size === 0) continue + + if (conn.info.state !== 'connected') { + if (conn.isConnecting) continue + // 退避定时器可能排到 30s 后,回前台时没有干等的必要 + if (conn.reconnectTimer) { + clearTimeout(conn.reconnectTimer) + conn.reconnectTimer = null + } + connectServer(conn.serverId) + continue + } + + const silentFor = Date.now() - conn.info.lastEventTime + if (conn.info.lastEventTime > 0 && silentFor > ONLINE_RESUME_SILENCE_MS) { + dropSilentConnection(conn) + } + } +} + function registerLifecycleListeners(): void { if (lifecycleListenersRegistered) return if (typeof document === 'undefined') return @@ -712,45 +780,28 @@ function registerLifecycleListeners(): void { isInBackground = document.visibilityState === 'hidden' if (isInBackground) { startBackgroundKeepalive() - } else { - stopBackgroundKeepalive() + return } + + /** + * 后台期间 JS 定时器会被冻结,看门狗不会 tick;回到前台若连接已是半开, + * 状态还停在 connected,用户要等最多 45s 才看到界面恢复。 + * + * 先留一个很短的窗口让恢复后缓冲的事件/心跳落地,再复核静默时长: + * 连接好好的时候,不该因为「后台没跑定时器」就白重连一次。 + */ + stopBackgroundKeepalive() + if (resumeProbeTimer) clearTimeout(resumeProbeTimer) + resumeProbeTimer = setTimeout(() => { + resumeProbeTimer = null + // 复核前又切走了:交给后台 keepalive,别在这里抢先重连 + if (document.visibilityState === 'hidden') return + revalidateConnections() + }, RESUME_PROBE_DELAY_MS) }) window.addEventListener('online', () => { - for (const conn of connections.values()) { - if (conn.subscribers.size === 0) continue - - if (conn.info.state !== 'connected') { - connectServer(conn.serverId) - continue - } - - /** - * 状态停在 connected 不等于连着:断网时 TCP 常常是半开的——流既不报错 - * 也不结束,状态就一直挂着,直到看门狗 45s 后才发现。等那么久,用户看到 - * 的就是「网回来了但界面不动,得刷新」。 - * - * 网络恢复是外部事实:此时若已有一段时间没收到任何字节(含心跳), - * 就当作可疑连接主动掐断重连。阈值取得比看门狗短得多——断网期间心跳 - * 必然收不到,恢复后按心跳间隔算早该有几个了。 - */ - const silentFor = Date.now() - conn.info.lastEventTime - if (conn.info.lastEventTime > 0 && silentFor > ONLINE_RESUME_SILENCE_MS) { - conn.watchdogDrop = true - conn.controller?.abort() - setTimeout(() => { - if (conn.isConnecting) { - conn.generation += 1 - conn.isConnecting = false - conn.watchdogDrop = false - conn.connectStartedAt = 0 - updateConnectionState(conn.serverId, { state: 'disconnected' }) - scheduleReconnect(conn) - } - }, 5_000) - } - } + revalidateConnections() }) } From 5b8be80d8f79d7f020bb33abe788c071d965fd02 Mon Sep 17 00:00:00 2001 From: lehhair Date: Fri, 23 Oct 2026 14:59:25 +0800 Subject: [PATCH 28/67] =?UTF-8?q?fix(files):=20=E5=88=87=E6=8D=A2=E9=A2=84?= =?UTF-8?q?=E8=A7=88=E6=A0=87=E7=AD=BE=E4=B8=8D=E5=86=8D=E6=94=B9=E5=8F=98?= =?UTF-8?q?=E6=A0=87=E7=AD=BE=E9=A1=BA=E5=BA=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 点标签激活时把条目移到列表末尾,导致标签位置跳动。标签顺序与最近激活拆成两份状态:previewFiles 只做 tab 顺序,previewActive 记录每个工作区的最近激活,切回工作区时仍能恢复上次看的文件。重复打开已存在的文件也原地替换,顺便修正关闭活跃标签后的回退到右邻。 --- src/components/BottomPanel.tsx | 1 + src/components/FileExplorer.tsx | 15 +++++++-- src/components/RightPanel.tsx | 1 + src/store/layoutStore.test.ts | 54 ++++++++++++++++++++++++++++++++- src/store/layoutStore.ts | 39 ++++++++++++++++++------ 5 files changed, 98 insertions(+), 12 deletions(-) diff --git a/src/components/BottomPanel.tsx b/src/components/BottomPanel.tsx index 3683383f6..11b4ae847 100644 --- a/src/components/BottomPanel.tsx +++ b/src/components/BottomPanel.tsx @@ -311,6 +311,7 @@ const FilesContent = memo(function FilesContent({ serverId={serverId} previewFile={tab.previewFile ?? null} previewFiles={tab.previewFiles ?? []} + previewActive={tab.previewActive} position="bottom" isPanelResizing={isPanelResizing} sessionId={sessionId} diff --git a/src/components/FileExplorer.tsx b/src/components/FileExplorer.tsx index 9cd65d357..bff2af011 100644 --- a/src/components/FileExplorer.tsx +++ b/src/components/FileExplorer.tsx @@ -9,7 +9,7 @@ import { createPortal } from 'react-dom' import { useTranslation } from 'react-i18next' import { useFileExplorer, type FileTreeNode } from '../hooks' import { useVerticalSplitResize } from '../hooks/useVerticalSplitResize' -import { layoutStore, previewMatchesDirectory, type PreviewFile } from '../store/layoutStore' +import { layoutStore, previewMatchesDirectory, type PreviewActiveEntry, type PreviewFile } from '../store/layoutStore' import { ChevronRightIcon, ChevronDownIcon, @@ -95,6 +95,8 @@ interface FileExplorerProps { serverId?: string previewFile: PreviewFile | null previewFiles: PreviewFile[] + /** 最近激活的预览(旧→新),切回工作区时恢复用,不参与 tab 排序 */ + previewActive?: PreviewActiveEntry[] position?: 'bottom' | 'right' isPanelResizing?: boolean sessionId?: string | null @@ -106,6 +108,7 @@ export const FileExplorer = memo(function FileExplorer({ serverId, previewFile, previewFiles, + previewActive, position = 'right', isPanelResizing = false, sessionId, @@ -167,8 +170,16 @@ export const FileExplorer = memo(function FileExplorer({ ) const scopedPreviewFile = useMemo(() => { if (previewFile && previewMatchesDirectory(previewFile, effectiveDirectory)) return previewFile + // 切回工作区:恢复该工作区最近激活的预览。用独立的「最近激活」记录, + // 而不是列表末尾——tab 顺序必须保持稳定,点标签不能让位置跳 + for (let index = (previewActive?.length ?? 0) - 1; index >= 0; index -= 1) { + const entry = previewActive![index] + if (!previewMatchesDirectory(entry, effectiveDirectory)) continue + const match = scopedPreviewFiles.find(file => file.path === entry.path) + if (match) return match + } return scopedPreviewFiles[scopedPreviewFiles.length - 1] ?? null - }, [previewFile, scopedPreviewFiles, effectiveDirectory]) + }, [previewFile, previewActive, scopedPreviewFiles, effectiveDirectory]) // 当 previewFile 改变时加载预览 useEffect(() => { diff --git a/src/components/RightPanel.tsx b/src/components/RightPanel.tsx index d98034c6a..7d01712f5 100644 --- a/src/components/RightPanel.tsx +++ b/src/components/RightPanel.tsx @@ -269,6 +269,7 @@ const FilesContent = memo(function FilesContent({ serverId={serverId} previewFile={tab.previewFile ?? null} previewFiles={tab.previewFiles ?? []} + previewActive={tab.previewActive} position="right" isPanelResizing={isPanelResizing} sessionId={sessionId} diff --git a/src/store/layoutStore.test.ts b/src/store/layoutStore.test.ts index 0e8db95c6..e61080aa4 100644 --- a/src/store/layoutStore.test.ts +++ b/src/store/layoutStore.test.ts @@ -202,7 +202,7 @@ describe('LayoutStore file preview workspace scoping', () => { store.openFilePreview({ path: 'b.ts', name: 'b.ts', directory: '/repo' }) store.activateFilePreview('files', 'a.ts', '/repo') - // a.ts 是活跃(且因激活移到末尾=最近) + // a.ts 是活跃(关闭后应回退到右邻) expect(store.getState().panelTabs.find(t => t.id === 'files')?.previewFile?.path).toBe('a.ts') store.closeFilePreview('files', 'a.ts', '/repo') @@ -221,4 +221,56 @@ describe('LayoutStore file preview workspace scoping', () => { expect(tab?.previewFiles).toHaveLength(1) expect(tab?.previewFiles?.[0]?.directory).toBe('/repo-a') }) + + it('切换标签不改变标签顺序', () => { + const store = new LayoutStore() + store.openFilePreview({ path: 'a.ts', name: 'a.ts', directory: '/repo' }) + store.openFilePreview({ path: 'b.ts', name: 'b.ts', directory: '/repo' }) + store.openFilePreview({ path: 'c.ts', name: 'c.ts', directory: '/repo' }) + + store.activateFilePreview('files', 'a.ts', '/repo') + + const tab = store.getState().panelTabs.find(item => item.id === 'files') + expect(tab?.previewFiles?.map(item => item.path)).toEqual(['a.ts', 'b.ts', 'c.ts']) + expect(tab?.previewFile?.path).toBe('a.ts') + }) + + it('重复打开已存在的文件保持原位,只更新元数据', () => { + const store = new LayoutStore() + store.openFilePreview({ path: 'a.ts', name: 'a.ts', directory: '/repo' }) + store.openFilePreview({ path: 'b.ts', name: 'b.ts', directory: '/repo' }) + + store.openFilePreview({ path: 'a.ts', name: 'a.ts', directory: '/repo', targetLine: 42 }) + + const tab = store.getState().panelTabs.find(item => item.id === 'files') + expect(tab?.previewFiles?.map(item => item.path)).toEqual(['a.ts', 'b.ts']) + expect(tab?.previewFiles?.[0]?.targetLine).toBe(42) + expect(tab?.previewFile?.path).toBe('a.ts') + }) + + it('关闭活跃标签后落到右邻标签', () => { + const store = new LayoutStore() + store.openFilePreview({ path: 'a.ts', name: 'a.ts', directory: '/repo' }) + store.openFilePreview({ path: 'b.ts', name: 'b.ts', directory: '/repo' }) + store.openFilePreview({ path: 'c.ts', name: 'c.ts', directory: '/repo' }) + + store.activateFilePreview('files', 'b.ts', '/repo') + store.closeFilePreview('files', 'b.ts', '/repo') + + const tab = store.getState().panelTabs.find(item => item.id === 'files') + expect(tab?.previewFile?.path).toBe('c.ts') + }) + + it('按工作区分别记录最近激活的预览', () => { + const store = new LayoutStore() + store.openFilePreview({ path: 'a1.ts', name: 'a1.ts', directory: '/repo-a' }) + store.openFilePreview({ path: 'a2.ts', name: 'a2.ts', directory: '/repo-a' }) + store.openFilePreview({ path: 'b1.ts', name: 'b1.ts', directory: '/repo-b' }) + + store.activateFilePreview('files', 'a1.ts', '/repo-a') + + const tab = store.getState().panelTabs.find(item => item.id === 'files') + expect(tab?.previewFiles?.map(item => item.path)).toEqual(['a1.ts', 'a2.ts', 'b1.ts']) + expect(tab?.previewActive?.at(-1)).toMatchObject({ path: 'a1.ts', directory: '/repo-a' }) + }) }) diff --git a/src/store/layoutStore.ts b/src/store/layoutStore.ts index d5e189921..a3520c287 100644 --- a/src/store/layoutStore.ts +++ b/src/store/layoutStore.ts @@ -16,6 +16,8 @@ export interface PanelTab { position: PanelPosition previewFile?: PreviewFile | null previewFiles?: PreviewFile[] + /** 最近激活的预览(按激活先后,旧的在前)。只用于切回工作区时恢复,不参与 tab 排序 */ + previewActive?: PreviewActiveEntry[] // Terminal 特有属性 ptyId?: string /** 终端所属服务器(PTY 创建时记录;连接/恢复时用该服务器,而不是当前焦点服务器) */ @@ -48,6 +50,12 @@ function samePreviewIdentity(a: { path: string; directory?: string }, b: { path: return a.path === b.path && (a.directory ?? '') === (b.directory ?? '') } +/** 「最近激活」记录:切回工作区时用来恢复上次看的文件,与 tab 顺序解耦 */ +export interface PreviewActiveEntry { + path: string + directory?: string +} + /** 条目是否属于当前工作区:无目录信息(旧数据/无工作区上下文)时始终可见 */ export function previewMatchesDirectory(file: { directory?: string }, directory: string | undefined): boolean { if (!file.directory || !directory) return true @@ -840,12 +848,15 @@ export class LayoutStore { ? { ...file, directory: normalizeToForwardSlash(file.directory) } : file - // 按身份(path+工作区)去重;已存在则移到末尾——列表顺序即「最近使用序」, - // FileExplorer 用它推导每个工作区自己的最近预览 - const rest = (targetTab.previewFiles ?? []).filter(item => !samePreviewIdentity(item, normalizedFile)) + // 按身份(path+工作区)去重;已存在就**原地替换**(更新 targetLine 等), + // 不改变 tab 顺序——浏览器/编辑器里点一个已打开的文件不会让标签跳位置 + const list = targetTab.previewFiles ?? [] + const index = list.findIndex(item => samePreviewIdentity(item, normalizedFile)) - targetTab.previewFiles = [...rest, normalizedFile] + targetTab.previewFiles = + index === -1 ? [...list, normalizedFile] : list.map((item, i) => (i === index ? normalizedFile : item)) targetTab.previewFile = normalizedFile + this.recordPreviewActive(targetTab, normalizedFile) this.state.activeTabId[targetTab.position] = targetTab.id this.setPanelOpen(targetTab.position, true) this.notify() @@ -858,9 +869,9 @@ export class LayoutStore { const identity = { path, directory } const file = files.find(item => samePreviewIdentity(item, identity)) if (!file) return - // 激活即最近:移到末尾,保持每个工作区的最近序 - tab.previewFiles = [...files.filter(item => !samePreviewIdentity(item, identity)), file] + // 只切换活跃项,不动 tab 顺序;「最近激活」另记,供切回工作区时恢复 tab.previewFile = file + this.recordPreviewActive(tab, file) this.notify() } @@ -871,18 +882,20 @@ export class LayoutStore { if (!tab || !previewFiles || !targetPath) return const identity = { path: targetPath, directory: directory ?? tab.previewFile?.directory } - if (!previewFiles.some(item => samePreviewIdentity(item, identity))) return + const index = previewFiles.findIndex(item => samePreviewIdentity(item, identity)) + if (index === -1) return const isActive = !!tab.previewFile && samePreviewIdentity(tab.previewFile, identity) const nextPreviewFiles = previewFiles.filter(item => !samePreviewIdentity(item, identity)) tab.previewFiles = nextPreviewFiles + tab.previewActive = (tab.previewActive ?? []).filter(item => !samePreviewIdentity(item, identity)) if (nextPreviewFiles.length === 0) { tab.previewFile = null } else if (isActive) { - // 关闭活跃预览后回退到最近使用的条目(末尾 = 最近) - tab.previewFile = nextPreviewFiles[nextPreviewFiles.length - 1] ?? null + // 关闭活跃预览后落到右邻标签(没有右邻就用最后一个),与浏览器一致 + tab.previewFile = nextPreviewFiles[Math.min(index, nextPreviewFiles.length - 1)] ?? null } this.notify() @@ -893,6 +906,7 @@ export class LayoutStore { if (!tab) return tab.previewFile = null tab.previewFiles = [] + tab.previewActive = [] this.notify() } @@ -913,6 +927,13 @@ export class LayoutStore { this.notify() } + /** 记录「最近激活」(按工作区各自维护),只影响切回工作区时的恢复 */ + private recordPreviewActive(tab: PanelTab, file: PreviewFile) { + const rest = (tab.previewActive ?? []).filter(item => !samePreviewIdentity(item, file)) + // 上限防止长时间使用后无界增长;只保留最近的条目 + tab.previewActive = [...rest, { path: file.path, directory: file.directory }].slice(-100) + } + private getTargetFilesTab(position?: PanelPosition): PanelTab | null { if (position) { const activeId = this.state.activeTabId[position] From 95e19efcb6406a64db8b7649a07fafa72884892b Mon Sep 17 00:00:00 2001 From: lehhair Date: Fri, 23 Oct 2026 15:00:12 +0800 Subject: [PATCH 29/67] =?UTF-8?q?fix(attachment):=20file://=20=E9=99=84?= =?UTF-8?q?=E4=BB=B6=E5=9C=B0=E5=9D=80=E6=8C=89=E6=AE=B5=E7=BC=96=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 官方 @opencode/util 的 encodeFilePath 会逐段 encodeURIComponent,我们之前直接拼原始路径。文件名带 # / ? / % 时会被 new URL 当成 hash / query / 转义符,服务端 fileURLToPath 截断或抛 URI malformed,发送直接失败。现在对齐官方实现,盘符冒号保留。 --- src/utils/pathUtils.test.ts | 24 +++++++++++++++++++++--- src/utils/pathUtils.ts | 34 ++++++++++++++++++++++++++++------ 2 files changed, 49 insertions(+), 9 deletions(-) diff --git a/src/utils/pathUtils.test.ts b/src/utils/pathUtils.test.ts index d6bae5d32..dea36deab 100644 --- a/src/utils/pathUtils.test.ts +++ b/src/utils/pathUtils.test.ts @@ -1,5 +1,5 @@ import { describe, it, expect } from 'vitest' -import { canonicalizePath, resolveEntryPath, fileBaseName, toAbsoluteFilePath } from './pathUtils' +import { absolutePathToFileUrl, canonicalizePath, resolveEntryPath, fileBaseName, toAbsoluteFilePath } from './pathUtils' describe('canonicalizePath', () => { it('折叠 .. 段(Windows 盘符根)', () => { @@ -32,8 +32,26 @@ describe('canonicalizePath', () => { }) }) -describe('resolveEntryPath', () => { - // v2 file.list 的条目 path 相对 location 根,浏览到根之外时带 ../ +describe('absolutePathToFileUrl', () => { + it('Windows 盘符保留冒号,路径分段做 URL 编码', () => { + expect(absolutePathToFileUrl('C:\\Users\\me\\My File.txt')).toBe('file:///C:/Users/me/My%20File.txt') + expect(absolutePathToFileUrl('C:/tmp/a#b?c%d.txt')).toBe('file:///C:/tmp/a%23b%3Fc%25d.txt') + }) + + it('Unix 绝对路径与相对路径都给出三斜杠形态', () => { + expect(absolutePathToFileUrl('/workspace/my file.ts')).toBe('file:///workspace/my%20file.ts') + expect(absolutePathToFileUrl('src/my file.ts')).toBe('file:///src/my%20file.ts') + }) + + it('中文与保留字符可被 new URL 原样还原', () => { + const path = '/tmp/目录/报告 (最终版)#2.txt' + const url = absolutePathToFileUrl(path) + expect(new URL(url).hash).toBe('') + expect(decodeURIComponent(new URL(url).pathname)).toBe(path) + }) +}) + +describe('resolveEntryPath', () => { // v2 file.list 的条目 path 相对 location 根,浏览到根之外时带 ../ it('根之内的条目直接拼到根上', () => { expect(resolveEntryPath('src/components/', 'D:/work/project')).toBe('D:/work/project/src/components') }) diff --git a/src/utils/pathUtils.ts b/src/utils/pathUtils.ts index a592687ac..329129468 100644 --- a/src/utils/pathUtils.ts +++ b/src/utils/pathUtils.ts @@ -31,18 +31,40 @@ export function normalizePathSeparators(path: string): string { return result } +/** + * 逐段做 URL 编码(官方 `@opencode/util` 的 encodeFilePath 同款)。 + * + * `new URL()` 会把空格自动转成 `%20`,但 `#` / `?` / `%` 会被当成结构字符: + * 路径里带这些字符时,服务端 `new URL(uri)` + `fileURLToPath` 会截断或抛 + * `URI malformed`,附件直接读不到。所以发出去之前必须逐段编码。 + */ +function encodeFilePath(normalized: string): string { + // Windows 盘符补前导斜杠:C:/x → /C:/x + const rooted = /^[a-zA-Z]:/.test(normalized) + ? `/${normalized}` + : normalized.startsWith('/') + ? normalized + : `/${normalized}` + + return rooted + .split('/') + .map((segment, index) => { + // 保留盘符里的冒号(/C:/...),否则 fileURLToPath 认不出盘符 + if (index === 1 && /^[a-zA-Z]:$/.test(segment)) return segment + return encodeURIComponent(segment) + }) + .join('/') +} + /** * 绝对路径 → `file://` URL(服务端 `readFileAttachment` 只接受 file: 协议, * 裸路径会被 `new URL` 解析成盘符协议而 400)。 * - * Windows 盘符要三斜杠(`file:///C:/x`),Unix 绝对路径两斜杠(`file:///x` 亦可, - * 这里保持与官方 `file://${encodeFilePath(path)}` 兼容的形态)。 + * Windows 盘符要三斜杠(`file:///C:/x`),Unix 绝对路径三斜杠 + * (`file:///x`)。路径分段做 URL 编码,空格 / `#` / `%` 等字符不会破坏 URI。 */ export function absolutePathToFileUrl(path: string): string { - const normalized = normalizePathSeparators(path).replace(/\/{2,}/g, '/') - if (/^[a-zA-Z]:/.test(normalized)) return `file:///${normalized}` - if (normalized.startsWith('/')) return `file://${normalized}` - return `file:///${normalized}` + return `file://${encodeFilePath(normalizePathSeparators(path))}` } /** From 9d5e40c8ce835b9d95457e4fa6bc26b15285b9d7 Mon Sep 17 00:00:00 2001 From: lehhair Date: Fri, 23 Oct 2026 15:00:35 +0800 Subject: [PATCH 30/67] =?UTF-8?q?fix(message):=20=E9=87=8D=E8=AF=95?= =?UTF-8?q?=E5=8D=A1=E7=89=87=E6=98=BE=E7=A4=BA=E5=AE=9E=E6=97=B6=E5=80=92?= =?UTF-8?q?=E8=AE=A1=E6=97=B6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 官方 session-retry.tsx 用 retry.at - Date.now() 算倒计时;我们之前只显示一条本地时间,看不出还有多久。现在对齐官方语义,顺带把错误摘要放到卡片标题下,和官方卡片的信息层级一致。 --- .../message/parts/SystemPartViews.test.tsx | 18 ++++++++++++++++-- .../message/parts/SystemPartViews.tsx | 19 ++++++++++++++++--- src/locales/en/message.json | 2 ++ src/locales/zh-CN/message.json | 2 ++ 4 files changed, 36 insertions(+), 5 deletions(-) diff --git a/src/features/message/parts/SystemPartViews.test.tsx b/src/features/message/parts/SystemPartViews.test.tsx index 7f2df59f1..011d3e890 100644 --- a/src/features/message/parts/SystemPartViews.test.tsx +++ b/src/features/message/parts/SystemPartViews.test.tsx @@ -28,8 +28,9 @@ describe('SystemPartViews', () => { it('toggles retry details with a semantic button', () => { render() - const toggle = screen.getByRole('button', { name: /Retry attempt 2/i }) + const toggle = screen.getByRole('button', { name: /Retrying now \(attempt 2\)/i }) expect(toggle).toHaveAttribute('aria-expanded', 'false') + expect(screen.queryByText('Status: 504')).toBeNull() fireEvent.click(toggle) act(() => { @@ -37,6 +38,19 @@ describe('SystemPartViews', () => { }) expect(toggle).toHaveAttribute('aria-expanded', 'true') - expect(screen.getByText('network timeout')).toBeInTheDocument() + expect(screen.getByText('Status: 504')).toBeInTheDocument() + }) + + it('shows a live countdown until the next retry', () => { + const at = Date.now() + 5000 + render() + + expect(screen.getByRole('button', { name: /Retrying in 5s \(attempt 2\)/i })).toBeInTheDocument() + + act(() => { + vi.advanceTimersByTime(2000) + }) + + expect(screen.getByRole('button', { name: /Retrying in 3s \(attempt 2\)/i })).toBeInTheDocument() }) }) diff --git a/src/features/message/parts/SystemPartViews.tsx b/src/features/message/parts/SystemPartViews.tsx index 220f6ee7c..958744e3b 100644 --- a/src/features/message/parts/SystemPartViews.tsx +++ b/src/features/message/parts/SystemPartViews.tsx @@ -4,6 +4,7 @@ import { RetryIcon, ChevronDownIcon } from '../../../components/Icons' import { CopyButton } from '../../../components/ui' import { MarkdownRenderer } from '../../../components/MarkdownRenderer' import { useDisclosureScrollLock } from '../../../hooks' +import { useNow } from '../../../hooks/useNow' import { useTheme } from '../../../hooks/useTheme' import type { SessionMessageAssistant, SessionMessageCompaction, SessionMessageInfo } from '@opencode/client/promise' import { useUiDisclosureState } from '../../../utils/uiDisclosureState' @@ -39,8 +40,16 @@ export const RetryPartView = memo(function RetryPartView({ retry, stateKey }: Re const shouldRenderBody = useMessageExpandRender(expanded) const { rootRef, headerRef, withScrollLock } = useDisclosureScrollLock() const { attempt, error, at } = retry + const now = useNow(250) + + // `at` 是下一次重试的绝对时间戳(与官方 session-retry.tsx 的 `next - Date.now()` 一致)。 + // 超过 10 分钟视为数据异常(旧版本/脏数据),宁可不显示倒计时。 + const remainingMs = at - now + const showCountdown = remainingMs > 0 && remainingMs <= 10 * 60_000 + const info = showCountdown + ? t('system.retryWaiting', { attempt, seconds: Math.ceil(remainingMs / 1000) }) + : t('system.retryNow', { attempt }) - const timeStr = new Date(at).toLocaleTimeString() const isRetryable = isRetryableStatus(error) return ( @@ -54,8 +63,12 @@ export const RetryPartView = memo(function RetryPartView({ retry, stateKey }: Re >
- {t('system.retryAttempt', { attempt })} - {timeStr} + {info} + {error.message && ( + + {unwrapErrorMessage(error.message)} + + )}
{isRetryable && ( diff --git a/src/locales/en/message.json b/src/locales/en/message.json index 161b0bcb4..b68b4732d 100644 --- a/src/locales/en/message.json +++ b/src/locales/en/message.json @@ -123,6 +123,8 @@ }, "system": { "retryAttempt": "Retry attempt {{attempt}}", + "retryWaiting": "Retrying in {{seconds}}s (attempt {{attempt}})", + "retryNow": "Retrying now (attempt {{attempt}})", "retryable": "Retryable", "statusCode": "Status: {{code}}", "contextCompacted": "History compacted", diff --git a/src/locales/zh-CN/message.json b/src/locales/zh-CN/message.json index 89c0719ac..bdc1e7a8d 100644 --- a/src/locales/zh-CN/message.json +++ b/src/locales/zh-CN/message.json @@ -95,6 +95,8 @@ }, "system": { "retryAttempt": "重试第 {{attempt}} 次", + "retryWaiting": "{{seconds}} 秒后重试(第 {{attempt}} 次)", + "retryNow": "正在重试(第 {{attempt}} 次)", "retryable": "可重试", "statusCode": "状态码:{{code}}", "contextCompacted": "历史已压缩", From 8c9e02e16986dacbce4d0690c3d24c088ed79a60 Mon Sep 17 00:00:00 2001 From: lehhair Date: Fri, 23 Oct 2026 16:03:12 +0800 Subject: [PATCH 31/67] =?UTF-8?q?feat(timeline):=20=E8=A1=A5=E9=BD=90?= =?UTF-8?q?=E5=88=87=E6=8D=A2=E8=AE=B0=E5=BD=95=E3=80=81=E5=8E=8B=E7=BC=A9?= =?UTF-8?q?=E6=8E=92=E9=98=9F=E4=B8=8E=E5=9B=9E=E5=90=88=20diff=20?= =?UTF-8?q?=E7=9A=84=E6=B8=B2=E6=9F=93?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/api/session.ts | 28 +++ src/features/chat/ChatArea.test.ts | 132 ++++++++++++++ src/features/chat/ChatArea.tsx | 40 ++++- src/features/chat/ChatPane.tsx | 2 + src/features/chat/chatAreaUtils.ts | 4 +- src/features/chat/chatAreaVisibility.ts | 33 ++++ src/features/chat/chatPageModel.ts | 122 ++++++++++++- src/features/message/MessageRenderer.tsx | 25 ++- .../message/parts/MessageErrorView.test.tsx | 37 ++++ .../message/parts/MessageErrorView.tsx | 64 ++++++- .../message/parts/NoticePartView.test.tsx | 64 +++++++ src/features/message/parts/NoticePartView.tsx | 169 ++++++++++++++++++ .../message/parts/TurnDiffPartView.test.tsx | 58 ++++++ .../message/parts/TurnDiffPartView.tsx | 145 +++++++++++++++ src/features/message/parts/index.ts | 3 + src/hooks/useChatSession.ts | 5 +- src/locales/en/message.json | 20 ++- src/locales/zh-CN/message.json | 20 ++- src/store/inboxStore.ts | 19 +- src/store/messageStore.ts | 19 +- 20 files changed, 989 insertions(+), 20 deletions(-) create mode 100644 src/features/message/parts/MessageErrorView.test.tsx create mode 100644 src/features/message/parts/NoticePartView.test.tsx create mode 100644 src/features/message/parts/NoticePartView.tsx create mode 100644 src/features/message/parts/TurnDiffPartView.test.tsx create mode 100644 src/features/message/parts/TurnDiffPartView.tsx diff --git a/src/api/session.ts b/src/api/session.ts index 4f0de83d5..3bcc8f97a 100644 --- a/src/api/session.ts +++ b/src/api/session.ts @@ -77,6 +77,34 @@ export async function getSessionDiff(sessionId: string, serverId?: string): Prom return normalizeFileDiffs(diffs) } +/** 单轮 diff 的 in-flight 去重(虚拟列表来回挂载时不重复请求) */ +const inflightTurnDiffs = new Map>() + +/** + * 取某一轮(从指定 user message 起)的文件 diff。 + * + * 官方 timeline 的 TurnDiff 行用 `session.diff({ sessionID, from })`, + * `from` 是该轮用户消息 id。返回的 patch 可直接交给 DiffView 渲染。 + */ +export async function getTurnDiff(sessionId: string, from: string, serverId?: string): Promise { + const target = resolveSessionTarget(sessionId, serverId) + const key = `${target.serverId}:${target.sessionId}:${from}` + const inflight = inflightTurnDiffs.get(key) + if (inflight) return inflight + + const request = (async () => { + try { + const sdk = getSDKClient(target.serverId) + const diffs = await sdk.session.diff({ sessionID: target.sessionId, from }) + return normalizeFileDiffs(diffs) + } finally { + inflightTurnDiffs.delete(key) + } + })() + inflightTurnDiffs.set(key, request) + return request +} + // ============================================ // 会话 CRUD // ============================================ diff --git a/src/features/chat/ChatArea.test.ts b/src/features/chat/ChatArea.test.ts index 84897a061..ffdd02bd4 100644 --- a/src/features/chat/ChatArea.test.ts +++ b/src/features/chat/ChatArea.test.ts @@ -14,6 +14,7 @@ import { reconcileStableChatPages, reuseProcessTimelineItems, seedMeasuredPageHeightsFromPreviousPages, + buildFlatTimeline, } from './chatPageModel' import { getStreamingHotIndexes, getTimelineRowYClass, mergeVirtualRangeIndexes } from './chatAreaUtils' import { buildVisibleMessageEntries, getVisibleMessageForkTargetId } from './chatAreaVisibility' @@ -115,6 +116,45 @@ describe('buildVisibleMessageEntries', () => { expect(entries.some(e => e.message.id === 'idle-abort')).toBe(false) }) + it('keeps timeline notices visible (switch records / system / skill / synthetic)', () => { + const notices = [ + { id: 'agent-switch', type: 'agent-switched', agent: 'plan', time: { created: 2 } }, + { + id: 'model-switch', + type: 'model-switched', + model: { providerID: 'openai', id: 'gpt-5' }, + time: { created: 3 }, + }, + { id: 'skill', type: 'skill', skill: 'pdf', name: 'PDF', text: '', time: { created: 4 } }, + { + id: 'system', + type: 'system', + text: 'x', + description: 'Instructions updated: AGENTS.md', + time: { created: 5 }, + }, + { id: 'synthetic', type: 'synthetic', text: 'ctx', description: 'Explore finished', time: { created: 6 } }, + // 纯注入上下文没有 description:默认不占行(官方 isNotice 同款) + { id: 'synthetic-context', type: 'synthetic', text: 'raw context', time: { created: 7 } }, + // 但错误状态必须露出 + { + id: 'synthetic-error', + type: 'synthetic', + text: 'failed', + metadata: { state: 'error' }, + time: { created: 8 }, + }, + ] as SessionMessageInfo[] + + const entries = buildVisibleMessageEntries([createUserMessage('user-1', 1, '你好'), ...notices]) + const ids = entries.map(entry => entry.message.id) + + expect(ids).toEqual( + expect.arrayContaining(['agent-switch', 'model-switch', 'skill', 'system', 'synthetic', 'synthetic-error']), + ) + expect(ids).not.toContain('synthetic-context') + }) + it('keeps source ids for merged assistant tool messages', () => { const first = createAssistantMessage('assistant-1', [createToolPart('tool-1', 'assistant-1')]) const second = createAssistantMessage('assistant-2', [createToolPart('tool-2', 'assistant-2')]) @@ -668,6 +708,33 @@ describe('buildProcessTimeline', () => { } }) + it('keeps notices outside the process shell, before/after by position', () => { + const agentSwitch = { + id: 'agent-switch', + type: 'agent-switched', + agent: 'plan', + time: { created: 1000 }, + } as SessionMessageInfo + const assistant = createAssistantMessage('assistant-1', [createToolPart('tool-1', 'assistant-1')], 1001, 1002) + const skill = { + id: 'skill-1', + type: 'skill', + skill: 'pdf', + name: 'PDF', + text: '', + time: { created: 1003 }, + } as SessionMessageInfo + const messages = [createUserMessage('user-1', 1000), agentSwitch, assistant, skill] + const timeline = buildProcessTimeline(messages, { + turnDurationMap: new Map(), + sessionIsStreaming: false, + messageHasProcess: hasProcess, + messageHasFinal: hasFinal, + }) + + expect(timeline.map(item => item.key)).toEqual(['user-1', 'agent-switch', 'process-shell:user-1', 'skill-1']) + }) + it('does not duplicate the error card when the last assistant already shows it', () => { // assistant.error 已由 MessageErrorView 渲染 → idle 卡片跳过(官方同款去重) const failedAssistant = createAssistantMessage( @@ -947,6 +1014,71 @@ describe('buildProcessTimeline', () => { expect(timeline.map(item => item.kind)).toEqual(['message', 'message']) expect(timeline[1]).toMatchObject({ kind: 'message', key: 'assistant-1' }) }) + + it('appends a turn diff after a settled turn with changed files', () => { + const assistant = createAssistantMessage('assistant-1', [createToolPart('tool-1', 'assistant-1')], 1001, 1002) + assistant.snapshot = { files: ['b.ts', 'a.ts', 'a.ts'] } + const messages = [createUserMessage('user-1', 1000), assistant] + const timeline = buildProcessTimeline(messages, { + turnDurationMap: new Map(), + sessionIsStreaming: false, + messageHasProcess: hasProcess, + messageHasFinal: hasFinal, + }) + + expect(timeline.at(-1)).toMatchObject({ + kind: 'turn-diff', + userMessageId: 'user-1', + files: ['a.ts', 'b.ts'], + }) + }) + + it('does not append a turn diff while the turn is still running', () => { + const assistant = createAssistantMessage('assistant-1', [createToolPart('tool-1', 'assistant-1')]) + assistant.snapshot = { files: ['a.ts'] } + const messages = [createUserMessage('user-1', 1000), assistant] + const timeline = buildProcessTimeline(messages, { + turnDurationMap: new Map(), + sessionIsStreaming: true, + messageHasProcess: hasProcess, + messageHasFinal: hasFinal, + isUserEntryReady: () => true, + }) + + expect(timeline.some(item => item.kind === 'turn-diff')).toBe(false) + }) +}) + +describe('buildFlatTimeline', () => { + it('keeps messages flat and inserts a turn diff for settled turns', () => { + const first = createAssistantMessage('assistant-1', [{ type: 'text', text: 'done' }], 1001, 1002) + first.snapshot = { files: ['src/a.ts'] } + const second = createAssistantMessage('assistant-2', [{ type: 'text', text: 'working' }], 2001) + const messages = [ + createUserMessage('user-1', 1000), + first, + createUserMessage('user-2', 2000), + second, + ] + + const timeline = buildFlatTimeline(messages, true) + expect(timeline.filter(item => item.kind === 'message')).toHaveLength(4) + expect(timeline.find(item => item.kind === 'turn-diff')).toMatchObject({ + userMessageId: 'user-1', + files: ['src/a.ts'], + }) + // 最后一个回合还在跑:不放摘要 + expect(timeline.filter(item => item.kind === 'turn-diff')).toHaveLength(1) + }) + + it('adds the last turn diff once streaming ends', () => { + const assistant = createAssistantMessage('assistant-1', [{ type: 'text', text: 'done' }], 1001, 1002) + assistant.snapshot = { files: ['src/a.ts'] } + const messages = [createUserMessage('user-1', 1000), assistant] + + expect(buildFlatTimeline(messages, true).some(item => item.kind === 'turn-diff')).toBe(false) + expect(buildFlatTimeline(messages, false).some(item => item.kind === 'turn-diff')).toBe(true) + }) }) describe('buildChatPages', () => { diff --git a/src/features/chat/ChatArea.tsx b/src/features/chat/ChatArea.tsx index c4e19a4a9..677acf481 100644 --- a/src/features/chat/ChatArea.tsx +++ b/src/features/chat/ChatArea.tsx @@ -28,8 +28,9 @@ import type { SessionMessageInfo } from '../../types/api/message' import { isAssistantMessage, isUserMessage } from '../../types/api/message' import type { APIError } from '../../types/api/common' import { RetryStatusInline, type RetryStatusInlineData } from './RetryStatusInline' +import { CompactionQueuedView, TurnDiffPartView } from '../message/parts' import { QueueBubbles } from './QueueBubbles' -import type { QueuedUserPrompt } from '../../store/inboxStore' +import type { QueuedUserPrompt, QueuedCompaction } from '../../store/inboxStore' import { buildVisibleMessageEntries, getVisibleMessageForkTargetId, @@ -38,6 +39,7 @@ import { import { AT_BOTTOM_THRESHOLD_PX } from '../../constants' import { useChatViewport } from './chatViewport' import { + buildFlatTimeline, buildProcessTimeline, buildTurnDurationMap, buildTurnLatestAssistantIdSet, @@ -62,12 +64,14 @@ const EMPTY_WORKING_SHELL_EXTRA_DELAY_MS = 500 const DEFAULT_BOTTOM_SPACER = 256 const SESSION_CACHE_LIMIT = 16 const EMPTY_QUEUE: QueuedUserPrompt[] = [] +const EMPTY_COMPACTIONS: QueuedCompaction[] = [] const bottomSpacerHeight = (bottomPadding: number) => (bottomPadding > 0 ? bottomPadding + 48 : DEFAULT_BOTTOM_SPACER) function estimateTimelineItemSize(item: ProcessTimelineItem | undefined): number { if (!item) return ROW_ESTIMATE if (item.kind === 'message') return ROW_ESTIMATE + if (item.kind === 'turn-diff') return 32 + Math.min(item.files.length, 5) * 20 // 进行中默认展开:header + 壳内消息(空回合至少占 header) if (item.isActive) { const body = Math.max(item.children.length, 1) * ROW_ESTIMATE @@ -106,6 +110,8 @@ interface ChatAreaProps { retryStatus?: RetryStatusInlineData | null /** 下轮队列气泡(PiUI 同款:融在消息流尾部,虚拟行之后、重试提示之前) */ queuedFollowUps?: QueuedUserPrompt[] + /** 已入队、尚未开始的压缩(官方 CompactionQueued 行,排在队列气泡之前) */ + queuedCompactions?: QueuedCompaction[] /** 正在编辑的队列条目 id(该条目的「撤回编辑」切换为「取消编辑」) */ queueEditingId?: string /** 队列 mutation 投影(编辑/重排期间显示期望形态,无事件落地跳变) */ @@ -194,6 +200,7 @@ const MessageBody = memo(function MessageBody({ interface RowProps { virtualItem: VirtualItem item: ProcessTimelineItem + sessionId: string | null maxWidthClass: string paddingClass: string rowYClass: string @@ -213,6 +220,7 @@ const VirtualRow = memo( function VirtualRow({ virtualItem, item, + sessionId, maxWidthClass, paddingClass, rowYClass, @@ -267,6 +275,13 @@ const VirtualRow = memo( processContentScope={item.processContentScope ?? 'all'} onEntryGrowComplete={onEntryGrowComplete} /> + ) : item.kind === 'turn-diff' ? ( + ) : (
@@ -321,6 +336,7 @@ const VirtualRow = memo( prev.virtualItem.start === next.virtualItem.start && prev.virtualItem.size === next.virtualItem.size && prev.item === next.item && + prev.sessionId === next.sessionId && prev.maxWidthClass === next.maxWidthClass && prev.paddingClass === next.paddingClass && prev.rowYClass === next.rowYClass && @@ -367,6 +383,7 @@ export const ChatArea = memo( registerMessage, retryStatus = null, queuedFollowUps = EMPTY_QUEUE, + queuedCompactions = EMPTY_COMPACTIONS, queueEditingId, queueMutation, onQueueSteer, @@ -422,11 +439,7 @@ export const ChatArea = memo( }>({ processCollapseEnabled }) const timeline = useMemo(() => { const next = !processCollapseEnabled - ? visibleMessages.map(message => ({ - kind: 'message' as const, - key: message.id, - message, - })) + ? buildFlatTimeline(visibleMessages, isStreaming) : buildProcessTimeline(visibleMessages, { turnDurationMap, sessionIsStreaming: isStreaming, @@ -459,6 +472,7 @@ export const ChatArea = memo( map.set(item.message.id, index) return } + if (item.kind === 'turn-diff') return if (item.userMessageId) map.set(item.userMessageId, index) for (const child of item.children) map.set(child.message.id, index) if (item.finalMessage) map.set(item.finalMessage.id, index) @@ -892,7 +906,7 @@ export const ChatArea = memo( // retry/error 出现消失、输入框高度变 → 底部 footer 高度变,贴底时要跟着滚 // 否则重试条进出后 scrollTop 停在旧位置,看起来没贴底 - const footerPinKey = `${retryStatus ? 'r' : ''}|${loadError || connectionError ? 'e' : ''}|${queuedFollowUps.map(item => item.id).join('')}|${spacerHeight}` + const footerPinKey = `${retryStatus ? 'r' : ''}|${loadError || connectionError ? 'e' : ''}|${queuedCompactions.map(item => item.id).join('')}|${queuedFollowUps.map(item => item.id).join('')}|${spacerHeight}` useLayoutEffect(() => { if (!shouldAnchorBottom() || prependLoading.current) return pinToBottom() @@ -1083,6 +1097,7 @@ export const ChatArea = memo( key={item.key} virtualItem={item} item={timelineItem} + sessionId={sessionId ?? null} maxWidthClass={maxWidthClass} paddingClass={paddingClass} rowYClass={getTimelineRowYClass(timelineItem, timeline[item.index - 1], timeline[item.index + 1])} @@ -1101,6 +1116,15 @@ export const ChatArea = memo( })}
+ {/* 已入队未开始的压缩:官方 CompactionQueued 行,排在待投递输入之前 */} + {queuedCompactions.length > 0 && ( +
+ {queuedCompactions.map(item => ( + + ))} +
+ )} + {/* 队列气泡:融在消息流尾部(PiUI 同款位置:虚拟行之后、重试提示之前) */} {queuedFollowUps.length > 0 && (
@@ -1117,7 +1141,7 @@ export const ChatArea = memo(
)} - {/* 顺序必须是:消息 → 队列 → 重试/错误提示 → 输入框占位。 + {/* 顺序必须是:消息 → 压缩排队 → 队列 → 重试/错误提示 → 输入框占位。 旧 Virtuoso Footer 就是这样;换 virtualizer 后 paddingEnd 在前、提示在后,会叠到输入框下。 */} {retryStatus && (
diff --git a/src/features/chat/ChatPane.tsx b/src/features/chat/ChatPane.tsx index 65f668ebd..9ff9451e9 100644 --- a/src/features/chat/ChatPane.tsx +++ b/src/features/chat/ChatPane.tsx @@ -306,6 +306,7 @@ export const ChatPane = memo(function ChatPane({ pendingQuestionRequests, pendingWebsearchRequest, queuedPrompts, + queuedCompactions, inboxUserPrompts, busyDelivery, setBusyDelivery, @@ -1061,6 +1062,7 @@ export const ChatPane = memo(function ChatPane({ registerMessage={registerMessage} retryStatus={retryStatus} queuedFollowUps={queuedPrompts} + queuedCompactions={queuedCompactions} queueEditingId={queueEditing?.item.id} queueMutation={queueMutation} onQueueSteer={handleSteerQueuedPrompt} diff --git a/src/features/chat/chatAreaUtils.ts b/src/features/chat/chatAreaUtils.ts index 8c165e324..4e90431ab 100644 --- a/src/features/chat/chatAreaUtils.ts +++ b/src/features/chat/chatAreaUtils.ts @@ -21,7 +21,9 @@ export function getTimelineRowYClass( prev?: ProcessTimelineItem, next?: ProcessTimelineItem, ): string { - if (item.kind === 'process-shell' || isUserMessage(item.message)) return ROW_Y_TURN + if (item.kind === 'process-shell') return ROW_Y_TURN + if (item.kind === 'turn-diff') return ROW_Y_ASSISTANT_STACK + if (isUserMessage(item.message)) return ROW_Y_TURN const prevAssistant = isAssistantMessageItem(prev) const nextAssistant = isAssistantMessageItem(next) diff --git a/src/features/chat/chatAreaVisibility.ts b/src/features/chat/chatAreaVisibility.ts index 337308138..be283fdfc 100644 --- a/src/features/chat/chatAreaVisibility.ts +++ b/src/features/chat/chatAreaVisibility.ts @@ -7,6 +7,7 @@ import { isUserMessage, userMessageText, } from '../../types/api/message' +import { shellResultFailed } from '../../types/api' import { isInterruptedError } from '../../utils/errorMessage' function isVisibleThinking(content: AssistantContent): boolean { @@ -28,6 +29,35 @@ function userMessageHasRenderableContent(message: UserMessage): boolean { ) } +/** synthetic 的可见性:官方 timelineNoticeRequired(错误 / shell 失败必须露出) */ +function syntheticNoticeRequired(message: Extract): boolean { + const metadata = message.metadata as Record | undefined + return ( + metadata?.['state'] === 'error' || + (metadata?.['source'] === 'shell' && metadata?.['state'] === 'completed' && shellResultFailed(metadata)) + ) +} + +/** + * 官方 projection.ts 的 `isNotice`:正文之外的记录行(切换记录 / 系统提示 / + * 技能 / 合成上下文)。它们也是一条消息,只是渲染成细提示行。 + * + * synthetic 特殊:没有 description 的纯上下文(如注入的规则文本)默认不占行, + * 但错误与 shell 失败必须可见,否则信息流里会凭空少一条失败记录。 + */ +export function isNoticeMessage(message: SessionMessageInfo): boolean { + if (message.type === 'synthetic') { + return !!message.description?.trim() || syntheticNoticeRequired(message) + } + return ( + message.type === 'system' || + message.type === 'skill' || + message.type === 'agent-switched' || + message.type === 'model-switched' || + message.type === 'location-switched' + ) +} + /** 对应旧视图模型的 `message.parts.length !== 0`(原始存在性,不做 trim) */ function hasAnyContent(message: SessionMessageInfo): boolean { if (isUserMessage(message)) return userMessageHasAnyContent(message) @@ -35,6 +65,8 @@ function hasAnyContent(message: SessionMessageInfo): boolean { if (message.type === 'compaction') return true // `!` shell 命令消息:command + 状态即内容(官方 timeline 里独立成行) if (message.type === 'shell') return true + // 切换记录 / 系统提示 / 技能 / 合成上下文:官方 timeline 的 Notice 行 + if (isNoticeMessage(message)) return true return false } @@ -50,6 +82,7 @@ function hasRenderableContent(message: SessionMessageInfo): boolean { } if (message.type === 'compaction') return true if (message.type === 'shell') return true + if (isNoticeMessage(message)) return true return false } diff --git a/src/features/chat/chatPageModel.ts b/src/features/chat/chatPageModel.ts index d99dcef25..bee96061f 100644 --- a/src/features/chat/chatPageModel.ts +++ b/src/features/chat/chatPageModel.ts @@ -1,6 +1,7 @@ import type { AssistantMessage, SessionMessageInfo, ToolState, UserMessage } from '../../types/api/message' import { contentEntries, isAssistantMessage, isFailedIdleMessage, isUserMessage, userMessageText } from '../../types/api/message' import { isInterruptedError } from '../../utils/errorMessage' +import { isNoticeMessage } from './chatAreaVisibility' export const PAGE_MESSAGE_COUNT = 20 export const PAGE_EXTREME_RENDER_WEIGHT = 700 @@ -767,6 +768,14 @@ export type ProcessTimelineItem = /** 壳外最终回答(结束后才有) */ finalMessage?: SessionMessageInfo } + | { + /** 回合结束后的文件变更摘要(官方 TurnDiff 行) */ + kind: 'turn-diff' + key: string + userMessageId: string + /** 该回合里各 step 记录到的变更文件(去重排序) */ + files: string[] + } /** 两行是否可共享同一对象(VirtualRow 靠 item 引用短路) */ export function sameProcessTimelineItem(a: ProcessTimelineItem, b: ProcessTimelineItem): boolean { @@ -798,6 +807,14 @@ export function sameProcessTimelineItem(a: ProcessTimelineItem, b: ProcessTimeli return true } + if (a.kind === 'turn-diff' && b.kind === 'turn-diff') { + return ( + a.userMessageId === b.userMessageId && + a.files.length === b.files.length && + a.files.every((file, index) => file === b.files[index]) + ) + } + return false } @@ -831,6 +848,72 @@ export function reuseProcessTimelineItems( return allSame ? previous : result } +/** 一个回合里所有 step 记录到的变更文件(去重、排序,官方 sort 同款) */ +function collectTurnFiles(assistants: AssistantMessage[]): string[] { + const files = new Set() + for (const message of assistants) { + for (const file of message.snapshot?.files ?? []) files.add(file) + } + return [...files].sort() +} + +/** + * 平铺模式(processCollapseEnabled=false):一行一条消息。 + * + * 回合结束后仍要补一条文件变更摘要(官方 TurnDiff 行),否则关掉过程折叠 + * 就看不出这轮改了什么。`isStreaming` 为 true 时最后一个回合还没结束, + * 先不显示(官方也是 idle 之后才追加)。 + */ +export function buildFlatTimeline( + messages: SessionMessageInfo[], + sessionIsStreaming: boolean, +): ProcessTimelineItem[] { + const items: ProcessTimelineItem[] = messages.map(message => ({ + kind: 'message', + key: message.id, + message, + })) + + const turns: Array<{ userId: string; lastIndex: number; files: Set }> = [] + let current: (typeof turns)[number] | null = null + + messages.forEach((message, index) => { + if (isUserMessage(message)) { + if (current) turns.push(current) + current = { userId: message.id, lastIndex: index, files: new Set() } + return + } + if (!current) return + current.lastIndex = index + if (isAssistantMessage(message)) { + for (const file of message.snapshot?.files ?? []) current.files.add(file) + } + }) + if (current) turns.push(current) + + const diffByIndex = new Map() + turns.forEach((turn, index) => { + if (turn.files.size === 0) return + if (index === turns.length - 1 && sessionIsStreaming) return + diffByIndex.set(turn.lastIndex, { userId: turn.userId, files: [...turn.files].sort() }) + }) + if (diffByIndex.size === 0) return items + + const result: ProcessTimelineItem[] = [] + items.forEach((item, index) => { + result.push(item) + const diff = diffByIndex.get(index) + if (!diff) return + result.push({ + kind: 'turn-diff', + key: `turn-diff:${diff.userId}`, + userMessageId: diff.userId, + files: diff.files, + }) + }) + return result +} + function assistantHasLiveWork(message: AssistantMessage): boolean { // completed == null 即旧模型的 message.isStreaming if (message.time.completed == null) return true @@ -899,6 +982,11 @@ export function buildProcessTimeline( type TurnBag = { user: UserMessage | null assistants: AssistantMessage[] + /** + * 提示行(模型/agent 切换、skill、system、synthetic)。`at` = 出现时的 + * assistant 数量:0 表示排在本回合过程壳之前,>0 表示之后。 + */ + notices: Array<{ at: number; message: SessionMessageInfo }> /** 独立成行的消息(shell 命令等):不进任何回合壳,按原位平铺 */ standalone?: SessionMessageInfo /** @@ -914,7 +1002,7 @@ export function buildProcessTimeline( for (const message of visibleMessages) { if (isUserMessage(message)) { if (current) turns.push(current) - current = { user: message, assistants: [] } + current = { user: message, assistants: [], notices: [] } continue } // shell 命令消息独立成行(官方 projection.ts:188:shell 是独立 timeline 行), @@ -924,7 +1012,13 @@ export function buildProcessTimeline( turns.push(current) current = null } - turns.push({ user: null, assistants: [], standalone: message }) + turns.push({ user: null, assistants: [], notices: [], standalone: message }) + continue + } + // 提示行:跟当前回合走(官方放进 turn 的 entries),没有回合就独立平铺 + if (isNoticeMessage(message)) { + if (current) current.notices.push({ at: current.assistants.length, message }) + else items.push({ kind: 'message', key: message.id, message }) continue } // 失败的 idle 标记:会话级错误(如 prompt 没能提升成 assistant 工作)只在这条 @@ -1005,6 +1099,15 @@ export function buildProcessTimeline( items.push({ kind: 'message', key: failedIdle.id, message: failedIdle }) } + /** 提示行跟随回合:0 的排在过程壳前,其余排在壳后 */ + const emitNotices = (turn: TurnBag, beforeFirstAssistant: boolean) => { + for (const notice of turn.notices) { + if ((notice.at === 0) === beforeFirstAssistant) { + items.push({ kind: 'message', key: notice.message.id, message: notice.message }) + } + } + } + for (const turn of turns) { if (turn.standalone) { items.push({ kind: 'message', key: turn.standalone.id, message: turn.standalone }) @@ -1016,19 +1119,24 @@ export function buildProcessTimeline( const assistants = turn.assistants if (!turn.user && assistants.length === 0) { + emitNotices(turn, true) appendFailedIdle(turn) continue } // 无 user 的续段:平铺 if (!turn.user) { + emitNotices(turn, true) for (const m of assistants) { items.push({ kind: 'message', key: m.id, message: m }) } + emitNotices(turn, false) appendFailedIdle(turn) continue } + emitNotices(turn, true) + const userId = turn.user.id const turnIsActive = activeUserId != null && userId === activeUserId @@ -1086,6 +1194,16 @@ export function buildProcessTimeline( } } + emitNotices(turn, false) + + // 回合结束后追加文件变更摘要(官方 TurnDiff:idle 后按 snapshot.files 汇总) + if (!turnIsActive) { + const files = collectTurnFiles(assistants) + if (files.length > 0) { + items.push({ kind: 'turn-diff', key: `turn-diff:${userId}`, userMessageId: userId, files }) + } + } + appendFailedIdle(turn) } diff --git a/src/features/message/MessageRenderer.tsx b/src/features/message/MessageRenderer.tsx index 2a02d9118..d04e4f010 100644 --- a/src/features/message/MessageRenderer.tsx +++ b/src/features/message/MessageRenderer.tsx @@ -24,8 +24,10 @@ import { StepFinishPartView, RetryPartView, CompactionPartView, + TimelineNoticeView, MessageErrorView, type StepFinishInfo, + type NoticeMessage, } from './parts' import { CollapsibleUserText, USER_HTML_ARTIFACT_PATTERN } from './CollapsibleUserText' import { extractToolData, type ToolViewPart } from './tools' @@ -341,13 +343,30 @@ export const MessageRenderer = memo(function MessageRenderer({ if (message.outcome === 'failed' && idleError) { return (
- +
) } return null } + // 提示行:模型 / agent / 工作目录切换、skill、系统指令、synthetic 上下文 + // (官方 timeline 的 Notice 行;可见性由 chatAreaVisibility.isNoticeMessage 判定) + if ( + message.type === 'system' || + message.type === 'synthetic' || + message.type === 'skill' || + message.type === 'agent-switched' || + message.type === 'model-switched' || + message.type === 'location-switched' + ) { + return + } + if (message.type !== 'assistant') return null return ( @@ -694,7 +713,7 @@ const AssistantMessageView = memo(function AssistantMessageView({ if (messageError) { return (
- +
) } @@ -770,7 +789,7 @@ const AssistantMessageView = memo(function AssistantMessageView({ {/* Message-level error:过程壳内不重复挂错误 */} {messageError && processContentScope !== 'process' && processContentScope !== 'inline' && ( - + )} {processContentScope !== 'process' && diff --git a/src/features/message/parts/MessageErrorView.test.tsx b/src/features/message/parts/MessageErrorView.test.tsx new file mode 100644 index 000000000..7d24e6971 --- /dev/null +++ b/src/features/message/parts/MessageErrorView.test.tsx @@ -0,0 +1,37 @@ +import { render, screen } from '@testing-library/react' +import { describe, expect, it } from 'vitest' +import type { SessionStructuredError } from '@opencode/client/promise' +import { MessageErrorView } from './MessageErrorView' + +function freeLimitError(retryAfterMs?: number): SessionStructuredError { + return { + type: 'provider.free-limit', + message: 'Free usage limit reached.', + ...(retryAfterMs != null ? { retryAfterMs } : {}), + } as SessionStructuredError +} + +describe('MessageErrorView free-limit', () => { + it('renders a quiet status line with the reset time when retryAfterMs is known', () => { + const base = new Date('2026-10-23T08:00:00Z').getTime() + render() + + const status = screen.getByRole('status') + expect(status).toHaveTextContent("You've used today's free messages.") + expect(status).toHaveTextContent('They reset at') + }) + + it('falls back to the plain title when retryAfterMs is missing', () => { + render() + + const status = screen.getByRole('status') + expect(status).toHaveTextContent("You've used today's free messages.") + expect(status).not.toHaveTextContent('They reset at') + }) + + it('ignores an out-of-range retryAfterMs', () => { + render() + + expect(screen.getByRole('status')).not.toHaveTextContent('They reset at') + }) +}) diff --git a/src/features/message/parts/MessageErrorView.tsx b/src/features/message/parts/MessageErrorView.tsx index c3b0eb444..69affa4bc 100644 --- a/src/features/message/parts/MessageErrorView.tsx +++ b/src/features/message/parts/MessageErrorView.tsx @@ -5,6 +5,7 @@ import { AlertCircleIcon, ChevronDownIcon } from '../../../components/Icons' import { useDisclosureScrollLock } from '../../../hooks' import { CodeBlock } from '../../../components/CodeBlock' import { useUiDisclosureState } from '../../../utils/uiDisclosureState' +import { useNow } from '../../../hooks/useNow' import { isInterruptedError, unwrapErrorMessage } from '../../../utils/errorMessage' import { chevronClass, MessageExpandPanel, useMessageExpandRender } from '../messageExpand' @@ -12,8 +13,63 @@ interface MessageErrorViewProps { /** v2 原生结构化错误:`{ type, message, status?, response? }` */ error: SessionStructuredError stateKey?: string + /** 消息时间:free-limit 用 created/completed + retryAfterMs 计算恢复时刻 */ + time?: { created: number; completed?: number } } +const MAX_FREE_LIMIT_RETRY_AFTER_MS = 7 * 86_400_000 + +/** 官方 freeLimit 同款:base + retryAfterMs,越界或非法值就不显示时刻 */ +function freeLimitResetAt( + error: SessionStructuredError, + time: { created: number; completed?: number } | undefined, +): number | undefined { + const delay = (error as SessionStructuredError & { retryAfterMs?: unknown }).retryAfterMs + const base = time?.completed ?? time?.created + if ( + typeof delay !== 'number' || + !Number.isFinite(delay) || + delay < 0 || + delay > MAX_FREE_LIMIT_RETRY_AFTER_MS || + base == null || + !Number.isFinite(base) + ) { + return undefined + } + const resetAt = base + delay + return Number.isNaN(new Date(resetAt).getTime()) ? undefined : resetAt +} + +/** 免费额度耗尽:官方渲染成静默状态行,而不是错误卡片 */ +const FreeLimitNotice = memo(function FreeLimitNotice({ + error, + time, +}: { + error: SessionStructuredError + time?: { created: number; completed?: number } +}) { + const { t, i18n } = useTranslation('message') + const resetAt = freeLimitResetAt(error, time) + // 恢复时刻的展示只关心“是不是今天”,按分钟刷新足够 + const now = useNow(60_000) + + let label = t('errors.freeLimitTitle') + if (resetAt != null) { + const sameDay = new Date(resetAt).toDateString() === new Date(now).toDateString() && resetAt - now < 86_400_000 + const formatted = new Intl.DateTimeFormat( + i18n.language, + sameDay ? { timeStyle: 'short' } : { dateStyle: 'medium', timeStyle: 'short' }, + ).format(resetAt) + label = t('errors.freeLimitReset', { time: formatted }) + } + + return ( +
+ {label} +
+ ) +}) + /** * 消息级别的错误显示(紧凑折叠式) * 用于 AssistantMessage 的 error 字段 / 失败的 compaction @@ -22,7 +78,7 @@ interface MessageErrorViewProps { * `type` 的关键字(abort / length / auth)与是否存在 HTTP status 分支, * 与 v1 那套 `MessageError` 联合表达的语义一一对应。 */ -export const MessageErrorView = memo(function MessageErrorView({ error, stateKey }: MessageErrorViewProps) { +const StructuredErrorView = memo(function StructuredErrorView({ error, stateKey }: MessageErrorViewProps) { const { t } = useTranslation('message') const { title, description, details, severity } = getErrorInfo(error, t) const hasDetails = !!(details || description) @@ -78,6 +134,12 @@ export const MessageErrorView = memo(function MessageErrorView({ error, stateKey ) }) +export const MessageErrorView = memo(function MessageErrorView({ error, stateKey, time }: MessageErrorViewProps) { + if (error.type === 'provider.free-limit') return + + return +}) + /** * 把 v2 结构化错误映射成「标题 / 描述 / 详情 / 严重度」。 * diff --git a/src/features/message/parts/NoticePartView.test.tsx b/src/features/message/parts/NoticePartView.test.tsx new file mode 100644 index 000000000..748dc7dfc --- /dev/null +++ b/src/features/message/parts/NoticePartView.test.tsx @@ -0,0 +1,64 @@ +import { render, screen } from '@testing-library/react' +import { describe, expect, it } from 'vitest' +import { CompactionQueuedView, TimelineNoticeView, type NoticeMessage } from './NoticePartView' + +function notice(overrides: Partial & Pick): NoticeMessage { + return { id: 'message-1', time: { created: 1 }, ...overrides } as NoticeMessage +} + +describe('TimelineNoticeView', () => { + it('renders agent switches with previous → next', () => { + render() + + expect(screen.getByText('Agent changed')).toBeInTheDocument() + expect(screen.getByText('Build → Plan')).toBeInTheDocument() + }) + + it('renders model switches as a separator line', () => { + render( + , + ) + + expect(screen.getByText('Switched to gpt-5 (high)')).toBeInTheDocument() + }) + + it('renders instruction updates with the changed keys', () => { + render( + , + ) + + expect(screen.getByText('Instructions updated')).toBeInTheDocument() + expect(screen.getByText('AGENTS.md')).toBeInTheDocument() + expect(screen.getByText('.cursor/rules')).toBeInTheDocument() + }) + + it('renders subagent outcomes from synthetic metadata', () => { + render( + , + ) + + expect(screen.getByText('explore failed')).toBeInTheDocument() + expect(screen.getByText('Subagent failed')).toBeInTheDocument() + }) + + it('renders queued compaction as a divider label', () => { + render() + + expect(screen.getByText('Session compaction queued')).toBeInTheDocument() + }) +}) diff --git a/src/features/message/parts/NoticePartView.tsx b/src/features/message/parts/NoticePartView.tsx new file mode 100644 index 000000000..e757b42ec --- /dev/null +++ b/src/features/message/parts/NoticePartView.tsx @@ -0,0 +1,169 @@ +// ============================================ +// 提示行(官方 session-ui timeline 的 Notice 行) +// +// 模型 / agent / 工作目录切换、skill 激活、系统指令更新、synthetic 上下文, +// 在官方 UI 里都是以细提示行的形式插在会话流里。它们本身不是正文,但少了 +// 它们就会觉得"信息流缺了一段"(尤其是压缩前后、切换模型之后)。 +// ============================================ + +import { memo } from 'react' +import { useTranslation } from 'react-i18next' +import type { SessionMessageInfo } from '@opencode/client/promise' + +/** 以提示行形式渲染的消息(官方 projection.ts 的 isNotice 分支) */ +export type NoticeMessage = Extract< + SessionMessageInfo, + { type: 'synthetic' | 'system' | 'skill' | 'agent-switched' | 'model-switched' | 'location-switched' } +> + +/** 官方 TimelineSeparator 同款:细分隔线 + 中间标签 */ +function NoticeSeparator({ label }: { label: string }) { + return ( +
+ + + {label} + + +
+ ) +} + +function capitalizeAgent(value: string): string { + return value ? value.charAt(0).toUpperCase() + value.slice(1) : value +} + +function metadataString(metadata: Record | undefined, key: string): string | undefined { + const value = metadata?.[key] + return typeof value === 'string' && value ? value : undefined +} + +/** 官方 system 提示的两种来源:metadata.instructionSources 或 description 前缀 */ +function instructionSources(message: Extract): string[] | undefined { + const metadata = message.metadata as Record | undefined + const fromMetadata = metadata?.['instructionSources'] + if (Array.isArray(fromMetadata)) { + const sources = fromMetadata.filter((item): item is string => typeof item === 'string') + if (sources.length > 0) return sources + } + + const prefix = 'Instructions updated: ' + if (message.description?.startsWith(prefix)) { + const keys = message.description + .slice(prefix.length) + .split(',') + .map(item => item.trim()) + .filter(Boolean) + if (keys.length > 0) return keys + } + + return undefined +} + +export const TimelineNoticeView = memo(function TimelineNoticeView({ message }: { message: NoticeMessage }) { + const { t } = useTranslation('message') + + if (message.type === 'model-switched') { + const variant = message.model.variant + return ( + + ) + } + + if (message.type === 'location-switched') { + return + } + + let label = '' + let detail: string | undefined + let items: string[] | undefined + + switch (message.type) { + case 'agent-switched': + label = t('notice.agentChanged') + detail = message.previous + ? `${capitalizeAgent(message.previous)} → ${capitalizeAgent(message.agent)}` + : capitalizeAgent(message.agent) + break + + case 'skill': + label = t('notice.skill') + detail = message.name + break + + case 'system': { + const sources = instructionSources(message) + if (sources) { + label = t('notice.instructionsUpdated') + items = sources + } else { + label = message.description ?? message.text + } + break + } + + case 'synthetic': { + const metadata = message.metadata as Record | undefined + if (metadata?.['notice'] === 'restart' || message.description === 'Continuing after restart') { + label = t('notice.restart') + break + } + + const source = metadata?.['source'] + if (source === 'subagent' || source === 'shell') { + const actor = + source === 'shell' + ? t('notice.actorShell') + : metadataString(metadata, 'agent') ?? t('notice.actorAgent') + const state = metadata?.['state'] + label = + state === 'error' + ? t('notice.failed', { actor }) + : state === 'cancelled' + ? t('notice.cancelled', { actor }) + : t('notice.finished', { actor }) + detail = message.description + break + } + + label = message.description ?? message.text + break + } + } + + const hasItems = (items?.length ?? 0) > 0 + if (!label && !detail && !hasItems) return null + const fullText = [label, detail, items?.join(' · ')].filter(Boolean).join(' ') + + return ( +
+ {label} + {detail && !hasItems && {detail}} + {hasItems && ( + + {items!.map(item => ( + {item} + ))} + + )} +
+ ) +}) + +/** 服务端已接收、尚未开始的压缩(官方 CompactionQueued 行) */ +export const CompactionQueuedView = memo(function CompactionQueuedView() { + const { t } = useTranslation('message') + return ( +
+ +
+ ) +}) diff --git a/src/features/message/parts/TurnDiffPartView.test.tsx b/src/features/message/parts/TurnDiffPartView.test.tsx new file mode 100644 index 000000000..8ada608c7 --- /dev/null +++ b/src/features/message/parts/TurnDiffPartView.test.tsx @@ -0,0 +1,58 @@ +import { fireEvent, render, screen, waitFor } from '@testing-library/react' +import { beforeEach, describe, expect, it, vi } from 'vitest' +import { TurnDiffPartView } from './TurnDiffPartView' +import { getTurnDiff } from '../../../api/session' + +vi.mock('../../../api/session', () => ({ + getTurnDiff: vi.fn(), +})) + +vi.mock('../../../components/DiffView', () => ({ + DiffView: ({ filePath }: { filePath?: string }) =>
{filePath}
, +})) + +const mockGetTurnDiff = vi.mocked(getTurnDiff) + +describe('TurnDiffPartView', () => { + beforeEach(() => { + mockGetTurnDiff.mockReset() + }) + + it('lists the recorded paths before diffs arrive', () => { + mockGetTurnDiff.mockReturnValue(new Promise(() => {})) + + render() + + expect(screen.getByText('2 files changed')).toBeInTheDocument() + expect(screen.getByText('src/a.ts')).toBeInTheDocument() + expect(screen.getByText('src/b.ts')).toBeInTheDocument() + }) + + it('shows change totals and expands a file diff on click', async () => { + mockGetTurnDiff.mockResolvedValue([ + { file: 'src/a.ts', patch: '@@ -1 +1 @@\n-a\n+b', additions: 1, deletions: 1, status: 'modified' }, + { file: 'src/b.ts', patch: '@@ -1 +1 @@\n-c\n+d', additions: 2, deletions: 0, status: 'modified' }, + ]) + + render() + + await waitFor(() => expect(mockGetTurnDiff).toHaveBeenCalledWith('server:session-b', 'user-2')) + expect(await screen.findByText('+3')).toBeInTheDocument() + + fireEvent.click(screen.getByText('src/a.ts')) + expect(screen.getByTestId('diff-view')).toHaveTextContent('src/a.ts') + }) + + it('caps the list at five files until show all is pressed', async () => { + mockGetTurnDiff.mockReturnValue(new Promise(() => {})) + const files = Array.from({ length: 7 }, (_, index) => `src/file-${index + 1}.ts`) + + render() + + expect(screen.getByText('7 files changed')).toBeInTheDocument() + expect(screen.queryByText('src/file-6.ts')).not.toBeInTheDocument() + + fireEvent.click(screen.getByText('Show all')) + expect(screen.getByText('src/file-6.ts')).toBeInTheDocument() + }) +}) diff --git a/src/features/message/parts/TurnDiffPartView.tsx b/src/features/message/parts/TurnDiffPartView.tsx new file mode 100644 index 000000000..faec17117 --- /dev/null +++ b/src/features/message/parts/TurnDiffPartView.tsx @@ -0,0 +1,145 @@ +// ============================================ +// 回合文件变更摘要(官方 timeline 的 TurnDiff 行) +// +// 官方在每个回合 idle 之后按 assistant.snapshot.files 汇总本轮改过的文件, +// 用 session.diff({ from: 该轮 user message }) 拉取补丁;列表先显示路径, +// 点开某个文件再渲染 diff。这里保持同样的行为(虚拟列表下按需渲染)。 +// ============================================ + +import { memo, useEffect, useState } from 'react' +import { useTranslation } from 'react-i18next' +import { ChevronDownIcon } from '../../../components/Icons' +import { DiffView } from '../../../components/DiffView' +import { getTurnDiff } from '../../../api/session' +import type { FileDiff } from '../../../api/types' +import { chevronClass } from '../messageExpand' + +/** 官方 turnDiffFileLimit 同款:列表默认最多露 5 个文件 */ +const TURN_DIFF_FILE_LIMIT = 5 + +interface TurnDiffPartViewProps { + /** 带服务器前缀的会话 key(getTurnDiff 内部会拆) */ + sessionId: string | null + /** 该轮用户消息 id */ + from: string + /** step 记录到的变更文件(diff 未到时先显示路径) */ + files: string[] + stateKey?: string +} + +/** 会话内跨虚拟行复用已拉到的 diff(只留最近若干轮,避免补丁长期占内存) */ +const turnDiffCache = new Map() +const MAX_CACHED_TURN_DIFFS = 50 + +function cacheTurnDiff(key: string, diffs: FileDiff[]) { + turnDiffCache.set(key, diffs) + while (turnDiffCache.size > MAX_CACHED_TURN_DIFFS) { + const oldest = turnDiffCache.keys().next().value + if (oldest === undefined) break + turnDiffCache.delete(oldest) + } +} + +export const TurnDiffPartView = memo(function TurnDiffPartView({ + sessionId, + from, + files, + stateKey, +}: TurnDiffPartViewProps) { + const { t } = useTranslation('message') + const cacheKey = sessionId ? `${sessionId}:${from}` : '' + const [fetched, setFetched] = useState<{ key: string; diffs: FileDiff[] } | null>(null) + // 已缓存的 diff 直接在渲染期取,避免在 effect 里同步 setState + const diffs = (fetched?.key === cacheKey ? fetched.diffs : undefined) ?? turnDiffCache.get(cacheKey) ?? null + const [showAll, setShowAll] = useState(false) + const [openFiles, setOpenFiles] = useState>(() => new Set()) + + useEffect(() => { + if (!sessionId || diffs) return + + let cancelled = false + getTurnDiff(sessionId, from) + .then(result => { + cacheTurnDiff(cacheKey, result) + if (!cancelled) setFetched({ key: cacheKey, diffs: result }) + }) + .catch(() => { + // 拉取失败时保留路径列表,不影响回放 + }) + return () => { + cancelled = true + } + }, [cacheKey, diffs, from, sessionId]) + + const allFiles = diffs?.map(diff => diff.file) ?? files + if (allFiles.length === 0) return null + + const visibleFiles = showAll ? allFiles : allFiles.slice(0, TURN_DIFF_FILE_LIMIT) + const additions = diffs?.reduce((total, diff) => total + diff.additions, 0) + const deletions = diffs?.reduce((total, diff) => total + diff.deletions, 0) + + const toggleFile = (file: string) => { + setOpenFiles(previous => { + const next = new Set(previous) + if (next.has(file)) next.delete(file) + else next.add(file) + return next + }) + } + + return ( +
+
+ + {t('system.filesChanged', { count: allFiles.length })} + + {diffs && diffs.length > 0 && ( + + +{additions ?? 0} + -{deletions ?? 0} + + )} + {allFiles.length > TURN_DIFF_FILE_LIMIT && ( + + )} +
+ +
+ {visibleFiles.map(file => { + const diff = diffs?.find(item => item.file === file) + const open = openFiles.has(file) + return ( +
+ + {open && diff?.patch && ( +
+ +
+ )} +
+ ) + })} +
+
+ ) +}) diff --git a/src/features/message/parts/index.ts b/src/features/message/parts/index.ts index 30a621d39..9f04fd976 100644 --- a/src/features/message/parts/index.ts +++ b/src/features/message/parts/index.ts @@ -6,4 +6,7 @@ export { StepFinishPartView } from './StepFinishPartView' export type { StepFinishInfo } from './StepFinishPartView' export { RetryPartView, CompactionPartView } from './SystemPartViews' export type { RetryInfo } from './SystemPartViews' +export { TimelineNoticeView, CompactionQueuedView } from './NoticePartView' +export type { NoticeMessage } from './NoticePartView' +export { TurnDiffPartView } from './TurnDiffPartView' export { MessageErrorView } from './MessageErrorView' diff --git a/src/hooks/useChatSession.ts b/src/hooks/useChatSession.ts index 37a53ca96..125f34fed 100644 --- a/src/hooks/useChatSession.ts +++ b/src/hooks/useChatSession.ts @@ -73,7 +73,7 @@ import { createMessageId } from '../utils/identifier' import { serverStore } from '../store/serverStore' import { STORAGE_KEY_SELECTED_AGENT } from '../constants' import type { ChatAreaHandle } from '../features/chat' -import { inboxStore, useInboxUserPrompts, queuedPromptText } from '../store/inboxStore' +import { inboxStore, useInboxUserPrompts, useInboxCompactions, queuedPromptText } from '../store/inboxStore' import type { QueuedUserPrompt } from '../store/inboxStore' import { themeStore } from '../store/themeStore' @@ -212,6 +212,8 @@ export function useChatSession({ // 队列视图只列 queue 条目(官方 queue.ts:83 同款过滤);steer 条目是瞬态的, // 其回声由转写投影(projectQueueEchoes)挪到末尾展示 const queuedPrompts = useMemo(() => inboxUserPrompts.filter(item => item.delivery === 'queue'), [inboxUserPrompts]) + // 排队中的压缩(官方 CompactionQueued 行):只在服务端已接收、尚未开始时存在 + const queuedCompactions = useInboxCompactions(routeSessionId) const perSessionStateRaw = useSessionState(routeSessionId) const perSessionState = perSessionStateRaw ?? EMPTY_SESSION_STATE @@ -1640,6 +1642,7 @@ export function useChatSession({ pendingWebsearchRequest, queuedPrompts, inboxUserPrompts, + queuedCompactions, busyDelivery, setBusyDelivery, composerDraft, diff --git a/src/locales/en/message.json b/src/locales/en/message.json index b68b4732d..7befa0339 100644 --- a/src/locales/en/message.json +++ b/src/locales/en/message.json @@ -1,5 +1,6 @@ { "showLess": "Show less", + "showAll": "Show all", "showMore": "Show more", "hideSystemContext": "Hide", "showSystemContext": "Show system context ({{count}})", @@ -139,6 +140,21 @@ "filesChanged": "{{count}} file changed", "filesChanged_other": "{{count}} files changed" }, + "notice": { + "agentChanged": "Agent changed", + "modelSwitched": "Switched to {{model}}", + "modelSwitchedVariant": "Switched to {{model}} ({{variant}})", + "movedTo": "Moved to {{directory}}", + "skill": "Skill", + "failed": "{{actor}} failed", + "cancelled": "{{actor}} cancelled", + "finished": "{{actor}} finished", + "actorShell": "Shell", + "actorAgent": "Agent", + "instructionsUpdated": "Instructions updated", + "restart": "Continuing after restart", + "compactionQueued": "Session compaction queued" + }, "subtask": { "running": "Running", "done": "Done", @@ -166,6 +182,8 @@ "apiError": "API Error", "apiErrorWithCode": "API Error ({{code}})", "unknownError": "Error", - "unknownErrorDesc": "An unknown error occurred." + "unknownErrorDesc": "An unknown error occurred.", + "freeLimitTitle": "You've used today's free messages.", + "freeLimitReset": "You've used today's free messages. They reset at {{time}}." } } diff --git a/src/locales/zh-CN/message.json b/src/locales/zh-CN/message.json index bdc1e7a8d..6170caaa8 100644 --- a/src/locales/zh-CN/message.json +++ b/src/locales/zh-CN/message.json @@ -1,5 +1,6 @@ { "showLess": "收起", + "showAll": "全部显示", "showMore": "展开", "hideSystemContext": "隐藏", "showSystemContext": "显示系统上下文 ({{count}})", @@ -111,6 +112,21 @@ "filesChanged": "{{count}} 个文件变更", "filesChanged_other": "{{count}} 个文件变更" }, + "notice": { + "agentChanged": "Agent 已切换", + "modelSwitched": "模型已切换到 {{model}}", + "modelSwitchedVariant": "模型已切换到 {{model}}({{variant}})", + "movedTo": "工作目录已切换到 {{directory}}", + "skill": "技能", + "failed": "{{actor}} 失败", + "cancelled": "{{actor}} 已取消", + "finished": "{{actor}} 完成", + "actorShell": "Shell", + "actorAgent": "Agent", + "instructionsUpdated": "指令已更新", + "restart": "重启后继续执行", + "compactionQueued": "上下文压缩已排队" + }, "subtask": { "running": "运行中", "done": "Done", @@ -138,6 +154,8 @@ "apiError": "API 错误", "apiErrorWithCode": "API 错误 ({{code}})", "unknownError": "错误", - "unknownErrorDesc": "发生未知错误。" + "unknownErrorDesc": "发生未知错误。", + "freeLimitTitle": "今日免费额度已用完", + "freeLimitReset": "今日免费额度已用完,将于 {{time}} 恢复" } } diff --git a/src/store/inboxStore.ts b/src/store/inboxStore.ts index c178235a6..9baa6fb5a 100644 --- a/src/store/inboxStore.ts +++ b/src/store/inboxStore.ts @@ -14,7 +14,9 @@ import type { SessionInboxInfo, SessionInboxDelivery } from '@opencode/client/pr const EMPTY_ITEMS: SessionInboxInfo[] = [] type QueuedUserPrompt = Extract +type QueuedCompaction = Extract const EMPTY_QUEUE: QueuedUserPrompt[] = [] +const EMPTY_COMPACTIONS: QueuedCompaction[] = [] class InboxStore { private itemsBySession = new Map() @@ -167,7 +169,7 @@ class InboxStore { } export const inboxStore = new InboxStore() -export type { QueuedUserPrompt } +export type { QueuedUserPrompt, QueuedCompaction } /** 官方 queuedPromptText 同款:优先 metadata.displayText */ export function queuedPromptText(item: QueuedUserPrompt): string { @@ -184,6 +186,21 @@ export function useInboxUserPrompts(sessionId: string | null): QueuedUserPrompt[ }, [sessionId, snapshot]) } +/** + * 服务端已接收、尚未开始的压缩(官方 `session.pending` 里 type=compaction 的条目)。 + * 官方在时间线上画一条 "Session compaction queued" 分隔行;不接的话,压缩排队期间 + * UI 完全没反应,只能等 compaction.started 到达才出现。 + */ +export function useInboxCompactions(sessionId: string | null): QueuedCompaction[] { + const snapshot = useSyncExternalStore(inboxStore.subscribe, inboxStore.getSnapshot) + return useMemo(() => { + if (!sessionId) return EMPTY_COMPACTIONS + return (snapshot.get(sessionId) ?? EMPTY_ITEMS).filter( + (item): item is QueuedCompaction => item.type === 'compaction', + ) + }, [sessionId, snapshot]) +} + /** 队列视图:只含排队中的用户 prompt(官方 queue.ts 的同款过滤) */ export function useInboxQueue(sessionId: string | null): QueuedUserPrompt[] { const items = useInboxUserPrompts(sessionId) diff --git a/src/store/messageStore.ts b/src/store/messageStore.ts index ebed2e386..324c174b7 100644 --- a/src/store/messageStore.ts +++ b/src/store/messageStore.ts @@ -935,7 +935,7 @@ class MessageStore { message.providerState = data.providerState message.cost = data.cost message.tokens = data.tokens - if (data.snapshot) message.snapshot = { ...message.snapshot, end: data.snapshot } + this.mergeSnapshot(message, data.snapshot, data.files) this.markMessageDirty(sessionID, assistantMessageID) this.notify([sessionID]) @@ -958,6 +958,7 @@ class MessageStore { message.cost = data.cost message.tokens = data.tokens } + this.mergeSnapshot(message, data.snapshot, data.files) this.markMessageDirty(sessionID, assistantMessageID) this.notify([sessionID]) @@ -1772,6 +1773,22 @@ class MessageStore { return message?.type === 'assistant' ? message : undefined } + /** + * 合并 step 产出的快照事实。 + * + * `session.step.ended/failed` 的 `snapshot` 是 step 末快照 id,`files` 是本 step + * 改动过的文件。回合级「N 个文件变更」提示要用这份列表(官方用 + * `message.snapshot.files`),所以不能只记住 end。 + */ + private mergeSnapshot(message: AssistantMessage, snapshot?: string, files?: string[]) { + if (!snapshot && (files?.length ?? 0) === 0) return + message.snapshot = { + ...message.snapshot, + ...(snapshot ? { end: snapshot } : {}), + ...(files && files.length > 0 ? { files } : {}), + } + } + /** 官方 `message.activeAssistant`:最后一条还没定稿的助手消息 */ private activeAssistant(messages: SessionMessageInfo[]): AssistantMessage | undefined { return messages.findLast(isOpenAssistant) From 45bf6945662db48ddf082ebef892e93d5836212d Mon Sep 17 00:00:00 2001 From: lehhair Date: Fri, 23 Oct 2026 16:12:48 +0800 Subject: [PATCH 32/67] =?UTF-8?q?feat(session):=20=E5=AE=9E=E6=97=B6?= =?UTF-8?q?=E5=A4=84=E7=90=86=20session.moved=20=E5=B9=B6=E6=B8=B2?= =?UTF-8?q?=E6=9F=93=E7=A7=BB=E5=8A=A8=E6=8F=90=E7=A4=BA?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/api/events.ts | 4 ++-- src/hooks/useGlobalEvents.ts | 5 ++++- src/locales/zh-CN/message.json | 2 +- src/store/messageStore.test.ts | 26 ++++++++++++++++++++++++++ src/store/messageStore.ts | 23 +++++++++++++++++++++++ 5 files changed, 56 insertions(+), 4 deletions(-) diff --git a/src/api/events.ts b/src/api/events.ts index df1b09e0d..45ac74fd6 100644 --- a/src/api/events.ts +++ b/src/api/events.ts @@ -216,8 +216,8 @@ function getReconnectDelay(attempt: number): number { // splice 掉 id >= to 的消息(data.ts:1076-1092),本端没做,因此 // 多客户端同时操作时可能不同步。单客户端使用不受影响。 // session.moved -// → 官方会插入 location-switched 消息并更新会话 location;本端切换 -// worktree 走的是整表重拉,因此没做。**已知偏差**,同上属多客户端场景。 +// → 已接入:更新会话 location 并插入 location-switched 消息 +// (官方 data.ts 同款;消息流里显示为“移动”提示行)。 // filesystem.changed // → 真机验证(v2.0.14):在监听目录里创建/修改/删除文件,12 秒内 // **没有**收到该事件(只有 server.connected)。因此"没消费它"目前 diff --git a/src/hooks/useGlobalEvents.ts b/src/hooks/useGlobalEvents.ts index e8d95571e..03d5058ed 100644 --- a/src/hooks/useGlobalEvents.ts +++ b/src/hooks/useGlobalEvents.ts @@ -1152,10 +1152,13 @@ export function useGlobalEvents(directories?: string[]) { } }, - onSessionMoved: data => { + onSessionMoved: (data, facts) => { + const scopedId = scope(data.sessionID) // 目录归属变了:交接缓存里的 location 立刻作废, // 否则 TTL 内进会话会带着旧目录(undo / 媒体路径都会用错) sessionInfoCache.forget(serverId, data.sessionID) + // 消息流里补一条 location-switched(官方 data.ts 同款) + messageStore.handleSessionMoved({ ...data, sessionID: scopedId }, facts) }, onSessionDeleted: data => { diff --git a/src/locales/zh-CN/message.json b/src/locales/zh-CN/message.json index 6170caaa8..1e9418e6e 100644 --- a/src/locales/zh-CN/message.json +++ b/src/locales/zh-CN/message.json @@ -116,7 +116,7 @@ "agentChanged": "Agent 已切换", "modelSwitched": "模型已切换到 {{model}}", "modelSwitchedVariant": "模型已切换到 {{model}}({{variant}})", - "movedTo": "工作目录已切换到 {{directory}}", + "movedTo": "会话已移动到 {{directory}}", "skill": "技能", "failed": "{{actor}} 失败", "cancelled": "{{actor}} 已取消", diff --git a/src/store/messageStore.test.ts b/src/store/messageStore.test.ts index bc1edfbef..e7ccbdcbc 100644 --- a/src/store/messageStore.test.ts +++ b/src/store/messageStore.test.ts @@ -163,6 +163,32 @@ describe('messageStore(原生 v2 消息)', () => { expect(messageStore.getSessionState(SESSION)?.model).toEqual({ id: 'gpt-4o', providerID: 'openai' }) }) + it('handleSessionMoved 更新目录并插入 location-switched(带 previous)', () => { + messageStore.setMessages(SESSION, [createUserMessage('msg-1')], { directory: '/repo' }) + + messageStore.handleSessionMoved( + { + sessionID: SESSION, + location: { directory: '/repo/wt-feature' }, + projectID: 'project-1', + subpath: 'wt-feature', + }, + { id: 'evt_moved', created: 123 }, + ) + + const state = messageStore.getSessionState(SESSION) + expect(state?.directory).toBe('/repo/wt-feature') + expect(state?.messages.at(-1)).toMatchObject({ + id: 'msg_moved', + type: 'location-switched', + location: { directory: '/repo/wt-feature' }, + projectID: 'project-1', + subpath: 'wt-feature', + previous: { location: { directory: '/repo' } }, + time: { created: 123 }, + }) + }) + // ============================================ // 整条落库 diff --git a/src/store/messageStore.ts b/src/store/messageStore.ts index 324c174b7..10384729f 100644 --- a/src/store/messageStore.ts +++ b/src/store/messageStore.ts @@ -1417,6 +1417,29 @@ class MessageStore { this.notify([sessionID]) } + /** + * `session.moved`:会话被移动到其他目录 / worktree。 + * + * 官方 data.ts 同款:更新会话 location,并在消息流里留一条 + * `location-switched`。以前本端不做这件事,只有下次重拉消息才看得到切换记录。 + */ + handleSessionMoved(data: EventPayload<'session.moved'>, facts?: EventFacts) { + const { sessionID, location, projectID, subpath } = data + const state = this.ensureSession(sessionID) + const previous = state.directory ? { location: { directory: state.directory } } : undefined + state.directory = location.directory + this.appendMessage(state, { + id: messageIDFromFacts(facts), + type: 'location-switched', + location, + projectID, + subpath, + previous, + time: { created: facts?.created ?? Date.now() }, + }) + this.notify([sessionID]) + } + /** * 单条 durable 回读替换(官方 data.ts:677-683 同款): * 事件先合成的乐观行,用 message.get 拉回来的服务端行原位替换; From af50264cf1e6c36099324c15c03a5587a6f6e130 Mon Sep 17 00:00:00 2001 From: lehhair Date: Fri, 23 Oct 2026 16:59:45 +0800 Subject: [PATCH 33/67] =?UTF-8?q?fix(timeline):=20=E6=8F=90=E7=A4=BA?= =?UTF-8?q?=E8=A1=8C=E7=BB=9F=E4=B8=80=E4=B8=BA=E5=88=86=E9=9A=94=E7=BA=BF?= =?UTF-8?q?=E6=A0=B7=E5=BC=8F=EF=BC=8C=E5=B9=B6=E6=96=B0=E5=A2=9E=E9=BB=98?= =?UTF-8?q?=E8=AE=A4=E5=85=B3=E9=97=AD=E5=BC=80=E5=85=B3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/features/chat/ChatArea.test.ts | 22 +++- src/features/chat/ChatArea.tsx | 10 +- src/features/chat/ChatPane.tsx | 9 +- src/features/chat/chatAreaUtils.ts | 7 ++ src/features/chat/chatAreaVisibility.ts | 22 ++-- src/features/chat/chatPageModel.ts | 7 +- src/features/chat/useChatPageViewModel.ts | 9 +- .../message/parts/NoticePartView.test.tsx | 22 ++-- src/features/message/parts/NoticePartView.tsx | 100 +++++---------- .../message/parts/SystemPartViews.tsx | 23 ++-- .../message/parts/TurnDiffPartView.test.tsx | 6 +- .../message/parts/TurnDiffPartView.tsx | 117 ++++++++++-------- .../settings/components/AgentSettings.tsx | 45 +++++++ .../settings/settingsSearchCatalog.ts | 3 + src/hooks/useTheme.ts | 20 +++ src/locales/en/message.json | 7 +- src/locales/en/settings.json | 6 + src/locales/zh-CN/message.json | 7 +- src/locales/zh-CN/settings.json | 6 + src/store/themeStore.ts | 74 +++++++++++ 20 files changed, 355 insertions(+), 167 deletions(-) diff --git a/src/features/chat/ChatArea.test.ts b/src/features/chat/ChatArea.test.ts index ffdd02bd4..01163cb9f 100644 --- a/src/features/chat/ChatArea.test.ts +++ b/src/features/chat/ChatArea.test.ts @@ -146,7 +146,9 @@ describe('buildVisibleMessageEntries', () => { }, ] as SessionMessageInfo[] - const entries = buildVisibleMessageEntries([createUserMessage('user-1', 1, '你好'), ...notices]) + const entries = buildVisibleMessageEntries([createUserMessage('user-1', 1, '你好'), ...notices], { + showNotices: true, + }) const ids = entries.map(entry => entry.message.id) expect(ids).toEqual( @@ -155,6 +157,16 @@ describe('buildVisibleMessageEntries', () => { expect(ids).not.toContain('synthetic-context') }) + it('hides timeline notices by default (setting off)', () => { + const entries = buildVisibleMessageEntries([ + createUserMessage('user-1', 1, '你好'), + { id: 'agent-switch', type: 'agent-switched', agent: 'plan', time: { created: 2 } } as SessionMessageInfo, + { id: 'skill', type: 'skill', skill: 'pdf', name: 'PDF', text: '', time: { created: 3 } } as SessionMessageInfo, + ]) + + expect(entries.map(entry => entry.message.id)).toEqual(['user-1']) + }) + it('keeps source ids for merged assistant tool messages', () => { const first = createAssistantMessage('assistant-1', [createToolPart('tool-1', 'assistant-1')]) const second = createAssistantMessage('assistant-2', [createToolPart('tool-2', 'assistant-2')]) @@ -1024,6 +1036,7 @@ describe('buildProcessTimeline', () => { sessionIsStreaming: false, messageHasProcess: hasProcess, messageHasFinal: hasFinal, + turnDiff: true, }) expect(timeline.at(-1)).toMatchObject({ @@ -1043,6 +1056,7 @@ describe('buildProcessTimeline', () => { messageHasProcess: hasProcess, messageHasFinal: hasFinal, isUserEntryReady: () => true, + turnDiff: true, }) expect(timeline.some(item => item.kind === 'turn-diff')).toBe(false) @@ -1061,7 +1075,7 @@ describe('buildFlatTimeline', () => { second, ] - const timeline = buildFlatTimeline(messages, true) + const timeline = buildFlatTimeline(messages, true, true) expect(timeline.filter(item => item.kind === 'message')).toHaveLength(4) expect(timeline.find(item => item.kind === 'turn-diff')).toMatchObject({ userMessageId: 'user-1', @@ -1076,8 +1090,8 @@ describe('buildFlatTimeline', () => { assistant.snapshot = { files: ['src/a.ts'] } const messages = [createUserMessage('user-1', 1000), assistant] - expect(buildFlatTimeline(messages, true).some(item => item.kind === 'turn-diff')).toBe(false) - expect(buildFlatTimeline(messages, false).some(item => item.kind === 'turn-diff')).toBe(true) + expect(buildFlatTimeline(messages, true, true).some(item => item.kind === 'turn-diff')).toBe(false) + expect(buildFlatTimeline(messages, false, true).some(item => item.kind === 'turn-diff')).toBe(true) }) }) diff --git a/src/features/chat/ChatArea.tsx b/src/features/chat/ChatArea.tsx index 677acf481..775764062 100644 --- a/src/features/chat/ChatArea.tsx +++ b/src/features/chat/ChatArea.tsx @@ -397,7 +397,7 @@ export const ChatArea = memo( ref, ) => { const { t } = useTranslation('chat') - const { processCollapseEnabled } = useTheme() + const { processCollapseEnabled, showTimelineNotices, showTurnDiff } = useTheme() const { presentation } = useChatViewport() const atBottomThreshold = presentation.isCompact ? 150 : AT_BOTTOM_THRESHOLD_PX const paddingClass = presentation.isCompact ? 'px-3' : 'px-5' @@ -407,8 +407,8 @@ export const ChatArea = memo( // ── 派生数据 ── const entries = useMemo( - () => visibleMessageEntriesProp ?? buildVisibleMessageEntries(messages), - [messages, visibleMessageEntriesProp], + () => visibleMessageEntriesProp ?? buildVisibleMessageEntries(messages, { showNotices: showTimelineNotices }), + [messages, visibleMessageEntriesProp, showTimelineNotices], ) const visibleMessages = useMemo( () => visibleMessagesProp ?? entries.map(e => e.message), @@ -439,13 +439,14 @@ export const ChatArea = memo( }>({ processCollapseEnabled }) const timeline = useMemo(() => { const next = !processCollapseEnabled - ? buildFlatTimeline(visibleMessages, isStreaming) + ? buildFlatTimeline(visibleMessages, isStreaming, showTurnDiff) : buildProcessTimeline(visibleMessages, { turnDurationMap, sessionIsStreaming: isStreaming, messageHasProcess: messageHasProcessContent, messageHasFinal: messageHasFinalContent, isUserEntryReady: emptyShellGate.isReady, + turnDiff: showTurnDiff, }) const previous = previousTimelineRef.current.processCollapseEnabled === processCollapseEnabled @@ -461,6 +462,7 @@ export const ChatArea = memo( visibleMessages, turnDurationMap, isStreaming, + showTurnDiff, emptyShellGate.version, emptyShellGate.isReady, ]) diff --git a/src/features/chat/ChatPane.tsx b/src/features/chat/ChatPane.tsx index 9ff9451e9..53dbfb5da 100644 --- a/src/features/chat/ChatPane.tsx +++ b/src/features/chat/ChatPane.tsx @@ -410,8 +410,6 @@ export const ChatPane = memo(function ChatPane({ const hasRenderableMessages = renderedMessages.length > 0 const chatAreaMountKey = messagesReady || hasRenderableMessages ? (routeSessionId ?? 'home') : null const inputDisabled = !!routeSessionId && loadState === 'error' && messages.length === 0 - const chatPageViewModel = useChatPageViewModel(projectedMessages) - // 切 session remount 时默认视为贴底,避免回底按钮闪一下 useEffect(() => { if (chatAreaMountKey == null) return @@ -844,8 +842,13 @@ export const ChatPane = memo(function ChatPane({ setChatContentWidth, chatInputWidth, setChatInputWidth, + showTimelineNotices, + showQueuedCompaction, } = useTheme() + // 提示行开关参与可见性过滤:关掉后这些消息不进入时间线 + const chatPageViewModel = useChatPageViewModel(projectedMessages, showTimelineNotices) + // ── 对话列/输入框宽度(左缘拖拽调宽,两个独立把手)── // 样式与交互抄 dsh ConversationWidthControls,按需求收窄成左缘单把手 × 2: // 把手(调整入口)只在桌面端单 panel / pane 全屏时挂载(分屏空间太碎不给拖), @@ -1062,7 +1065,7 @@ export const ChatPane = memo(function ChatPane({ registerMessage={registerMessage} retryStatus={retryStatus} queuedFollowUps={queuedPrompts} - queuedCompactions={queuedCompactions} + queuedCompactions={showQueuedCompaction ? queuedCompactions : undefined} queueEditingId={queueEditing?.item.id} queueMutation={queueMutation} onQueueSteer={handleSteerQueuedPrompt} diff --git a/src/features/chat/chatAreaUtils.ts b/src/features/chat/chatAreaUtils.ts index 4e90431ab..bb26507b4 100644 --- a/src/features/chat/chatAreaUtils.ts +++ b/src/features/chat/chatAreaUtils.ts @@ -1,5 +1,6 @@ import { isAssistantMessage, isUserMessage } from '../../types/api/message' import type { ProcessTimelineItem } from './chatPageModel' +import { isNoticeMessage } from './chatAreaVisibility' /** 回合边界 / 用户消息:上下各 12px */ const ROW_Y_TURN = 'py-3' @@ -12,6 +13,11 @@ function isAssistantMessageItem(item: ProcessTimelineItem | undefined): boolean return item?.kind === 'message' && isAssistantMessage(item.message) } +/** 提示行自带上下留白,行容器不再加 py */ +function isNoticeItem(item: ProcessTimelineItem | undefined): boolean { + return item?.kind === 'message' && isNoticeMessage(item.message) +} + /** * 用户和过程壳保留回合边界;连续助手按消息内 stack 节奏收紧。 * 连续助手 py-1+py-1=8px,与 MSG_SPACING.stack / processBody 的 gap-2 同距。 @@ -23,6 +29,7 @@ export function getTimelineRowYClass( ): string { if (item.kind === 'process-shell') return ROW_Y_TURN if (item.kind === 'turn-diff') return ROW_Y_ASSISTANT_STACK + if (isNoticeItem(item)) return '' if (isUserMessage(item.message)) return ROW_Y_TURN const prevAssistant = isAssistantMessageItem(prev) diff --git a/src/features/chat/chatAreaVisibility.ts b/src/features/chat/chatAreaVisibility.ts index be283fdfc..fc176ef85 100644 --- a/src/features/chat/chatAreaVisibility.ts +++ b/src/features/chat/chatAreaVisibility.ts @@ -59,19 +59,19 @@ export function isNoticeMessage(message: SessionMessageInfo): boolean { } /** 对应旧视图模型的 `message.parts.length !== 0`(原始存在性,不做 trim) */ -function hasAnyContent(message: SessionMessageInfo): boolean { +function hasAnyContent(message: SessionMessageInfo, showNotices: boolean): boolean { if (isUserMessage(message)) return userMessageHasAnyContent(message) if (isAssistantMessage(message)) return message.content.length > 0 || message.retry != null if (message.type === 'compaction') return true // `!` shell 命令消息:command + 状态即内容(官方 timeline 里独立成行) if (message.type === 'shell') return true // 切换记录 / 系统提示 / 技能 / 合成上下文:官方 timeline 的 Notice 行 - if (isNoticeMessage(message)) return true + if (showNotices && isNoticeMessage(message)) return true return false } /** 对应旧视图模型的 `hasRenderableParts(message)` */ -function hasRenderableContent(message: SessionMessageInfo): boolean { +function hasRenderableContent(message: SessionMessageInfo, showNotices: boolean): boolean { if (isUserMessage(message)) return userMessageHasRenderableContent(message) if (isAssistantMessage(message)) { if (message.retry) return true @@ -82,12 +82,12 @@ function hasRenderableContent(message: SessionMessageInfo): boolean { } if (message.type === 'compaction') return true if (message.type === 'shell') return true - if (isNoticeMessage(message)) return true + if (showNotices && isNoticeMessage(message)) return true return false } -function messageHasContent(message: SessionMessageInfo): boolean { - const hasRenderable = hasRenderableContent(message) +function messageHasContent(message: SessionMessageInfo, showNotices: boolean): boolean { + const hasRenderable = hasRenderableContent(message, showNotices) // 有非 abort 错误的助手消息始终可见(展示错误信息)。 // abort 只有在已经产生可见内容时才显示;空 abort 不占信息流位置。 if (isAssistantMessage(message) && message.error) { @@ -96,7 +96,7 @@ function messageHasContent(message: SessionMessageInfo): boolean { // 失败 idle 标记(会话级错误,如 pre-promotion failure)始终可见: // 它没有 assistant 消息,错误卡片就是它唯一的内容(官方 isFailedIdle → Error 卡片) if (isFailedIdleMessage(message)) return true - if (!hasAnyContent(message)) { + if (!hasAnyContent(message, showNotices)) { // 任何角色的空消息都不可见:没有内容可展示 // 内容到达后自动进入可见列表;abort 后永远不会有内容 → 永远不可见 return false @@ -180,7 +180,11 @@ export function getVisibleMessageForkTargetId(entry: VisibleMessageEntry): strin return entry.sourceIds[entry.sourceIds.length - 1] || entry.message.id } -export function buildVisibleMessageEntries(messages: SessionMessageInfo[]): VisibleMessageEntry[] { +export function buildVisibleMessageEntries( + messages: SessionMessageInfo[], + options?: { showNotices?: boolean }, +): VisibleMessageEntry[] { + const showNotices = options?.showNotices ?? false // 防御性去重:保证输入无重复 ID const seenIds = new Set() const unique: SessionMessageInfo[] = [] @@ -190,7 +194,7 @@ export function buildVisibleMessageEntries(messages: SessionMessageInfo[]): Visi unique.push(m) } } - const filteredMessages = unique.filter(messageHasContent) + const filteredMessages = unique.filter(message => messageHasContent(message, showNotices)) const result: VisibleMessageEntry[] = [] for (let i = 0; i < filteredMessages.length; i++) { diff --git a/src/features/chat/chatPageModel.ts b/src/features/chat/chatPageModel.ts index bee96061f..be79c55bb 100644 --- a/src/features/chat/chatPageModel.ts +++ b/src/features/chat/chatPageModel.ts @@ -867,6 +867,7 @@ function collectTurnFiles(assistants: AssistantMessage[]): string[] { export function buildFlatTimeline( messages: SessionMessageInfo[], sessionIsStreaming: boolean, + turnDiff = false, ): ProcessTimelineItem[] { const items: ProcessTimelineItem[] = messages.map(message => ({ kind: 'message', @@ -892,6 +893,7 @@ export function buildFlatTimeline( if (current) turns.push(current) const diffByIndex = new Map() + if (!turnDiff) return items turns.forEach((turn, index) => { if (turn.files.size === 0) return if (index === turns.length - 1 && sessionIsStreaming) return @@ -968,6 +970,8 @@ export function buildProcessTimeline( messageHasFinal: (message: AssistantMessage) => boolean /** 用户消息入场生长是否完成;缺省视为已完成(历史消息 / 测试) */ isUserEntryReady?: (userMessageId: string) => boolean + /** 是否在回合结束后追加文件变更摘要(默认关闭) */ + turnDiff?: boolean }, ): ProcessTimelineItem[] { const { @@ -976,6 +980,7 @@ export function buildProcessTimeline( messageHasProcess, messageHasFinal, isUserEntryReady = () => true, + turnDiff = false, } = options const items: ProcessTimelineItem[] = [] @@ -1197,7 +1202,7 @@ export function buildProcessTimeline( emitNotices(turn, false) // 回合结束后追加文件变更摘要(官方 TurnDiff:idle 后按 snapshot.files 汇总) - if (!turnIsActive) { + if (!turnIsActive && turnDiff) { const files = collectTurnFiles(assistants) if (files.length > 0) { items.push({ kind: 'turn-diff', key: `turn-diff:${userId}`, userMessageId: userId, files }) diff --git a/src/features/chat/useChatPageViewModel.ts b/src/features/chat/useChatPageViewModel.ts index 11129a666..fda84f408 100644 --- a/src/features/chat/useChatPageViewModel.ts +++ b/src/features/chat/useChatPageViewModel.ts @@ -241,10 +241,11 @@ function reuseSet(previous: Set | undefined, next: Set) { export function buildChatPageViewModel( messages: SessionMessageInfo[], previous?: ChatPageViewModel, + showNotices = false, ): ChatPageViewModel { const visibleMessageEntries = reuseVisibleMessageEntries( previous?.visibleMessageEntries, - buildVisibleMessageEntries(messages), + buildVisibleMessageEntries(messages, { showNotices }), ) const visibleMessages = visibleMessagesFromEntries(previous?.visibleMessages, visibleMessageEntries) const forkTargetIdMap = reuseMap(previous?.forkTargetIdMap, buildForkTargetIdMap(visibleMessageEntries)) @@ -279,11 +280,11 @@ export function buildChatPageViewModel( } } -export function useChatPageViewModel(messages: SessionMessageInfo[]): ChatPageViewModel { +export function useChatPageViewModel(messages: SessionMessageInfo[], showNotices = false): ChatPageViewModel { const previousRef = useRef(undefined) return useMemo(() => { - const viewModel = buildChatPageViewModel(messages, previousRef.current) + const viewModel = buildChatPageViewModel(messages, previousRef.current, showNotices) previousRef.current = viewModel return viewModel - }, [messages]) + }, [messages, showNotices]) } diff --git a/src/features/message/parts/NoticePartView.test.tsx b/src/features/message/parts/NoticePartView.test.tsx index 748dc7dfc..2369991cb 100644 --- a/src/features/message/parts/NoticePartView.test.tsx +++ b/src/features/message/parts/NoticePartView.test.tsx @@ -10,8 +10,7 @@ describe('TimelineNoticeView', () => { it('renders agent switches with previous → next', () => { render() - expect(screen.getByText('Agent changed')).toBeInTheDocument() - expect(screen.getByText('Build → Plan')).toBeInTheDocument() + expect(screen.getByText('Agent changed · Build → Plan')).toBeInTheDocument() }) it('renders model switches as a separator line', () => { @@ -35,9 +34,7 @@ describe('TimelineNoticeView', () => { />, ) - expect(screen.getByText('Instructions updated')).toBeInTheDocument() - expect(screen.getByText('AGENTS.md')).toBeInTheDocument() - expect(screen.getByText('.cursor/rules')).toBeInTheDocument() + expect(screen.getByText('Instructions updated · AGENTS.md, .cursor/rules')).toBeInTheDocument() }) it('renders subagent outcomes from synthetic metadata', () => { @@ -52,8 +49,19 @@ describe('TimelineNoticeView', () => { />, ) - expect(screen.getByText('explore failed')).toBeInTheDocument() - expect(screen.getByText('Subagent failed')).toBeInTheDocument() + expect(screen.getByText('explore failed · Subagent failed')).toBeInTheDocument() + }) + + it('renders skill activation with the skill name', () => { + render() + + expect(screen.getByText('Skill · Commit')).toBeInTheDocument() + }) + + it('renders notices as a centered separator', () => { + const { container } = render() + + expect(container.querySelector('[data-component="timeline-separator"]')).toBeTruthy() }) it('renders queued compaction as a divider label', () => { diff --git a/src/features/message/parts/NoticePartView.tsx b/src/features/message/parts/NoticePartView.tsx index e757b42ec..c636c48be 100644 --- a/src/features/message/parts/NoticePartView.tsx +++ b/src/features/message/parts/NoticePartView.tsx @@ -2,13 +2,14 @@ // 提示行(官方 session-ui timeline 的 Notice 行) // // 模型 / agent / 工作目录切换、skill 激活、系统指令更新、synthetic 上下文, -// 在官方 UI 里都是以细提示行的形式插在会话流里。它们本身不是正文,但少了 -// 它们就会觉得"信息流缺了一段"(尤其是压缩前后、切换模型之后)。 +// 在官方 UI 里都以「横线 + 中间标签」的分隔行出现(和压缩分隔线同款)。 +// 默认关闭,可在设置里打开。 // ============================================ import { memo } from 'react' import { useTranslation } from 'react-i18next' import type { SessionMessageInfo } from '@opencode/client/promise' +import { TimelineSeparator } from './SystemPartViews' /** 以提示行形式渲染的消息(官方 projection.ts 的 isNotice 分支) */ export type NoticeMessage = Extract< @@ -16,19 +17,6 @@ export type NoticeMessage = Extract< { type: 'synthetic' | 'system' | 'skill' | 'agent-switched' | 'model-switched' | 'location-switched' } > -/** 官方 TimelineSeparator 同款:细分隔线 + 中间标签 */ -function NoticeSeparator({ label }: { label: string }) { - return ( -
- - - {label} - - -
- ) -} - function capitalizeAgent(value: string): string { return value ? value.charAt(0).toUpperCase() + value.slice(1) : value } @@ -63,46 +51,37 @@ function instructionSources(message: Extract) export const TimelineNoticeView = memo(function TimelineNoticeView({ message }: { message: NoticeMessage }) { const { t } = useTranslation('message') - if (message.type === 'model-switched') { - const variant = message.model.variant - return ( - - ) - } + let label: string | null = null - if (message.type === 'location-switched') { - return - } + switch (message.type) { + case 'model-switched': + label = message.model.variant + ? t('notice.modelSwitchedVariant', { model: message.model.id, variant: message.model.variant }) + : t('notice.modelSwitched', { model: message.model.id }) + break - let label = '' - let detail: string | undefined - let items: string[] | undefined + case 'location-switched': + label = t('notice.movedTo', { directory: message.location.directory }) + break - switch (message.type) { case 'agent-switched': - label = t('notice.agentChanged') - detail = message.previous - ? `${capitalizeAgent(message.previous)} → ${capitalizeAgent(message.agent)}` - : capitalizeAgent(message.agent) + label = message.previous + ? t('notice.agentChangedDetail', { + previous: capitalizeAgent(message.previous), + agent: capitalizeAgent(message.agent), + }) + : t('notice.agentChangedTo', { agent: capitalizeAgent(message.agent) }) break case 'skill': - label = t('notice.skill') - detail = message.name + label = t('notice.skillActivated', { name: message.name }) break case 'system': { const sources = instructionSources(message) - if (sources) { - label = t('notice.instructionsUpdated') - items = sources - } else { - label = message.description ?? message.text - } + label = sources + ? t('notice.instructionsUpdatedDetail', { sources: sources.join(', ') }) + : (message.description ?? message.text) break } @@ -116,17 +95,15 @@ export const TimelineNoticeView = memo(function TimelineNoticeView({ message }: const source = metadata?.['source'] if (source === 'subagent' || source === 'shell') { const actor = - source === 'shell' - ? t('notice.actorShell') - : metadataString(metadata, 'agent') ?? t('notice.actorAgent') + source === 'shell' ? t('notice.actorShell') : (metadataString(metadata, 'agent') ?? t('notice.actorAgent')) const state = metadata?.['state'] - label = + const outcome = state === 'error' ? t('notice.failed', { actor }) : state === 'cancelled' ? t('notice.cancelled', { actor }) : t('notice.finished', { actor }) - detail = message.description + label = message.description ? `${outcome} · ${message.description}` : outcome break } @@ -135,27 +112,8 @@ export const TimelineNoticeView = memo(function TimelineNoticeView({ message }: } } - const hasItems = (items?.length ?? 0) > 0 - if (!label && !detail && !hasItems) return null - const fullText = [label, detail, items?.join(' · ')].filter(Boolean).join(' ') - - return ( -
- {label} - {detail && !hasItems && {detail}} - {hasItems && ( - - {items!.map(item => ( - {item} - ))} - - )} -
- ) + if (!label?.trim()) return null + return }) /** 服务端已接收、尚未开始的压缩(官方 CompactionQueued 行) */ @@ -163,7 +121,7 @@ export const CompactionQueuedView = memo(function CompactionQueuedView() { const { t } = useTranslation('message') return (
- +
) }) diff --git a/src/features/message/parts/SystemPartViews.tsx b/src/features/message/parts/SystemPartViews.tsx index 958744e3b..e997c6c99 100644 --- a/src/features/message/parts/SystemPartViews.tsx +++ b/src/features/message/parts/SystemPartViews.tsx @@ -112,13 +112,22 @@ interface CompactionPartViewProps { canUndo?: boolean } -/** 官方 TimelineSeparator 同款:细分隔线 + 中间标签 */ -function Separator({ label }: { label: string }) { +/** + * 官方 TimelineSeparator 同款:细分隔线 + 中间标签。 + * 时间线提示行(切换记录 / 技能 / 指令更新 / 压缩排队)都复用它。 + */ +export function TimelineSeparator({ label, title }: { label: string; title?: string }) { return ( -
- - {label} - +
+ + + {label} + +
) } @@ -227,7 +236,7 @@ export const CompactionPartView = memo(function CompactionPartView({ if (!hasContent) { return (
- +
) } diff --git a/src/features/message/parts/TurnDiffPartView.test.tsx b/src/features/message/parts/TurnDiffPartView.test.tsx index 8ada608c7..7aa00eea2 100644 --- a/src/features/message/parts/TurnDiffPartView.test.tsx +++ b/src/features/message/parts/TurnDiffPartView.test.tsx @@ -24,6 +24,9 @@ describe('TurnDiffPartView', () => { render() expect(screen.getByText('2 files changed')).toBeInTheDocument() + expect(screen.queryByText('src/a.ts')).not.toBeInTheDocument() + + fireEvent.click(screen.getByText('2 files changed')) expect(screen.getByText('src/a.ts')).toBeInTheDocument() expect(screen.getByText('src/b.ts')).toBeInTheDocument() }) @@ -35,6 +38,7 @@ describe('TurnDiffPartView', () => { ]) render() + fireEvent.click(screen.getByText('2 files changed')) await waitFor(() => expect(mockGetTurnDiff).toHaveBeenCalledWith('server:session-b', 'user-2')) expect(await screen.findByText('+3')).toBeInTheDocument() @@ -48,8 +52,8 @@ describe('TurnDiffPartView', () => { const files = Array.from({ length: 7 }, (_, index) => `src/file-${index + 1}.ts`) render() + fireEvent.click(screen.getByText('7 files changed')) - expect(screen.getByText('7 files changed')).toBeInTheDocument() expect(screen.queryByText('src/file-6.ts')).not.toBeInTheDocument() fireEvent.click(screen.getByText('Show all')) diff --git a/src/features/message/parts/TurnDiffPartView.tsx b/src/features/message/parts/TurnDiffPartView.tsx index faec17117..985beb4b4 100644 --- a/src/features/message/parts/TurnDiffPartView.tsx +++ b/src/features/message/parts/TurnDiffPartView.tsx @@ -1,9 +1,9 @@ // ============================================ // 回合文件变更摘要(官方 timeline 的 TurnDiff 行) // -// 官方在每个回合 idle 之后按 assistant.snapshot.files 汇总本轮改过的文件, -// 用 session.diff({ from: 该轮 user message }) 拉取补丁;列表先显示路径, -// 点开某个文件再渲染 diff。这里保持同样的行为(虚拟列表下按需渲染)。 +// 默认收起成一行「N 个文件变更」,点开才列文件、再点文件看 diff。 +// 官方是列表常驻,这里按本项目的信息流密度收了一级,避免每轮都铺一屏。 +// 默认关闭,可在设置里打开。 // ============================================ import { memo, useEffect, useState } from 'react' @@ -12,6 +12,7 @@ import { ChevronDownIcon } from '../../../components/Icons' import { DiffView } from '../../../components/DiffView' import { getTurnDiff } from '../../../api/session' import type { FileDiff } from '../../../api/types' +import { useUiDisclosureState } from '../../../utils/uiDisclosureState' import { chevronClass } from '../messageExpand' /** 官方 turnDiffFileLimit 同款:列表默认最多露 5 个文件 */ @@ -48,14 +49,17 @@ export const TurnDiffPartView = memo(function TurnDiffPartView({ }: TurnDiffPartViewProps) { const { t } = useTranslation('message') const cacheKey = sessionId ? `${sessionId}:${from}` : '' + const [expanded, setExpanded] = useUiDisclosureState(stateKey ?? `turn-diff:${cacheKey}`, false) const [fetched, setFetched] = useState<{ key: string; diffs: FileDiff[] } | null>(null) - // 已缓存的 diff 直接在渲染期取,避免在 effect 里同步 setState - const diffs = (fetched?.key === cacheKey ? fetched.diffs : undefined) ?? turnDiffCache.get(cacheKey) ?? null const [showAll, setShowAll] = useState(false) const [openFiles, setOpenFiles] = useState>(() => new Set()) + // 已缓存的 diff 直接在渲染期取,避免在 effect 里同步 setState + const diffs = (fetched?.key === cacheKey ? fetched.diffs : undefined) ?? turnDiffCache.get(cacheKey) ?? null + useEffect(() => { - if (!sessionId || diffs) return + // 收起时不请求:历史回合很多,展开哪个才拉哪个 + if (!expanded || !sessionId || diffs) return let cancelled = false getTurnDiff(sessionId, from) @@ -69,7 +73,7 @@ export const TurnDiffPartView = memo(function TurnDiffPartView({ return () => { cancelled = true } - }, [cacheKey, diffs, from, sessionId]) + }, [cacheKey, diffs, expanded, from, sessionId]) const allFiles = diffs?.map(diff => diff.file) ?? files if (allFiles.length === 0) return null @@ -88,58 +92,71 @@ export const TurnDiffPartView = memo(function TurnDiffPartView({ } return ( -
+
- - {t('system.filesChanged', { count: allFiles.length })} - + {diffs && diffs.length > 0 && ( - + +{additions ?? 0} -{deletions ?? 0} )} - {allFiles.length > TURN_DIFF_FILE_LIMIT && ( - - )}
-
- {visibleFiles.map(file => { - const diff = diffs?.find(item => item.file === file) - const open = openFiles.has(file) - return ( -
- - {open && diff?.patch && ( -
- + {expanded && ( + <> +
+ {visibleFiles.map(file => { + const diff = diffs?.find(item => item.file === file) + const open = openFiles.has(file) + return ( +
+ + {open && diff?.patch && ( +
+ +
+ )}
- )} -
- ) - })} -
+ ) + })} +
+ + {allFiles.length > TURN_DIFF_FILE_LIMIT && ( + + )} + + )}
) }) diff --git a/src/features/settings/components/AgentSettings.tsx b/src/features/settings/components/AgentSettings.tsx index 55f0b97d7..36063a06f 100644 --- a/src/features/settings/components/AgentSettings.tsx +++ b/src/features/settings/components/AgentSettings.tsx @@ -19,6 +19,9 @@ export function AgentSettings() { const [compactionAutoCollapse, setCompactionAutoCollapse] = useState(themeStore.compactionAutoCollapse) const [queueAutoCollapse, setQueueAutoCollapse] = useState(themeStore.queueAutoCollapse) const [processCollapseEnabled, setProcessCollapseEnabled] = useState(themeStore.processCollapseEnabled) + const [showTimelineNotices, setShowTimelineNotices] = useState(themeStore.showTimelineNotices) + const [showTurnDiff, setShowTurnDiff] = useState(themeStore.showTurnDiff) + const [showQueuedCompaction, setShowQueuedCompaction] = useState(themeStore.showQueuedCompaction) const handleAlwaysAllowModeChange = (mode: AlwaysAllowMode) => { const hasFrontendRules = autoApproveStore.getDebugInfo().sessions.some(session => session.rules.length > 0) @@ -79,6 +82,24 @@ export function AgentSettings() { themeStore.setProcessCollapseEnabled(next) } + const toggleShowTimelineNotices = () => { + const next = !showTimelineNotices + setShowTimelineNotices(next) + themeStore.setShowTimelineNotices(next) + } + + const toggleShowTurnDiff = () => { + const next = !showTurnDiff + setShowTurnDiff(next) + themeStore.setShowTurnDiff(next) + } + + const toggleShowQueuedCompaction = () => { + const next = !showQueuedCompaction + setShowQueuedCompaction(next) + themeStore.setShowQueuedCompaction(next) + } + const toggleCompactInlinePermission = () => { const next = !compactInlinePermission setCompactInlinePermission(next) @@ -171,6 +192,30 @@ export function AgentSettings() { + + + + + + + + + + + + { + themeStore.setShowTimelineNotices(enabled) + }, []) + + const setShowTurnDiff = useCallback((enabled: boolean) => { + themeStore.setShowTurnDiff(enabled) + }, []) + + const setShowQueuedCompaction = useCallback((enabled: boolean) => { + themeStore.setShowQueuedCompaction(enabled) + }, []) + const setCodeBlockThemeLight = useCallback((id: string) => { themeStore.setCodeBlockThemeLight(id) }, []) @@ -391,6 +403,14 @@ export function useTheme() { processCollapseEnabled: state.processCollapseEnabled, setProcessCollapseEnabled, + // 时间线提示行 / 回合文件变更 / 压缩排队 + showTimelineNotices: state.showTimelineNotices, + setShowTimelineNotices, + showTurnDiff: state.showTurnDiff, + setShowTurnDiff, + showQueuedCompaction: state.showQueuedCompaction, + setShowQueuedCompaction, + // 输入框选择器样式(独立图标按钮 / DSH 风格汇总菜单) composerSelectorStyle: state.composerSelectorStyle, setComposerSelectorStyle: useCallback( diff --git a/src/locales/en/message.json b/src/locales/en/message.json index 7befa0339..38bde85df 100644 --- a/src/locales/en/message.json +++ b/src/locales/en/message.json @@ -141,17 +141,18 @@ "filesChanged_other": "{{count}} files changed" }, "notice": { - "agentChanged": "Agent changed", + "agentChangedDetail": "Agent changed · {{previous}} → {{agent}}", + "agentChangedTo": "Agent changed · {{agent}}", "modelSwitched": "Switched to {{model}}", "modelSwitchedVariant": "Switched to {{model}} ({{variant}})", "movedTo": "Moved to {{directory}}", - "skill": "Skill", + "skillActivated": "Skill · {{name}}", "failed": "{{actor}} failed", "cancelled": "{{actor}} cancelled", "finished": "{{actor}} finished", "actorShell": "Shell", "actorAgent": "Agent", - "instructionsUpdated": "Instructions updated", + "instructionsUpdatedDetail": "Instructions updated · {{sources}}", "restart": "Continuing after restart", "compactionQueued": "Session compaction queued" }, diff --git a/src/locales/en/settings.json b/src/locales/en/settings.json index 10fe2db27..117651efd 100644 --- a/src/locales/en/settings.json +++ b/src/locales/en/settings.json @@ -212,6 +212,12 @@ "descriptiveToolStepsDesc": "Replace plain step counts with tool-aware summaries and show a steps line even for single tool calls", "processCollapse": "Collapse process", "processCollapseDesc": "Show a live Working timer after you send, fold intermediate work into a collapsible block, and keep the final answer outside", + "showTimelineNotices": "Show session event notices", + "showTimelineNoticesDesc": "Show model / agent switches, session moves, skill activations, instruction updates, and subagent outcomes as separator lines", + "showTurnDiff": "Show turn file changes", + "showTurnDiffDesc": "List the files changed by each turn after it finishes; click a file to view its diff", + "showQueuedCompaction": "Show queued compaction", + "showQueuedCompactionDesc": "Show a notice while a compaction request is queued but has not started yet", "inlineToolRequests": "Inline Tool Requests", "inlineToolRequestsDesc": "Show pending permission and question requests under the related tool call instead of floating dialogs", "compactInlinePermission": "Compact Inline Permission", diff --git a/src/locales/zh-CN/message.json b/src/locales/zh-CN/message.json index 1e9418e6e..6e1fd57f4 100644 --- a/src/locales/zh-CN/message.json +++ b/src/locales/zh-CN/message.json @@ -113,17 +113,18 @@ "filesChanged_other": "{{count}} 个文件变更" }, "notice": { - "agentChanged": "Agent 已切换", + "agentChangedDetail": "Agent 已切换 · {{previous}} → {{agent}}", + "agentChangedTo": "Agent 已切换 · {{agent}}", "modelSwitched": "模型已切换到 {{model}}", "modelSwitchedVariant": "模型已切换到 {{model}}({{variant}})", "movedTo": "会话已移动到 {{directory}}", - "skill": "技能", + "skillActivated": "技能 · {{name}}", "failed": "{{actor}} 失败", "cancelled": "{{actor}} 已取消", "finished": "{{actor}} 完成", "actorShell": "Shell", "actorAgent": "Agent", - "instructionsUpdated": "指令已更新", + "instructionsUpdatedDetail": "指令已更新 · {{sources}}", "restart": "重启后继续执行", "compactionQueued": "上下文压缩已排队" }, diff --git a/src/locales/zh-CN/settings.json b/src/locales/zh-CN/settings.json index 147560702..e4c8e913a 100644 --- a/src/locales/zh-CN/settings.json +++ b/src/locales/zh-CN/settings.json @@ -212,6 +212,12 @@ "descriptiveToolStepsDesc": "把普通 steps 计数改成带工具描述的摘要,并让单工具调用也显示步骤描述", "processCollapse": "过程折叠", "processCollapseDesc": "用户发送后显示处理计时,并把中间过程收进折叠块;最终回答留在外面", + "showTimelineNotices": "显示会话事件提示", + "showTimelineNoticesDesc": "在消息流里用分隔行显示模型 / agent 切换、会话移动、技能激活、指令更新和子任务结果", + "showTurnDiff": "显示回合文件变更", + "showTurnDiffDesc": "每轮结束后列出本轮改动的文件,点开可查看 diff", + "showQueuedCompaction": "显示压缩排队提示", + "showQueuedCompactionDesc": "压缩已提交但尚未开始时,在消息流尾部显示一行提示", "inlineToolRequests": "工具内嵌请求", "inlineToolRequestsDesc": "把待处理的权限和提问显示在对应工具下方,而不是浮层弹窗", "compactInlinePermission": "精简内嵌权限", diff --git a/src/store/themeStore.ts b/src/store/themeStore.ts index 3831bd29c..63d6c4dd2 100644 --- a/src/store/themeStore.ts +++ b/src/store/themeStore.ts @@ -177,6 +177,12 @@ const DEFAULT_ACTIONS_ON_LATEST_ASSISTANT_ONLY = true const DEFAULT_DESKTOP_COLLAPSED_INPUT_DOCK = true /** 过程折叠:按用户消息把中间过程收成计时折叠块 */ const DEFAULT_PROCESS_COLLAPSE_ENABLED = false +/** 时间线提示行(模型/agent 切换、移动、技能、指令更新、合成上下文)默认关闭 */ +const DEFAULT_SHOW_TIMELINE_NOTICES = false +/** 回合文件变更摘要默认关闭 */ +const DEFAULT_SHOW_TURN_DIFF = false +/** 压缩排队提示默认关闭 */ +const DEFAULT_SHOW_QUEUED_COMPACTION = false /** 输入框选择器默认样式:独立图标按钮 */ const DEFAULT_COMPOSER_SELECTOR_STYLE: ComposerSelectorStyle = 'icons' @@ -249,6 +255,12 @@ export interface ThemeState { desktopCollapsedInputDock: boolean /** 过程折叠:用户发送后显示 Working 计时,结束后收成折叠块,最终回答留在外面 */ processCollapseEnabled: boolean + /** 在消息流里显示会话事件提示行(模型/agent 切换、移动、技能、指令更新、合成上下文) */ + showTimelineNotices: boolean + /** 每轮结束后显示文件变更摘要 */ + showTurnDiff: boolean + /** 压缩已入队、尚未开始时显示提示 */ + showQueuedCompaction: boolean /** 输入框选择器样式:独立图标按钮 / DSH 风格汇总菜单 */ composerSelectorStyle: ComposerSelectorStyle /** 代码块语法高亮主题(亮色模式),Shiki theme id */ @@ -297,6 +309,9 @@ const STORAGE_KEY_OUTLINE_CURRENT_HIGHLIGHT = 'outline-current-highlight' const STORAGE_KEY_ACTIONS_ON_LATEST_ASSISTANT_ONLY = 'actions-on-latest-assistant-only' const STORAGE_KEY_DESKTOP_COLLAPSED_INPUT_DOCK = 'desktop-collapsed-input-dock' const STORAGE_KEY_PROCESS_COLLAPSE_ENABLED = 'process-collapse-enabled' +const STORAGE_KEY_SHOW_TIMELINE_NOTICES = 'show-timeline-notices' +const STORAGE_KEY_SHOW_TURN_DIFF = 'show-turn-diff' +const STORAGE_KEY_SHOW_QUEUED_COMPACTION = 'show-queued-compaction' const STORAGE_KEY_COMPOSER_SELECTOR_STYLE = 'composer-selector-style' const STORAGE_KEY_CODE_BLOCK_THEME_LIGHT = 'code-block-theme-light' const STORAGE_KEY_CODE_BLOCK_THEME_DARK = 'code-block-theme-dark' @@ -474,6 +489,17 @@ class ThemeStore { ? DEFAULT_PROCESS_COLLAPSE_ENABLED : savedProcessCollapseEnabled === 'true' + const savedShowTimelineNotices = localStorage.getItem(STORAGE_KEY_SHOW_TIMELINE_NOTICES) + const showTimelineNotices = + savedShowTimelineNotices === null ? DEFAULT_SHOW_TIMELINE_NOTICES : savedShowTimelineNotices === 'true' + + const savedShowTurnDiff = localStorage.getItem(STORAGE_KEY_SHOW_TURN_DIFF) + const showTurnDiff = savedShowTurnDiff === null ? DEFAULT_SHOW_TURN_DIFF : savedShowTurnDiff === 'true' + + const savedShowQueuedCompaction = localStorage.getItem(STORAGE_KEY_SHOW_QUEUED_COMPACTION) + const showQueuedCompaction = + savedShowQueuedCompaction === null ? DEFAULT_SHOW_QUEUED_COMPACTION : savedShowQueuedCompaction === 'true' + const savedComposerSelectorStyle = localStorage.getItem(STORAGE_KEY_COMPOSER_SELECTOR_STYLE) const composerSelectorStyle: ComposerSelectorStyle = savedComposerSelectorStyle === 'seat' ? 'seat' : DEFAULT_COMPOSER_SELECTOR_STYLE @@ -522,6 +548,9 @@ class ThemeStore { actionsOnLatestAssistantOnly, desktopCollapsedInputDock, processCollapseEnabled, + showTimelineNotices, + showTurnDiff, + showQueuedCompaction, composerSelectorStyle, codeBlockThemeLight, codeBlockThemeDark, @@ -641,6 +670,18 @@ class ThemeStore { return this.state.processCollapseEnabled } + get showTimelineNotices() { + return this.state.showTimelineNotices + } + + get showTurnDiff() { + return this.state.showTurnDiff + } + + get showQueuedCompaction() { + return this.state.showQueuedCompaction + } + get composerSelectorStyle() { return this.state.composerSelectorStyle } @@ -1034,6 +1075,27 @@ class ThemeStore { this.emit() } + setShowTimelineNotices(enabled: boolean) { + if (this.state.showTimelineNotices === enabled) return + this.state = { ...this.state, showTimelineNotices: enabled } + localStorage.setItem(STORAGE_KEY_SHOW_TIMELINE_NOTICES, String(enabled)) + this.emit() + } + + setShowTurnDiff(enabled: boolean) { + if (this.state.showTurnDiff === enabled) return + this.state = { ...this.state, showTurnDiff: enabled } + localStorage.setItem(STORAGE_KEY_SHOW_TURN_DIFF, String(enabled)) + this.emit() + } + + setShowQueuedCompaction(enabled: boolean) { + if (this.state.showQueuedCompaction === enabled) return + this.state = { ...this.state, showQueuedCompaction: enabled } + localStorage.setItem(STORAGE_KEY_SHOW_QUEUED_COMPACTION, String(enabled)) + this.emit() + } + setComposerSelectorStyle(style: ComposerSelectorStyle) { if (this.state.composerSelectorStyle === style) return this.state = { ...this.state, composerSelectorStyle: style } @@ -1334,6 +1396,15 @@ function normalizeThemeBackup(raw: unknown): ThemeBackup { typeof parsed?.processCollapseEnabled === 'boolean' ? parsed.processCollapseEnabled : DEFAULT_PROCESS_COLLAPSE_ENABLED, + showTimelineNotices: + typeof parsed?.showTimelineNotices === 'boolean' + ? parsed.showTimelineNotices + : DEFAULT_SHOW_TIMELINE_NOTICES, + showTurnDiff: typeof parsed?.showTurnDiff === 'boolean' ? parsed.showTurnDiff : DEFAULT_SHOW_TURN_DIFF, + showQueuedCompaction: + typeof parsed?.showQueuedCompaction === 'boolean' + ? parsed.showQueuedCompaction + : DEFAULT_SHOW_QUEUED_COMPACTION, composerSelectorStyle: parsed?.composerSelectorStyle === 'seat' ? 'seat' : DEFAULT_COMPOSER_SELECTOR_STYLE, codeBlockThemeLight: normalizeCodeBlockTheme( @@ -1400,6 +1471,9 @@ export function importThemeBackup(raw: unknown): void { ) localStorage.setItem(STORAGE_KEY_DESKTOP_COLLAPSED_INPUT_DOCK, String(backup.desktopCollapsedInputDock)) localStorage.setItem(STORAGE_KEY_PROCESS_COLLAPSE_ENABLED, String(backup.processCollapseEnabled)) + localStorage.setItem(STORAGE_KEY_SHOW_TIMELINE_NOTICES, String(backup.showTimelineNotices)) + localStorage.setItem(STORAGE_KEY_SHOW_TURN_DIFF, String(backup.showTurnDiff)) + localStorage.setItem(STORAGE_KEY_SHOW_QUEUED_COMPACTION, String(backup.showQueuedCompaction)) localStorage.setItem(STORAGE_KEY_COMPOSER_SELECTOR_STYLE, backup.composerSelectorStyle) localStorage.setItem(STORAGE_KEY_CODE_BLOCK_THEME_LIGHT, backup.codeBlockThemeLight) localStorage.setItem(STORAGE_KEY_CODE_BLOCK_THEME_DARK, backup.codeBlockThemeDark) From e921d91b993306b4004c5f721652b125dec9fdd7 Mon Sep 17 00:00:00 2001 From: lehhair Date: Fri, 23 Oct 2026 17:21:56 +0800 Subject: [PATCH 34/67] =?UTF-8?q?chore(preview):=20=E5=A2=9E=E5=8A=A0?= =?UTF-8?q?=E6=97=B6=E9=97=B4=E7=BA=BF=20UI=20=E7=9A=84=E6=B5=8F=E8=A7=88?= =?UTF-8?q?=E5=99=A8=E9=A2=84=E8=A7=88=E9=A1=B5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- preview.html | 12 + .../message/parts/TurnDiffPartView.tsx | 11 +- src/preview/TimelinePreview.tsx | 363 ++++++++++++++++++ src/preview/main.tsx | 32 ++ 4 files changed, 416 insertions(+), 2 deletions(-) create mode 100644 preview.html create mode 100644 src/preview/TimelinePreview.tsx create mode 100644 src/preview/main.tsx diff --git a/preview.html b/preview.html new file mode 100644 index 000000000..6cd2ad85c --- /dev/null +++ b/preview.html @@ -0,0 +1,12 @@ + + + + + + Timeline UI Preview + + +
+ + + diff --git a/src/features/message/parts/TurnDiffPartView.tsx b/src/features/message/parts/TurnDiffPartView.tsx index 985beb4b4..96c5121ac 100644 --- a/src/features/message/parts/TurnDiffPartView.tsx +++ b/src/features/message/parts/TurnDiffPartView.tsx @@ -26,6 +26,10 @@ interface TurnDiffPartViewProps { /** step 记录到的变更文件(diff 未到时先显示路径) */ files: string[] stateKey?: string + /** 外部传入的 diff(预览/测试用;提供时不再请求接口) */ + diffs?: FileDiff[] + /** 预览用:初始是否展开 */ + defaultExpanded?: boolean } /** 会话内跨虚拟行复用已拉到的 diff(只留最近若干轮,避免补丁长期占内存) */ @@ -46,16 +50,19 @@ export const TurnDiffPartView = memo(function TurnDiffPartView({ from, files, stateKey, + diffs: diffsProp, + defaultExpanded, }: TurnDiffPartViewProps) { const { t } = useTranslation('message') const cacheKey = sessionId ? `${sessionId}:${from}` : '' - const [expanded, setExpanded] = useUiDisclosureState(stateKey ?? `turn-diff:${cacheKey}`, false) + const [expanded, setExpanded] = useUiDisclosureState(stateKey ?? `turn-diff:${cacheKey}`, defaultExpanded ?? false) const [fetched, setFetched] = useState<{ key: string; diffs: FileDiff[] } | null>(null) const [showAll, setShowAll] = useState(false) const [openFiles, setOpenFiles] = useState>(() => new Set()) // 已缓存的 diff 直接在渲染期取,避免在 effect 里同步 setState - const diffs = (fetched?.key === cacheKey ? fetched.diffs : undefined) ?? turnDiffCache.get(cacheKey) ?? null + const loadedDiffs = (fetched?.key === cacheKey ? fetched.diffs : undefined) ?? turnDiffCache.get(cacheKey) ?? null + const diffs = diffsProp ?? loadedDiffs useEffect(() => { // 收起时不请求:历史回合很多,展开哪个才拉哪个 diff --git a/src/preview/TimelinePreview.tsx b/src/preview/TimelinePreview.tsx new file mode 100644 index 000000000..a7bfe51d1 --- /dev/null +++ b/src/preview/TimelinePreview.tsx @@ -0,0 +1,363 @@ +// ============================================ +// Timeline UI Preview(仅 dev) +// +// 打开方式:npm run dev 后访问 /preview.html +// 这里只做一件事:用**生产组件本身**铺一页,方便直接看渲染效果。 +// 不接后端、不写 session,fake 数据只存在于这个页面。 +// ============================================ + +import type { ReactNode } from 'react' +import { useTranslation } from 'react-i18next' +import type { FileDiff } from '../api/types' +import { MessageRenderer } from '../features/message/MessageRenderer' +import { + CompactionPartView, + CompactionQueuedView, + TimelineNoticeView, + TurnDiffPartView, + type NoticeMessage, +} from '../features/message/parts' +import { useTheme } from '../hooks/useTheme' +import type { SessionMessageCompaction, SessionMessageInfo } from '@opencode/client/promise' + +const NOW = Date.now() + +function textAssistant(id: string, text: string, createdOffset: number, completedOffset: number): SessionMessageInfo { + return { + id, + type: 'assistant', + agent: 'build', + model: { providerID: 'anthropic', id: 'claude-sonnet-4-5' }, + content: [{ type: 'text', text }], + time: { created: NOW + createdOffset, completed: NOW + completedOffset }, + } +} + +const userMessage: SessionMessageInfo = { + id: 'preview-user', + type: 'user', + text: '帮我把时间线里的会话事件提示改成和压缩一样的分隔线,并且默认关闭。', + time: { created: NOW - 60_000 }, +} + +const assistantMessage = textAssistant( + 'preview-assistant', + '已经改成左右横线 + 中间标签的分隔行。长路径会截断,悬停可以看完整内容。', + -59_000, + -58_000, +) + +const agentSwitched: NoticeMessage = { + id: 'preview-agent-switched', + type: 'agent-switched', + agent: 'plan', + previous: 'build', + time: { created: NOW - 59_500 }, +} + +const modelSwitched: NoticeMessage = { + id: 'preview-model-switched', + type: 'model-switched', + model: { providerID: 'anthropic', id: 'claude-sonnet-4-5', variant: 'high' }, + time: { created: NOW - 58_500 }, +} + +const moveNotice: NoticeMessage = { + id: 'preview-location', + type: 'location-switched', + location: { + directory: 'E:/dev/re_agent_UI/OpenCodeUI-worktrees/feature/timeline-notices-looks-and-settings', + }, + time: { created: NOW - 58_000 }, +} + +const skillNotice: NoticeMessage = { + id: 'preview-skill', + type: 'skill', + skill: 'commit', + name: 'Commit', + text: '', + time: { created: NOW - 57_000 }, +} + +const systemNotice: NoticeMessage = { + id: 'preview-system', + type: 'system', + text: 'Instructions updated', + description: 'Instructions updated: AGENTS.md, docs/v2-migration-contract.md, docs-ui-api-usage.md', + metadata: { + notice: 'instructions', + instructionSources: ['AGENTS.md', 'docs/v2-migration-contract.md', 'docs-ui-api-usage.md'], + }, + time: { created: NOW - 56_000 }, +} + +const subagentFailed: NoticeMessage = { + id: 'preview-subagent', + type: 'synthetic', + text: 'Explore failed', + description: 'Error: connect ETIMEDOUT 127.0.0.1:7890', + metadata: { source: 'subagent', agent: 'explore', state: 'error' }, + time: { created: NOW - 55_000 }, +} + +const restartNotice: NoticeMessage = { + id: 'preview-restart', + type: 'synthetic', + text: 'Continuing after restart', + metadata: { notice: 'restart' }, + time: { created: NOW - 54_000 }, +} + +const genericSynthetic: NoticeMessage = { + id: 'preview-synthetic', + type: 'synthetic', + text: 'Model switched while the turn was running; continuing from the previous step.', + time: { created: NOW - 53_000 }, +} + +const noticeSamples: Array<{ caption: string; message: NoticeMessage }> = [ + { caption: 'agent 切换', message: agentSwitched }, + { caption: '模型切换(含 variant)', message: modelSwitched }, + { caption: '会话移动到 worktree(长路径截断)', message: moveNotice }, + { caption: '技能激活', message: skillNotice }, + { caption: '指令更新', message: systemNotice }, + { caption: '子任务失败', message: subagentFailed }, + { caption: '重启后继续', message: restartNotice }, + { caption: '普通 synthetic 文本', message: genericSynthetic }, +] + +const previewDiffs: FileDiff[] = [ + { + file: 'src/features/message/parts/NoticePartView.tsx', + status: 'modified', + additions: 12, + deletions: 6, + patch: [ + '--- a/NoticePartView.tsx', + '+++ b/NoticePartView.tsx', + '@@ -1,4 +1,4 @@', + '-import { NoticeSeparator } from "./NoticeSeparator"', + '+import { TimelineSeparator } from "./SystemPartViews"', + ' ', + '-return ', + '+return ', + ' ', + ].join('\n'), + }, + { + file: 'src/features/chat/chatAreaVisibility.ts', + status: 'modified', + additions: 8, + deletions: 2, + patch: [ + '--- a/chatAreaVisibility.ts', + '+++ b/chatAreaVisibility.ts', + '@@ -62,3 +62,5 @@', + ' function hasAnyContent(message, showNotices) {', + '- if (isNoticeMessage(message)) return true', + '+ if (showNotices && isNoticeMessage(message)) return true', + '+ // 默认关闭时提示行不进时间线', + ' return false', + ' }', + ].join('\n'), + }, + { + file: 'src/locales/zh-CN/message.json', + status: 'modified', + additions: 3, + deletions: 0, + patch: [ + '--- a/message.json', + '+++ b/message.json', + '@@ -115,2 +115,5 @@', + ' "notice": {', + '+ "skillActivated": "技能 · {{name}}",', + '+ "movedTo": "会话已移动到 {{directory}}",', + '+ "agentChangedDetail": "Agent 已切换 · {{previous}} → {{agent}}",', + ' }', + ].join('\n'), + }, +] + +const runningCompaction: SessionMessageCompaction = { + id: 'preview-compaction-running', + type: 'compaction', + status: 'running', + reason: 'manual', + summary: '正在整理前 40 轮对话…', + recent: '', + time: { created: NOW - 52_000 }, +} + +function Section({ title, description, children }: { title: string; description?: string; children: ReactNode }) { + return ( +
+
+

{title}

+ {description &&

{description}

} +
+ {children} +
+ ) +} + +function ToolbarButton({ active, onClick, children }: { active?: boolean; onClick: () => void; children: ReactNode }) { + return ( + + ) +} + +export function TimelinePreview() { + const { t, i18n } = useTranslation(['message', 'settings']) + const { mode, setTheme } = useTheme() + + return ( +
+
+
+
+
+

Timeline UI Preview

+

+ 仅开发环境。下面全部是生产组件本身,不走 mock 组件。正式入口里三项都默认关闭。 +

+
+
+ void i18n.changeLanguage('zh-CN')}> + 中文 + + void i18n.changeLanguage('en')}> + English + + + setTheme('light')}> + 浅色 + + setTheme('dark')}> + 深色 + + setTheme('system')}> + 跟随系统 + +
+
+
+ +
+
+
+ {noticeSamples.map(sample => ( +
+
{sample.caption}
+ +
+ ))} +
+
压缩排队
+ +
+
+
+ +
+
+ + +
+
+ +
+
+
+
默认:收起成一行
+ diff.file)} + diffs={previewDiffs} + stateKey="preview-turn-diff-collapsed" + /> +
+
+
展开:文件列表 + 点文件看 diff
+ diff.file)} + diffs={previewDiffs} + defaultExpanded + stateKey="preview-turn-diff-expanded" + /> +
+
+
+ +
+
+
+ +
+ +
+ +
+ + +
+ diff.file)} + diffs={previewDiffs} + stateKey="preview-turn-diff-inline" + /> +
+ +
+ +
+
+
+ +
+
+
{t('settings:chat.showTimelineNotices')}:默认关闭
+
{t('settings:chat.showTurnDiff')}:默认关闭
+
{t('settings:chat.showQueuedCompaction')}:默认关闭
+
+
+
+
+
+ ) +} diff --git a/src/preview/main.tsx b/src/preview/main.tsx new file mode 100644 index 000000000..b18e389e2 --- /dev/null +++ b/src/preview/main.tsx @@ -0,0 +1,32 @@ +import { StrictMode } from 'react' +import { createRoot } from 'react-dom/client' +import 'katex/dist/katex.min.css' +import '../index.css' +import i18n from '../i18n' +import { themeStore } from '../store/themeStore' +import { TimelinePreview } from './TimelinePreview' + +// 与 src/main.tsx 相同:React 渲染前先把主题 CSS 变量注入 +themeStore.init() + +// 方便直接分享审查链接:?theme=light|dark&lang=zh|en +const params = new URLSearchParams(window.location.search) +const themeParam = params.get('theme') +if (themeParam === 'light' || themeParam === 'dark') themeStore.setColorMode(themeParam) +const langParam = params.get('lang') +if (langParam === 'zh') void i18n.changeLanguage('zh-CN') +if (langParam === 'en') void i18n.changeLanguage('en') + +// 生产入口把 html/body/#root 锁成 100dvh + overflow hidden(聊天区自己滚)。 +// 预览页是普通长文档,这里放开滚动。 +for (const element of [document.documentElement, document.body, document.getElementById('root')]) { + if (!element) continue + element.style.height = 'auto' + element.style.overflow = 'visible' +} + +createRoot(document.getElementById('root')!).render( + + + , +) From d9ee30c497a744e37879e1d27c8bf88c20597817 Mon Sep 17 00:00:00 2001 From: lehhair Date: Fri, 23 Oct 2026 17:32:32 +0800 Subject: [PATCH 35/67] =?UTF-8?q?fix(timeline):=20=E5=9B=9E=E5=90=88?= =?UTF-8?q?=E6=96=87=E4=BB=B6=E5=8F=98=E6=9B=B4=E6=94=B9=E4=B8=BA=E6=AD=A3?= =?UTF-8?q?=E6=96=87=E6=9C=AB=E5=B0=BE=E7=9A=84=E5=8D=A1=E7=89=87?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/features/chat/ChatArea.test.ts | 30 ++-- src/features/chat/ChatArea.tsx | 29 ++-- src/features/chat/chatAreaUtils.ts | 1 - src/features/chat/chatPageModel.ts | 96 ++++++------- src/features/message/MessageRenderer.tsx | 24 ++++ .../message/parts/TurnDiffPartView.test.tsx | 12 +- .../message/parts/TurnDiffPartView.tsx | 132 ++++++++++-------- src/features/message/parts/index.ts | 1 + src/features/message/parts/turnDiffCache.ts | 24 ++++ src/preview/TimelinePreview.tsx | 22 +-- 10 files changed, 227 insertions(+), 144 deletions(-) create mode 100644 src/features/message/parts/turnDiffCache.ts diff --git a/src/features/chat/ChatArea.test.ts b/src/features/chat/ChatArea.test.ts index 01163cb9f..aabea5d1b 100644 --- a/src/features/chat/ChatArea.test.ts +++ b/src/features/chat/ChatArea.test.ts @@ -1039,11 +1039,11 @@ describe('buildProcessTimeline', () => { turnDiff: true, }) - expect(timeline.at(-1)).toMatchObject({ - kind: 'turn-diff', - userMessageId: 'user-1', - files: ['a.ts', 'b.ts'], - }) + const shell = timeline.at(-1) + expect(shell?.kind).toBe('process-shell') + if (shell?.kind === 'process-shell') { + expect(shell.turnDiff).toEqual({ from: 'user-1', files: ['a.ts', 'b.ts'] }) + } }) it('does not append a turn diff while the turn is still running', () => { @@ -1059,7 +1059,8 @@ describe('buildProcessTimeline', () => { turnDiff: true, }) - expect(timeline.some(item => item.kind === 'turn-diff')).toBe(false) + const shell = timeline.find(item => item.kind === 'process-shell') + if (shell?.kind === 'process-shell') expect(shell.turnDiff).toBeUndefined() }) }) @@ -1077,12 +1078,13 @@ describe('buildFlatTimeline', () => { const timeline = buildFlatTimeline(messages, true, true) expect(timeline.filter(item => item.kind === 'message')).toHaveLength(4) - expect(timeline.find(item => item.kind === 'turn-diff')).toMatchObject({ - userMessageId: 'user-1', - files: ['src/a.ts'], + expect(timeline[1]).toMatchObject({ + kind: 'message', + key: 'assistant-1', + turnDiff: { from: 'user-1', files: ['src/a.ts'] }, }) // 最后一个回合还在跑:不放摘要 - expect(timeline.filter(item => item.kind === 'turn-diff')).toHaveLength(1) + expect(timeline.filter(item => item.kind === 'message' && item.turnDiff)).toHaveLength(1) }) it('adds the last turn diff once streaming ends', () => { @@ -1090,8 +1092,12 @@ describe('buildFlatTimeline', () => { assistant.snapshot = { files: ['src/a.ts'] } const messages = [createUserMessage('user-1', 1000), assistant] - expect(buildFlatTimeline(messages, true, true).some(item => item.kind === 'turn-diff')).toBe(false) - expect(buildFlatTimeline(messages, false, true).some(item => item.kind === 'turn-diff')).toBe(true) + expect( + buildFlatTimeline(messages, true, true).every(item => item.kind !== 'message' || !item.turnDiff), + ).toBe(true) + expect(buildFlatTimeline(messages, false, true)[1]).toMatchObject({ + turnDiff: { from: 'user-1', files: ['src/a.ts'] }, + }) }) }) diff --git a/src/features/chat/ChatArea.tsx b/src/features/chat/ChatArea.tsx index 775764062..369b91467 100644 --- a/src/features/chat/ChatArea.tsx +++ b/src/features/chat/ChatArea.tsx @@ -45,6 +45,7 @@ import { buildTurnLatestAssistantIdSet, reuseProcessTimelineItems, type ProcessTimelineItem, + type TurnDiffInfo, } from './chatPageModel' import { useTheme } from '../../hooks/useTheme' import { getStreamingHotIndexes, getTimelineRowYClass, mergeVirtualRangeIndexes } from './chatAreaUtils' @@ -71,7 +72,6 @@ const bottomSpacerHeight = (bottomPadding: number) => (bottomPadding > 0 ? botto function estimateTimelineItemSize(item: ProcessTimelineItem | undefined): number { if (!item) return ROW_ESTIMATE if (item.kind === 'message') return ROW_ESTIMATE - if (item.kind === 'turn-diff') return 32 + Math.min(item.files.length, 5) * 20 // 进行中默认展开:header + 壳内消息(空回合至少占 header) if (item.isActive) { const body = Math.max(item.children.length, 1) * ROW_ESTIMATE @@ -149,6 +149,9 @@ interface MessageBodyProps { processContentScope?: 'all' | 'process' | 'final' | 'inline' /** step 完成信息是否由本实例渲染(壳内那截且壳外还有一份时传 false) */ stepFinishVisible?: boolean + /** 回合文件变更摘要(渲染在正文末尾、step 信息之前) */ + turnDiff?: TurnDiffInfo + sessionId?: string | null onEntryGrowComplete?: (messageId: string) => void } @@ -164,6 +167,8 @@ const MessageBody = memo(function MessageBody({ allowStreamingLayoutAnimation, processContentScope = 'all', stepFinishVisible, + turnDiff, + sessionId, onEntryGrowComplete, }: MessageBodyProps) { const messageId = message.id @@ -189,6 +194,8 @@ const MessageBody = memo(function MessageBody({ onFork={onFork} forkMessageId={forkMessageId} canUndo={undoable ? canUndo : undefined} + turnDiff={turnDiff} + sessionId={sessionId} onEntryGrowComplete={isUser ? onEntryGrowComplete : undefined} />
@@ -273,14 +280,9 @@ const VirtualRow = memo( } allowStreamingLayoutAnimation={allowStreamingLayoutAnimation} processContentScope={item.processContentScope ?? 'all'} - onEntryGrowComplete={onEntryGrowComplete} - /> - ) : item.kind === 'turn-diff' ? ( - ) : (
@@ -322,6 +324,16 @@ const VirtualRow = memo( isTurnLatestAssistant allowStreamingLayoutAnimation={allowStreamingLayoutAnimation} processContentScope="final" + turnDiff={item.turnDiff} + sessionId={sessionId} + /> + )} + {!item.finalMessage && item.turnDiff && ( + )}
@@ -474,7 +486,6 @@ export const ChatArea = memo( map.set(item.message.id, index) return } - if (item.kind === 'turn-diff') return if (item.userMessageId) map.set(item.userMessageId, index) for (const child of item.children) map.set(child.message.id, index) if (item.finalMessage) map.set(item.finalMessage.id, index) diff --git a/src/features/chat/chatAreaUtils.ts b/src/features/chat/chatAreaUtils.ts index bb26507b4..50df1a931 100644 --- a/src/features/chat/chatAreaUtils.ts +++ b/src/features/chat/chatAreaUtils.ts @@ -28,7 +28,6 @@ export function getTimelineRowYClass( next?: ProcessTimelineItem, ): string { if (item.kind === 'process-shell') return ROW_Y_TURN - if (item.kind === 'turn-diff') return ROW_Y_ASSISTANT_STACK if (isNoticeItem(item)) return '' if (isUserMessage(item.message)) return ROW_Y_TURN diff --git a/src/features/chat/chatPageModel.ts b/src/features/chat/chatPageModel.ts index be79c55bb..136c7ee89 100644 --- a/src/features/chat/chatPageModel.ts +++ b/src/features/chat/chatPageModel.ts @@ -744,6 +744,14 @@ export function buildTurnLatestAssistantIdSet(visibleMessages: SessionMessageInf return latestIds } +/** 回合文件变更摘要(附着在回合最后一条正文消息上,渲染在其正文末尾) */ +export interface TurnDiffInfo { + /** 该轮用户消息 id */ + from: string + /** 各 step 记录到的变更文件(去重排序) */ + files: string[] +} + /** 过程折叠:虚拟时间线上的一行 */ export type ProcessTimelineItem = | { @@ -752,6 +760,8 @@ export type ProcessTimelineItem = message: SessionMessageInfo /** 过程壳内消息的内容范围 */ processContentScope?: 'process' | 'final' | 'inline' + /** 回合文件变更摘要(仅挂在回合最后一条正文消息上) */ + turnDiff?: TurnDiffInfo } | { kind: 'process-shell' @@ -767,14 +777,8 @@ export type ProcessTimelineItem = }> /** 壳外最终回答(结束后才有) */ finalMessage?: SessionMessageInfo - } - | { - /** 回合结束后的文件变更摘要(官方 TurnDiff 行) */ - kind: 'turn-diff' - key: string - userMessageId: string - /** 该回合里各 step 记录到的变更文件(去重排序) */ - files: string[] + /** 回合文件变更摘要:有壳外 final 时挂在 final 上,没有时由壳外单独渲染 */ + turnDiff?: TurnDiffInfo } /** 两行是否可共享同一对象(VirtualRow 靠 item 引用短路) */ @@ -783,7 +787,12 @@ export function sameProcessTimelineItem(a: ProcessTimelineItem, b: ProcessTimeli if (a.kind !== b.kind || a.key !== b.key) return false if (a.kind === 'message' && b.kind === 'message') { - return a.message === b.message && a.processContentScope === b.processContentScope + return ( + a.message === b.message && + a.processContentScope === b.processContentScope && + a.turnDiff?.from === b.turnDiff?.from && + a.turnDiff?.files === b.turnDiff?.files + ) } if (a.kind === 'process-shell' && b.kind === 'process-shell') { @@ -793,6 +802,8 @@ export function sameProcessTimelineItem(a: ProcessTimelineItem, b: ProcessTimeli a.durationMs !== b.durationMs || a.isActive !== b.isActive || a.finalMessage !== b.finalMessage || + a.turnDiff?.from !== b.turnDiff?.from || + a.turnDiff?.files !== b.turnDiff?.files || a.children.length !== b.children.length ) { return false @@ -807,14 +818,6 @@ export function sameProcessTimelineItem(a: ProcessTimelineItem, b: ProcessTimeli return true } - if (a.kind === 'turn-diff' && b.kind === 'turn-diff') { - return ( - a.userMessageId === b.userMessageId && - a.files.length === b.files.length && - a.files.every((file, index) => file === b.files[index]) - ) - } - return false } @@ -874,46 +877,37 @@ export function buildFlatTimeline( key: message.id, message, })) + if (!turnDiff) return items - const turns: Array<{ userId: string; lastIndex: number; files: Set }> = [] + const turns: Array<{ userId: string; lastAssistantIndex: number | null; files: Set }> = [] let current: (typeof turns)[number] | null = null messages.forEach((message, index) => { if (isUserMessage(message)) { if (current) turns.push(current) - current = { userId: message.id, lastIndex: index, files: new Set() } + current = { userId: message.id, lastAssistantIndex: null, files: new Set() } return } if (!current) return - current.lastIndex = index if (isAssistantMessage(message)) { + current.lastAssistantIndex = index for (const file of message.snapshot?.files ?? []) current.files.add(file) } }) if (current) turns.push(current) - const diffByIndex = new Map() - if (!turnDiff) return items turns.forEach((turn, index) => { - if (turn.files.size === 0) return + if (turn.lastAssistantIndex == null || turn.files.size === 0) return if (index === turns.length - 1 && sessionIsStreaming) return - diffByIndex.set(turn.lastIndex, { userId: turn.userId, files: [...turn.files].sort() }) - }) - if (diffByIndex.size === 0) return items - - const result: ProcessTimelineItem[] = [] - items.forEach((item, index) => { - result.push(item) - const diff = diffByIndex.get(index) - if (!diff) return - result.push({ - kind: 'turn-diff', - key: `turn-diff:${diff.userId}`, - userMessageId: diff.userId, - files: diff.files, - }) + const target = items[turn.lastAssistantIndex] + if (target?.kind !== 'message') return + items[turn.lastAssistantIndex] = { + ...target, + turnDiff: { from: turn.userId, files: [...turn.files].sort() }, + } }) - return result + + return items } function assistantHasLiveWork(message: AssistantMessage): boolean { @@ -1173,6 +1167,9 @@ export function buildProcessTimeline( const finalOutside = !turnIsActive && finalAssistant && messageHasFinal(finalAssistant) ? finalAssistant : undefined + const files = !turnIsActive && turnDiff ? collectTurnFiles(assistants) : [] + const turnDiffInfo: TurnDiffInfo | undefined = files.length > 0 ? { from: userId, files } : undefined + // 进行中或有过程内容 → 挂壳 // 更晚的空 pending 回合:turnIsActive=false 且无 children → 不挂壳(只显示 user) // 纯 final 正文、无过程 → 直接平铺 @@ -1186,29 +1183,28 @@ export function buildProcessTimeline( isActive: turnIsActive, children, finalMessage: finalOutside, + turnDiff: turnDiffInfo, }) } else if (finalOutside) { items.push({ kind: 'message', key: finalOutside.id, message: finalOutside, + turnDiff: turnDiffInfo, }) } else { - for (const m of assistants) { - items.push({ kind: 'message', key: m.id, message: m }) - } + assistants.forEach((m, index) => { + items.push({ + kind: 'message', + key: m.id, + message: m, + turnDiff: index === assistants.length - 1 ? turnDiffInfo : undefined, + }) + }) } emitNotices(turn, false) - // 回合结束后追加文件变更摘要(官方 TurnDiff:idle 后按 snapshot.files 汇总) - if (!turnIsActive && turnDiff) { - const files = collectTurnFiles(assistants) - if (files.length > 0) { - items.push({ kind: 'turn-diff', key: `turn-diff:${userId}`, userMessageId: userId, files }) - } - } - appendFailedIdle(turn) } diff --git a/src/features/message/MessageRenderer.tsx b/src/features/message/MessageRenderer.tsx index d04e4f010..0a380ed4f 100644 --- a/src/features/message/MessageRenderer.tsx +++ b/src/features/message/MessageRenderer.tsx @@ -25,10 +25,12 @@ import { RetryPartView, CompactionPartView, TimelineNoticeView, + TurnDiffPartView, MessageErrorView, type StepFinishInfo, type NoticeMessage, } from './parts' +import type { TurnDiffInfo } from '../chat/chatPageModel' import { CollapsibleUserText, USER_HTML_ARTIFACT_PATTERN } from './CollapsibleUserText' import { extractToolData, type ToolViewPart } from './tools' import { ForkActionButton, UndoActionButton, useMessageActionBarClass } from './MessageActionBar' @@ -285,6 +287,10 @@ interface MessageRendererProps { onFork?: (message: SessionMessageInfo, forkMessageId?: string) => Promise | void forkMessageId?: string canUndo?: boolean + /** 回合文件变更摘要:渲染在正文末尾、step 信息之前 */ + turnDiff?: TurnDiffInfo + /** 带服务器前缀的 session key,供 diff 拉取 */ + sessionId?: string | null /** 用户消息入场生长完成(供过程壳等待挂载) */ onEntryGrowComplete?: (messageId: string) => void } @@ -300,6 +306,8 @@ export const MessageRenderer = memo(function MessageRenderer({ onFork, forkMessageId, canUndo, + turnDiff, + sessionId, onEntryGrowComplete, }: MessageRendererProps) { if (message.type === 'user') { @@ -379,6 +387,8 @@ export const MessageRenderer = memo(function MessageRenderer({ stepFinishVisible={stepFinishVisible} onFork={onFork} forkMessageId={forkMessageId} + turnDiff={turnDiff} + sessionId={sessionId} /> ) }) @@ -616,6 +626,8 @@ const AssistantMessageView = memo(function AssistantMessageView({ stepFinishVisible = true, onFork, forkMessageId, + turnDiff, + sessionId, }: { message: AssistantMessage allowStreamingLayoutAnimation?: boolean @@ -625,6 +637,8 @@ const AssistantMessageView = memo(function AssistantMessageView({ stepFinishVisible?: boolean onFork?: (message: SessionMessageInfo, forkMessageId?: string) => Promise | void forkMessageId?: string + turnDiff?: TurnDiffInfo + sessionId?: string | null }) { const { t } = useTranslation('message') const { stepFinishDisplay, completedAtFormat, actionsOnLatestAssistantOnly } = useTheme() @@ -764,6 +778,16 @@ const AssistantMessageView = memo(function AssistantMessageView({ } })} + {/* 回合文件变更:放在正文末尾、step 信息之前,避免和正文分离 */} + {turnDiff && processContentScope !== 'process' && processContentScope !== 'inline' && ( + + )} + {/* step 完成信息:v2 里一个助手消息就是一整个 step,tokens / cost / finish 全挂在消息上,所以固定放在本消息内容末尾一行。 diff --git a/src/features/message/parts/TurnDiffPartView.test.tsx b/src/features/message/parts/TurnDiffPartView.test.tsx index 7aa00eea2..b85bce7d8 100644 --- a/src/features/message/parts/TurnDiffPartView.test.tsx +++ b/src/features/message/parts/TurnDiffPartView.test.tsx @@ -24,11 +24,11 @@ describe('TurnDiffPartView', () => { render() expect(screen.getByText('2 files changed')).toBeInTheDocument() - expect(screen.queryByText('src/a.ts')).not.toBeInTheDocument() + expect(screen.queryByTitle('src/a.ts')).not.toBeInTheDocument() fireEvent.click(screen.getByText('2 files changed')) - expect(screen.getByText('src/a.ts')).toBeInTheDocument() - expect(screen.getByText('src/b.ts')).toBeInTheDocument() + expect(screen.getByTitle('src/a.ts')).toBeInTheDocument() + expect(screen.getByTitle('src/b.ts')).toBeInTheDocument() }) it('shows change totals and expands a file diff on click', async () => { @@ -43,7 +43,7 @@ describe('TurnDiffPartView', () => { await waitFor(() => expect(mockGetTurnDiff).toHaveBeenCalledWith('server:session-b', 'user-2')) expect(await screen.findByText('+3')).toBeInTheDocument() - fireEvent.click(screen.getByText('src/a.ts')) + fireEvent.click(screen.getByTitle('src/a.ts')) expect(screen.getByTestId('diff-view')).toHaveTextContent('src/a.ts') }) @@ -54,9 +54,9 @@ describe('TurnDiffPartView', () => { render() fireEvent.click(screen.getByText('7 files changed')) - expect(screen.queryByText('src/file-6.ts')).not.toBeInTheDocument() + expect(screen.queryByTitle('src/file-6.ts')).not.toBeInTheDocument() fireEvent.click(screen.getByText('Show all')) - expect(screen.getByText('src/file-6.ts')).toBeInTheDocument() + expect(screen.getByTitle('src/file-6.ts')).toBeInTheDocument() }) }) diff --git a/src/features/message/parts/TurnDiffPartView.tsx b/src/features/message/parts/TurnDiffPartView.tsx index 96c5121ac..999077709 100644 --- a/src/features/message/parts/TurnDiffPartView.tsx +++ b/src/features/message/parts/TurnDiffPartView.tsx @@ -1,19 +1,20 @@ // ============================================ // 回合文件变更摘要(官方 timeline 的 TurnDiff 行) // -// 默认收起成一行「N 个文件变更」,点开才列文件、再点文件看 diff。 -// 官方是列表常驻,这里按本项目的信息流密度收了一级,避免每轮都铺一屏。 +// 以卡片形式挂在回合正文末尾(step 信息之前),默认收起成一行。 +// 展开后列出文件;点某个文件再内联展开 diff。 // 默认关闭,可在设置里打开。 // ============================================ import { memo, useEffect, useState } from 'react' import { useTranslation } from 'react-i18next' -import { ChevronDownIcon } from '../../../components/Icons' +import { ChevronDownIcon, GitDiffIcon } from '../../../components/Icons' import { DiffView } from '../../../components/DiffView' import { getTurnDiff } from '../../../api/session' import type { FileDiff } from '../../../api/types' import { useUiDisclosureState } from '../../../utils/uiDisclosureState' import { chevronClass } from '../messageExpand' +import { cacheTurnDiff, getCachedTurnDiff } from './turnDiffCache' /** 官方 turnDiffFileLimit 同款:列表默认最多露 5 个文件 */ const TURN_DIFF_FILE_LIMIT = 5 @@ -32,17 +33,17 @@ interface TurnDiffPartViewProps { defaultExpanded?: boolean } -/** 会话内跨虚拟行复用已拉到的 diff(只留最近若干轮,避免补丁长期占内存) */ -const turnDiffCache = new Map() -const MAX_CACHED_TURN_DIFFS = 50 +function splitPath(file: string): { dir: string; name: string } { + const index = Math.max(file.lastIndexOf('/'), file.lastIndexOf('\\')) + if (index < 0) return { dir: '', name: file } + return { dir: file.slice(0, index + 1), name: file.slice(index + 1) } +} -function cacheTurnDiff(key: string, diffs: FileDiff[]) { - turnDiffCache.set(key, diffs) - while (turnDiffCache.size > MAX_CACHED_TURN_DIFFS) { - const oldest = turnDiffCache.keys().next().value - if (oldest === undefined) break - turnDiffCache.delete(oldest) - } +function statusOf(diff: FileDiff | undefined): { letter: string; className: string } { + if (!diff) return { letter: '·', className: 'text-text-500' } + if (diff.status === 'added') return { letter: 'A', className: 'text-success-100' } + if (diff.status === 'deleted') return { letter: 'D', className: 'text-danger-100' } + return { letter: 'M', className: 'text-warning-100' } } export const TurnDiffPartView = memo(function TurnDiffPartView({ @@ -55,13 +56,16 @@ export const TurnDiffPartView = memo(function TurnDiffPartView({ }: TurnDiffPartViewProps) { const { t } = useTranslation('message') const cacheKey = sessionId ? `${sessionId}:${from}` : '' - const [expanded, setExpanded] = useUiDisclosureState(stateKey ?? `turn-diff:${cacheKey}`, defaultExpanded ?? false) + const [expanded, setExpanded] = useUiDisclosureState( + stateKey ?? `turn-diff:${cacheKey}`, + defaultExpanded ?? false, + ) const [fetched, setFetched] = useState<{ key: string; diffs: FileDiff[] } | null>(null) const [showAll, setShowAll] = useState(false) const [openFiles, setOpenFiles] = useState>(() => new Set()) // 已缓存的 diff 直接在渲染期取,避免在 effect 里同步 setState - const loadedDiffs = (fetched?.key === cacheKey ? fetched.diffs : undefined) ?? turnDiffCache.get(cacheKey) ?? null + const loadedDiffs = (fetched?.key === cacheKey ? fetched.diffs : undefined) ?? getCachedTurnDiff(cacheKey) ?? null const diffs = diffsProp ?? loadedDiffs useEffect(() => { @@ -99,56 +103,72 @@ export const TurnDiffPartView = memo(function TurnDiffPartView({ } return ( -
-
- +
+
+ + {expanded && ( - <> -
+
+
{visibleFiles.map(file => { const diff = diffs?.find(item => item.file === file) const open = openFiles.has(file) + const { dir, name } = splitPath(file) + const status = statusOf(diff) + + if (open && diff?.patch) { + return ( +
+ +
+ ) + } + return ( -
- - {open && diff?.patch && ( -
- -
+ {status.letter} + + + {dir} + {name} + + {diff && ( + + +{diff.additions}{' '} + -{diff.deletions} + )} -
+ ) })}
@@ -156,13 +176,13 @@ export const TurnDiffPartView = memo(function TurnDiffPartView({ {allFiles.length > TURN_DIFF_FILE_LIMIT && ( )} - +
)}
) diff --git a/src/features/message/parts/index.ts b/src/features/message/parts/index.ts index 9f04fd976..a4ab74ac2 100644 --- a/src/features/message/parts/index.ts +++ b/src/features/message/parts/index.ts @@ -9,4 +9,5 @@ export type { RetryInfo } from './SystemPartViews' export { TimelineNoticeView, CompactionQueuedView } from './NoticePartView' export type { NoticeMessage } from './NoticePartView' export { TurnDiffPartView } from './TurnDiffPartView' +export { primeTurnDiffCache } from './turnDiffCache' export { MessageErrorView } from './MessageErrorView' diff --git a/src/features/message/parts/turnDiffCache.ts b/src/features/message/parts/turnDiffCache.ts new file mode 100644 index 000000000..491a4c4b2 --- /dev/null +++ b/src/features/message/parts/turnDiffCache.ts @@ -0,0 +1,24 @@ +// 回合 diff 的会话内缓存:虚拟列表来回挂载时不重复请求,也给预览页提供 seed 入口。 + +import type { FileDiff } from '../../../api/types' + +const turnDiffCache = new Map() +const MAX_CACHED_TURN_DIFFS = 50 + +export function getCachedTurnDiff(key: string): FileDiff[] | undefined { + return turnDiffCache.get(key) +} + +export function cacheTurnDiff(key: string, diffs: FileDiff[]) { + turnDiffCache.set(key, diffs) + while (turnDiffCache.size > MAX_CACHED_TURN_DIFFS) { + const oldest = turnDiffCache.keys().next().value + if (oldest === undefined) break + turnDiffCache.delete(oldest) + } +} + +/** 预览/测试用:预先塞入某轮的 diff,避免走接口 */ +export function primeTurnDiffCache(sessionId: string, from: string, diffs: FileDiff[]) { + cacheTurnDiff(`${sessionId}:${from}`, diffs) +} diff --git a/src/preview/TimelinePreview.tsx b/src/preview/TimelinePreview.tsx index a7bfe51d1..acbe3edd5 100644 --- a/src/preview/TimelinePreview.tsx +++ b/src/preview/TimelinePreview.tsx @@ -15,6 +15,7 @@ import { CompactionQueuedView, TimelineNoticeView, TurnDiffPartView, + primeTurnDiffCache, type NoticeMessage, } from '../features/message/parts' import { useTheme } from '../hooks/useTheme' @@ -29,6 +30,9 @@ function textAssistant(id: string, text: string, createdOffset: number, complete agent: 'build', model: { providerID: 'anthropic', id: 'claude-sonnet-4-5' }, content: [{ type: 'text', text }], + cost: 0.0123, + tokens: { input: 12_400, output: 860, reasoning: 0, cache: { read: 0, write: 0 } }, + finish: 'stop', time: { created: NOW + createdOffset, completed: NOW + completedOffset }, } } @@ -180,6 +184,9 @@ const previewDiffs: FileDiff[] = [ }, ] +// 真实对话流里让卡片直接拿到假 diff,不走接口 +primeTurnDiffCache('preview', 'preview-user', previewDiffs) + const runningCompaction: SessionMessageCompaction = { id: 'preview-compaction-running', type: 'compaction', @@ -322,19 +329,14 @@ export function TimelinePreview() {
- + diff.file) }} + />
-
- diff.file)} - diffs={previewDiffs} - stateKey="preview-turn-diff-inline" - /> -
Date: Fri, 23 Oct 2026 17:37:35 +0800 Subject: [PATCH 36/67] =?UTF-8?q?fix(timeline):=20=E6=96=87=E4=BB=B6=20dif?= =?UTF-8?q?f=20=E6=94=B9=E4=B8=BA=E8=A1=8C=E4=B8=8B=E5=B1=95=E5=BC=80?= =?UTF-8?q?=EF=BC=8C=E5=8E=BB=E6=8E=89=E5=A5=97=E5=A8=83=E5=8D=A1=E7=89=87?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/components/DiffView.tsx | 24 ++++++ .../message/parts/TurnDiffPartView.tsx | 75 +++++++++++-------- src/preview/TimelinePreview.tsx | 12 +++ src/preview/main.tsx | 5 +- 4 files changed, 84 insertions(+), 32 deletions(-) diff --git a/src/components/DiffView.tsx b/src/components/DiffView.tsx index 5daacc5be..bcc2aa78a 100644 --- a/src/components/DiffView.tsx +++ b/src/components/DiffView.tsx @@ -24,6 +24,8 @@ interface DiffViewProps { maxHeight?: number /** Explicit language */ language?: string + /** 去掉外层卡片 / 头部 / 边框,只渲染 diff 正文(挂在文件行下面时用) */ + bare?: boolean } /** 轻量统计 additions/deletions,不做高亮 */ @@ -47,6 +49,7 @@ export const DiffView = memo(function DiffView({ defaultCollapsed = false, maxHeight = 300, language: explicitLanguage, + bare = false, }: DiffViewProps) { const { t } = useTranslation(['components', 'common']) const [collapsed, setCollapsed] = useState(defaultCollapsed) @@ -126,6 +129,27 @@ export const DiffView = memo(function DiffView({ return () => window.removeEventListener('resize', checkWidth) }, [fullscreenOpen]) + if (bare) { + if (!content) { + return diff ? ( +
{diff}
+ ) : null + } + return ( +
+ +
+ ) + } + // Fallback for unified diff string only if (!hasContent && diff) { return ( diff --git a/src/features/message/parts/TurnDiffPartView.tsx b/src/features/message/parts/TurnDiffPartView.tsx index 999077709..5624720a5 100644 --- a/src/features/message/parts/TurnDiffPartView.tsx +++ b/src/features/message/parts/TurnDiffPartView.tsx @@ -31,6 +31,8 @@ interface TurnDiffPartViewProps { diffs?: FileDiff[] /** 预览用:初始是否展开 */ defaultExpanded?: boolean + /** 预览用:初始展开的文件 */ + defaultOpenFiles?: string[] } function splitPath(file: string): { dir: string; name: string } { @@ -53,6 +55,7 @@ export const TurnDiffPartView = memo(function TurnDiffPartView({ stateKey, diffs: diffsProp, defaultExpanded, + defaultOpenFiles, }: TurnDiffPartViewProps) { const { t } = useTranslation('message') const cacheKey = sessionId ? `${sessionId}:${from}` : '' @@ -62,7 +65,9 @@ export const TurnDiffPartView = memo(function TurnDiffPartView({ ) const [fetched, setFetched] = useState<{ key: string; diffs: FileDiff[] } | null>(null) const [showAll, setShowAll] = useState(false) - const [openFiles, setOpenFiles] = useState>(() => new Set()) + const [openFiles, setOpenFiles] = useState>( + () => new Set(defaultOpenFiles ?? []), + ) // 已缓存的 diff 直接在渲染期取,避免在 effect 里同步 setState const loadedDiffs = (fetched?.key === cacheKey ? fetched.diffs : undefined) ?? getCachedTurnDiff(cacheKey) ?? null @@ -135,40 +140,48 @@ export const TurnDiffPartView = memo(function TurnDiffPartView({ const { dir, name } = splitPath(file) const status = statusOf(diff) - if (open && diff?.patch) { - return ( -
- -
- ) - } - return ( - + + {open && diff?.patch && ( +
+ +
)} - +
) })}
diff --git a/src/preview/TimelinePreview.tsx b/src/preview/TimelinePreview.tsx index acbe3edd5..c65f262cb 100644 --- a/src/preview/TimelinePreview.tsx +++ b/src/preview/TimelinePreview.tsx @@ -316,6 +316,18 @@ export function TimelinePreview() { stateKey="preview-turn-diff-expanded" />
+
+
点开文件:路径保留,diff 直接铺在行下面
+ diff.file)} + diffs={previewDiffs} + defaultExpanded + defaultOpenFiles={[previewDiffs[0].file]} + stateKey="preview-turn-diff-file-open" + /> +
diff --git a/src/preview/main.tsx b/src/preview/main.tsx index b18e389e2..4a29c37ed 100644 --- a/src/preview/main.tsx +++ b/src/preview/main.tsx @@ -4,6 +4,7 @@ import 'katex/dist/katex.min.css' import '../index.css' import i18n from '../i18n' import { themeStore } from '../store/themeStore' +import { FullscreenProvider } from '../contexts' import { TimelinePreview } from './TimelinePreview' // 与 src/main.tsx 相同:React 渲染前先把主题 CSS 变量注入 @@ -27,6 +28,8 @@ for (const element of [document.documentElement, document.body, document.getElem createRoot(document.getElementById('root')!).render( - + + + , ) From 0418523f2e1672708a95c879f6d0ba08be1dbf52 Mon Sep 17 00:00:00 2001 From: lehhair Date: Fri, 23 Oct 2026 18:09:29 +0800 Subject: [PATCH 37/67] =?UTF-8?q?fix(timeline):=20=E5=8E=8B=E7=BC=A9?= =?UTF-8?q?=E6=B6=88=E6=81=AF=E7=8B=AC=E7=AB=8B=E6=88=90=E8=A1=8C=EF=BC=8C?= =?UTF-8?q?=E5=A4=B1=E8=B4=A5=E6=8F=90=E7=A4=BA=E4=B8=8D=E5=86=8D=E8=A2=AB?= =?UTF-8?q?=E5=BC=80=E5=85=B3=E9=9A=90=E8=97=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - compaction 既不是 assistant 也不是 notice,构建 timeline 时被直接跳过, 导致压缩完成/进行中在 UI 上完全不可见;现在独立成行并结束上一回合 - synthetic 的错误和 shell 失败是失败唯一记录,不再受「显示会话事件提示」开关影响 - 只带 skills 附件的用户消息不再被整条过滤 --- src/features/chat/ChatArea.test.ts | 41 +++++++++++++++++++++++-- src/features/chat/chatAreaVisibility.ts | 28 ++++++++++++++--- src/features/chat/chatPageModel.ts | 11 +++++++ 3 files changed, 74 insertions(+), 6 deletions(-) diff --git a/src/features/chat/ChatArea.test.ts b/src/features/chat/ChatArea.test.ts index aabea5d1b..27267cc95 100644 --- a/src/features/chat/ChatArea.test.ts +++ b/src/features/chat/ChatArea.test.ts @@ -157,14 +157,22 @@ describe('buildVisibleMessageEntries', () => { expect(ids).not.toContain('synthetic-context') }) - it('hides timeline notices by default (setting off)', () => { + it('hides timeline notices by default but keeps synthetic failures', () => { const entries = buildVisibleMessageEntries([ createUserMessage('user-1', 1, '你好'), { id: 'agent-switch', type: 'agent-switched', agent: 'plan', time: { created: 2 } } as SessionMessageInfo, { id: 'skill', type: 'skill', skill: 'pdf', name: 'PDF', text: '', time: { created: 3 } } as SessionMessageInfo, + { + id: 'synthetic-error', + type: 'synthetic', + text: 'failed', + metadata: { state: 'error' }, + time: { created: 4 }, + } as SessionMessageInfo, ]) - expect(entries.map(entry => entry.message.id)).toEqual(['user-1']) + // 普通提示默认关;错误是失败唯一记录,必须无条件露出 + expect(entries.map(entry => entry.message.id)).toEqual(['user-1', 'synthetic-error']) }) it('keeps source ids for merged assistant tool messages', () => { @@ -747,6 +755,35 @@ describe('buildProcessTimeline', () => { expect(timeline.map(item => item.key)).toEqual(['user-1', 'agent-switch', 'process-shell:user-1', 'skill-1']) }) + it('renders a compaction message as its own timeline row', () => { + // 回归:compaction 既不是 assistant 也不是 notice,早先被 timeline 构建直接跳过, + // 导致服务端明明压缩了、UI 刷新也看不到任何压缩记录。 + const before = createAssistantMessage('assistant-before', [createToolPart('tool-1', 'assistant-before')], 1001, 1002) + const compaction = { + id: 'compaction-1', + type: 'compaction', + status: 'completed', + reason: 'manual', + summary: '压缩完成', + time: { created: 1003 }, + } as SessionMessageInfo + const messages = [createUserMessage('user-1', 1000), before, compaction, createUserMessage('user-2', 1004)] + const timeline = buildProcessTimeline(messages, { + turnDurationMap: new Map(), + sessionIsStreaming: false, + messageHasProcess: hasProcess, + messageHasFinal: hasFinal, + }) + + const compactionItem = timeline.find(item => item.key === 'compaction-1') + expect(compactionItem).toMatchObject({ kind: 'message', key: 'compaction-1' }) + // 压缩行独立,不塞进上一回合的过程壳 + const shell = timeline.find(item => item.kind === 'process-shell') + if (shell?.kind === 'process-shell') { + expect(shell.children.some(child => child.message.id === 'compaction-1')).toBe(false) + } + }) + it('does not duplicate the error card when the last assistant already shows it', () => { // assistant.error 已由 MessageErrorView 渲染 → idle 卡片跳过(官方同款去重) const failedAssistant = createAssistantMessage( diff --git a/src/features/chat/chatAreaVisibility.ts b/src/features/chat/chatAreaVisibility.ts index fc176ef85..502cabcc1 100644 --- a/src/features/chat/chatAreaVisibility.ts +++ b/src/features/chat/chatAreaVisibility.ts @@ -20,12 +20,20 @@ function isVisibleText(content: AssistantContent): boolean { /** 用户消息在 v2 里自带正文与附件 */ function userMessageHasAnyContent(message: UserMessage): boolean { - return userMessageText(message).length > 0 || (message.files?.length ?? 0) > 0 || (message.agents?.length ?? 0) > 0 + return ( + userMessageText(message).length > 0 || + (message.files?.length ?? 0) > 0 || + (message.agents?.length ?? 0) > 0 || + (message.skills?.length ?? 0) > 0 + ) } function userMessageHasRenderableContent(message: UserMessage): boolean { return ( - userMessageText(message).trim().length > 0 || (message.files?.length ?? 0) > 0 || (message.agents?.length ?? 0) > 0 + userMessageText(message).trim().length > 0 || + (message.files?.length ?? 0) > 0 || + (message.agents?.length ?? 0) > 0 || + (message.skills?.length ?? 0) > 0 ) } @@ -38,6 +46,18 @@ function syntheticNoticeRequired(message: Extract Date: Fri, 23 Oct 2026 18:09:31 +0800 Subject: [PATCH 38/67] =?UTF-8?q?fix(timeline):=20=E6=96=87=E4=BB=B6?= =?UTF-8?q?=E5=8F=98=E6=9B=B4=E6=94=B6=E6=95=9B=E4=B8=BA=E6=8F=8F=E8=BF=B0?= =?UTF-8?q?=E6=80=A7=E4=B8=80=E8=A1=8C=EF=BC=8Cdiff=20=E5=A4=8D=E7=94=A8?= =?UTF-8?q?=E5=B7=A5=E5=85=B7=E5=8D=A1?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 摘要行改成 compact 工具 step 的描述样式,去掉外层卡片和箭头 - 收起时也拉取 turn diff,变更量直接显示,展开不重复请求 - 每个文件使用 ContentBlock,复用 diff 渲染、分栏自适应和全屏 ViewModeSwitch - ContentBlock 新增 showFullPath / hideChevron,供该场景使用 --- src/components/ContentBlock.tsx | 10 +- src/components/DiffView.tsx | 4 +- .../message/parts/TurnDiffPartView.test.tsx | 63 ++++++-- .../message/parts/TurnDiffPartView.tsx | 153 ++++++------------ src/preview/TimelinePreview.tsx | 3 +- 5 files changed, 109 insertions(+), 124 deletions(-) diff --git a/src/components/ContentBlock.tsx b/src/components/ContentBlock.tsx index 2ebd7a0dc..45020b92d 100644 --- a/src/components/ContentBlock.tsx +++ b/src/components/ContentBlock.tsx @@ -34,8 +34,12 @@ export interface ContentBlockProps { labelIcon?: ReactNode /** 隐藏标签文本,仅保留图标 / 文件名 */ hideLabel?: boolean + /** 隐藏折叠箭头(外层已有展开控制时用) */ + hideChevron?: boolean /** 文件路径 */ filePath?: string + /** header 显示完整路径(默认只显示文件名) */ + showFullPath?: boolean /** 语言 */ language?: string /** 样式变体 */ @@ -80,7 +84,9 @@ export const ContentBlock = memo(function ContentBlock({ label, labelIcon, hideLabel = false, + hideChevron = false, filePath, + showFullPath = false, language, variant = 'default', defaultCollapsed = false, @@ -117,7 +123,7 @@ export const ContentBlock = memo(function ContentBlock({ const hasContent = !!content?.trim() || isDiff || stats?.exit !== undefined const canCollapse = !compact && collapsible && hasContent const lang = language || (filePath ? detectLanguage(filePath) : 'text') - const fileName = filePath?.split(/[/\\]/).pop() + const fileName = filePath ? (showFullPath ? filePath : filePath.split(/[/\\]/).pop()) : undefined const resolvedFullscreenId = fullscreenId ?? `content-block:${generatedFullscreenId}` const collapsed = compact ? false : cachedCollapsed @@ -283,7 +289,7 @@ export const ContentBlock = memo(function ContentBlock({ > {/* Left: chevron + label + filename */}
- {canCollapse && ( + {canCollapse && !hideChevron && ( {collapsed ? : } diff --git a/src/components/DiffView.tsx b/src/components/DiffView.tsx index bcc2aa78a..a637a1e05 100644 --- a/src/components/DiffView.tsx +++ b/src/components/DiffView.tsx @@ -47,7 +47,7 @@ export const DiffView = memo(function DiffView({ after, filePath, defaultCollapsed = false, - maxHeight = 300, + maxHeight, language: explicitLanguage, bare = false, }: DiffViewProps) { @@ -208,7 +208,7 @@ export const DiffView = memo(function DiffView({ after={content.after} language={language} viewMode="unified" - maxHeight={maxHeight} + maxHeight={maxHeight ?? 300} data={diffViewerData} />
diff --git a/src/features/message/parts/TurnDiffPartView.test.tsx b/src/features/message/parts/TurnDiffPartView.test.tsx index b85bce7d8..01865f3c7 100644 --- a/src/features/message/parts/TurnDiffPartView.test.tsx +++ b/src/features/message/parts/TurnDiffPartView.test.tsx @@ -2,17 +2,45 @@ import { fireEvent, render, screen, waitFor } from '@testing-library/react' import { beforeEach, describe, expect, it, vi } from 'vitest' import { TurnDiffPartView } from './TurnDiffPartView' import { getTurnDiff } from '../../../api/session' +import type { FileDiff } from '../../../api/types' vi.mock('../../../api/session', () => ({ getTurnDiff: vi.fn(), })) -vi.mock('../../../components/DiffView', () => ({ - DiffView: ({ filePath }: { filePath?: string }) =>
{filePath}
, +vi.mock('../../../components', () => ({ + ContentBlock: ({ + filePath, + diff, + diffStats, + }: { + filePath?: string + diff?: string + diffStats?: { additions: number; deletions: number } + }) => ( +
+ {filePath} + {diffStats && ( + + +{diffStats.additions} -{diffStats.deletions} + + )} +
+ ), })) const mockGetTurnDiff = vi.mocked(getTurnDiff) +function diff(file: string, additions = 1, deletions = 1): FileDiff { + return { + file, + patch: ['@@ -1 +1 @@', '-a', '+b'].join('\n'), + additions, + deletions, + status: 'modified', + } +} + describe('TurnDiffPartView', () => { beforeEach(() => { mockGetTurnDiff.mockReset() @@ -24,39 +52,40 @@ describe('TurnDiffPartView', () => { render() expect(screen.getByText('2 files changed')).toBeInTheDocument() - expect(screen.queryByTitle('src/a.ts')).not.toBeInTheDocument() + expect(screen.queryByText('src/a.ts')).not.toBeInTheDocument() fireEvent.click(screen.getByText('2 files changed')) - expect(screen.getByTitle('src/a.ts')).toBeInTheDocument() - expect(screen.getByTitle('src/b.ts')).toBeInTheDocument() + expect(screen.getByText('src/a.ts')).toBeInTheDocument() + expect(screen.getByText('src/b.ts')).toBeInTheDocument() }) - it('shows change totals and expands a file diff on click', async () => { - mockGetTurnDiff.mockResolvedValue([ - { file: 'src/a.ts', patch: '@@ -1 +1 @@\n-a\n+b', additions: 1, deletions: 1, status: 'modified' }, - { file: 'src/b.ts', patch: '@@ -1 +1 @@\n-c\n+d', additions: 2, deletions: 0, status: 'modified' }, - ]) + it('shows totals while collapsed and passes the patch into the tool-card diff', async () => { + mockGetTurnDiff.mockResolvedValue([diff('src/a.ts', 2, 1), diff('src/b.ts', 3, 0)]) render() - fireEvent.click(screen.getByText('2 files changed')) + // 收起状态也要直接看到变更量 await waitFor(() => expect(mockGetTurnDiff).toHaveBeenCalledWith('server:session-b', 'user-2')) - expect(await screen.findByText('+3')).toBeInTheDocument() + expect(await screen.findByText('+5')).toBeInTheDocument() + expect(screen.queryByText('src/a.ts')).not.toBeInTheDocument() - fireEvent.click(screen.getByTitle('src/a.ts')) - expect(screen.getByTestId('diff-view')).toHaveTextContent('src/a.ts') + fireEvent.click(screen.getByText('2 files changed')) + const card = screen + .getAllByTestId('content-block') + .find(node => node.getAttribute('data-file') === 'src/a.ts') + expect(card).toHaveAttribute('data-has-diff', 'true') }) - it('caps the list at five files until show all is pressed', async () => { + it('caps the list at five files until show all is pressed', () => { mockGetTurnDiff.mockReturnValue(new Promise(() => {})) const files = Array.from({ length: 7 }, (_, index) => `src/file-${index + 1}.ts`) render() fireEvent.click(screen.getByText('7 files changed')) - expect(screen.queryByTitle('src/file-6.ts')).not.toBeInTheDocument() + expect(screen.queryByText('src/file-6.ts')).not.toBeInTheDocument() fireEvent.click(screen.getByText('Show all')) - expect(screen.getByTitle('src/file-6.ts')).toBeInTheDocument() + expect(screen.getByText('src/file-6.ts')).toBeInTheDocument() }) }) diff --git a/src/features/message/parts/TurnDiffPartView.tsx b/src/features/message/parts/TurnDiffPartView.tsx index 5624720a5..41d9cf052 100644 --- a/src/features/message/parts/TurnDiffPartView.tsx +++ b/src/features/message/parts/TurnDiffPartView.tsx @@ -1,19 +1,19 @@ // ============================================ // 回合文件变更摘要(官方 timeline 的 TurnDiff 行) // -// 以卡片形式挂在回合正文末尾(step 信息之前),默认收起成一行。 -// 展开后列出文件;点某个文件再内联展开 diff。 +// 外层只是一行轻量标题,展开后每个文件直接复用工具卡的 ContentBlock: +// diff 渲染、分栏自适应、全屏里的 ViewModeSwitch、+/- 统计字体全部同源, +// 不再单独造一套 diff / 全屏。 // 默认关闭,可在设置里打开。 // ============================================ import { memo, useEffect, useState } from 'react' import { useTranslation } from 'react-i18next' -import { ChevronDownIcon, GitDiffIcon } from '../../../components/Icons' -import { DiffView } from '../../../components/DiffView' +import { ContentBlock } from '../../../components' import { getTurnDiff } from '../../../api/session' import type { FileDiff } from '../../../api/types' import { useUiDisclosureState } from '../../../utils/uiDisclosureState' -import { chevronClass } from '../messageExpand' +import { MessageExpandPanel, useMessageExpandRender } from '../messageExpand' import { cacheTurnDiff, getCachedTurnDiff } from './turnDiffCache' /** 官方 turnDiffFileLimit 同款:列表默认最多露 5 个文件 */ @@ -31,14 +31,6 @@ interface TurnDiffPartViewProps { diffs?: FileDiff[] /** 预览用:初始是否展开 */ defaultExpanded?: boolean - /** 预览用:初始展开的文件 */ - defaultOpenFiles?: string[] -} - -function splitPath(file: string): { dir: string; name: string } { - const index = Math.max(file.lastIndexOf('/'), file.lastIndexOf('\\')) - if (index < 0) return { dir: '', name: file } - return { dir: file.slice(0, index + 1), name: file.slice(index + 1) } } function statusOf(diff: FileDiff | undefined): { letter: string; className: string } { @@ -55,7 +47,6 @@ export const TurnDiffPartView = memo(function TurnDiffPartView({ stateKey, diffs: diffsProp, defaultExpanded, - defaultOpenFiles, }: TurnDiffPartViewProps) { const { t } = useTranslation('message') const cacheKey = sessionId ? `${sessionId}:${from}` : '' @@ -65,17 +56,16 @@ export const TurnDiffPartView = memo(function TurnDiffPartView({ ) const [fetched, setFetched] = useState<{ key: string; diffs: FileDiff[] } | null>(null) const [showAll, setShowAll] = useState(false) - const [openFiles, setOpenFiles] = useState>( - () => new Set(defaultOpenFiles ?? []), - ) + const shouldRenderBody = useMessageExpandRender(expanded) // 已缓存的 diff 直接在渲染期取,避免在 effect 里同步 setState const loadedDiffs = (fetched?.key === cacheKey ? fetched.diffs : undefined) ?? getCachedTurnDiff(cacheKey) ?? null const diffs = diffsProp ?? loadedDiffs useEffect(() => { - // 收起时不请求:历史回合很多,展开哪个才拉哪个 - if (!expanded || !sessionId || diffs) return + // 收起时也要拉一次:变更量(+N -N)必须在摘要行上直接可见。 + // 每个回合只请求一次,结果进缓存,展开时不再重复请求。 + if (!sessionId || diffs) return let cancelled = false getTurnDiff(sessionId, from) @@ -89,7 +79,7 @@ export const TurnDiffPartView = memo(function TurnDiffPartView({ return () => { cancelled = true } - }, [cacheKey, diffs, expanded, from, sessionId]) + }, [cacheKey, diffs, from, sessionId]) const allFiles = diffs?.map(diff => diff.file) ?? files if (allFiles.length === 0) return null @@ -98,105 +88,66 @@ export const TurnDiffPartView = memo(function TurnDiffPartView({ const additions = diffs?.reduce((total, diff) => total + diff.additions, 0) const deletions = diffs?.reduce((total, diff) => total + diff.deletions, 0) - const toggleFile = (file: string) => { - setOpenFiles(previous => { - const next = new Set(previous) - if (next.has(file)) next.delete(file) - else next.add(file) - return next - }) - } - return ( -
+
- {expanded && ( -
-
+ + {shouldRenderBody && ( +
{visibleFiles.map(file => { const diff = diffs?.find(item => item.file === file) - const open = openFiles.has(file) - const { dir, name } = splitPath(file) const status = statusOf(diff) - return ( -
- - - {open && diff?.patch && ( -
- -
- )} -
+ } + filePath={file} + showFullPath + hideChevron + diff={diff?.patch} + diffStats={diff ? { additions: diff.additions, deletions: diff.deletions } : undefined} + defaultCollapsed + stateKey={`turn-diff:${cacheKey}:${file}`} + /> ) })} -
- {allFiles.length > TURN_DIFF_FILE_LIMIT && ( - - )} -
- )} + {allFiles.length > TURN_DIFF_FILE_LIMIT && ( + + )} +
+ )} +
) }) diff --git a/src/preview/TimelinePreview.tsx b/src/preview/TimelinePreview.tsx index c65f262cb..182a46705 100644 --- a/src/preview/TimelinePreview.tsx +++ b/src/preview/TimelinePreview.tsx @@ -317,14 +317,13 @@ export function TimelinePreview() { />
-
点开文件:路径保留,diff 直接铺在行下面
+
默认收起:点任一文件展开,diff 用工具卡同款渲染
diff.file)} diffs={previewDiffs} defaultExpanded - defaultOpenFiles={[previewDiffs[0].file]} stateKey="preview-turn-diff-file-open" />
From acf287d6d819b6ec566cde212fadcc44dce710c0 Mon Sep 17 00:00:00 2001 From: lehhair Date: Fri, 23 Oct 2026 18:16:24 +0800 Subject: [PATCH 39/67] =?UTF-8?q?fix(message):=20=E6=B8=B2=E6=9F=93?= =?UTF-8?q?=E7=94=A8=E6=88=B7=E6=B6=88=E6=81=AF=E9=87=8C=E7=9A=84=20skill?= =?UTF-8?q?=20=E9=99=84=E4=BB=B6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 新增 SkillPartView,复用文件 / agent 提及的 AttachmentItem chip - 技能正文可展开查看,带正文时详情和复制可用 - 补齐 PromptSkillAttachment 类型导出 --- src/features/attachment/utils.ts | 2 ++ src/features/message/MessageRenderer.test.tsx | 12 ++++++++ src/features/message/MessageRenderer.tsx | 7 ++++- .../message/parts/AttachmentPartViews.tsx | 30 ++++++++++++++++++- src/features/message/parts/index.ts | 2 +- src/types/api/message.ts | 4 +++ 6 files changed, 54 insertions(+), 3 deletions(-) diff --git a/src/features/attachment/utils.ts b/src/features/attachment/utils.ts index dc92f3b7c..31b1b5970 100644 --- a/src/features/attachment/utils.ts +++ b/src/features/attachment/utils.ts @@ -114,6 +114,8 @@ export function hasExpandableContent(attachment: Attachment): boolean { return !!attachment.relativePath case 'agent': return !!attachment.agentName + case 'skill': + return !!attachment.content case 'text': return !!attachment.content default: diff --git a/src/features/message/MessageRenderer.test.tsx b/src/features/message/MessageRenderer.test.tsx index cbe0c2ca0..d5a78b9a7 100644 --- a/src/features/message/MessageRenderer.test.tsx +++ b/src/features/message/MessageRenderer.test.tsx @@ -74,6 +74,7 @@ vi.mock('./parts', () => ({
{file.name ?? file.mime}
), AgentPartView: ({ agent }: { agent: { name: string } }) =>
{agent.name}
, + SkillPartView: ({ skill }: { skill: { name: string } }) =>
{skill.name}
, StepFinishPartView: () => null, RetryPartView: () => null, CompactionPartView: ({ message }: { message: { status?: string } }) => @@ -182,6 +183,17 @@ describe('MessageRenderer assistant fork', () => { expect(screen.getByTestId('agent-part')).toHaveTextContent('explore') }) + it('renders skill mentions from the native skills array', () => { + const message: UserMessage = { + ...createUserTextMessage('use skill'), + skills: [{ id: 'commit', name: 'Commit', text: 'skill body' }], + } + + render() + + expect(screen.getByTestId('skill-part')).toHaveTextContent('Commit') + }) + it('keeps user text plain by default', () => { render() diff --git a/src/features/message/MessageRenderer.tsx b/src/features/message/MessageRenderer.tsx index 0a380ed4f..8b1d165f0 100644 --- a/src/features/message/MessageRenderer.tsx +++ b/src/features/message/MessageRenderer.tsx @@ -21,6 +21,7 @@ import { ToolPartView, FilePartView, AgentPartView, + SkillPartView, StepFinishPartView, RetryPartView, CompactionPartView, @@ -570,6 +571,7 @@ const UserMessageView = memo(function UserMessageView({ const messageText = userMessageText(message) const files = message.files ?? [] const agents = message.agents ?? [] + const skills = message.skills ?? [] const hasUserHtmlArtifact = renderUserMarkdown && USER_HTML_ARTIFACT_PATTERN.test(messageText) return ( @@ -590,7 +592,7 @@ const UserMessageView = memo(function UserMessageView({ )} {/* 用户附件 */} - {(files.length > 0 || agents.length > 0) && ( + {(files.length > 0 || agents.length > 0 || skills.length > 0) && (
{files.map((file, index) => ( @@ -598,6 +600,9 @@ const UserMessageView = memo(function UserMessageView({ {agents.map((agent, index) => ( ))} + {skills.map((skill, index) => ( + + ))}
)} diff --git a/src/features/message/parts/AttachmentPartViews.tsx b/src/features/message/parts/AttachmentPartViews.tsx index 6ba7c6eb9..725e8c48a 100644 --- a/src/features/message/parts/AttachmentPartViews.tsx +++ b/src/features/message/parts/AttachmentPartViews.tsx @@ -1,6 +1,6 @@ import { memo } from 'react' import { AttachmentItem } from '../../attachment' -import type { PromptAgentAttachment, PromptFileAttachment } from '../../../types/api/message' +import type { PromptAgentAttachment, PromptFileAttachment, PromptSkillAttachment } from '../../../types/api/message' // ============================================ // v2 用户消息附件 → 统一 Attachment // @@ -85,3 +85,31 @@ export const AgentPartView = memo(function AgentPartView({ agent, index }: Agent /> ) }) + +// ============================================ +// Skill Attachment View +// ============================================ + +interface SkillPartViewProps { + skill: PromptSkillAttachment + index: number +} + +/** `@skill` 提及:和文件 / agent 附件同一套 chip,展开可看技能正文 */ +export const SkillPartView = memo(function SkillPartView({ skill, index }: SkillPartViewProps) { + return ( + + ) +}) diff --git a/src/features/message/parts/index.ts b/src/features/message/parts/index.ts index a4ab74ac2..0bfc9247b 100644 --- a/src/features/message/parts/index.ts +++ b/src/features/message/parts/index.ts @@ -1,7 +1,7 @@ export { TextPartView } from './TextPartView' export { ReasoningPartView } from './ReasoningPartView' export { ToolPartView } from './ToolPartView' -export { FilePartView, AgentPartView } from './AttachmentPartViews' +export { FilePartView, AgentPartView, SkillPartView } from './AttachmentPartViews' export { StepFinishPartView } from './StepFinishPartView' export type { StepFinishInfo } from './StepFinishPartView' export { RetryPartView, CompactionPartView } from './SystemPartViews' diff --git a/src/types/api/message.ts b/src/types/api/message.ts index 4dc0a3f07..b7bf3d884 100644 --- a/src/types/api/message.ts +++ b/src/types/api/message.ts @@ -23,6 +23,7 @@ import type { PromptAgentAttachment as V2PromptAgentAttachment, PromptFileAttachment as V2PromptFileAttachment, + PromptSkillAttachment as V2PromptSkillAttachment, SessionMessageAgentSelected as V2AgentSelected, SessionMessageAssistant as V2Assistant, SessionMessageAssistantReasoning as V2AssistantReasoning, @@ -93,6 +94,9 @@ export type PromptFileAttachment = V2PromptFileAttachment /** 用户消息里的 agent 提及 */ export type PromptAgentAttachment = V2PromptAgentAttachment +/** 用户消息里的 skill 附件(@ 技能提及) */ +export type PromptSkillAttachment = V2PromptSkillAttachment + // ============================================ // 助手内容(content 数组元素) // ============================================ From 1bf39b22a099221556b93b9acfb65d2ed7fbec49 Mon Sep 17 00:00:00 2001 From: lehhair Date: Fri, 23 Oct 2026 18:19:51 +0800 Subject: [PATCH 40/67] =?UTF-8?q?fix(attachment):=20skill=20=E9=99=84?= =?UTF-8?q?=E4=BB=B6=E5=B1=95=E5=BC=80=E5=90=8E=E8=A1=A5=E4=B8=8A=E7=B1=BB?= =?UTF-8?q?=E5=9E=8B=E5=92=8C=E6=8A=80=E8=83=BD=20ID?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit skill 的元信息字段全是 undefined,展开后只剩一个空的 p-2 容器。 现在显示「类型: 技能」和「技能 ID」,command / agent 的类型行也一并补全。 --- .../attachment/AttachmentItem.test.tsx | 27 ++++++++++++++++++- src/features/attachment/AttachmentItem.tsx | 18 +++++++++++-- src/locales/en/commands.json | 3 +++ src/locales/zh-CN/commands.json | 3 +++ 4 files changed, 48 insertions(+), 3 deletions(-) diff --git a/src/features/attachment/AttachmentItem.test.tsx b/src/features/attachment/AttachmentItem.test.tsx index 393330d45..9c5c5085b 100644 --- a/src/features/attachment/AttachmentItem.test.tsx +++ b/src/features/attachment/AttachmentItem.test.tsx @@ -1,4 +1,4 @@ -import { render, screen } from '@testing-library/react' +import { fireEvent, render, screen } from '@testing-library/react' import { describe, expect, it } from 'vitest' import { AttachmentItem } from './AttachmentItem' import { FullscreenProvider } from '../../contexts' @@ -61,3 +61,28 @@ describe('AttachmentItem 上传态', () => { expect(screen.getByText('262 B')).toBeTruthy() }) }) + +describe('AttachmentItem skill 附件', () => { + it('展开后显示技能类型和技能 ID,而不是空的信息块', () => { + render( + + + , + ) + + fireEvent.click(screen.getByText('Commit')) + + expect(screen.getByText('Skill')).toBeTruthy() + expect(screen.getByText('commit')).toBeTruthy() + expect(screen.getByText('skill body')).toBeTruthy() + }) +}) diff --git a/src/features/attachment/AttachmentItem.tsx b/src/features/attachment/AttachmentItem.tsx index 5df623341..a78810132 100644 --- a/src/features/attachment/AttachmentItem.tsx +++ b/src/features/attachment/AttachmentItem.tsx @@ -222,7 +222,7 @@ function MetaRow({ function ExpandedContent({ attachment, imageError, onImageError, onOpenDetail }: ExpandedContentProps) { const { t } = useTranslation(['commands', 'common']) - const { type, url, content, relativePath, mime, agentName, agentDescription } = attachment + const { type, url, content, relativePath, mime, agentName, agentDescription, skillId } = attachment const isImage = mime?.startsWith('image/') const hasContent = !!content const hasDownloadable = hasContent || (!!isImage && !!url) @@ -286,7 +286,21 @@ function ExpandedContent({ attachment, imageError, onImageError, onOpenDetail }: /> - + + {type === 'skill' && } {attachment.originalSource && typeof attachment.originalSource === 'object' && ( <> diff --git a/src/locales/en/commands.json b/src/locales/en/commands.json index 39bbb1385..2a4c24d1e 100644 --- a/src/locales/en/commands.json +++ b/src/locales/en/commands.json @@ -125,6 +125,9 @@ "refPath": "Ref Path", "type": "Type", "directory": "Directory", + "skill": "Skill", + "skillId": "Skill ID", + "command": "Command", "symbol": "Symbol", "kind": "Kind", "range": "Range", diff --git a/src/locales/zh-CN/commands.json b/src/locales/zh-CN/commands.json index 9d391c8de..6280d2cc0 100644 --- a/src/locales/zh-CN/commands.json +++ b/src/locales/zh-CN/commands.json @@ -125,6 +125,9 @@ "refPath": "引用路径", "type": "类型", "directory": "目录", + "skill": "技能", + "skillId": "技能 ID", + "command": "命令", "symbol": "符号", "kind": "种类", "range": "范围", From 696177079967d86778c5e99b7aee8025ad1d89be Mon Sep 17 00:00:00 2001 From: lehhair Date: Fri, 23 Oct 2026 19:09:15 +0800 Subject: [PATCH 41/67] =?UTF-8?q?fix(input):=20Android=20WebView=20?= =?UTF-8?q?=E5=85=A8=E9=80=89=E5=88=A0=E9=99=A4=E5=90=8E=E9=87=8D=E5=BB=BA?= =?UTF-8?q?=20textarea=20=E8=8A=82=E7=82=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 搜狗全选删除会让原 textarea 的 WebView 编辑节点变成僵尸连接: DOM、焦点、系统 InputConnection 都还在,但 commitText 永远进不来, blur/focus/readOnly 都无法恢复,同页新建的 textarea 反而正常。 检测到全选删除清空后重建节点并接回焦点。 --- src/features/chat/InputBox.test.tsx | 26 ++++++++++++ src/features/chat/InputBox.tsx | 61 +++++++++++++++++++++++++++++ 2 files changed, 87 insertions(+) diff --git a/src/features/chat/InputBox.test.tsx b/src/features/chat/InputBox.test.tsx index c5a4d4361..0e067b159 100644 --- a/src/features/chat/InputBox.test.tsx +++ b/src/features/chat/InputBox.test.tsx @@ -108,6 +108,32 @@ describe('InputBox slash command selection', () => { promptHistoryStore.reset() }) + it('Android 全选删除后重建 textarea 节点', async () => { + const userAgent = vi + .spyOn(navigator, 'userAgent', 'get') + .mockReturnValue( + 'Mozilla/5.0 (Linux; Android 14; Pixel 8) AppleWebKit/537.36 Chrome/120.0.0.0 Mobile Safari/537.36', + ) + + render() + const textarea = screen.getByRole('textbox') as HTMLTextAreaElement + + textarea.focus() + fireEvent.input(textarea, { target: { value: 'hello' } }) + textarea.setSelectionRange(0, textarea.value.length) + document.dispatchEvent(new Event('selectionchange')) + + fireEvent.input(textarea, { target: { value: '' } }) + + await waitFor(() => { + const next = screen.getByRole('textbox') as HTMLTextAreaElement + expect(next).not.toBe(textarea) + expect(next.value).toBe('') + }) + + userAgent.mockRestore() + }) + it('executes frontend commands immediately on selection', async () => { slashCommands = [{ name: 'compact', description: 'Compact session', source: 'frontend' }] const onCommand = vi.fn() diff --git a/src/features/chat/InputBox.tsx b/src/features/chat/InputBox.tsx index fd9f9ef8f..278a107f9 100644 --- a/src/features/chat/InputBox.tsx +++ b/src/features/chat/InputBox.tsx @@ -90,6 +90,10 @@ const COMPOSER_MIN_HEIGHT = 144 const COMPOSER_DESKTOP_MAX_HEIGHT = 420 const COMPOSER_COMPACT_MAX_HEIGHT = 320 +function isAndroidWebView(): boolean { + return typeof navigator !== 'undefined' && /Android/i.test(navigator.userAgent) +} + function clamp(value: number, min: number, max: number) { return Math.min(Math.max(value, min), max) } @@ -508,6 +512,9 @@ function InputBoxComponent({ const footerRef = useRef(null) const isComposingRef = useRef(false) const compositionEndTimerRef = useRef(null) + const selectAllRef = useRef(false) + const imeRebuildRef = useRef(false) + const [imeResetKey, setImeResetKey] = useState(0) const [composerMaxHeight, setComposerMaxHeight] = useState(280) const [inputContainerMaxHeight, setInputContainerMaxHeight] = useState(240) const [textareaMaxHeight, setTextareaMaxHeight] = useState(180) @@ -694,6 +701,59 @@ function InputBoxComponent({ } }, [updateComposerHeightBudget]) + // Android WebView:搜狗全选删除会把 textarea 的编辑节点弄成僵尸连接 + // (DOM、焦点、系统 InputConnection 都还在,但 commitText 永远进不来; + // 同一页面里新建的 textarea 却正常)。文本被一次清空时直接重建节点。 + const rebuildImeNode = useCallback(() => { + if (imeRebuildRef.current) return + imeRebuildRef.current = true + setText('') + setImeResetKey(key => key + 1) + window.setTimeout(() => { + imeRebuildRef.current = false + }, 300) + }, []) + + useEffect(() => { + if (!isAndroidWebView()) return + const textarea = textareaRef.current + if (!textarea) return + + const rememberSelectAll = () => { + selectAllRef.current = + textarea.value.length > 0 && + textarea.selectionStart === 0 && + textarea.selectionEnd === textarea.value.length + } + const onSelectionChange = () => { + if (document.activeElement === textarea) rememberSelectAll() + } + const onInput = () => { + if (textarea.value !== '' || !selectAllRef.current) return + selectAllRef.current = false + rebuildImeNode() + } + + textarea.addEventListener('select', rememberSelectAll) + textarea.addEventListener('selectstart', rememberSelectAll) + textarea.addEventListener('input', onInput) + document.addEventListener('selectionchange', onSelectionChange) + return () => { + textarea.removeEventListener('select', rememberSelectAll) + textarea.removeEventListener('selectstart', rememberSelectAll) + textarea.removeEventListener('input', onInput) + document.removeEventListener('selectionchange', onSelectionChange) + } + }, [imeResetKey, rebuildImeNode]) + + useLayoutEffect(() => { + if (imeResetKey === 0) return + const textarea = textareaRef.current + if (!textarea) return + textarea.focus({ preventScroll: true }) + textarea.setSelectionRange(0, 0) + }, [imeResetKey]) + // 自动调整 textarea 高度 useLayoutEffect(() => { const textarea = textareaRef.current @@ -1991,6 +2051,7 @@ function InputBoxComponent({
)}