fix: 减少 changes.ops 空窗重复请求

This commit is contained in:
kelvinwww committed 2026-10-07 00:53:36 +08:00
1 parent 4e51e0789c
commit 96e5a2cb87
8 files changed
+183 -75

No files matched your search

+4 -4
View File
@@ -28,8 +28,9 @@
## 3. 设计(`src/client/ops-stream.ts` + `EditorHost.tsx`)
**每会话一条流、成员选举一个 leader。** 编辑器 tab(成员)加入会话的流,只有 leader 跑
`usePolling`(`mode: 'self-scheduling'`,2.5s,与文件变动页同一节奏;`use-polling.ts` 是侧栏唯一的轮询循环)。
所以「一个会话开 N 个编辑器 tab」每 tick 仍只有 **1 个** `changes.ops` 请求;成员全部离开即停。
`usePolling`(`mode: 'self-scheduling'`,两次响应之间间隔 2.5s;`use-polling.ts` 是侧栏唯一的轮询循环)。
首次请求立即取得基线;后续请求在空窗时等待宿主的 `session/event` 通知,最长 25s。收到 tool 事件即返回增量。
所以「一个会话开 N 个编辑器 tab」同时只有 **1 个** `changes.ops` 请求;成员全部离开即停。
**没有 `fs.watch`,没有任何周期性 `fsRead`。**
**只认结算成功的写入。** `kind ∈ {write, edit}` 且 `running === false && !isError` 才发布 ——
@@ -48,8 +49,7 @@
1. **不做「每 tick 至多 1 次请求」的跨页合并**:文件变动页的会话透镜保留**自己的**轮询器(它的启停条件是
「tab 可见 **且** 会话透镜在屏」,与编辑器的「页签在屏」是两条不同的可见性)。因此一个会话同时开着
文件变动页(会话透镜)与编辑器时,该会话每 tick 最多有 2 个 `changes.ops` 请求(原来就有 1 个)。
**实测(一次性探针,同一会话同一 cwd):会话透镜单独 1/tick、编辑器单独 1/tick、两者同开 2/tick。**
文件变动页(会话透镜)与编辑器时,该会话最多同时有 2 个 `changes.ops` 请求;空窗时各自等待通知或 25s 期限。
把两者合并到同一条流会改动一个已被 591 行 spec 钉住的既有特性(含「只在会话透镜在屏时轮询」这条断言),
超出本 issue 的范围。**已如实记录为后续可选项。**
2. **不给 dirty 态加「有新版本」提示**:改为静默跳过。理由是加提示需要新词典 key(20 份),而
+72
View File
@@ -0,0 +1,72 @@
import type { Context, SidebarSessionEvent } from './context-types.ts'
import { readPersistedSession } from './session-store.ts'
import { requireString, SidebarError } from './wire.ts'
const EVENTS_CAP = 4000
const WAIT_MS = 25_000
/** 返回会话文件工具事件,并让后续请求等待新的工具事件。 */
export function createChangesOpsApi(ctx: Context): (payload: unknown, signal?: AbortSignal) => Promise<{ events: SidebarSessionEvent[]; lastSeq: number }> {
return async (payload, signal) => {
const sessionId = requireString(payload, 'sessionId')
const record = payload as { afterSeq?: unknown; wait?: unknown }
const rawAfter = record.afterSeq
if (rawAfter !== undefined && (typeof rawAfter !== 'number' || !Number.isSafeInteger(rawAfter) || rawAfter < -1)) {
throw new SidebarError('bad-request', 'afterSeq must be an integer of at least -1')
}
if (record.wait !== undefined && typeof record.wait !== 'boolean') {
throw new SidebarError('bad-request', 'wait must be a boolean')
}
const afterSeq = rawAfter ?? -1
/** 读取运行中或已保存的会话日志,只保留游标之后的工具事件。 */
const readWindow = async (): Promise<{ events: SidebarSessionEvent[]; lastSeq: number }> => {
let events: readonly SidebarSessionEvent[] | undefined = ctx.sessions.get(sessionId)?.snapshotEvents()
if (events === undefined) {
const persistence = ctx.get('sessionPersistence')
if (persistence !== undefined) {
try {
events = (await readPersistedSession(persistence, sessionId)).events
} catch {
// 尚未保存会话日志时,事件窗口为空。
}
}
}
const filtered = (events ?? []).filter(event => (event.type === 'tool/call' || event.type === 'tool/result') && event.seq > afterSeq)
const window = filtered.length > EVENTS_CAP ? filtered.slice(-EVENTS_CAP) : filtered
return { events: window, lastSeq: window.at(-1)?.seq ?? afterSeq }
}
if (record.wait !== true) return readWindow()
const pending: SidebarSessionEvent[] = []
let wake: (() => void) | undefined
const notified = new Promise<void>(resolve => { wake = resolve })
// 读取前订阅,确保读取期间追加的事件仍会唤醒请求。
const dispose = ctx.on('session/event', (session, event) => {
if ((session as { id?: unknown } | null)?.id !== sessionId || (event.type !== 'tool/call' && event.type !== 'tool/result') || event.seq <= afterSeq) return
pending.push(event)
if (pending.length > EVENTS_CAP) pending.shift()
wake?.()
})
const timer = setTimeout(() => wake?.(), WAIT_MS)
const abort = (): void => { wake?.() }
signal?.addEventListener('abort', abort, { once: true })
try {
const initial = await readWindow()
if (initial.events.length > 0 || signal?.aborted === true) return initial
await notified
const current = await readWindow()
if (pending.length === 0) return current
// 事件通知可能早于快照更新;合并通知中的事件,及时返回工具结果。
const merged = new Map(current.events.map(event => [event.seq, event]))
for (const event of pending) merged.set(event.seq, event)
const events = [...merged.values()].sort((left, right) => left.seq - right.seq).slice(-EVENTS_CAP)
return { events, lastSeq: events.at(-1)?.seq ?? afterSeq }
} finally {
clearTimeout(timer)
signal?.removeEventListener('abort', abort)
dispose()
}
}
}
+4 -6
View File
@@ -464,13 +464,11 @@ export const api = {
* an empty list. Called on hover only — a file is never prefetched. */
gitBlame: (scope: SessionScope, path: string, startLine: number, endLine: number, worktree?: string, signal?: AbortSignal) =>
call<{ lines: GitBlameLine[] }>('git.blame', gitPayload(scope, worktree, { path, startLine, endLine }), signal),
/** The session's file-tool events for the changes tab's session lens: the
* `tool/call` + `tool/result` rows past `afterSeq` (0 = whole window),
* capped to the recent window host-side. The client runtime exposes no
* event-log face, so the lens polls this delta route. */
changesOps: (scope: SessionScope, afterSeq?: number, signal?: AbortSignal) =>
/** 读取文件工具事件增量;后续请求等待事件或等待期限结束。 */
changesOps: (scope: SessionScope, afterSeq?: number, signal?: AbortSignal, wait = false) =>
call<{ events: SidebarSessionEvent[]; lastSeq: number }>('changes.ops', scopePayload(scope, {
...(afterSeq !== undefined && afterSeq > 0 ? { afterSeq } : {}),
...(afterSeq !== undefined ? { afterSeq } : {}),
...(wait ? { wait: true } : {}),
}), signal),
/** Discard the worktree changes of one file (the index is untouched). */
gitDiscard: (scope: SessionScope, path: string, worktree?: string) =>
+10 -16
View File
@@ -75,18 +75,13 @@ export function ChangesTab({ ctx, store, scope, tab, visible, onOpenFile, onOpen
/** The header refresh action for the Git lens (the lens owns its own queue). */
const [gitRefresh, setGitRefresh] = useState(0)
// ── Session-event accumulation: one catch-up pull when the tab becomes
// visible, then a 2.5s delta poll while the SESSION lens is on screen.
// The cursor is the last delivered seq, so each poll ships only what the
// accumulator lacks. ───────────────────────────────────────────────────
// 页签显示时读取一次会话事件;会话视图在屏幕上时,两次响应之间间隔 2.5 秒。
// 游标记录已经收到的最后序号,空窗请求等待宿主事件。
const eventsRef = useRef<readonly SidebarSessionEvent[]>([])
// The fold of eventsRef as of the last poll. extractFileOps parses every
// accumulated tool/call (up to EVENTS_CAP events); running it once per
// poll and REUSING the result across renders (the render used to re-fold
// the whole window, twice per tick, and the fresh array defeated the
// downstream memo on every poll) keeps the 2.5s tick at one fold.
// `extractFileOps` 处理已经收到的工具事件,每次响应只处理一次并保留结果引用。
const opsRef = useRef<readonly FileOp[]>([])
const seqRef = useRef(0)
const seqRef = useRef(-1)
const primedRef = useRef(false)
const pollGen = useRef(0)
/** One delta request in flight at a time (the poller is fixed-interval, so a
* slow host would otherwise run two pulls over the same cursor and append
@@ -100,14 +95,12 @@ export function ChangesTab({ ctx, store, scope, tab, visible, onOpenFile, onOpen
if (pullingRef.current) return
pullingRef.current = true
try {
const { events, lastSeq } = await api.changesOps(scope, seqRef.current, signal)
const { events, lastSeq } = await api.changesOps(scope, primedRef.current ? seqRef.current : undefined, signal, primedRef.current)
// An aborted poll belongs to a torn-down run: its answer must never
// publish state (the transport may deliver it anyway).
if (generation !== pollGen.current || signal?.aborted === true) return
// Nothing new: KEEP the previous fold's identity. Re-folding an
// unchanged window produced a fresh array every 2.5s, which defeated
// every downstream memo — the session lens re-encoded each op body into
// a Blob to size it, on every idle tick.
primedRef.current = true
// 事件没有变化时保留结果引用,避免重新编码每条操作的正文。
if (events.length === 0 && lastSeq <= seqRef.current && opsRef.current.length > 0) {
setOpsError(false)
return
@@ -137,7 +130,8 @@ export function ChangesTab({ ctx, store, scope, tab, visible, onOpenFile, onOpen
pollGen.current += 1
eventsRef.current = []
opsRef.current = []
seqRef.current = 0
seqRef.current = -1
primedRef.current = false
setOpsError(false)
}, [scope.sessionId])
// One catch-up whenever the tab becomes visible (the badge count follows the
+7 -11
View File
@@ -16,14 +16,10 @@
* (editor tabs) elect ONE leader per session; that leader owns the single
* `usePolling` loop and every member reads the same published state. Any
* member leaving re-elects, and the loop stops when the last one goes.
* - **The plugin's own `changes.ops` delta stream, on ONE poller per session.**
* No `fs.watch`, no `fsRead` fingerprint polling, and no per-tab interval —
* a per-tab poll would multiply the same request by the number of mounted
* editors. Requests ride `use-polling.ts` (the sidebar's one polling loop)
* on the changes tab's own 2.5s cadence, and stop entirely while no editor
* of the session is on screen. The plugin's OWN saves go through
* `/sidebar/file` and leave no session event, so a reload can never
* re-trigger itself.
* - 每个会话通过 `changes.ops` 保持一条工具事件流,由 `use-polling.ts` 调度。
* 两次响应之间间隔 2.5 秒;空窗请求等待宿主事件,最长 25 秒。
* 当前会话没有可见编辑器时停止请求。插件自行保存文件时使用 `/sidebar/file`,
* 不产生会话工具事件,因此不会引发重复刷新。
* - **Settled successes only.** A `write`/`edit` call fires once its result
* landed without an error, so a half-written file never reaches a preview
* and a failed call never triggers a pointless reload.
@@ -129,7 +125,7 @@ interface Stream {
listeners: Set<() => void>
members: Set<Member>
leader: Member | undefined
/** The delivered cursor (`0` = no cursor yet, so the next pull is the baseline). */
/** The delivered cursor (`-1` includes an eventual first event at seq 0). */
seq: number
/** Whether the baseline pull completed (only then may a delta publish). */
primed: boolean
@@ -152,7 +148,7 @@ function streamOf(sessionId: string): Stream {
listeners: new Set(),
members: new Set(),
leader: undefined,
seq: 0,
seq: -1,
primed: false,
events: [],
published: new Set(),
@@ -212,7 +208,7 @@ function fold(stream: Stream, events: readonly SidebarSessionEvent[], baseline:
/** One leader's delta pull: advance the cursor, then fold (or baseline) it. */
async function pullStream(stream: Stream, scope: SessionScope, signal: AbortSignal): Promise<void> {
const { events, lastSeq } = await api.changesOps(scope, stream.seq, signal)
const { events, lastSeq } = await api.changesOps(scope, stream.primed ? stream.seq : undefined, signal, stream.primed)
// A torn-down run's answer must never publish state: the transport may
// deliver an aborted response anyway.
if (signal.aborted === true) return
+16 -38
View File
@@ -15,11 +15,11 @@
import { randomUUID } from 'node:crypto'
import { mkdir, open, readFile, rename, rm, stat, writeFile } from 'node:fs/promises'
import { basename, dirname, extname, isAbsolute, join, sep } from 'node:path'
import type { IncomingMessage } from 'node:http'
import type { IncomingMessage, ServerResponse } from 'node:http'
import type { Duplex } from 'node:stream'
import { WebSocket, WebSocketServer } from 'ws'
import { parse as parseYaml } from 'yaml'
import type { Context, SidebarHttpRequest, SidebarSessionEvent, SidebarSettingsService } from './context-types.ts'
import type { Context, SidebarHttpRequest, SidebarSettingsService } from './context-types.ts'
import {
Config,
resolveSidebarConfig,
@@ -52,6 +52,7 @@ import { buildSidechatApi } from './sidechat-routes.ts'
import { createAssistantLiveBuffer, type AssistantLiveBuffer } from './assistant-live.ts'
import { readJsonBody, requireString, SidebarError, writeError, writeJson, writeOk } from './wire.ts'
import { readPersistedSession } from './session-store.ts'
import { createChangesOpsApi } from './changes-ops.ts'
import { BlockAssembler, createUserMessage, type GenerateOptions, type StreamChunk } from '@deepseek-ai/dsh-llm'
import {
buildCommitPrompt,
@@ -444,7 +445,7 @@ async function readText(path: string, readLimit: number): Promise<{
}
/** One API method dispatch table entry. */
type ApiMethod = (payload: unknown) => Promise<unknown> | unknown
type ApiMethod = (payload: unknown, signal?: AbortSignal) => Promise<unknown> | unknown
/**
* The live face of the side card settings namespace, bound to the settings
@@ -498,6 +499,7 @@ function buildApi(
// `subagents.history` calls. The route degrades to a 503 when the host
// subagent runtime is absent (the page has no topology to show anyway).
const subagentLiveApi: SidebarSubagentLiveRoutes = buildSubagentLiveApi(ctx)
const changesOps = createChangesOpsApi(ctx)
// Workflow runs: no service registry exists in DSH (runs are
// holder-owned), so the route folds the `tool-workflow/*` session events
// the tool's recorder appends — the same four types the official panel
@@ -911,39 +913,8 @@ function buildApi(
// access, so the events cross the wire here — live session log first,
// the persisted logical log for not-yet-hydrated sessions. Only the
// two event types the lens folds are sent, narrowed to `seq > afterSeq`
// so polling is a small delta, with the same recent-window cap the
// client accumulator applies.
'changes.ops': async (payload) => {
const sessionId = requireString(payload, 'sessionId')
const rawAfter = (payload as { afterSeq?: unknown } | null)?.afterSeq
if (rawAfter !== undefined
&& (typeof rawAfter !== 'number' || !Number.isSafeInteger(rawAfter) || rawAfter < 0)) {
throw new SidebarError('bad-request', 'afterSeq must be a non-negative integer')
}
// An absent cursor means "from the very first event" — a session whose
// log opens on a tool event (subagent seeds do) carries seq 0, which a
// literal `> 0` comparison would drop, so the absent case floors at -1.
const afterSeq = rawAfter ?? -1
let events: readonly SidebarSessionEvent[] | undefined = ctx.sessions.get(sessionId)?.snapshotEvents()
if (events === undefined) {
const persistence = ctx.get('sessionPersistence')
if (persistence !== undefined) {
try {
events = (await readPersistedSession(persistence, sessionId)).events
} catch {
// Cold read unavailable (session never persisted): an empty
// window is the honest answer, not a wire error.
}
}
}
if (events === undefined) return { events: [], lastSeq: Math.max(afterSeq, 0) }
const CHANGES_EVENTS_CAP = 4000
const filtered = events.filter(
event => (event.type === 'tool/call' || event.type === 'tool/result') && event.seq > afterSeq,
)
const window = filtered.length > CHANGES_EVENTS_CAP ? filtered.slice(filtered.length - CHANGES_EVENTS_CAP) : filtered
return { events: window, lastSeq: window.at(-1)?.seq ?? afterSeq }
},
// 后续请求返回增量或等待新的工具事件,返回数量沿用客户端的窗口上限。
'changes.ops': changesOps,
// Subagent live previews: one batch request per refresh; the route folds
// the newest text/tool activity of every running child in the tree.
'subagents.live': (payload) => subagentLiveApi.live(payload),
@@ -1334,6 +1305,10 @@ export function apply(ctx: Context, config?: SidebarConfig): void {
writeError(res, new SidebarError('not-found', 'unknown sidebar API method', 404))
return
}
const controller = method === 'changes.ops' ? new AbortController() : undefined
const response = controller === undefined ? undefined : res as ServerResponse
const abort = (): void => { controller?.abort() }
response?.once('close', abort)
try {
const payload = await readJsonBody(req)
// Own properties only. The dispatch table is an object literal, so a
@@ -1345,9 +1320,12 @@ export function apply(ctx: Context, config?: SidebarConfig): void {
if (typeof handler !== 'function') {
throw new SidebarError('not-found', `unknown sidebar API method "${method}"`, 404)
}
writeOk(res, await handler(payload))
const result = await handler(payload, controller?.signal)
if (controller?.signal.aborted !== true) writeOk(res, result)
} catch (error) {
writeError(res, error)
if (controller?.signal.aborted !== true) writeError(res, error)
} finally {
response?.off('close', abort)
}
},
}), 'dsh-better-sidebar: /sidebar/api routes')
+58
View File
@@ -0,0 +1,58 @@
import { Context as CordisContext } from '@deepseek-ai/cordis'
import { SessionStore } from '@deepseek-ai/dsh-session'
import { ToolCallId } from '@deepseek-ai/dsh-llm'
import { describe, expect, it } from 'vitest'
import { createChangesOpsApi } from '../src/changes-ops.ts'
import type { Context } from '../src/context-types.ts'
describe('changes.ops 等待请求', () => {
it('空窗请求保持等待,并及时返回序号为 0 的真实会话事件', async () => {
const runtime = new CordisContext()
const fiber = await runtime.plugin(SessionStore)
const session = runtime.sessions.create()
const changesOps = createChangesOpsApi(runtime as Context)
try {
const baseline = await changesOps({ sessionId: session.id })
expect(baseline).toEqual({ events: [], lastSeq: -1 })
let settled = false
const waiting = changesOps({ sessionId: session.id, afterSeq: -1, wait: true }).then(result => {
settled = true
return result
})
await new Promise(resolve => setTimeout(resolve, 2_600))
expect(settled).toBe(false)
const appendedAt = Date.now()
session.append('tool/call', {
turn: 0,
step: 0,
callId: ToolCallId('first-call'),
name: 'write',
arguments: JSON.stringify({ file_path: 'hello.txt', content: 'hello' }),
})
const answer = await waiting
expect(Date.now() - appendedAt).toBeLessThan(1_000)
expect(answer.events.map(event => [event.seq, event.type])).toEqual([[0, 'tool/call']])
expect(answer.lastSeq).toBe(0)
expect(await changesOps({ sessionId: session.id, afterSeq: 0 })).toEqual({ events: [], lastSeq: 0 })
} finally {
await fiber.dispose()
}
})
it('客户端断开连接后结束空窗等待', async () => {
const runtime = new CordisContext()
const fiber = await runtime.plugin(SessionStore)
const session = runtime.sessions.create()
const changesOps = createChangesOpsApi(runtime as Context)
const controller = new AbortController()
try {
const waiting = changesOps({ sessionId: session.id, afterSeq: -1, wait: true }, controller.signal)
controller.abort()
expect(await waiting).toEqual({ events: [], lastSeq: -1 })
} finally {
await fiber.dispose()
}
})
})
+12
View File
@@ -335,7 +335,19 @@ test('plugin mounts into the DSH shell and survives a built-in tab sweep', async
if (await page.locator('[data-sidebar-right-guide]').count() === 0) await addTab.click()
const entry = page.locator(`[data-sidebar-right-guide-entry="${kind}"]`)
await expect(entry, `guide entry "${kind}" must be reachable`).toHaveCount(1, { timeout: 30_000 })
let changesRequests = 0
/** 统计空窗期间浏览器实际发出的会话事件请求。 */
const countChangesRequest = (request: { url(): string }): void => {
if (request.url().includes('/sidebar/api/changes.ops')) changesRequests += 1
}
if (kind === 'git') page.on('request', countChangesRequest)
await entry.click()
if (kind === 'git') {
await page.locator('[data-dsh-native-tab-host]:visible').getByRole('tab', { name: /^(Session|本轮文件)$/ }).click()
await page.waitForTimeout(8_000)
page.off('request', countChangesRequest)
expect(changesRequests, '空窗 8 秒内应有一次基线请求和一条等待中的增量请求').toBe(2)
}
await page.waitForTimeout(1_500)
await assertNoCrash()
}