DeepSeek Harness Tauri 桌面版 | Only 8mb installer, zero environment setup, preset plugins, Windows / macOS / Linux.
feat(turnrewind): 跨进程工作区互斥锁 + 屏障共享等待预算(新架构移植)
yingtianlan7c7250ef230e
diff --git a/packages/dsh-tauri-turnrewind/src/host/config/constants.ts b/packages/dsh-tauri-turnrewind/src/host/config/constants.tsindex 390f7053..56dbe48e 100644--- a/packages/dsh-tauri-turnrewind/src/host/config/constants.ts+++ b/packages/dsh-tauri-turnrewind/src/host/config/constants.ts@@ -12,6 +12,7 @@ import {TURNREWIND_REASON_SNAPSHOT_FAILED,TURNREWIND_REASON_TURN_ACTIVE,TURNREWIND_REASON_UNSAFE_PATH,+ TURNREWIND_REASON_WORKSPACE_BUSY,} from '../../shared/constants'/** 私有快照仓中快照 ref 的命名空间前缀。 */@@ -80,4 +81,30 @@ export const REASON_UNSAFE_PATH = TURNREWIND_REASON_UNSAFE_PATH/** 目标路径当前是非空目录:撤销不递归删除目录。 */export const REASON_NON_EMPTY_DIR = 'TURNREWIND_NON_EMPTY_DIR'+/** 工作区被另一个宿主进程占用(跨进程锁等待超时):撤销回 409,用户稍后重试。 */+export const REASON_WORKSPACE_BUSY = TURNREWIND_REASON_WORKSPACE_BUSY+/** 恢复路径丢失/损坏的 tmp 残骸后缀(崩溃清扫用;本插件不写这类文件,仅防御性识别)。 */++/** 旧版单文件锁协议的围栏/诊断目录(真正互斥由内核监听句柄持有,见 utils/lock.ts)。 */+export const LOCK_DIR_NAME = 'locks'++/**+ * 跨进程锁的等待上限:与 git 重活同预算。+ *+ * 拿到锁意味着「轮到我动这个工作区的私有仓」,而一次捕获/结算本身就是 git 重活+ * (大仓库首次要几十秒),所以等待时长必须覆盖对方**一整次操作**。等不到就给调用方+ * 一个明确的结论(撤销照实回 409,捕获照实记不可用)。没有任何 TTL 接管活锁的通道:+ * 持有者挂死时这里就是唯一的收口——如实报「占用」,宁可暂时不可用也不去抢一把活着的锁。+ */+export const LOCK_WAIT_TIMEOUT_MS = GIT_TIMEOUT_MS++/**+ * **屏障上**容量治理与 before 共用的等待截止预算,包含进程内 FIFO 和跨进程锁等待。+ * 已开始的任务不被预算截断;到期只取消尚未开始的任务,防止迟到的 before 在模型已经+ * 执行后补拍出错误基线(见 service/capture.ts 的 runBegin)。+ */+export const LOCK_BARRIER_TIMEOUT_MS = 20 * 1000++/** 锁竞争时的重试间隔:轮询粒度,太小会空转 I/O,太大则让短临界区白等。 */+export const LOCK_RETRY_INTERVAL_MS = 200diff --git a/packages/dsh-tauri-turnrewind/src/host/config/runtime.ts b/packages/dsh-tauri-turnrewind/src/host/config/runtime.tsindex 59e2a87e..f183e9b4 100644--- a/packages/dsh-tauri-turnrewind/src/host/config/runtime.ts+++ b/packages/dsh-tauri-turnrewind/src/host/config/runtime.ts@@ -7,13 +7,18 @@import type { ActiveTurn, BeginningTurn } from '../service/capture.types'import type { HostContext, WorkspaceProbe } from '../types'-import { defineHostRuntime } from 'dsh-tauri'+import { defineHostRuntime, DSH_HOME } from 'dsh-tauri'+import { createWorkspaceLock } from '../utils/lock'import { createWorkspaceQueue } from '../utils/queue'export const { setCurrentHostInstance, getCurrentHostInstance } = defineHostRuntime<HostContext>()-/** 工作区级串行队列:私有仓 index/refs 是共享可变状态,捕获、结算、实时读数、容量治理与撤销全部串行。 */-export const workspaceQueue = createWorkspaceQueue()+/**+ * 工作区级串行队列:私有仓 index/refs 是共享可变状态,捕获、结算、实时读数、容量治理+ * 与撤销全部串行。队列内再叠一层**跨进程内核锁**:同一个 `DSH_HOME` 下的第二个宿主进程+ * 也走同一把锁,两个进程才真正不会同动一份私有仓(见 utils/lock.ts)。+ */+export const workspaceQueue = createWorkspaceQueue({ lock: createWorkspaceLock({ dshHome: DSH_HOME }) })/** 工作区资格探测缓存(60s TTL,stale-while-revalidate)。 */export const probeCache = new Map<string, { at: number, result: WorkspaceProbe }>()diff --git a/packages/dsh-tauri-turnrewind/src/host/service/capture.test.ts b/packages/dsh-tauri-turnrewind/src/host/service/capture.test.tsindex fb01e241..2db3b131 100644--- a/packages/dsh-tauri-turnrewind/src/host/service/capture.test.ts+++ b/packages/dsh-tauri-turnrewind/src/host/service/capture.test.ts@@ -7,8 +7,10 @@ import { join } from 'pathe'import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'import { resetTestDshHome, testDshHome } from '../../../../.test/test-utils'import { PLUGIN_ID, TURNREWIND_REASON_SNAPSHOT_FAILED } from '../../shared/constants'+import { LOCK_BARRIER_TIMEOUT_MS } from '../config/constants'import { clearHostRuntime, resetHostRuntime, setCurrentHostInstance, workspaceQueue } from '../config/runtime'import { turnrewindHooks } from '../events'+import { WorkspaceLockTimeoutError } from '../utils/lock'import { capture } from './capture'import { ledger } from './ledger'@@ -396,3 +398,84 @@ describe('运行中提示条的读数生命周期', () => {expect(capture.live('s16')).toMatchObject({ active: true, turn: 1, fileCount: 1, insertions: 1, deletions: 0 })})})++describe('屏障等待预算(容量治理与 before 共用截止时间)', () => {+ /** 记录每次 queue.run 收到的等待参数;真实队列照常放行。 */+ function recordingQueue(): Array<{ lockTimeoutMs: number | undefined, waitDeadline: number | undefined }> {+ const real = workspaceQueue.run+ const recorded: Array<{ lockTimeoutMs: number | undefined, waitDeadline: number | undefined }> = []+ workspaceQueue.run = <T>(key: string, task: () => Promise<T>, lockTimeoutMs?: number, options?: { waitDeadline?: number }): Promise<T> => {+ recorded.push({ lockTimeoutMs, waitDeadline: options?.waitDeadline })+ return real(key, task, lockTimeoutMs, options)+ }+ return recorded+ }++ it('屏障上的两次排队共用同一截止时间,后台结算仍用默认预算', async () => {+ const { worktree } = await fixture()+ captureFor()+ const recorded = recordingQueue()++ await capture.begin('s-barrier', 1)+ // begin 返回时实时轮询刚起表,还没有别的排队:恰好是容量治理 + before 两次。+ expect(recorded).toHaveLength(2)+ expect(recorded[0]).toMatchObject({ lockTimeoutMs: LOCK_BARRIER_TIMEOUT_MS })+ expect(recorded[1]).toMatchObject({ lockTimeoutMs: LOCK_BARRIER_TIMEOUT_MS })+ // 同一个截止对象:第一阶段超时后第二阶段不会重新获得完整预算。+ expect(recorded[0]!.waitDeadline).toBe(recorded[1]!.waitDeadline)++ await writeFile(join(worktree, 'a.txt'), 'one\ntwo\nthree\n', 'utf8')+ await capture.settle('s-barrier', 1)+ // 结算在后台、不占屏障:不传任何预算(用锁的默认值),草率放弃会直接丢掉这一轮的卡片。+ expect(recorded.at(-1)).toMatchObject({ lockTimeoutMs: undefined, waitDeadline: undefined })+ })++ it('容量治理拿不到跨进程锁时直接放弃本轮,不再申请第二次 before', async () => {+ await fixture()+ captureFor()+ const real = workspaceQueue.run+ let calls = 0+ workspaceQueue.run = <T>(): Promise<T> => {+ calls += 1+ return Promise.reject(new WorkspaceLockTimeoutError('workspace lock not acquired (barrier)'))+ }+ try {+ await capture.begin('s-busy', 1)+ // 第一阶段超时后必须就此打住:再排一次 before 就等于重新申请完整预算,+ // 用户的 turn 开场就要多等一份 20 秒。+ expect(calls).toBe(1)+ const current = await ledger.load('s-busy')+ expect(current.turns.map(turn => turn.turn)).toEqual([1])+ expect(current.turns[0]?.unavailable).toBe(TURNREWIND_REASON_SNAPSHOT_FAILED)+ expect(current.turns[0]?.beforeRef).toBe('')+ }+ finally {+ workspaceQueue.run = real+ }+ })++ it('第二阶段拿不到锁同样只留不可用审计行,绝不迟到补拍 before', async () => {+ await fixture()+ captureFor()+ const real = workspaceQueue.run+ let calls = 0+ workspaceQueue.run = <T>(key: string, task: () => Promise<T>, lockTimeoutMs?: number, options?: { waitDeadline?: number }): Promise<T> => {+ calls += 1+ if (calls === 1)+ return real(key, task, lockTimeoutMs, options)+ return Promise.reject(new WorkspaceLockTimeoutError('workspace lock not acquired (before)'))+ }+ try {+ await capture.begin('s-expired', 1)+ expect(calls).toBe(2)+ // 没有基线就没有可撤销的承诺:条目不登记、结算无事可做,账本留一行审计。+ expect(capture.pending('s-expired', 1)).toBe(false)+ const current = await ledger.load('s-expired')+ expect(current.turns[0]?.unavailable).toBe(TURNREWIND_REASON_SNAPSHOT_FAILED)+ expect(current.turns[0]?.beforeRef).toBe('')+ }+ finally {+ workspaceQueue.run = real+ }+ })+})diff --git a/packages/dsh-tauri-turnrewind/src/host/service/capture.ts b/packages/dsh-tauri-turnrewind/src/host/service/capture.tsindex bd3bd1ba..a2edcf68 100644--- a/packages/dsh-tauri-turnrewind/src/host/service/capture.ts+++ b/packages/dsh-tauri-turnrewind/src/host/service/capture.ts@@ -13,7 +13,7 @@import type { LiveSnapshot, SnapshotStore, TurnFileChange, TurnRecord } from '../types'import type { ActiveTurn, BeginningTurn, CaptureLogger } from './capture.types'import { defineService } from 'dsh-tauri'-import { REASON_SNAPSHOT_FAILED, REASON_UNSAFE_WORKSPACE } from '../config/constants'+import { LOCK_BARRIER_TIMEOUT_MS, REASON_SNAPSHOT_FAILED, REASON_UNSAFE_WORKSPACE } from '../config/constants'import {activeTurns,beginningTurns,@@ -25,6 +25,7 @@ import {} from '../config/runtime'import { turnrewindHooks } from '../events'import { pruneLooseObjects } from '../utils/git'+import { WorkspaceLockTimeoutError } from '../utils/lock'import { retention } from './retention'import { snapshot } from './snapshot'import { turns } from './turns'@@ -288,17 +289,29 @@ async function runBegin(sessionId: string, turn: number): Promise<void> {return}const store = snapshot.resolve(probe.root, probe.commonDir)+ // 两个屏障阶段共用从首次入队开始的截止时间,覆盖进程内 FIFO 与跨进程锁等待:+ // 到期放弃尚未开始的任务;已开始的 git 必须完整等待,不能让迟到的 before 捕到模型改动。+ const waitOptions = { waitDeadline: Date.now() + LOCK_BARRIER_TIMEOUT_MS }// 工作区首次触碰:容量治理(prune 不可达对象 / 超限整仓重建 / 排除清单复检)。const exclusions = await workspaceQueue.run(probe.root, async () => {const outcome = await retention.ensure(store)if (outcome?.rebuilt)warn(`dsh-tauri-turnrewind: snapshot repository for ${probe.root} exceeded the size cap and was rebuilt; older turns are now expired`)return outcome?.exclusions ?? await retention.read(store)- }).catch(() => [] as string[])+ }, LOCK_BARRIER_TIMEOUT_MS, waitOptions).catch((error: unknown) => {+ // 锁/排队超时意味着本轮已放弃,不能吞掉后再申请一次完整预算重排 before。+ if (error instanceof WorkspaceLockTimeoutError)+ throw error+ return [] as string[]+ })const nestedDirs = snapshot.scan(probe.root)- const result = await workspaceQueue.run(probe.root, () =>- snapshot.capture(store, snapshot.ref(sessionId, turn, 'before'), `turn ${turn} before`, { exclude: exclusions, nestedDirs }))+ const result = await workspaceQueue.run(+ probe.root,+ () => snapshot.capture(store, snapshot.ref(sessionId, turn, 'before'), `turn ${turn} before`, { exclude: exclusions, nestedDirs }),+ LOCK_BARRIER_TIMEOUT_MS,+ waitOptions,+ )if (!result.ok) {warn(`dsh-tauri-turnrewind: before snapshot for session ${sessionId} turn ${turn} unavailable: ${result.reason}`)await turns.note(sessionId, { workspaceRoot: probe.root, isGit: true, unavailableReason: null }).catch(() => undefined)diff --git a/packages/dsh-tauri-turnrewind/src/host/service/undo.test.ts b/packages/dsh-tauri-turnrewind/src/host/service/undo.test.tsindex 408743bc..d1feaaa8 100644--- a/packages/dsh-tauri-turnrewind/src/host/service/undo.test.ts+++ b/packages/dsh-tauri-turnrewind/src/host/service/undo.test.ts@@ -8,8 +8,9 @@ import { join } from 'pathe'import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'import { resetTestDshHome, testDshHome } from '../../../../.test/test-utils'import { PLUGIN_ID } from '../../shared/constants'-import { REASON_ALREADY_UNDONE, REASON_CONFLICT, REASON_EXPIRED, REASON_GIT_REQUIRED, REASON_TURN_ACTIVE } from '../config/constants'-import { clearHostRuntime, resetHostRuntime, setCurrentHostInstance } from '../config/runtime'+import { REASON_ALREADY_UNDONE, REASON_CONFLICT, REASON_EXPIRED, REASON_GIT_REQUIRED, REASON_TURN_ACTIVE, REASON_WORKSPACE_BUSY } from '../config/constants'+import { clearHostRuntime, resetHostRuntime, setCurrentHostInstance, workspaceQueue } from '../config/runtime'+import { WorkspaceLockTimeoutError } from '../utils/lock'import { capture } from './capture'import { ledger } from './ledger'import { snapshot } from './snapshot'@@ -249,4 +250,28 @@ describe('undo.turn', () => {// 拒绝发生在动文件之前。expect(await readFile(join(worktree, 'a.txt'), 'utf8')).toBe('first\nsecond\n')})++ it('工作区被另一个宿主进程占用(跨进程锁超时):回 409 + WORKSPACE_BUSY,而不是 500', async () => {+ const { worktree, sessionId, turn } = await fixture()+ // 队列以锁超时拒绝,等价于「另一个 DSH 进程正占着这个工作区,等满了上限也没轮到我们」。+ const real = workspaceQueue.run+ workspaceQueue.run = <T>(): Promise<T> => Promise.reject(new WorkspaceLockTimeoutError('workspace lock not acquired'))+ try {+ const outcome = await undo.turn(sessionId, turn)+ expect(outcome.ok).toBe(false)+ if (!outcome.ok) {+ expect(outcome.code).toBe(409)+ expect(outcome.error).toBe(REASON_WORKSPACE_BUSY)+ }+ // 「现在不是时候」而不是「这一轮不能撤销」:工作区一个字节没动,也没有标成已撤销——+ // 用户稍后重试仍然有效。+ expect(await readFile(join(worktree, 'a.txt'), 'utf8')).toBe('first\nsecond\n')+ expect(existsSync(join(worktree, 'added.txt'))).toBe(true)+ const current = await ledger.load(sessionId)+ expect(current.turns.find(item => item.turn === turn)?.undoneAt ?? null).toBeNull()+ }+ finally {+ workspaceQueue.run = real+ }+ })})diff --git a/packages/dsh-tauri-turnrewind/src/host/service/undo.ts b/packages/dsh-tauri-turnrewind/src/host/service/undo.tsindex 3adb093b..f22b8800 100644--- a/packages/dsh-tauri-turnrewind/src/host/service/undo.ts+++ b/packages/dsh-tauri-turnrewind/src/host/service/undo.ts@@ -17,8 +17,10 @@ import {REASON_EXPIRED,REASON_GIT_REQUIRED,REASON_TURN_ACTIVE,+ REASON_WORKSPACE_BUSY,} from '../config/constants'import { workspaceQueue } from '../config/runtime'+import { WorkspaceLockTimeoutError } from '../utils/lock'import { workspaceKey } from '../utils/workspace'import { capture } from './capture'import { ledger } from './ledger'@@ -86,6 +88,13 @@ export const undo = defineService({const report = await snapshot.restore(store, beforeCommit, record.files)return { ok: true, restored: report.restored, removed: report.removed, failed: report.failed }+ }).catch((error: unknown): UndoOutcome => {+ // 拿不到跨进程锁:工作区正被**另一个宿主进程**占着(它正在同一工作区里捕获/结算/撤销)。+ // 这不是「这一轮不能撤销」,而是「现在不是时候」——如实回可重试的 409,+ // 而不是把它当成内部错误报 500(其余异常仍原样上抛)。+ if (error instanceof WorkspaceLockTimeoutError)+ return { ok: false, code: 409, error: REASON_WORKSPACE_BUSY }+ throw error})if (outcome.ok && outcome.failed.length === 0)diff --git a/packages/dsh-tauri-turnrewind/src/host/utils/fixtures/lock-worker.ts b/packages/dsh-tauri-turnrewind/src/host/utils/fixtures/lock-worker.tsnew file mode 100644index 00000000..ad7eaedf--- /dev/null+++ b/packages/dsh-tauri-turnrewind/src/host/utils/fixtures/lock-worker.ts@@ -0,0 +1,65 @@+/** Real Node/tsx worker: no mocks and no inherited Vitest module registry. */+import { open, unlink } from 'node:fs/promises'+import process from 'node:process'+import { createWorkspaceLock, workspaceLockPort } from '../lock'++const [dshHome, key, guardPath] = process.argv.slice(2)+if (!dshHome || !key || !process.send)+ throw new Error('lock-worker requires dshHome, key and an IPC channel')++const lock = createWorkspaceLock({ dshHome, timeoutMs: 10_000, retryMs: 2 })+let release: (() => void) | undefined+let activeRound: number | undefined++function send(message: object): void {+ process.send?.(message)+}++async function start(round: number, timeoutMs?: number): Promise<void> {+ if (activeRound !== undefined)+ throw new Error('start received while a round is active')+ activeRound = round+ const released = new Promise<void>((resolve) => {+ release = resolve+ })+ send({ type: 'started', round })+ try {+ await lock.run(key!, async () => {+ // Independent of the TCP protocol: wx detects even very short double entry.+ const guard = guardPath ? await open(guardPath, 'wx') : undefined+ try {+ await guard?.writeFile(`${process.pid}:${round}`)+ send({ type: 'entered', round, pid: process.pid })+ await released+ }+ finally {+ await guard?.close()+ if (guard)+ await unlink(guardPath!)+ }+ }, timeoutMs)+ activeRound = undefined+ release = undefined+ send({ type: 'finished', round })+ }+ catch (error) {+ activeRound = undefined+ release = undefined+ const caught = error as Error & { reason?: string, code?: string }+ send({ type: 'failed', round, name: caught.name, reason: caught.reason, code: caught.code, message: caught.message })+ }+}++process.on('message', (message: { type: string, round: number, timeoutMs?: number }) => {+ if (message.type === 'start') {+ void start(message.round, message.timeoutMs).catch((error: Error) => {+ send({ type: 'failed', round: message.round, message: error.stack })+ })+ }+ else if (message.type === 'release' && message.round === activeRound) {+ release?.()+ }+})+// A failed parent must not leave an orphan listening forever.+process.on('disconnect', () => process.exit(0))+send({ type: 'ready', pid: process.pid, port: workspaceLockPort(dshHome, key) })diff --git a/packages/dsh-tauri-turnrewind/src/host/utils/lock.test.ts b/packages/dsh-tauri-turnrewind/src/host/utils/lock.test.tsnew file mode 100644index 00000000..12b55a2b--- /dev/null+++ b/packages/dsh-tauri-turnrewind/src/host/utils/lock.test.ts@@ -0,0 +1,472 @@+/**+ * host/utils/lock.test.ts — 内核独占工作区锁的契约,含真实独立 Node 进程竞争。+ *+ * 三条不变量:**互斥**(任意时刻只有一个持有者,跨进程成立)、**自愈**(持有者被强杀后+ * 内核释放句柄,等待者能继续)、**不误放**(外部占用端口/旧文件锁一律 fail-closed,+ * 绝不换端口、绝不自动清理)。互斥用独立进程 + `wx` 独占守卫文件验证,单事件循环里的+ * 多个锁实例无法交错同步系统调用,覆盖不到真实的调度窗口。+ */+import type { ChildProcess } from 'node:child_process'+import type { WorkspaceLock } from './lock.types'+import { spawn } from 'node:child_process'+import { mkdir, mkdtemp, readdir, readFile, rm, stat, symlink, writeFile } from 'node:fs/promises'+import { createServer, Server } from 'node:net'+import { tmpdir } from 'node:os'+import process from 'node:process'+import { fileURLToPath } from 'node:url'+import { dirname, join } from 'pathe'+import { afterEach, describe, expect, it, vi } from 'vitest'+import { REASON_WORKSPACE_BUSY } from '../config/constants'+import { createWorkspaceLock, workspaceLockPort, WorkspaceLockTimeoutError } from './lock'++const temporaryDirectories: string[] = []+const repositoryRoot = fileURLToPath(new URL('../../../../../', import.meta.url))+const workerFile = fileURLToPath(new URL('./fixtures/lock-worker.ts', import.meta.url))+const tick = (ms: number): Promise<void> => new Promise(resolve => setTimeout(resolve, ms))++async function fixture(): Promise<string> {+ const root = await mkdtemp(join(tmpdir(), 'dsh-turnrewind-lock-'))+ temporaryDirectories.push(root)+ const dshHome = join(root, 'home')+ await mkdir(dshHome, { recursive: true })+ return dshHome+}++afterEach(async () => {+ while (temporaryDirectories.length > 0)+ await rm(temporaryDirectories.pop()!, { recursive: true, force: true })+})++function lockFor(dshHome: string, timeoutMs = 2000): WorkspaceLock {+ return createWorkspaceLock({ dshHome, timeoutMs, retryMs: 5 })+}++function gate(): { wait: Promise<void>, open: () => void } {+ let open: () => void = () => {}+ const wait = new Promise<void>((resolve) => {+ open = resolve+ })+ return { wait, open }+}++/** Always release and collect the holder, including on assertion failure. */+async function withHeld(lock: WorkspaceLock, key: string, test: () => Promise<void>): Promise<void> {+ const entered = gate()+ const release = gate()+ const holding = lock.run(key, async () => {+ entered.open()+ await release.wait+ })+ try {+ await Promise.race([entered.wait, holding])+ await test()+ }+ finally {+ release.open()+ await holding+ }+}++interface WorkerMessage {+ type: string+ round?: number+ pid?: number+ port?: number+ name?: string+ reason?: string+ code?: string+ message?: string+}++/** Buffered IPC avoids missing messages delivered before a test installs its waiter. */+class LockWorker {+ readonly child: ChildProcess+ readonly messages: WorkerMessage[] = []+ readonly closed: Promise<void>+ private readonly listeners = new Set<() => void>()+ private output = ''+ private ended = false+ private spawnError: Error | undefined++ constructor(dshHome: string, key: string, guardPath?: string) {+ this.child = spawn(process.execPath, ['--import', 'tsx', workerFile, dshHome, key, ...(guardPath ? [guardPath] : [])], {+ cwd: repositoryRoot,+ stdio: ['ignore', 'pipe', 'pipe', 'ipc'],+ windowsHide: true,+ })+ this.child.stdout!.on('data', (chunk) => {+ this.output += String(chunk)+ })+ this.child.stderr!.on('data', (chunk) => {+ this.output += String(chunk)+ })+ this.child.on('message', (message) => {+ this.messages.push(message as WorkerMessage)+ this.notify()+ })+ this.child.on('error', (error) => {+ this.spawnError = error+ this.notify()+ })+ this.closed = new Promise((resolve) => {+ this.child.once('close', () => {+ this.ended = true+ this.notify()+ resolve()+ })+ })+ }++ private notify(): void {+ for (const listener of [...this.listeners])+ listener()+ }++ wait(type: string, round?: number): Promise<WorkerMessage> {+ return new Promise((resolve, reject) => {+ let timer: ReturnType<typeof setTimeout>+ let check: () => void+ const finish = (error?: Error, message?: WorkerMessage): void => {+ clearTimeout(timer)+ this.listeners.delete(check)+ if (error)+ reject(error)+ else+ resolve(message!)+ }+ check = (): void => {+ const message = this.messages.find(item => item.type === type && item.round === round)+ const failure = this.messages.find(item => item.type === 'failed' && item.round === round)+ if (message)+ finish(undefined, message)+ else if (failure || this.spawnError || this.ended)+ finish(new Error(`worker ${this.child.pid}: ${JSON.stringify(failure ?? this.spawnError ?? 'exited')}\n${this.output}`))+ }+ timer = setTimeout(() => finish(new Error(`worker ${this.child.pid} waiting for ${type}/${round}\n${this.output}\n${JSON.stringify(this.messages)}`)), 15_000)+ this.listeners.add(check)+ check()+ })+ }++ send(type: 'start' | 'release', round: number, timeoutMs?: number): void {+ this.child.send({ type, round, timeoutMs })+ }++ async stop(): Promise<void> {+ if (!this.ended)+ this.child.kill('SIGKILL')+ await this.closed+ }+}++async function withWorkers(+ specs: { home: string, key: string, guard?: string }[],+ test: (workers: LockWorker[]) => Promise<void>,+): Promise<void> {+ const workers: LockWorker[] = []+ try {+ for (const spec of specs)+ workers.push(new LockWorker(spec.home, spec.key, spec.guard))+ await Promise.all(workers.map(worker => worker.wait('ready')))+ expect(new Set(workers.map(worker => worker.child.pid)).size).toBe(workers.length)+ expect(workers.every(worker => worker.child.pid !== process.pid)).toBe(true)+ await test(workers)+ }+ finally {+ // Do not remove temp directories until all children and their piped stdio close.+ await Promise.all(workers.map(worker => worker.stop()))+ }+}++describe('createWorkspaceLock — public contract', () => {+ it('same workspace serializes independent lock instances', async () => {+ const home = await fixture()+ const first = lockFor(home)+ const second = lockFor(home)+ let entered = false+ let waiting: Promise<void> | undefined+ try {+ await withHeld(first, 'C:/repo', async () => {+ waiting = second.run('C:/repo', async () => {+ entered = true+ })+ await tick(60)+ expect(entered).toBe(false)+ })+ await waiting+ expect(entered).toBe(true)+ }+ finally {+ await waiting+ }+ })++ it('different workspace keys can enter before the holder releases', async () => {+ const home = await fixture()+ const lock = lockFor(home)+ expect(workspaceLockPort(home, 'C:/repo-a')).not.toBe(workspaceLockPort(home, 'C:/repo-b'))+ await withHeld(lock, 'C:/repo-a', async () => {+ await expect(lock.run('C:/repo-b', async () => 'parallel')).resolves.toBe('parallel')+ })+ })++ it('timeout preserves WorkspaceLockTimeoutError and the busy reason', async () => {+ const home = await fixture()+ await withHeld(lockFor(home), 'C:/repo', async () => {+ let entered = false+ const failure = lockFor(home, 80).run('C:/repo', async () => {+ entered = true+ })+ await expect(failure).rejects.toBeInstanceOf(WorkspaceLockTimeoutError)+ await expect(failure).rejects.toMatchObject({ name: 'WorkspaceLockTimeoutError', reason: REASON_WORKSPACE_BUSY })+ expect(entered).toBe(false)+ })+ })++ it('per-call timeout overrides the default without changing subsequent calls', async () => {+ const home = await fixture()+ const late = lockFor(home, 5000)+ await withHeld(lockFor(home), 'C:/repo', async () => {+ const started = Date.now()+ await expect(late.run('C:/repo', async () => 'never', 80)).rejects.toBeInstanceOf(WorkspaceLockTimeoutError)+ expect(Date.now() - started).toBeLessThan(1500)+ })+ await expect(late.run('C:/repo', async () => 'ok')).resolves.toBe('ok')+ })++ it('throwing tasks release the kernel handle, but retain the empty fence directory', async () => {+ const home = await fixture()+ const lock = lockFor(home)+ const failure = new Error('capture failed')+ await expect(lock.run('C:/repo', async () => {+ throw failure+ })).rejects.toBe(failure)+ await expect(lockFor(home).run('C:/repo', async () => 'ok')).resolves.toBe('ok')+ expect((await stat(lock.lockPath('C:/repo'))).isDirectory()).toBe(true)+ expect(await readdir(lock.lockPath('C:/repo'))).toEqual([])+ })+})++describe('createWorkspaceLock — legacy fencing and diagnostics', () => {+ it.each([+ ['live pid', JSON.stringify({ pid: process.pid, token: 'live', acquiredAt: 1 })],+ ['dead pid', JSON.stringify({ pid: 2147483647, token: 'dead', acquiredAt: 1 })],+ ['empty file', ''],+ ['partial JSON', '{"pid": 4242, "token": "cut-of'],+ ])('%s is fail-closed and untouched until explicitly removed', async (_name, content) => {+ const home = await fixture()+ const lock = lockFor(home, 80)+ const path = lock.lockPath('C:/repo')+ await mkdir(dirname(path), { recursive: true })+ await writeFile(path, content)+ let entered = false+ await expect(lock.run('C:/repo', async () => {+ entered = true+ })).rejects.toBeInstanceOf(WorkspaceLockTimeoutError)+ expect(entered).toBe(false)+ expect((await stat(path)).isFile()).toBe(true)+ expect(await readFile(path, 'utf8')).toBe(content)+ expect(await readdir(dirname(path))).toEqual([path.split('/').at(-1)])++ // This is an explicit offline migration, never an automatic PID/token takeover.+ await rm(path)+ await expect(lockFor(home).run('C:/repo', async () => 'migrated')).resolves.toBe('migrated')+ expect((await stat(path)).isDirectory()).toBe(true)+ expect(await readdir(path)).toEqual([])+ })++ it('permanent empty lock directory and its parent can be rebuilt', async () => {+ const home = await fixture()+ const lock = lockFor(home)+ const path = lock.lockPath('C:/repo')+ await mkdir(path, { recursive: true })+ await expect(lock.run('C:/repo', async () => 'existing')).resolves.toBe('existing')+ expect(await readdir(path)).toEqual([])+ for (const removed of [path, dirname(path)]) {+ await rm(removed, { recursive: true })+ await expect(lock.run('C:/repo', async () => 'rebuilt')).resolves.toBe('rebuilt')+ expect((await stat(path)).isDirectory()).toBe(true)+ expect(await readdir(path)).toEqual([])+ }+ })++ it('lockPath stays under DSH_HOME, with stable normalized workspace identity', async () => {+ const home = await fixture()+ const lock = lockFor(home)+ const path = lock.lockPath('C:/repo')+ expect(dirname(path)).toBe(join(home, 'dsh-tauri-turnrewind', 'locks'))+ expect(path.endsWith('.lock')).toBe(true)+ expect(lock.lockPath('C:/repo')).toBe(path)+ expect(lock.lockPath('C:/other-repo')).not.toBe(path)+ expect(lock.lockPath('C:/Repo') === lock.lockPath('c:/repo')).toBe(process.platform === 'win32')+ })+})++describe('workspaceLockPort — fixed kernel identity', () => {+ it('is stable, path-normalized and includes DSH_HOME', async () => {+ const home = await fixture()+ const key = join(home, 'repo')+ const port = workspaceLockPort(home, key)+ expect(Number.isInteger(port)).toBe(true)+ expect(port).toBeGreaterThanOrEqual(20000)+ expect(port).toBeLessThan(60000)+ expect(workspaceLockPort(home, key)).toBe(port)+ expect(workspaceLockPort(`${home}/.`, `${key}/child/..`)).toBe(port)+ // Fixed identities: a collision is permitted in general, not expected for this pair.+ expect(workspaceLockPort('C:/dsh-home-a', 'C:/repo')).not.toBe(workspaceLockPort('C:/dsh-home-b', 'C:/repo'))+ if (process.platform === 'win32') {+ expect(workspaceLockPort(home.toUpperCase(), key.toUpperCase())).toBe(port)+ expect(workspaceLockPort(home.replaceAll('/', '\\'), key.replaceAll('/', '\\'))).toBe(port)+ }+ await withWorkers([{ home, key }, { home, key }], async (workers) => {+ for (const worker of workers)+ expect((await worker.wait('ready')).port).toBe(port)+ })+ })++ it('an unrelated external listener forces timeout, never a fallback port/file lock', async () => {+ const home = await fixture()+ const key = 'C:/repo'+ const listener = createServer(socket => socket.destroy())+ try {+ await new Promise<void>((resolve, reject) => {+ listener.once('error', reject)+ listener.listen({ host: '127.0.0.1', port: workspaceLockPort(home, key), exclusive: true }, resolve)+ })+ let entered = false+ await expect(lockFor(home, 100).run(key, async () => {+ entered = true+ })).rejects.toBeInstanceOf(WorkspaceLockTimeoutError)+ expect(entered).toBe(false)+ await withWorkers([{ home, key }], async ([worker]) => {+ worker!.send('start', 0, 100)+ const failure = await worker!.wait('failed', 0)+ expect(failure).toMatchObject({ name: 'WorkspaceLockTimeoutError', reason: REASON_WORKSPACE_BUSY })+ expect(worker!.messages.some(message => message.type === 'entered')).toBe(false)+ })+ }+ finally {+ if (listener.listening)+ await new Promise<void>((resolve, reject) => listener.close(error => error ? reject(error) : resolve()))+ }+ await expect(lockFor(home).run(key, async () => 'released')).resolves.toBe('released')+ })+})++describe('createWorkspaceLock — real process contention', () => {+ it('repeated multi-process races never double-enter an independent wx guard', async () => {+ const home = await fixture()+ const guard = join(home, 'critical-section.guard')+ await withWorkers(Array.from({ length: 4 }, () => ({ home, key: 'C:/repo', guard })), async (workers) => {+ for (let round = 0; round < 8; round += 1) {+ for (const worker of workers)+ worker.send('start', round)+ await Promise.all(workers.map(worker => worker.wait('started', round)))+ await Promise.all(workers.map(async (worker) => {+ await worker.wait('entered', round)+ expect(await readFile(guard, 'utf8')).toBe(`${worker.child.pid}:${round}`)+ await tick(10)+ worker.send('release', round)+ await worker.wait('finished', round)+ }))+ await expect(stat(guard)).rejects.toMatchObject({ code: 'ENOENT' })+ }+ expect(workers.flatMap(worker => worker.messages).filter(message => message.type === 'entered')).toHaveLength(32)+ expect(workers.flatMap(worker => worker.messages).filter(message => message.type === 'failed')).toEqual([])+ })+ })++ it('different keys enter in different processes while the first remains held', async () => {+ const home = await fixture()+ await withWorkers([{ home, key: 'C:/repo-a' }, { home, key: 'C:/repo-b' }], async ([first, second]) => {+ first!.send('start', 0)+ await first!.wait('entered', 0)+ second!.send('start', 0)+ await second!.wait('entered', 0)+ expect(first!.messages.some(message => message.type === 'finished')).toBe(false)+ for (const worker of [first!, second!]) {+ worker.send('release', 0)+ await worker.wait('finished', 0)+ }+ })+ })++ it('deleting diagnostics while a child holds the kernel lock cannot admit another process', async () => {+ const home = await fixture()+ const key = 'C:/repo'+ const guard = join(home, 'critical-section.guard')+ const lock = lockFor(home, 100)+ await withWorkers([{ home, key, guard }, { home, key, guard }], async ([holder, waiter]) => {+ holder!.send('start', 0)+ await holder!.wait('entered', 0)+ await rm(dirname(lock.lockPath(key)), { recursive: true })+ waiter!.send('start', 0, 100)+ expect(await waiter!.wait('failed', 0)).toMatchObject({ name: 'WorkspaceLockTimeoutError', reason: REASON_WORKSPACE_BUSY })+ await expect(lock.run(key, async () => 'never')).rejects.toBeInstanceOf(WorkspaceLockTimeoutError)+ expect(await readFile(guard, 'utf8')).toBe(`${holder!.child.pid}:0`)+ holder!.send('release', 0)+ await holder!.wait('finished', 0)+ waiter!.send('start', 1)+ await waiter!.wait('entered', 1)+ expect((await stat(lock.lockPath(key))).isDirectory()).toBe(true)+ waiter!.send('release', 1)+ await waiter!.wait('finished', 1)+ })+ })++ it('killing a holder with SIGKILL lets an already waiting child and then the parent acquire', async () => {+ const home = await fixture()+ const key = 'C:/repo'+ // No guard here: a killed process intentionally cannot unlink a filesystem guard.+ await withWorkers([{ home, key }, { home, key }], async ([holder, waiter]) => {+ holder!.send('start', 0)+ await holder!.wait('entered', 0)+ waiter!.send('start', 0)+ await waiter!.wait('started', 0)+ await tick(80)+ expect(waiter!.messages.some(message => message.type === 'entered')).toBe(false)+ await holder!.stop()+ await waiter!.wait('entered', 0)+ await expect(lockFor(home, 80).run(key, async () => 'never')).rejects.toBeInstanceOf(WorkspaceLockTimeoutError)+ waiter!.send('release', 0)+ await waiter!.wait('finished', 0)+ await expect(lockFor(home).run(key, async () => 'parent')).resolves.toBe('parent')+ expect((await stat(lockFor(home).lockPath(key))).isDirectory()).toBe(true)+ })+ })+})++describe('kernel lock lifecycle regressions', () => {+ it('canonicalizes a missing home through an alias before deriving its port', async () => {+ const root = await fixture()+ const real = join(root, 'real')+ const alias = join(root, 'alias')+ await mkdir(real)+ await symlink(real, alias, process.platform === 'win32' ? 'junction' : 'dir')+ const home = join(alias, 'new-home')+ await withHeld(lockFor(home), 'ws', async () => {+ await expect(lockFor(home, 60).run('ws', async () => 'never')).rejects.toBeInstanceOf(WorkspaceLockTimeoutError)+ await expect(lockFor(join(real, 'new-home'), 60).run('ws', async () => 'never')).rejects.toBeInstanceOf(WorkspaceLockTimeoutError)+ })+ })++ it('handles a listening server error without throwing from emit or releasing an active task', async () => {+ const home = await fixture()+ const failure = new Error('simulated accept failure')+ const listen = vi.spyOn(Server.prototype, 'listen')+ try {+ await expect(lockFor(home).run('ws', async () => {+ const server = listen.mock.instances[0]+ if (!(server instanceof Server))+ throw new Error('listener was not created')+ expect(() => server.emit('error', failure)).not.toThrow()+ await expect(lockFor(home, 60).run('ws', async () => 'never')).rejects.toBeInstanceOf(WorkspaceLockTimeoutError)+ return 'done'+ })).rejects.toBe(failure)+ await expect(lockFor(home).run('ws', async () => 'released')).resolves.toBe('released')+ }+ finally {+ listen.mockRestore()+ }+ })+})diff --git a/packages/dsh-tauri-turnrewind/src/host/utils/lock.ts b/packages/dsh-tauri-turnrewind/src/host/utils/lock.tsnew file mode 100644index 00000000..df94590f--- /dev/null+++ b/packages/dsh-tauri-turnrewind/src/host/utils/lock.ts@@ -0,0 +1,149 @@+/**+ * host/utils/lock.ts — 操作系统持有的工作区级跨进程互斥。+ *+ * 不通过「读旧锁 → rename/unlink」接管共享锁位:两次调用之间它可能已属于新持有者(这是+ * 旧文件锁协议被审查确认的互斥漏洞)。每个 (canonical DSH_HOME, workspace) 确定性映射到+ * 一个 IPv4 loopback TCP 端口,只有 `listen` 成功才能执行任务,整个任务完成后才 close。+ * 进程退出由内核释放句柄,不猜 PID、不抢活锁;`exclusive` 禁止 cluster 共享句柄,+ * 不启用 reusePort,也绝不尝试备用端口。+ *+ * 哈希碰撞或外部程序占用端口只会额外串行/报忙,不会同时放行。要求同机同网络命名空间;+ * 不支持多个容器/WSL 网络命名空间或多台机器共用同一份快照仓。宿主崩溃后的孤儿 Git+ * 不由本层监管:重启前须确认旧写者已退出,不能把句柄回收当成进程树终止。+ *+ * `locks/<hash>.lock/` 是永久空目录,仅阻止旧版单文件协议创建锁,不承载新协议的所有权。+ * 旧文件(含死 PID/空文件/半截 JSON)不自动删除;升级须停止所有旧宿主,残骸只能离线人工清除。+ */++import type { Server } from 'node:net'+import type { WorkspaceLock, WorkspaceLockOptions } from './lock.types'+import { createHash } from 'node:crypto'+import { mkdir, realpath } from 'node:fs/promises'+import { createServer } from 'node:net'+import { join } from 'pathe'+import {+ LOCK_DIR_NAME,+ LOCK_RETRY_INTERVAL_MS,+ LOCK_WAIT_TIMEOUT_MS,+ REASON_WORKSPACE_BUSY,+ SNAPSHOT_FEATURE_DIR,+} from '../config/constants'+import { workspaceHash, workspaceKey } from './workspace'++/** 等待超时:撤销据此回 409;屏障据此取消尚未开始的快照。 */+export class WorkspaceLockTimeoutError extends Error {+ /** 线协议原因码(客户端据此给文案)。 */+ readonly reason = REASON_WORKSPACE_BUSY++ constructor(message: string) {+ super(message)+ this.name = 'WorkspaceLockTimeoutError'+ }+}++/** 固定映射是协议的一部分:碰撞只能等待,不能换端口(换了就不再互斥)。 */+export function workspaceLockPort(dshHome: string, key: string): number {+ const identity = JSON.stringify([workspaceKey(dshHome), workspaceKey(key)])+ const hash = createHash('sha256').update(identity).digest().readUInt32BE(0)+ return 20000 + hash % 40000+}++/** 监听成功后的异步错误延迟到 task 完成后处理,不能提前释放正在工作的句柄。 */+const listenerErrors = new WeakMap<Server, Error>()++/** 一次内核原子竞争。监听连接立刻销毁,避免 close 等待外部连接而无法释放。 */+async function tryListen(port: number): Promise<Server | null> {+ const server = createServer((socket) => {+ socket.on('error', () => {})+ socket.destroy()+ })+ return new Promise<Server | null>((resolve, reject) => {+ const onError = (error: NodeJS.ErrnoException): void => {+ if (error.code === 'EADDRINUSE')+ resolve(null)+ else+ reject(error)+ }+ server.once('error', onError)+ server.listen({ host: '127.0.0.1', port, exclusive: true }, () => {+ server.removeListener('error', onError)+ server.on('error', (error) => {+ listenerErrors.set(server, error)+ })+ resolve(server)+ })+ })+}++async function closeServer(server: Server): Promise<void> {+ await new Promise<void>((resolve, reject) => {+ server.close(error => error ? reject(error) : resolve())+ })+}++async function delay(ms: number): Promise<void> {+ await new Promise<void>((resolve) => {+ setTimeout(resolve, ms)+ })+}++/** 同一进程的多个实例也各自竞争内核句柄,不共享所有权。 */+export function createWorkspaceLock(options: WorkspaceLockOptions): WorkspaceLock {+ const timeoutMs = options.timeoutMs ?? LOCK_WAIT_TIMEOUT_MS+ const retryMs = options.retryMs ?? LOCK_RETRY_INTERVAL_MS+ const lockPath = (key: string): string =>+ join(options.dshHome, SNAPSHOT_FEATURE_DIR, LOCK_DIR_NAME, `${workspaceHash(key)}.lock`)++ async function acquire(key: string, waitMs: number): Promise<Server> {+ const deadline = Date.now() + Math.max(0, waitMs)+ // 必须先创建并严格解析数据目录:不存在的 symlink 子路径会从词法路径变成真实路径,+ // 若先散列再 mkdir,同一个 options 字符串在首次获取前后也会映射到两个端口。+ await mkdir(options.dshHome, { recursive: true })+ const canonicalHome = await realpath(options.dshHome)+ const port = workspaceLockPort(canonicalHome, key)+ const timeout = (): WorkspaceLockTimeoutError =>+ new WorkspaceLockTimeoutError(`workspace lock not acquired after ${waitMs}ms (key=${key}, port=${port})`)+ for (;;) {+ if (Date.now() >= deadline)+ throw timeout()+ const server = await tryListen(port)+ if (server !== null) {+ try {+ // 不覆盖旧版文件锁。旧宿主释放文件后可建目录;死文件需离线人工迁移。+ await mkdir(lockPath(key), { recursive: true })+ if (Date.now() >= deadline)+ throw timeout()+ return server+ }+ catch (error) {+ await closeServer(server)+ const code = (error as NodeJS.ErrnoException)?.code+ if (code !== 'EEXIST' && code !== 'ENOTDIR')+ throw error+ }+ }+ const remaining = deadline - Date.now()+ if (remaining <= 0)+ throw timeout()+ await delay(Math.min(Math.max(1, retryMs), remaining))+ }+ }++ return {+ async run<T>(key: string, task: () => Promise<T>, lockTimeoutMs?: number): Promise<T> {+ const server = await acquire(key, lockTimeoutMs ?? timeoutMs)+ try {+ const result = await task()+ const error = listenerErrors.get(server)+ if (error !== undefined)+ throw error+ return result+ }+ finally {+ // 只关闭自己的内核句柄,没有会误删新持有者锁位的读改写窗口。+ await closeServer(server)+ }+ },+ lockPath,+ }+}diff --git a/packages/dsh-tauri-turnrewind/src/host/utils/lock.types.ts b/packages/dsh-tauri-turnrewind/src/host/utils/lock.types.tsnew file mode 100644index 00000000..58e69d31--- /dev/null+++ b/packages/dsh-tauri-turnrewind/src/host/utils/lock.types.ts@@ -0,0 +1,34 @@+/**+ * host/utils/lock.types.ts — 跨进程工作区锁的类型面(实现见 ./lock.ts)。+ *+ * 与进程内的 {@link WorkspaceQueue} 是两件事:队列只能串行化**本进程**里的任务,+ * 而同一个 `DSH_HOME` 下可能有多个宿主进程(桌面端重启交叠、手动再起的 `dsh web`、+ * 离线维护脚本)——它们各有一份自己的内存队列,却共用同一份私有快照仓。+ */++/** 跨进程工作区锁的构造选项(缺省值见 host/config/constants)。 */+export interface WorkspaceLockOptions {+ /** 宿主数据根目录(`DSH_HOME`)。 */+ dshHome: string+ /** 等待上限(毫秒);超时抛 WorkspaceLockTimeoutError。 */+ timeoutMs?: number+ /** 竞争时的重试间隔(毫秒)。 */+ retryMs?: number+}++/**+ * 工作区级**跨进程**互斥锁(内核独占监听句柄,见 ./lock.ts)。+ */+export interface WorkspaceLock {+ /**+ * 在跨进程互斥区内执行任务(获取 → 执行 → 释放;失败原样透出)。+ * @param key - 工作区键。+ * @param task - 要执行的异步任务。+ * @param lockTimeoutMs - 本次获取锁的等待上限(毫秒);缺省用构造时的 `timeoutMs`。+ * 屏障上的调用会传一个更短的值:等不到的代价只是「这一轮没有快照」,+ * 不该让它拖住用户的对话(见 host/config/constants 的 LOCK_BARRIER_TIMEOUT_MS)。+ */+ run: <T>(key: string, task: () => Promise<T>, lockTimeoutMs?: number) => Promise<T>+ /** 某个工作区的旧协议围栏目录路径(诊断与测试用,不承载内核锁所有权)。 */+ lockPath: (key: string) => string+}diff --git a/packages/dsh-tauri-turnrewind/src/host/utils/queue.test.ts b/packages/dsh-tauri-turnrewind/src/host/utils/queue.test.tsindex 89748cbf..c254f11a 100644--- a/packages/dsh-tauri-turnrewind/src/host/utils/queue.test.ts+++ b/packages/dsh-tauri-turnrewind/src/host/utils/queue.test.ts@@ -6,7 +6,9 @@* (否则长期运行的 Host 每见一个工作区就常驻一条 Promise,无界增长)。*/-import { describe, expect, it } from 'vitest'+import type { WorkspaceLock } from './lock.types'+import { describe, expect, it, vi } from 'vitest'+import { WorkspaceLockTimeoutError } from './lock'import { createWorkspaceQueue } from './queue'const tick = (ms = 0): Promise<void> => new Promise(resolve => setTimeout(resolve, ms))@@ -100,3 +102,171 @@ describe('createWorkspaceQueue', () => {expect(queue.size()).toBe(0)})})++describe('createWorkspaceQueue — 跨进程锁与等待截止', () => {+ it('每个任务都包在锁内执行:获取 → 任务 → 释放', async () => {+ const events: string[] = []+ const lock: WorkspaceLock = {+ async run<T>(key: string, task: () => Promise<T>): Promise<T> {+ events.push(`acquire:${key}`)+ try {+ return await task()+ }+ finally {+ events.push(`release:${key}`)+ }+ },+ lockPath: (key: string) => key,+ }++ const queue = createWorkspaceQueue({ lock })+ await queue.run('ws', async () => {+ events.push('task')+ })++ expect(events).toEqual(['acquire:ws', 'task', 'release:ws'])+ })++ it('把本次的跨进程等待上限透传给锁(缺省时传 undefined,由锁用自己的默认值)', async () => {+ const seen: Array<number | undefined> = []+ const lock: WorkspaceLock = {+ async run<T>(_key: string, task: () => Promise<T>, lockTimeoutMs?: number): Promise<T> {+ seen.push(lockTimeoutMs)+ return task()+ },+ lockPath: (key: string) => key,+ }++ const queue = createWorkspaceQueue({ lock })+ await queue.run('ws', async () => 'a', 250)+ await queue.run('ws', async () => 'b')++ expect(seen).toEqual([250, undefined])+ })++ it('锁获取失败:错误原样透出,且不阻断后续排队者', async () => {+ let calls = 0+ const lock: WorkspaceLock = {+ async run<T>(key: string, task: () => Promise<T>): Promise<T> {+ calls += 1+ if (calls === 1)+ throw new WorkspaceLockTimeoutError(`workspace lock not acquired (key=${key})`)+ return task()+ },+ lockPath: (key: string) => key,+ }++ const queue = createWorkspaceQueue({ lock })+ await expect(queue.run('ws', async () => 'never')).rejects.toBeInstanceOf(WorkspaceLockTimeoutError)+ await expect(queue.run('ws', async () => 'ok')).resolves.toBe('ok')+ await tick(5)+ expect(queue.size()).toBe(0)+ })++ it('队内等待耗时从传给跨进程锁的剩余预算扣除', async () => {+ vi.useFakeTimers()+ try {+ const timeouts: Array<number | undefined> = []+ const lock: WorkspaceLock = {+ lockPath: key => key,+ async run<T>(_key: string, task: () => Promise<T>, timeout?: number): Promise<T> {+ timeouts.push(timeout)+ return task()+ },+ }+ const queue = createWorkspaceQueue({ lock })+ const first = queue.run('ws', () => tick(12))+ const barrier = queue.run('ws', async () => 'ok', 20, { waitDeadline: Date.now() + 20 })+ await vi.advanceTimersByTimeAsync(12)+ await Promise.all([first, barrier])+ // deadline 从入队前起算:队头的 12ms 排队被扣除,锁只拿到剩余 8ms。+ expect(timeouts).toEqual([undefined, 8])+ }+ finally {+ vi.useRealTimers()+ }+ })++ it('截止时间只取消尚未开始的任务:队头被占用时调用者按时返回,任务永不执行', async () => {+ const lock: WorkspaceLock = { lockPath: key => key, run: async (_key, task) => task() }+ const queue = createWorkspaceQueue({ lock })+ let releaseHead: () => void = () => {}+ const head = queue.run('ws', () => new Promise<void>((resolve) => {+ releaseHead = resolve+ }))+ await tick(5)++ const started: string[] = []+ const barrier = queue.run('ws', async () => {+ started.push('before')+ }, 20, { waitDeadline: Date.now() + 20 })+ await expect(barrier).rejects.toBeInstanceOf(WorkspaceLockTimeoutError)+ expect(started).toEqual([])++ // 取消是永久的:真正轮到它时也不能执行(否则迟到的 before 会拍到模型改动)。+ releaseHead()+ await head+ await tick(10)+ expect(started).toEqual([])+ })++ it('迟到拿锁也不能执行任务:预算过期后即使锁就位也只释放', async () => {+ const events: string[] = []+ let releaseAcquire: () => void = () => {}+ const lock: WorkspaceLock = {+ lockPath: key => key,+ run: <T>(_key: string, task: () => Promise<T>): Promise<T> => {+ events.push('acquire')+ return new Promise<T>((resolve, reject) => {+ // startTask 在预算过期后会同步抛错:延后一步让它变成拒绝,而不是砸进测试。+ releaseAcquire = () => Promise.resolve().then(task).then(resolve, reject)+ })+ },+ }+ const queue = createWorkspaceQueue({ lock })+ const attempt = queue.run('ws', async () => {+ events.push('task')+ }, 5000, { waitDeadline: Date.now() + 30 })++ await tick(10)+ // 锁获取还在飞(模拟「邻居刚好释放」前的一瞬),deadline 先到:调用者拿到超时。+ await expect(attempt).rejects.toBeInstanceOf(WorkspaceLockTimeoutError)+ releaseAcquire()+ await tick(10)+ expect(events).toEqual(['acquire'])+ await tick(5)+ expect(queue.size()).toBe(0)+ })++ it('已开始的任务完整执行:执行开始后等待预算不再生效', async () => {+ const events: string[] = []+ const lock: WorkspaceLock = {+ async run<T>(_key: string, task: () => Promise<T>): Promise<T> {+ events.push('acquire')+ try {+ return await task()+ }+ finally {+ events.push('release')+ }+ },+ lockPath: key => key,+ }+ const queue = createWorkspaceQueue({ lock })+ const started = Date.now()+ const slow = queue.run('ws', async () => {+ events.push('task:start')+ await tick(60)+ events.push('task:end')+ return 'done'+ }, 1000, { waitDeadline: Date.now() + 20 })++ // 任务在预算内开始:一旦开始就必须完整等待——绝不半途放弃 git,也绝不让屏障+ // 在 before 快照执行中放行(否则模型改动会混进基线)。+ await expect(slow).resolves.toBe('done')+ expect(Date.now() - started).toBeGreaterThanOrEqual(60)+ expect(events).toEqual(['acquire', 'task:start', 'task:end', 'release'])+ await tick(5)+ expect(queue.size()).toBe(0)+ })+})diff --git a/packages/dsh-tauri-turnrewind/src/host/utils/queue.ts b/packages/dsh-tauri-turnrewind/src/host/utils/queue.tsindex 74506fce..64a911ad 100644--- a/packages/dsh-tauri-turnrewind/src/host/utils/queue.ts+++ b/packages/dsh-tauri-turnrewind/src/host/utils/queue.ts@@ -1,35 +1,111 @@/**- * host/utils/queue.ts — 工作区级 FIFO 串行的纯工厂。+ * host/utils/queue.ts — 工作区级串行的纯工厂:进程内 FIFO + 跨进程内核锁。** 私有快照仓的 index 与 refs 是每个工作区共享的可变状态:捕获、结算、运行中实时读数、* 撤销与容量治理都在动同一份 index,任何两件并发就会撞 `index.lock` 或读到半更新的- * index,因此全部经同一个队列串行(不同工作区互不影响)。+ * index。两道闸门各解决一半,缺一不可:+ * 1. **进程内 FIFO**(本文件):同一进程的任务按提交顺序串行。顺序是**先排队再拿锁**——+ * 反过来会让同一条道里的下一个任务去跟自己人争跨进程锁,白烧掉等待预算;+ * 2. **跨进程内核锁**(utils/lock.ts):同一个 `DSH_HOME` 下可能同时有多个宿主进程+ * (桌面端重启交叠、用户手动再起的 `dsh web`、离线维护脚本),内存队列对它们无效。+ *+ * 等待上限(`lockTimeoutMs`)只约束**跨进程锁**那一段;`options.waitDeadline` 是绝对+ * 截止时间(Date.now 毫秒),从**入队前**开始覆盖进程内排队与锁竞争,可被同一屏障的+ * 多个阶段共用(见 service/capture.ts 的 runBegin)。到期只取消**尚未开始**的任务:+ * 已开始的 git 必须完整等待,绝不在执行中超时放行屏障,否则迟到的 before 会把模型+ * 已经改过的文件拍成错误基线。** 队尾在结算后立即出队:否则每见过一个工作区就常驻一条 Promise,长期运行会无界增长。+ * 队尾守卫跟随真实操作(含迟到的锁释放),而不是跟随调用方拿到的 Promise.race。*/+import type { WorkspaceLock } from './lock.types'+import { WorkspaceLockTimeoutError } from './lock'++/** 单次任务的等待策略;执行开始后不再受等待预算约束。 */+export interface WorkspaceQueueRunOptions {+ /** 绝对截止时间(Date.now 毫秒):覆盖进程内排队与跨进程锁等待,可供多个阶段共用。 */+ waitDeadline?: number+}+/** 工作区级串行队列。 */export interface WorkspaceQueue {- /** 在指定工作区的串行区内执行任务(拒绝原样透出)。 */- run: <T>(key: string, task: () => Promise<T>) => Promise<T>+ /**+ * 在指定工作区的串行区内执行任务(拒绝原样透出)。+ * @param key - 工作区键。+ * @param task - 要执行的异步任务。+ * @param lockTimeoutMs - 本次获取**跨进程锁**的等待上限(毫秒);缺省用锁的默认值。+ * @param options - 跨阶段共享等待截止时间;超时后未开始的任务永不执行,已开始的任务完整等待。+ */+ run: <T>(key: string, task: () => Promise<T>, lockTimeoutMs?: number, options?: WorkspaceQueueRunOptions) => Promise<T>/** 当前仍在排队/在飞的工作区数(诊断与测试用)。 */size: () => number}-export function createWorkspaceQueue(): WorkspaceQueue {+/** 队列选项。 */+export interface WorkspaceQueueOptions {+ /**+ * 跨进程锁(见 utils/lock.ts)。只要同一个 `DSH_HOME` 下可能出现第二个宿主进程就必须传:+ * 只靠进程内队列,两个进程会并发动同一份私有仓的 index 与 refs。+ * 缺省(省略)时只做进程内串行。+ */+ lock?: WorkspaceLock | undefined+}++export function createWorkspaceQueue(options: WorkspaceQueueOptions = {}): WorkspaceQueue {+ const lock = options.lockconst tails = new Map<string, Promise<unknown>>()return {- run<T>(key: string, task: () => Promise<T>): Promise<T> {+ run<T>(key: string, task: () => Promise<T>, lockTimeoutMs?: number, runOptions: WorkspaceQueueRunOptions = {}): Promise<T> {const previous = tails.get(key) ?? Promise.resolve()- // 前一个任务失败不能阻断后续排队者:队尾只保留「已结算」的守卫 promise。- const settled = previous.then(task)+ const deadline = runOptions.waitDeadline+ let cancelled = false+ let timer: ReturnType<typeof setTimeout> | undefined+ const timeoutError = (): WorkspaceLockTimeoutError =>+ new WorkspaceLockTimeoutError(`workspace wait deadline exceeded (key=${key})`)+ const clearTimer = (): void => {+ if (timer !== undefined)+ clearTimeout(timer)+ }+ const assertWaiting = (): void => {+ if (cancelled || (deadline !== undefined && Date.now() >= deadline)) {+ cancelled = true+ throw timeoutError()+ }+ }+ const startTask = (): Promise<T> => {+ // 定时器只能放弃等待,不能让排在队内或迟到拿锁的任务在等待预算过期后执行。+ assertWaiting()+ clearTimer()+ // 一旦开始执行,就必须等其完成及锁释放;绝不在执行中超时放行屏障。+ return task()+ }+ // 调用者可以提前结束等待,但队尾必须跟随真实操作(含迟到的锁释放),不能跟随 race。+ const settled = previous.then(async (): Promise<T> => {+ assertWaiting()+ if (lock === undefined)+ return startTask()+ const remaining = deadline === undefined ? lockTimeoutMs : Math.min(lockTimeoutMs ?? Number.POSITIVE_INFINITY, deadline - Date.now())+ if (deadline !== undefined && remaining <= 0)+ throw timeoutError()+ return lock.run(key, startTask, remaining)+ })const guard = settled.then(() => undefined, () => undefined)tails.set(key, guard)void guard.then(() => {+ clearTimer()if (tails.get(key) === guard)tails.delete(key)})- return settled+ if (deadline === undefined)+ return settled+ const expired = new Promise<never>((_resolve, reject) => {+ timer = setTimeout(() => {+ cancelled = true+ reject(timeoutError())+ }, Math.max(0, deadline - Date.now()))+ })+ return Promise.race([settled, expired])},size: () => tails.size,}