Skip to content

DeepSeek Harness Tauri 桌面版 | Only 8mb installer, zero environment setup, preset plugins, Windows / macOS / Linux.

fix(worktree): 节流状态复核,消除 /status 请求风暴

hairyffd509bf85d57
diff --git a/packages/dsh-tauri-worktree/README.md b/packages/dsh-tauri-worktree/README.md
index e0bc1f42..218fbdbc 100644
--- a/packages/dsh-tauri-worktree/README.md
+++ b/packages/dsh-tauri-worktree/README.md
@@ -87,6 +87,18 @@ checkout_worktree({ worktree_hash_dirname: '[hash]/[dirname]', branch_name: 'dsh
- 客户端乐观标记 `deleting` 并轮询直至收敛;归档会话的清理在请求失败/任务失败时清除
去重标记,等待下次快照重试。
+## 状态复核节流
+
+`GET /status` 由客户端 hydration 驱动,触发源是**会话事件流**与**会话列表快照**——二者在
+流式输出期间每秒可通知上百次。逐次复核会把只读状态查询放大成持续请求风暴,因此:
+
+- 每个会话的复核经 `SESSION_RECONCILE_MIN_INTERVAL_MS`(默认 1200ms)节流:窗口内首次
+ 请求立即执行(不引入启动延迟),窗口内后续请求合并为窗口末尾的一次拖尾执行(状态变化
+ 不丢失);空闲(无事件、无快照变化)时完全不发请求。
+- 只有「尚未解析成功」或「处于工作树模式」的会话参与复核:已解析的本地会话不再轮询。
+- 宿主侧 `/status` 对已绑定工作树的会话直接判定 `isGit: true`(工作树由 `git worktree add`
+ 创建,必然在 Git 仓库内),不再为每次复核 fork 一个 `git rev-parse` 子进程。
+
## 用户流程
1. 用户明确要求使用 worktree 后,Agent 调用 `create_worktree`。
diff --git a/packages/dsh-tauri-worktree/src/client/constants/index.ts b/packages/dsh-tauri-worktree/src/client/constants/index.ts
index a1383653..81d9bbf3 100644
--- a/packages/dsh-tauri-worktree/src/client/constants/index.ts
+++ b/packages/dsh-tauri-worktree/src/client/constants/index.ts
@@ -27,6 +27,15 @@ export const SESSION_SWITCH_MAX_ATTEMPTS = 30
/** hydration 失败/未知状态的重试间隔与上限(1.5s × 30 ≈ 45s,成功后立即停止)。 */
export const HYDRATION_RETRY_DELAY_MS = 1500
export const HYDRATION_MAX_RETRIES = 30
+/**
+ * 会话事件流/列表快照触发的状态复核最小间隔。
+ *
+ * 会话事件流在流式输出期间每秒可通知上百次,列表快照同样随事件更新;不节流时每个
+ * 通知都会打一次 `GET /status`(宿主还要为每次请求 fork 一个 git 子进程),把只读
+ * 状态查询放大成持续请求风暴。窗口内合并为一次拖尾执行:Agent 调用
+ * `checkout_worktree` / `discard_worktree` 后 UI 最迟在该间隔内收敛,不丢状态变化。
+ */
+export const SESSION_RECONCILE_MIN_INTERVAL_MS = 1200
/** Discard job polling cadence and retry limit. */
export const DISCARD_POLL_DELAY_MS = 500
export const DISCARD_MAX_POLLS = 120
diff --git a/packages/dsh-tauri-worktree/src/client/register/hydration.test.ts b/packages/dsh-tauri-worktree/src/client/register/hydration.test.ts
new file mode 100644
index 00000000..b2b58b96
--- /dev/null
+++ b/packages/dsh-tauri-worktree/src/client/register/hydration.test.ts
@@ -0,0 +1,246 @@
+/**
+ * hydration.test.ts — registerWorktreeHydration 的请求频率回归测试。
+ *
+ * 背景(issue 现象):会话事件流在流式输出期间每秒可通知上百次,列表快照同样随事件
+ * 持续变化;两者都触发 /status 复核,于是只读状态查询被放大成「每秒上百次请求」
+ * (宿主每次还要 fork 一个 git 子进程)。本用例把事件流/列表快照的触发频率全量拉满,
+ * 断言 /status 请求被节流到每窗口至多一次,同时保证拖尾执行不丢状态变化。
+ *
+ * 通过 vi.mock 替换 dsh-tauri/client:既避免在 node 环境加载客户端 barrel,又把
+ * fetch(HTTP 边界)与定时器收敛成可观察的替身。
+ */
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { SESSION_RECONCILE_MIN_INTERVAL_MS } from '../constants'
+import { registerWorktreeHydration } from './hydration'
+
+const mocks = vi.hoisted(() => ({ fetch: vi.fn() }))
+
+vi.mock('dsh-tauri/client', () => ({
+ fetch: mocks.fetch,
+ createStorage: () => ({ getItem: async () => null, setItem: async () => {} }),
+ localStorageDriver: () => ({}),
+ createExternalStore: <T>(initial: T) => {
+ let state = initial
+ const listeners = new Set<() => void>()
+ return {
+ getSnapshot: () => state,
+ subscribe: (listener: () => void) => {
+ listeners.add(listener)
+ return () => listeners.delete(listener)
+ },
+ set: (next: T | ((current: T) => T)) => {
+ state = typeof next === 'function' ? (next as (current: T) => T)(state) : next
+ for (const listener of [...listeners])
+ listener()
+ },
+ }
+ },
+ // 最小生命周期控制器替身:timeout 走真实 setTimeout(测试用 vi.useFakeTimers 驱动),
+ // dispose 清理全部定时器与 disposer,与 dsh-tauri 的语义一致。
+ createLifecycleController: () => {
+ let disposed = false
+ const disposers = new Set<() => void>()
+ const timers = new Set<ReturnType<typeof setTimeout>>()
+ return {
+ add: (disposer: () => void) => {
+ disposers.add(disposer)
+ },
+ timeout: (fn: () => void, ms: number) => {
+ if (disposed)
+ return () => {}
+ const timer = setTimeout(() => {
+ timers.delete(timer)
+ if (!disposed)
+ fn()
+ }, ms)
+ timers.add(timer)
+ return () => {
+ timers.delete(timer)
+ clearTimeout(timer)
+ }
+ },
+ interval: () => () => {},
+ listen: () => () => {},
+ observe: () => ({ disconnect: () => {} }),
+ isDisposed: () => disposed,
+ dispose: () => {
+ if (disposed)
+ return
+ disposed = true
+ for (const timer of timers)
+ clearTimeout(timer)
+ timers.clear()
+ for (const disposer of [...disposers])
+ disposer()
+ disposers.clear()
+ },
+ }
+ },
+}))
+
+/** 可订阅的最小快照源(对应 ctx.sessions.list / ctx.workspaces.list)。 */
+function snapshotSource<T>(initial: T) {
+ let state = initial
+ const listeners = new Set<() => void>()
+ return {
+ getSnapshot: () => state,
+ subscribe: (listener: () => void) => {
+ listeners.add(listener)
+ return () => listeners.delete(listener)
+ },
+ publish: (next: T) => {
+ state = next
+ for (const listener of [...listeners])
+ listener()
+ },
+ }
+}
+
+/** 只排空微任务队列(不推进假时钟),让首次 /status 的 patchSession 落到 store。 */
+async function flushMicrotasks(times = 10): Promise<void> {
+ for (let i = 0; i < times; i++)
+ await Promise.resolve()
+}
+
+interface Harness {
+ dispose: () => void
+ emitSessionEvent: () => void
+ publishList: () => void
+ statusCalls: () => number
+}
+
+/** 装配一个「单会话 + 可手动触发事件流/列表快照」的 hydration 环境。 */
+function harness(status: Record<string, unknown>): Harness {
+ const sessionId = 'session-1'
+ const sessionListeners = new Set<() => void>()
+ const list = snapshotSource({ ids: [sessionId], current: sessionId })
+ const workspaces = snapshotSource({ archivedSessionIds: [] as string[] })
+
+ mocks.fetch.mockImplementation(async (url: string) => {
+ if (url.includes('/status'))
+ return status
+ return { ok: true }
+ })
+
+ const ctx = {
+ sessions: {
+ list,
+ binding: (id: string) => id === sessionId
+ ? {
+ session: {
+ subscribe: (listener: () => void) => {
+ sessionListeners.add(listener)
+ return () => sessionListeners.delete(listener)
+ },
+ },
+ }
+ : undefined,
+ open: () => {},
+ refresh: async () => {},
+ },
+ workspaces: { list: workspaces },
+ }
+
+ const dispose = registerWorktreeHydration(ctx as never)
+ return {
+ dispose,
+ emitSessionEvent: () => {
+ for (const listener of [...sessionListeners])
+ listener()
+ },
+ publishList: () => list.publish({ ids: [sessionId], current: sessionId }),
+ statusCalls: () => mocks.fetch.mock.calls.filter(call => String(call[0]).includes('/status')).length,
+ }
+}
+
+describe('registerWorktreeHydration /status 请求频率', () => {
+ beforeEach(() => {
+ vi.useFakeTimers()
+ mocks.fetch.mockReset()
+ })
+
+ afterEach(() => {
+ vi.useRealTimers()
+ })
+
+ it('工作树会话:事件风暴合并为窗口末尾的一次复核', async () => {
+ const h = harness({ mode: 'worktree', worktreeKey: 'h/d', worktreePath: 'C:/wt', projectPath: 'C:/repo', log: [], isGit: true })
+ // 首次 hydrate 立即发一次(前沿语义:不引入启动延迟)。
+ expect(h.statusCalls()).toBe(1)
+ await flushMicrotasks()
+
+ // 模拟流式输出:一个窗口内 300 次会话事件 + 300 次列表快照。
+ for (let i = 0; i < 300; i++) {
+ h.emitSessionEvent()
+ h.publishList()
+ }
+ expect(h.statusCalls()).toBe(1)
+
+ await vi.advanceTimersByTimeAsync(SESSION_RECONCILE_MIN_INTERVAL_MS)
+ expect(h.statusCalls()).toBe(2)
+
+ // 空闲(无事件、无列表变化)时不再有任何请求。
+ await vi.advanceTimersByTimeAsync(SESSION_RECONCILE_MIN_INTERVAL_MS * 5)
+ expect(h.statusCalls()).toBe(2)
+ h.dispose()
+ })
+
+ it('工作树会话:持续 10 个窗口的高频触发只产生 1 次/窗口的请求', async () => {
+ const h = harness({ mode: 'worktree', worktreeKey: 'h/d', worktreePath: 'C:/wt', projectPath: 'C:/repo', log: [], isGit: true })
+ await flushMicrotasks()
+ for (let window = 0; window < 10; window++) {
+ for (let i = 0; i < 200; i++) {
+ h.emitSessionEvent()
+ h.publishList()
+ }
+ await vi.advanceTimersByTimeAsync(SESSION_RECONCILE_MIN_INTERVAL_MS)
+ }
+ // 1 次首次复核 + 每个窗口 1 次拖尾复核(此前是每个事件一次,约 2000 次)。
+ expect(h.statusCalls()).toBe(11)
+ h.dispose()
+ })
+
+ it('事件率提高 10 倍不改变请求数(节流与触发频率解耦)', async () => {
+ const h = harness({ mode: 'worktree', worktreeKey: 'h/d', worktreePath: 'C:/wt', projectPath: 'C:/repo', log: [], isGit: true })
+ await flushMicrotasks()
+ // 每个窗口 2000 次事件 + 2000 次列表快照(≈2000 次/秒,是上一用例的 10 倍)。
+ for (let window = 0; window < 10; window++) {
+ for (let i = 0; i < 2000; i++) {
+ h.emitSessionEvent()
+ h.publishList()
+ }
+ await vi.advanceTimersByTimeAsync(SESSION_RECONCILE_MIN_INTERVAL_MS)
+ }
+ // 与低频用例完全一致:请求数只由窗口数决定,与事件率无关。
+ expect(h.statusCalls()).toBe(11)
+ h.dispose()
+ })
+
+ it('本地会话:解析成功后事件/列表变化都不再触发请求', async () => {
+ const h = harness({ mode: 'local', projectPath: 'C:/repo', isGit: true })
+ expect(h.statusCalls()).toBe(1)
+ await flushMicrotasks()
+
+ for (let window = 0; window < 5; window++) {
+ for (let i = 0; i < 200; i++) {
+ h.emitSessionEvent()
+ h.publishList()
+ }
+ await vi.advanceTimersByTimeAsync(SESSION_RECONCILE_MIN_INTERVAL_MS)
+ }
+ expect(h.statusCalls()).toBe(1)
+ h.dispose()
+ })
+
+ it('dispose 取消待执行的拖尾复核', async () => {
+ const h = harness({ mode: 'worktree', worktreeKey: 'h/d', worktreePath: 'C:/wt', projectPath: 'C:/repo', log: [], isGit: true })
+ await flushMicrotasks()
+ h.emitSessionEvent()
+ // 拖尾任务已排定但尚未执行(请求数仍为首次的那一次)。
+ expect(vi.getTimerCount()).toBeGreaterThan(0)
+ expect(h.statusCalls()).toBe(1)
+ h.dispose()
+ await vi.advanceTimersByTimeAsync(SESSION_RECONCILE_MIN_INTERVAL_MS * 5)
+ expect(h.statusCalls()).toBe(1)
+ })
+})
diff --git a/packages/dsh-tauri-worktree/src/client/register/hydration.ts b/packages/dsh-tauri-worktree/src/client/register/hydration.ts
index 87db920e..dafae059 100644
--- a/packages/dsh-tauri-worktree/src/client/register/hydration.ts
+++ b/packages/dsh-tauri-worktree/src/client/register/hydration.ts
@@ -7,6 +7,11 @@
* 启动/新建会话存在竞态(客户端列表先于宿主会话就绪):/status 失败或返回未知
* (isGit: null)时按固定间隔重试,直到拿到确定答案,保证「刷新才有」的工作树 UI 自愈。
*
+ * 复核触发源有两个:会话事件流(流式输出期间每秒上百次通知)与会话列表快照。二者都经
+ * `SESSION_RECONCILE_MIN_INTERVAL_MS` 的 per-session 节流器合并,避免把只读 /status
+ * 放大成每秒上百次请求(宿主每次还要 fork 一个 git 子进程);窗口内最后一次请求由拖尾
+ * 执行兜底,状态变化不会丢失。
+ *
* create_worktree 自动交接只允许发生在「本次运行期间新出现」的工作树会话首次复核时,
* 且每个来源只交接一次、有时效窗口——历史遗留工作树、用户事后回到源会话、点击新建
* 会话等场景绝不抢焦点(否则「新建会话」会被误跳到工作树会话)。
@@ -14,10 +19,11 @@
import type { ClientContext } from 'dsh-tauri/client'
import type { SessionListSnapshot, WorkspaceListSnapshot, WorktreeHydrationSessionsRuntime } from '../types'
import { createLifecycleController } from 'dsh-tauri/client'
-import { DISCARD_MAX_POLLS, DISCARD_POLL_DELAY_MS, HANDOFF_WINDOW_MS, HYDRATION_MAX_RETRIES, HYDRATION_RETRY_DELAY_MS } from '../constants'
+import { DISCARD_MAX_POLLS, DISCARD_POLL_DELAY_MS, HANDOFF_WINDOW_MS, HYDRATION_MAX_RETRIES, HYDRATION_RETRY_DELAY_MS, SESSION_RECONCILE_MIN_INTERVAL_MS } from '../constants'
import { attachWorktreeSession, discardWorktree, fetchStatus } from '../service/actions'
import { openWorktreeSession } from '../service/handoff'
import { patchSession, selectSessionState, worktreeStore } from '../store'
+import { createKeyedThrottle } from '../utils/throttle'
export function registerWorktreeHydration(ctx: ClientContext): () => void {
// HARDCODE: SessionRuntime.binding() is an internal DSH 0.1.1-rc.2 API.
@@ -49,6 +55,12 @@ export function registerWorktreeHydration(ctx: ClientContext): () => void {
// 已绑定过 Session source 的会话(bindSessionEvents 去重)。
const subscribedSessions = new Set<string>()
const discardPolls = new Map<string, { jobId: string, attempts: number }>()
+ // 复核节流器:定时器登记进 controller,卸载时随 dispose 一并清理。
+ const reconcileThrottle = createKeyedThrottle({
+ intervalMs: SESSION_RECONCILE_MIN_INTERVAL_MS,
+ schedule: (fn, ms) => controller.timeout(fn, ms),
+ })
+ controller.add(() => reconcileThrottle.clear())
controller.add(() => {
retryAttempts.clear()
discardPolls.clear()
@@ -73,7 +85,8 @@ export function registerWorktreeHydration(ctx: ClientContext): () => void {
return
}
discardPolls.delete(sessionId)
- reconcileSession(sessionId, true)
+ // 删除任务刚结束:立即复核,不等节流窗口(一次性收敛,不参与高频路径)。
+ reconcileSession(sessionId)
})
.catch(() => scheduleDiscardPoll(sessionId, jobId, attempts + 1))
}, DISCARD_POLL_DELAY_MS)
@@ -122,21 +135,44 @@ export function registerWorktreeHydration(ctx: ClientContext): () => void {
controller.timeout(() => {
if (controller.isDisposed())
return
- reconcileSession(sessionId, true)
+ requestReconcile(sessionId)
}, HYDRATION_RETRY_DELAY_MS)
}
- function reconcileSession(sessionId: string, force = false): void {
+ /**
+ * 该会话是否需要向宿主复核状态:
+ * - 尚未解析成功(首次 hydrate,或失败/未知后从 seen 移除待重试);
+ * - 处于工作树模式:Agent 可能刚调用 checkout_worktree / discard_worktree,
+ * 需要在其事件流变化时对齐回本地状态。
+ * 其余会话(已解析的本地/待创建会话)不再发请求。
+ */
+ function needsReconcile(sessionId: string): boolean {
+ if (!seen.has(sessionId))
+ return true
+ return selectSessionState(worktreeStore.getSnapshot(), sessionId).mode === 'worktree'
+ }
+
+ /**
+ * 复核请求的唯一入口:事件流/列表快照/重试都经节流器合并,每个会话每个窗口至多
+ * 一次 /status;窗口内的最后一次请求由拖尾执行兜底。
+ * 执行前重新判定 needsReconcile:排队期间会话可能已解析为本地模式(例如 Agent 刚
+ * 完成 checkout 并由别的路径收敛),此时拖尾请求直接跳过,不再多发一次。
+ */
+ function requestReconcile(sessionId: string): void {
+ if (!needsReconcile(sessionId))
+ return
+ reconcileThrottle.request(sessionId, () => {
+ if (needsReconcile(sessionId))
+ reconcileSession(sessionId)
+ })
+ }
+
+ function reconcileSession(sessionId: string): void {
if (inFlight.has(sessionId)) {
- if (force)
- queued.add(sessionId)
+ queued.add(sessionId)
return
}
const previous = selectSessionState(worktreeStore.getSnapshot(), sessionId)
- // 普通 hydration 每个会话只做一次;已绑定会话则在其事件流变化时强制复核,
- // 以便 Agent 调用 checkout_worktree / discard_worktree 后无刷新切回本地状态。
- if (!force && seen.has(sessionId))
- return
seen.add(sessionId)
inFlight.add(sessionId)
void fetchStatus(sessionId)
@@ -253,14 +289,18 @@ export function registerWorktreeHydration(ctx: ClientContext): () => void {
})
.finally(() => {
inFlight.delete(sessionId)
+ // 请求在途期间又到达复核请求:立即补一次(不经节流器,避免丢掉在途期间的变更);
+ // 该路径被 inFlight 串行化,稳态下每个窗口至多补一次。
if (queued.delete(sessionId) && !controller.isDisposed())
- reconcileSession(sessionId, true)
+ reconcileSession(sessionId)
})
}
+ // 列表快照驱动的复核同样经节流器:快照在流式输出期间持续变化,逐次请求会放大成风暴;
+ // 首次 hydrate 仍由节流器的前沿立即执行保证(不引入启动延迟)。
const hydrate = (): void => {
const snapshot = sessionsRuntime.list.getSnapshot() as SessionListSnapshot
- for (const sessionId of snapshot.ids) reconcileSession(sessionId)
+ for (const sessionId of snapshot.ids) requestReconcile(sessionId)
}
const pollArchivedDiscard = (sessionId: string, jobId: string, attempts = 0): void => {
@@ -323,11 +363,9 @@ export function registerWorktreeHydration(ctx: ClientContext): () => void {
if (!session?.subscribe)
continue
subscribedSessions.add(sessionId)
- controller.add(session.subscribe(() => {
- const state = selectSessionState(worktreeStore.getSnapshot(), sessionId)
- if (state.mode === 'worktree')
- reconcileSession(sessionId, true)
- }))
+ // 会话事件流在流式输出期间每秒可通知上百次:复核必须经节流器合并,
+ // 否则每个事件都会打一次 /status(宿主还会 fork 一个 git 子进程)。
+ controller.add(session.subscribe(() => requestReconcile(sessionId)))
}
}
const unsubscribeSessions = sessionsRuntime.list.subscribe(() => {
diff --git a/packages/dsh-tauri-worktree/src/client/utils/throttle.test.ts b/packages/dsh-tauri-worktree/src/client/utils/throttle.test.ts
new file mode 100644
index 00000000..c33b34e8
--- /dev/null
+++ b/packages/dsh-tauri-worktree/src/client/utils/throttle.test.ts
@@ -0,0 +1,141 @@
+/**
+ * throttle.test.ts — createKeyedThrottle 单测。
+ *
+ * 注入假时钟与假调度器在 node 环境确定性地验证节流语义:前沿立即执行、窗口内合并为
+ * 一次拖尾执行、窗口结束后恢复立即执行、key 之间互不影响、cancel/clear 清理定时器。
+ */
+import { describe, expect, it } from 'vitest'
+import { createKeyedThrottle } from './throttle'
+
+/** 假时钟 + 假调度器:advance 推进时间并按到期顺序触发已排定的任务。 */
+function harness(intervalMs: number) {
+ let time = 0
+ let timers: { at: number, fn: () => void }[] = []
+ const throttle = createKeyedThrottle({
+ intervalMs,
+ now: () => time,
+ schedule: (fn, ms) => {
+ const timer = { at: time + ms, fn }
+ timers.push(timer)
+ return () => {
+ timers = timers.filter(item => item !== timer)
+ }
+ },
+ })
+ return {
+ throttle,
+ now: () => time,
+ pendingTimers: () => timers.length,
+ advance(ms: number): void {
+ time += ms
+ const due = timers.filter(timer => timer.at <= time).sort((a, b) => a.at - b.at)
+ for (const timer of due) {
+ timers = timers.filter(item => item !== timer)
+ timer.fn()
+ }
+ },
+ }
+}
+
+describe('createKeyedThrottle', () => {
+ it('首次请求立即执行', () => {
+ const h = harness(1000)
+ let runs = 0
+ h.throttle.request('s1', () => {
+ runs += 1
+ })
+ expect(runs).toBe(1)
+ expect(h.pendingTimers()).toBe(0)
+ })
+
+ it('窗口内的高频请求合并为窗口末尾的一次拖尾执行', () => {
+ const h = harness(1000)
+ let runs = 0
+ const run = (): void => {
+ runs += 1
+ }
+ h.throttle.request('s1', run)
+ // 模拟流式输出期间的上百次通知:全部落在同一节流窗口内。
+ for (let i = 0; i < 100; i++) {
+ h.advance(1)
+ h.throttle.request('s1', run)
+ }
+ expect(runs).toBe(1)
+ h.advance(1000)
+ expect(runs).toBe(2)
+ // 拖尾执行后窗口重新计时,不产生额外执行。
+ h.advance(1000)
+ expect(runs).toBe(2)
+ })
+
+ it('间隔已满时立即执行,不排定拖尾任务', () => {
+ const h = harness(1000)
+ let runs = 0
+ const run = (): void => {
+ runs += 1
+ }
+ h.throttle.request('s1', run)
+ h.advance(1000)
+ h.throttle.request('s1', run)
+ expect(runs).toBe(2)
+ expect(h.pendingTimers()).toBe(0)
+ })
+
+ it('持续高频请求下执行频率收敛到每窗口至多一次', () => {
+ const h = harness(1000)
+ let runs = 0
+ const run = (): void => {
+ runs += 1
+ }
+ // 10s 内每 10ms 请求一次(共 1000 次):1 次立即执行 + 每个窗口末尾 1 次拖尾
+ // (t=1000…10000 各一次)。
+ for (let i = 0; i < 1000; i++) {
+ h.throttle.request('s1', run)
+ h.advance(10)
+ }
+ expect(runs).toBe(11)
+ })
+
+ it('不同 key 各自独立计时', () => {
+ const h = harness(1000)
+ const runs: string[] = []
+ h.throttle.request('s1', () => runs.push('s1'))
+ h.throttle.request('s2', () => runs.push('s2'))
+ expect(runs).toEqual(['s1', 's2'])
+ })
+
+ it('cancel 取消待执行的拖尾任务并重置窗口', () => {
+ const h = harness(1000)
+ let runs = 0
+ const run = (): void => {
+ runs += 1
+ }
+ h.throttle.request('s1', run)
+ h.advance(200)
+ h.throttle.request('s1', run)
+ h.throttle.cancel('s1')
+ expect(h.pendingTimers()).toBe(0)
+ h.advance(5000)
+ expect(runs).toBe(1)
+ // 取消后视为全新 key:下一次请求立即执行。
+ h.throttle.request('s1', run)
+ expect(runs).toBe(2)
+ })
+
+ it('clear 清空全部 key 的待执行任务', () => {
+ const h = harness(1000)
+ let runs = 0
+ const run = (): void => {
+ runs += 1
+ }
+ h.throttle.request('s1', run)
+ h.throttle.request('s2', run)
+ h.throttle.request('s1', run)
+ h.throttle.request('s2', run)
+ expect(h.pendingTimers()).toBe(2)
+ h.throttle.clear()
+ expect(h.pendingTimers()).toBe(0)
+ h.advance(5000)
+ expect(runs).toBe(2)
+ })
+})
diff --git a/packages/dsh-tauri-worktree/src/client/utils/throttle.ts b/packages/dsh-tauri-worktree/src/client/utils/throttle.ts
new file mode 100644
index 00000000..ed52bd7b
--- /dev/null
+++ b/packages/dsh-tauri-worktree/src/client/utils/throttle.ts
@@ -0,0 +1,92 @@
+/**
+ * utils/throttle.ts — 按 key 的前沿 + 拖尾节流(无 React / 无 DOM / 不直接持有全局定时器)。
+ *
+ * 为什么需要:hydrate 的状态复核由「会话事件流」和「会话列表快照」双路触发,二者在
+ * 流式输出期间每秒可通知上百次。逐次复核会把只读的 GET /status 放大成持续请求风暴
+ * (宿主还会为每次请求 fork 一个 git 子进程)。本模块把同一 key 的执行频率压到
+ * 「每 intervalMs 至多一次」:窗口内的首个请求立即执行(前沿),窗口内的后续请求
+ * 合并为窗口末尾的一次拖尾执行(最后一次不丢失,也不需要退避重排定时器)。
+ *
+ * 时间源与调度器由调用方注入:生产走 createLifecycleController().timeout(卸载自动
+ * 清理),单测注入假时钟即可在 node 环境确定性地断言节流行为。
+ */
+
+export interface KeyedThrottleOptions {
+ /** 同一 key 两次执行之间的最小间隔(毫秒)。 */
+ intervalMs: number
+ /** 当前时间源(默认 Date.now;单测注入假时钟)。 */
+ now?: () => number
+ /** 延迟调度器,返回提前取消句柄(默认 setTimeout;生产注入 controller.timeout)。 */
+ schedule?: (fn: () => void, ms: number) => () => void
+}
+
+export interface KeyedThrottle {
+ /** 请求执行:首次立即执行,窗口内合并为一次拖尾执行。 */
+ request: (key: string, run: () => void) => void
+ /** 取消某 key 待执行的拖尾任务并清空其节流窗口。 */
+ cancel: (key: string) => void
+ /** 清空全部 key(插件卸载时调用)。 */
+ clear: () => void
+}
+
+interface KeyEntry {
+ lastRunAt: number
+ cancelTimer: () => void
+ pending: (() => void) | null
+}
+
+/** 创建按 key 的节流器。 */
+export function createKeyedThrottle(options: KeyedThrottleOptions): KeyedThrottle {
+ const intervalMs = Math.max(0, options.intervalMs)
+ const now = options.now ?? Date.now
+ const schedule = options.schedule ?? ((fn: () => void, ms: number) => {
+ const timer = setTimeout(fn, ms)
+ return () => clearTimeout(timer)
+ })
+ const entries = new Map<string, KeyEntry>()
+
+ return {
+ request(key, run) {
+ const entry = entries.get(key)
+ if (!entry) {
+ // 先登记再执行:run 同步重入同一 key 时进入节流分支,不会无限递归立即执行。
+ entries.set(key, { lastRunAt: now(), cancelTimer: () => {}, pending: null })
+ run()
+ return
+ }
+ // 已排定拖尾执行:只替换回调(同窗口合并为一次),不堆叠第二次执行。
+ if (entry.pending) {
+ entry.pending = run
+ return
+ }
+ const delay = intervalMs - (now() - entry.lastRunAt)
+ if (delay <= 0) {
+ entry.lastRunAt = now()
+ run()
+ return
+ }
+ entry.pending = run
+ entry.cancelTimer = schedule(() => {
+ const pending = entry.pending
+ entry.pending = null
+ entry.cancelTimer = () => {}
+ if (!pending)
+ return
+ entry.lastRunAt = now()
+ pending()
+ }, delay)
+ },
+ cancel(key) {
+ const entry = entries.get(key)
+ if (!entry)
+ return
+ entry.cancelTimer()
+ entries.delete(key)
+ },
+ clear() {
+ for (const entry of entries.values())
+ entry.cancelTimer()
+ entries.clear()
+ },
+ }
+}
diff --git a/packages/dsh-tauri-worktree/src/host/routes/index.ts b/packages/dsh-tauri-worktree/src/host/routes/index.ts
index 9cb6f8cf..bd83ec54 100644
--- a/packages/dsh-tauri-worktree/src/host/routes/index.ts
+++ b/packages/dsh-tauri-worktree/src/host/routes/index.ts
@@ -116,7 +116,9 @@ export function buildRoutes(ctx: HostContext, config: PluginConfig): any[] {
// 会话工作目录不在 git 仓库内时禁止工作树:isGit 供客户端隐藏模式选择器并强制本地模式。
// 会话未知(新建/启动竞态,尚无 cwd)时不猜测:isGit 置 null,客户端保持默认并稍后
// 重试,避免把 git 目录误判成非 git 而隐藏工作树模式选择器。
- const isGit = projectPath ? Boolean(await gitToplevel(projectPath)) : null
+ // 已绑定工作树的会话必然位于 Git 仓库内(工作树由 git worktree add 创建):直接置 true,
+ // 省掉每次 status 都 fork 一个 git 子进程——status 会被客户端 hydration 反复复核。
+ const isGit = activeBinding ? true : projectPath ? Boolean(await gitToplevel(projectPath)) : null
return [200, activeBinding
? {
mode: 'worktree',