merge pr-885 (#885 fix: 减少 changes.ops 空窗重复请求) into dev(@wang-kaopu)

冲突解决:保留 #885 的路由抽取(src/changes-ops.ts + 'changes.ops': changesOps),
把 dev 的现役内容搬进新模块:PTC 四种事件类型、-1 游标下限、会话/持久化双读与 4000 窗口;
index.ts 的 import 块取 dev(只补 ServerResponse),订阅回调按仓内惯例restate 最小结构切片。
测试:路由 spec 加一条 PTC 事件穿透断言,用例名与注释统一英文。
This commit is contained in:
Menghuan1918 committed 2026-10-16 16:44:20 +08:00
commit bd65b41e9d
8 files changed
+254 -67

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 份),而
+111
View File
@@ -0,0 +1,111 @@
/**
* The `changes.ops` route: the session's file-tool events, as a `seq > afterSeq`
* delta. Split out of `src/index.ts` because the wait form keeps a request open
* (see below) and that plumbing deserves its own module.
*
* A PRIMED client (one that already holds the baseline) asks with `wait: true`:
* the request parks until a matching tool event lands — or {@link WAIT_MS}
* expires — instead of re-reading an unchanged window every poll. The reply is
* still the same delta shape, so the client never needs a second code path.
*/
import type { Context, SidebarSessionEvent } from './context-types.ts'
import { readPersistedSession } from './session-store.ts'
import { requireString, SidebarError } from './wire.ts'
/** Recent-window bound: the lens shows the recent tail, not eternity. */
const EVENTS_CAP = 4000
/** How long one `wait: true` request parks before answering with the window. */
const WAIT_MS = 25_000
/** The event types the session lens folds — a plain tool pair, or a PTC one. */
function isFileToolEvent(event: SidebarSessionEvent): boolean {
return event.type === 'tool/call' || event.type === 'tool/result'
|| event.type === 'tool/ptc-dispatch-start' || event.type === 'tool/ptc-dispatch'
}
/**
* Build the `changes.ops` handler for one plugin context.
* @param ctx - host plugin context (sessions + sessionPersistence).
* @returns the route handler.
*/
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
// 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 floor is -1 and it is spelled out.
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
/** Read the live or persisted log, keeping only the delta past the cursor. */
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 {
// Cold read unavailable (session never persisted): an empty window
// is the honest answer, not a wire error.
}
}
}
const filtered = (events ?? []).filter(event => isFileToolEvent(event) && 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 })
// Subscribe BEFORE the read: an event appended while we read must still
// wake this request (otherwise the poll would answer with nothing new).
const dispose = ctx.on('session/event', (session, event) => {
// The vendored cordis `on` overload wins over the string-keyed one and
// types the event as the rich SessionEvent union; this route only needs
// the minimal structural slice, so restate it (same as the workflow and
// sidechat subscriptions do).
const minimal: SidebarSessionEvent = {
type: event.type,
seq: event.seq,
time: event.time,
data: event.data as Record<string, unknown>,
}
if ((session as { id?: unknown } | null)?.id !== sessionId
|| !isFileToolEvent(minimal) || minimal.seq <= afterSeq) return
pending.push(minimal)
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
// The notification can beat the snapshot refresh, so merge the events the
// subscription already saw rather than answering "nothing happened".
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()
}
}
}
+7 -6
View File
@@ -545,13 +545,14 @@ 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) =>
/** The session's file-tool events past `afterSeq` (absent = whole window,
* floored at -1 host-side so a log opening on seq 0 is not dropped). With
* `wait` the host parks the request until the next tool event (or 25 s)
* instead of re-reading an unchanged window. */
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) =>
+14 -12
View File
@@ -79,15 +79,16 @@ export function ChangesTab({ ctx, store, scope, tab, visible, onOpenFile, onOpen
// ── 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. ───────────────────────────────────────────────────
// accumulator lacks; once primed, the poll WAITS host-side for the next
// tool event (25s ceiling) instead of replaying an unchanged window. ────
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.
// accumulated tool call (up to EVENTS_CAP events); running it once per
// poll and REUSING the result across renders keeps the 2.5s tick at one
// fold, and an unchanged answer never hands downstream memos a new array.
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
@@ -101,14 +102,14 @@ 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
// Nothing new: KEEP the previous fold's identity. Re-folding an unchanged
// window produced a fresh array every tick, which defeated every
// downstream memo (the session lens re-encodes each op body to size it).
if (events.length === 0 && lastSeq <= seqRef.current && opsRef.current.length > 0) {
setOpsError(false)
return
@@ -138,7 +139,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
+8 -6
View File
@@ -23,9 +23,11 @@
* 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.
* of the session is on screen. A primed stream asks the host to WAIT for the
* next tool event (25s ceiling) instead of re-reading an unchanged window,
* so an idle session costs one parked request rather than a full replay. The
* plugin's OWN saves go through `/sidebar/file` and leave no session event,
* so a reload can never re-trigger itself.
* - **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.
@@ -147,7 +149,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
@@ -181,7 +183,7 @@ function streamOf(sessionId: string): Stream {
listeners: new Set(),
members: new Set(),
leader: undefined,
seq: 0,
seq: -1,
primed: false,
events: [],
published: new Set(),
@@ -247,7 +249,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
+18 -39
View File
@@ -15,11 +15,11 @@
import { open, readFile, stat } from 'node:fs/promises'
import { basename, extname, isAbsolute, join, sep } from 'node:path'
import type { Stats } from 'node:fs'
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,
@@ -53,6 +53,7 @@ import { createAssistantLiveBuffer, type AssistantLiveBuffer } from './assistant
import { readJsonBody, readTextBody, requireString, SidebarError, writeError, writeJson, writeOk } from './wire.ts'
import { streamFileToResponse } from './file-stream.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,
@@ -599,7 +600,7 @@ async function readPage(path: string, offset: number): Promise<ReadPageResult> {
}
/** 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
@@ -653,6 +654,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
@@ -1050,40 +1052,10 @@ function buildApi(
// the persisted logical log for not-yet-hydrated sessions. Only the event
// types the lens folds are sent (a plain `tool/call` + `tool/result` pair,
// or a PTC `tool/ptc-dispatch-start` / `tool/ptc-dispatch` pair), 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.type === 'tool/ptc-dispatch-start' || event.type === 'tool/ptc-dispatch') && 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 }
},
// to `seq > afterSeq` so polling is a small delta. A primed client asks the
// host to WAIT for the next tool event instead of re-reading an unchanged
// window (see `src/changes-ops.ts`).
'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),
@@ -1475,6 +1447,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
@@ -1486,9 +1462,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')
+80
View File
@@ -0,0 +1,80 @@
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 waiting form', () => {
it('parks an empty window and answers a real seq-0 event promptly', 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('ships the PTC sub-call pair, not just the plain tool pair', async () => {
const runtime = new CordisContext()
const fiber = await runtime.plugin(SessionStore)
const session = runtime.sessions.create()
const changesOps = createChangesOpsApi(runtime as Context)
try {
const at = () => ({ turn: 0, step: 0, rootCallId: ToolCallId('root'), parentCallId: ToolCallId('root'), subCallId: 'root:ptc:1', name: 'write' })
session.append('tool/ptc-dispatch-start', { ...at(), arguments: { file_path: 'notes.txt', content: 'x' } })
session.append('tool/ptc-dispatch', {
...at(),
arguments: { file_path: 'notes.txt', content: 'x' },
isError: false,
content: [{ type: 'text', text: 'written' }],
})
const answer = await changesOps({ sessionId: session.id })
expect(answer.events.map(event => event.type))
.toEqual(['tool/ptc-dispatch-start', 'tool/ptc-dispatch'])
} finally {
await fiber.dispose()
}
})
it('ends the empty-window wait when the client disconnects', 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
/** Count the session-event requests the browser actually issues while idle. */
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()
}