merge #1146: fix(data-safety) literal pathspecs, archive operands, save races, task CAS, release dry-run

This commit is contained in:
Menghuan1918 committed 2026-11-08 00:11:16 +08:00
commit 31449826ae
15 files changed
+887 -79

No files matched your search

+10 -4
View File
@@ -25,12 +25,16 @@ name: Release
on:
release:
types: [published]
# Manual runs default to dry-run. A real publish from workflow_dispatch must
# be an explicit opt-in (exact `dry_run == 'false'`); empty / missing / any
# other value stays on the dry-run path, since the tag/version guard below
# only runs for `release` events.
workflow_dispatch:
inputs:
dry_run:
description: Pack and verify everything, but do not publish
description: Pack and verify everything, but do not publish (default)
type: boolean
default: false
default: true
permissions:
contents: read
@@ -105,11 +109,13 @@ jobs:
run: pnpm check:consumer-types
- name: Dry-run publish (validation only)
if: github.event_name == 'workflow_dispatch' && github.event.inputs.dry_run == 'true'
if: github.event_name == 'workflow_dispatch' && github.event.inputs.dry_run != 'false'
run: pnpm publish --dry-run --no-git-checks
# Match 'false' exactly: `!= 'true'` would fail open on an empty / missing
# input (see the dry_run input comment above).
- name: Publish to npm
if: github.event_name == 'release' || github.event.inputs.dry_run != 'true'
if: github.event_name == 'release' || github.event.inputs.dry_run == 'false'
run: |
TAG=$(node -p "require('./package.json').version.includes('-') ? 'alpha' : 'latest'")
echo "publishing to npm dist-tag: ${TAG}"
+4 -2
View File
@@ -11,8 +11,9 @@ import tseslint from 'typescript-eslint'
export default tseslint.config(
// 构建产物 / 工具目录不参与 lint(node_modules 默认不进,但**点开头目录
// 并不自动排除**——`.worktrees/` 与 `.delta/` 都必须显式列出,否则 ESLint
// 会走进那些陈旧检出,把别的分支的错误报成我们的:实测一次 1115 errors)。
// 并不自动排除**——`.worktrees/`、`.delta/`、`.agents/worktrees/` 都必须
// 显式列出,否则 ESLint 会走进那些陈旧检出,把别的分支的错误报成我们的:
// 实测一次 1115 errors)。`.agents/skills/` 仍要 lint,不能整个忽略 `.agents/`。
{
ignores: [
'lib/',
@@ -24,6 +25,7 @@ export default tseslint.config(
'node_modules/',
'.worktrees/',
'.delta/',
'.agents/worktrees/',
],
},
+16 -3
View File
@@ -24,7 +24,9 @@
*
* Nothing in this module runs a shell: `spawn` takes an argv array, and every
* path is data. A path is never interpolated into a command string, so a
* filename with `;` or `$(...)` in it is a filename.
* filename with `;` or `$(...)` in it is a filename. A name starting with `-`
* is still refused by `planArchive` (verified on GNU tar 1.35): the bytes are
* safe, but the tool itself would parse it as an option.
*
* The spawn/probe functions are injectable so the test suite never depends on
* a real `zip` being installed (AGENTS §6) — the same pattern `open-external`
@@ -182,7 +184,8 @@ function toArchiveName(path: string): string {
* @param selections - absolute paths, already fenced by the caller.
* @param spec - the resolved tool.
* @returns the plan to spawn.
* @throws {SidebarError} bad-request when a selection has no usable name.
* @throws {SidebarError} bad-request when a selection has no usable name or
* starts with `-`.
*/
export function planArchive(selections: readonly string[], spec: ArchiveToolSpec): ArchivePlan {
if (selections.length === 0) {
@@ -203,7 +206,17 @@ export function planArchive(selections: readonly string[], spec: ArchiveToolSpec
if (args.some(name => name === '' || name === '..' || name.startsWith('../'))) {
throw new SidebarError('bad-request', 'selection is not below the archive root')
}
return { spec, cwd: base, args: [...spec.flags, ...args] }
// Refused, not quoted — see the module header.
if (args.some(name => name.startsWith('-'))) {
throw new SidebarError('bad-request', 'archive entry name may not start with "-"')
}
// GNU/bsdtar honor `--` as end-of-options. Info-ZIP zip 3.0 has no portable
// bare `--` (3.1 rejects it before the archive name), so zip operands get a
// `./` prefix instead — a name can then never be read as an option.
const operands = spec.tool === 'zip'
? args.map(name => `./${name}`)
: ['--', ...args]
return { spec, cwd: base, args: [...spec.flags, ...operands] }
}
/**
+50 -2
View File
@@ -240,6 +240,19 @@ export function TaskWindow(props: TaskWindowProps): ReactNode {
const [busy, setBusy] = useState(false)
const [note, setNote] = useState<string | undefined>(undefined)
const [armedDelete, setArmedDelete] = useState(false)
/** Revision the draft was opened against: the projection keeps delivering
* new revisions while the window stays open, and saving with the live one
* would silently overwrite a teammate's write. */
const editRevisionRef = useRef<number | undefined>(task?.revision)
/** Render-time mirror of the projection's latest revision: `mutate`'s
* closure captures the `task` of the render that began the save, which can
* be stale by the time a conflict comes back. */
const latestRevisionRef = useRef<number | undefined>(task?.revision)
latestRevisionRef.current = task?.revision
/** The revision a rejected Save submitted. The conflict response carries no
* revision of its own, so when the mirror has not moved past it yet the true
* base is the NEXT revision the projection delivers (see the effect below). */
const staleFromRef = useRef<number | undefined>(undefined)
// Re-seed the draft when the caller swaps the subject task: the projection
// hands us fresh revisions, and unsaved text must not leak across tasks.
@@ -266,8 +279,21 @@ export function TaskWindow(props: TaskWindowProps): ReactNode {
// task. Carried into the next one it makes that reader's first click the
// delete itself.
setArmedDelete(false)
// A re-base mark belongs to the task that produced it.
staleFromRef.current = undefined
}, [task?.id])
// A rejected Save re-bases only once the projection actually overtakes the
// revision that was submitted: re-basing to the render-time mirror while it
// still shows that same revision would just hand the stale value back and
// make the next Save conflict again.
useEffect(() => {
const staleFrom = staleFromRef.current
if (staleFrom === undefined || task?.revision === undefined || task.revision <= staleFrom) return
editRevisionRef.current = task.revision
staleFromRef.current = undefined
}, [task?.revision])
const teammates = members.filter(member => member.role === 'teammate')
/** Run one CAS mutation with the shared busy/conflict handling. */
@@ -287,6 +313,19 @@ export function TaskWindow(props: TaskWindowProps): ReactNode {
// projection, so a committed revision lands in this window's props
// by itself.
} else {
if (result.code === CONFLICT_CODE) {
// A stale write is rejected WITHOUT advancing the revision. Use the
// mirror once it has overtaken the rejected one; until then the effect
// above takes the projection's next revision. The note, the draft and
// editing stay put (exiting would lose the draft), and the next Save
// submits against the new base — an explicit "overwrite anyway".
const submitted = editRevisionRef.current ?? task?.revision
const latest = latestRevisionRef.current
if (submitted !== undefined) {
if (latest !== undefined && latest > submitted) editRevisionRef.current = latest
else staleFromRef.current = submitted
}
}
setNote(result.code === CONFLICT_CODE
? t('teamTaskConflict')
: t('teamTaskError', { message: result.message }))
@@ -309,7 +348,7 @@ export function TaskWindow(props: TaskWindowProps): ReactNode {
? api.teamsTaskCreate(rootId, { subject: nextSubject, description: description.trim() })
: api.teamsTaskUpdate(rootId, {
taskId: task.id,
expectedRevision: task.revision,
expectedRevision: editRevisionRef.current ?? task.revision,
action: 'edit',
subject: nextSubject,
description: description.trim(),
@@ -378,7 +417,16 @@ export function TaskWindow(props: TaskWindowProps): ReactNode {
variant="outline"
size="sm"
icon={<IconEditOutlineRegular size={12} />}
onClick={() => { setEditing(true) }}
onClick={() => {
// Draft and CAS base from the same read (see editRevisionRef),
// so a pending conflict re-base has nothing left to correct.
editRevisionRef.current = task.revision
staleFromRef.current = undefined
setSubject(task.subject)
setDescription(task.description)
setSubjectTouched(false)
setEditing(true)
}}
>
{t('teamTaskEdit')}
</Button>
+27 -7
View File
@@ -816,7 +816,8 @@ export function TextEditor(props: FileViewerProps) {
if (view === null || savingRef.current) return
// The bytes this request writes: the same string becomes the baseline text
// once the host accepts it (the draft may keep changing while in flight).
const text = view.state.doc.toString()
const sentDoc = view.state.doc
const text = sentDoc.toString()
savingRef.current = true
setSaveState('saving')
// Optimistic concurrency: the draft was based on the bytes read at
@@ -825,23 +826,42 @@ export function TextEditor(props: FileViewerProps) {
// external editor). `null` = the file did not exist when loaded.
api.fsWrite(scope, path, text, mtimeRef.current ?? null).then((result) => {
savingRef.current = false
// A file switch during the write destroys `view` and re-seats viewRef on
// the NEW document. This result then belongs to the OLD file: write
// nothing else, or A's text / save state / mtime leak into B. The save
// lock is already released above so B can still save.
if (viewRef.current !== view) return
// Adopt the fresh baseline the host reports (absent on a stat failure —
// keep the old one, the next save just re-checks).
if (typeof result.mtimeMs === 'number') mtimeRef.current = result.mtimeMs
savedTextRef.current = text
setDraft(null)
setDirty(false)
setConflict(false)
setSaveState('saved')
// Saved: nothing is unsaved any more, so the durable backup must not
// offer itself back on the next open.
clearDraftBackup(scope.sessionId, path)
// Keystrokes during the write are NOT the bytes on disk: keep the tab
// dirty and its durable backup, or the next close/quit drops them.
// CM's `Text` is immutable: an unchanged doc is the same object, so
// `text` can be reused instead of stringifying the document again.
const liveDoc = view.state.doc
const live = liveDoc === sentDoc ? text : liveDoc.toString()
if (live !== text) {
setDraft(live)
setSaveState('idle')
} else {
setDraft(null)
setDirty(false)
setSaveState('saved')
// Saved: nothing is unsaved any more, so the durable backup must not
// offer itself back on the next open.
clearDraftBackup(scope.sessionId, path)
}
// The saved bytes are a new revision of the uncommitted diff: re-read
// the change set (the file's XY status code usually stays the same, so
// the status store alone would never wake the gutter up again).
setGitRevision(value => value + 1)
}).catch((error: unknown) => {
savingRef.current = false
// Same expiry guard as the success path: an error from the OLD file must
// not raise B's conflict banner or mark B's save failed.
if (viewRef.current !== view) return
if (error instanceof SidebarApiError && error.code === 'fs-conflict') {
setConflict(true)
setSaveState('idle')
+21 -14
View File
@@ -538,6 +538,13 @@ export function runGit(cwd: string, args: string[], timeoutMs = 30_000, options:
})
}
/** 路径是用户给的字面文件名:不加这个全局选项,git 会把 `a[1].txt` 里的
* `[1]` 当 pathspec 通配符,连 `a1.txt` 一起丢弃/暂存(改动不可恢复)。
* 选项必须前置在子命令前才是 git 全局选项。 */
function literalPathspec(path: string | readonly string[] | undefined): string[] {
return path === undefined ? [] : ['--literal-pathspecs']
}
/** One parsed `git blame --porcelain` row (the editor's hover blame). */
export interface GitBlameLine {
/** 1-based line number in the file as it exists in the worktree. */
@@ -633,7 +640,7 @@ export async function blame(
try {
const root = await repoRoot(cwd, selected)
const output = await runGit(root, [
'blame', '--porcelain', '-L', `${String(startLine)},${String(endLine)}`, '--', path,
...literalPathspec(path), 'blame', '--porcelain', '-L', `${String(startLine)},${String(endLine)}`, '--', path,
])
return parseBlamePorcelain(output)
} catch {
@@ -860,9 +867,7 @@ function numstatPathsof(porcelainZ: string): string[] | undefined {
* both numstat diffs: the counts only ever ride rows the status read itself
* reports, and limiting the diffs to those paths is what keeps an unignored
* nested `node_modules` (59 631 entries / 9.24 MB of numstat) out of the two
* whole-repo walks. `--literal-pathspecs` is required: porcelain paths are
* literal file names, and without it a name like `:colon.txt` is parsed as
* pathspec magic and silently loses its counts.
* whole-repo walks. 两条 numstat 也要字面 pathspec,理由见 literalPathspec()。
*
* Each side's reading lands on its own field of the entry
* ({@link GitStatusEntry} documents why the two are never summed).
@@ -891,10 +896,7 @@ export async function status(cwd: string, selected?: string): Promise<GitStatusR
// to the whole-repo diff); `[]` = no tracked change at all, so both diffs are
// known empty and neither process is spawned.
if (pathspec === undefined || pathspec.length > 0) {
// `--literal-pathspecs` must precede the subcommand (`git <flag> diff …`).
// Porcelain paths are literal file names, and without it a name like
// `:colon.txt` is parsed as pathspec magic and silently loses its counts.
const literal = pathspec === undefined ? [] : ['--literal-pathspecs']
const literal = literalPathspec(pathspec)
const paths = pathspec === undefined ? [] : ['--', ...pathspec]
const [unstaged, staged] = await Promise.all([
runGit(root, [...literal, 'diff', '--numstat', '-z', ...paths]).catch(() => ''),
@@ -1009,7 +1011,7 @@ export async function resolveWorktree(cwd: string, requested?: string): Promise<
/** Diff text of the worktree (unstaged) or the index (staged). */
export async function diff(cwd: string, path: string | undefined, staged: boolean, selected?: string): Promise<string> {
const root = await repoRoot(cwd, selected)
const args = ['diff', '--no-ext-diff', '--no-color', '-U3']
const args = [...literalPathspec(path), 'diff', '--no-ext-diff', '--no-color', '-U3']
if (staged) args.push('--cached')
if (path !== undefined) args.push('--', path)
return runGit(root, args)
@@ -1027,22 +1029,27 @@ export async function diff(cwd: string, path: string | undefined, staged: boolea
*/
export async function diffHead(cwd: string, path: string | undefined, selected?: string): Promise<string> {
const root = await repoRoot(cwd, selected)
const literal = literalPathspec(path)
const tail = path !== undefined ? ['--', path] : []
try {
return await runGit(root, ['diff', '--no-ext-diff', '--no-color', '-U3', 'HEAD', ...tail])
return await runGit(root, [...literal, 'diff', '--no-ext-diff', '--no-color', '-U3', 'HEAD', ...tail])
} catch {
return runGit(root, ['diff', '--no-ext-diff', '--no-color', '-U3', '--cached', ...tail])
return runGit(root, [...literal, 'diff', '--no-ext-diff', '--no-color', '-U3', '--cached', ...tail])
}
}
/** Stage paths (all when path is undefined). */
export async function stage(cwd: string, path: string | undefined, selected?: string): Promise<void> {
await runGit(await repoRoot(cwd, selected), ['add', '-A', ...(path !== undefined ? ['--', path] : [])])
await runGit(await repoRoot(cwd, selected), [
...literalPathspec(path), 'add', '-A', ...(path !== undefined ? ['--', path] : []),
])
}
/** Unstage paths (all when path is undefined). */
export async function unstage(cwd: string, path: string | undefined, selected?: string): Promise<void> {
await runGit(await repoRoot(cwd, selected), ['reset', '-q', ...(path !== undefined ? ['--', path] : [])])
await runGit(await repoRoot(cwd, selected), [
...literalPathspec(path), 'reset', '-q', ...(path !== undefined ? ['--', path] : []),
])
}
/** Commit the staged changes with a message (global identity untouched). */
@@ -1110,7 +1117,7 @@ export async function commitDiff(cwd: string, hash: string, selected?: string):
/** Discard the worktree changes of one path (`git checkout -- <path>`; the index is untouched). */
export async function discard(cwd: string, path: string, selected?: string): Promise<void> {
await runGit(await repoRoot(cwd, selected), ['checkout', '--', path])
await runGit(await repoRoot(cwd, selected), [...literalPathspec(path), 'checkout', '--', path])
}
/** Revert one commit onto the current branch with an auto-generated message.
+56 -24
View File
@@ -14,11 +14,13 @@
* whose name matches (no file path carries it, so rg cannot see it; fd and
* the walk both report it).
*
* A runtime failure disables that engine for the rest of the process (a
* broken binary must not slow every later search); the caller falls back to
* the plain walk. A timeout is NOT a failure: it means this tree was too
* large, so it must not strip every other root of the engine. Hooks are
* swappable for tests (setEngineHooks).
* Repeated consecutive failures disable that engine (a broken binary must not
* slow every later search); a single bad query or a timeout only degrades THAT
* one search, and a timeout breaks the failure streak. A disabled engine is
* retried after a cooldown — a transient cause (a replaced binary, one EMFILE
* burst) must not cost the fast path for the rest of the session — and a
* success recovers it immediately. Hooks are swappable for tests
* (setEngineHooks).
*/
import { spawn, type ChildProcess } from 'node:child_process'
import { createInterface } from 'node:readline'
@@ -204,7 +206,7 @@ function verify(binary: string): Promise<boolean> {
/** Escape glob metacharacters so a query matches literally inside -g.
* Braces are metacharacters too ({a,b} alternation): an unbalanced '{'
* makes rg fail to parse the glob (exit 2 → the engine looks broken), and
* makes rg fail to parse the glob (exit 2 → the run fails), and
* a balanced one silently matches a DIFFERENT literal ('a{b}' searches
* 'ab'). Verified against rg 15: '\{' is a valid brace escape. */
export function escapeGlob(query: string): string {
@@ -359,14 +361,16 @@ export function normalizeEnginePaths(lines: readonly string[], separator: string
* pinned, and --max-results one ABOVE the stream sentinel (cap + 1) so a
* full result set overflows into the same truncation detected for rg
* (see runChild). Directory matches are read from a second invocation
* (`type: 'd'`, see runChild) because fd cannot label its matches. */
* (`type: 'd'`, see runChild) because fd cannot label its matches.
* `--` ends option parsing BEFORE the query: a `-`-leading pattern must stay
* a positional, not become an fd option. */
export function fdArgv(cap: number, query: string, type?: 'd'): string[] {
return [
'--hidden', '--no-ignore',
...SKIP_DIR_NAMES.flatMap(name => ['--exclude', name]),
'--fixed-strings', '--ignore-case',
...(type === undefined ? [] : ['--type', type]),
'--path-separator', '/', '--max-results', String(cap + 1), query, '.',
'--path-separator', '/', '--max-results', String(cap + 1), '--', query, '.',
]
}
@@ -481,8 +485,8 @@ function runChild(
return Promise.all([
streamLines(child, cap),
// The directory run's failure is NOT swallowed (#883): a rejected dirs
// stream rejects the whole engine call, so runEngine marks the engine
// broken and this one search falls back to the plain walk — exactly
// stream rejects the whole engine call, so runEngine records the failure
// and this one search falls back to the plain walk — exactly
// the main run's failure handling. The old swallow-catch degraded the
// failure into "zero directories", invisible in every environment.
streamLines(dirChild, cap),
@@ -512,8 +516,14 @@ export type EngineSpawner = (
/** Child spawn behind runChild — injectable so tests can drive the real
* orchestration with scripted children (event order, stream timing). */
let spawner: EngineSpawner = spawn
/** Engines failed at runtime: skipped for the rest of this process. */
const broken = new Set<Engine>()
/** Engines disabled after repeated failures → the moment each may be retried;
* a success clears the entry outright. */
const broken = new Map<Engine, number>()
/** Streak length that disables an engine (failure policy: see module header). */
const BROKEN_AFTER = 3
/** Cooldown before a disabled engine gets one more attempt. */
const BROKEN_RETRY_MS = 60_000
const failures = new Map<Engine, number>()
let probePromise: Promise<readonly EngineProbe[]> | null = null
/** Probe once per process (lazy): each engine's first working candidate. */
@@ -538,12 +548,8 @@ export function probeEngines(): Promise<readonly EngineProbe[]> {
return probePromise
}
/** Run one engine and get capped, normalized matches; a runtime failure
* disables that engine for the rest of the process (a broken binary must
* not slow every later search) — but a TIMEOUT does not: a timeout means
* THIS tree was too big, while the broken-set is per-engine, so disabling
* here would strip every other (small) root of the engine over one huge
* directory. */
/** Run one engine and get capped, normalized matches. Failure policy: see
* the module header. */
export async function runEngine(
probe: EngineProbe,
root: string,
@@ -551,22 +557,47 @@ export async function runEngine(
maxMatches: number,
): Promise<EngineResult> {
try {
return await runner(probe, root, query, maxMatches)
const result = await runner(probe, root, query, maxMatches)
// Success is recovery: clear the streak and lift any `broken` mark, so a
// late in-flight success cannot leave the engine filtered out forever.
failures.delete(probe.engine)
broken.delete(probe.engine)
return result
} catch (error) {
if (error instanceof EngineTimeoutError) {
// A timeout breaks the streak like a success: a huge tree is not a dead
// binary, so its count must not roll into the next search.
failures.delete(probe.engine)
debugLog(`[dsh-search] engine ${probe.engine} timed out (tree too large), falling back`)
} else {
broken.add(probe.engine)
debugLog(`[dsh-search] engine ${probe.engine} failed at runtime, disabled: ${error instanceof Error ? error.message : String(error)}`)
const count = (failures.get(probe.engine) ?? 0) + 1
failures.set(probe.engine, count)
const why = error instanceof Error ? error.message : String(error)
if (count >= BROKEN_AFTER) {
broken.set(probe.engine, Date.now() + BROKEN_RETRY_MS)
debugLog(`[dsh-search] engine ${probe.engine} failed ${String(count)} times in a row, disabled: ${why}`)
} else {
debugLog(`[dsh-search] engine ${probe.engine} query failed (${String(count)}/${String(BROKEN_AFTER)}), will retry: ${why}`)
}
}
throw error
}
}
/** The engines a caller may actually try (verified, not broken). */
/** The engines a caller may actually try (verified, and not inside a disable
* cooldown). */
export async function usableEngines(): Promise<readonly EngineProbe[]> {
const probes = await probeEngines()
return probes.filter((probe) => !broken.has(probe.engine))
const now = Date.now()
return probes.filter((probe) => {
const retryAt = broken.get(probe.engine)
if (retryAt === undefined) return true
if (now < retryAt) return false
// Probation: one attempt. A failure re-arms the cooldown, a success lifts
// the mark entirely (runEngine).
broken.delete(probe.engine)
return true
})
}
/** Test seam: replace the probe / child-runner / spawn implementations. */
@@ -576,10 +607,11 @@ export function setEngineHooks(next: { prober?: typeof prober; runner?: typeof r
if (next.spawner !== undefined) spawner = next.spawner
}
/** Reset probe cache, broken-set and hooks (test isolation). */
/** Reset probe cache, failure state and hooks (test isolation). */
export function resetEngines(): void {
probePromise = null
broken.clear()
failures.clear()
prober = (): Promise<readonly EngineProbe[]> => probeOnce()
runner = runChild
spawner = spawn
+37 -5
View File
@@ -5,7 +5,9 @@
* reader is gone with it — there is nothing of OURS left to inflate. What is
* worth pinning is the PLAN (where the tool runs and what argv it gets), the
* NAME the client ends up with, the tool PROBE (which binary answers), and how
* ONE run reports success, failure and stderr.
* ONE run reports success, failure and stderr. The plan also guards against
* option injection: `-`-leading entry names are refused, tar separates its
* operands with `--`, and zip (which has no portable `--`) prefixes with `./`.
*
* Every case here injects the spawn face: `zip` does not exist on Windows
* (bsdtar does), the ubuntu runner is not guaranteed either, and a spec that
@@ -180,7 +182,8 @@ describe('planArchive', () => {
expect(plan.cwd).toBe(join(PLAN_ROOT, 'ws'))
// `-y` is not decoration: without it Info-ZIP FOLLOWS symlinks, and a
// `loop -> .` in the tree then recurses until the process is killed.
expect(plan.args).toEqual(['-r', '-q', '-X', '-y', '-', 'src'])
// `./` keeps the operand out of option position — zip 3.0 has no `--`.
expect(plan.args).toEqual(['-r', '-q', '-X', '-y', '-', './src'])
expect(plan.spec).toBe(spec)
})
@@ -189,7 +192,11 @@ describe('planArchive', () => {
const ws = join(PLAN_ROOT, 'ws')
const plan = planArchive([join(ws, 'src', 'index.ts'), join(ws, 'lib', 'util.ts')], spec)
expect(plan.cwd).toBe(ws)
expect(plan.args.slice(spec.flags.length)).toEqual(['src/index.ts', 'lib/util.ts'])
expect(plan.args.slice(0, spec.flags.length)).toEqual([...spec.flags])
expect(plan.args).not.toContain('--')
expect(plan.args.slice(spec.flags.length)).toEqual(['./src/index.ts', './lib/util.ts'])
// The `-` stdout archive name must stay in flags, ahead of every operand.
expect(plan.args[spec.flags.length - 1]).toBe('-')
// The separator is normalized whatever the platform produced: the tool
// gets in-archive names, not host paths.
expect(plan.args.every(arg => !arg.includes('\\'))).toBe(true)
@@ -203,14 +210,15 @@ describe('planArchive', () => {
const plan = planArchive([join(ws, 'src'), join(ws, 'src', 'index.ts')], spec)
expect(plan.cwd).toBe(ws)
const names = plan.args.slice(spec.flags.length)
expect(names).toEqual(['src', 'src/index.ts'])
expect(names).toEqual(['./src', './src/index.ts'])
expect(names.every(name => name !== '')).toBe(true)
})
it('uses the tar invocation for a tar-only host', async () => {
const spec = await specOf('tar')
const plan = planArchive([join(PLAN_ROOT, 'ws', 'notes.md')], spec)
expect(plan.args).toEqual(['-czf', '-', 'notes.md'])
expect(plan.args).toEqual(['-czf', '-', '--', 'notes.md'])
expect(plan.args.indexOf('--')).toBe(spec.flags.length)
expect(plan.spec.ext).toBe('.tar.gz')
})
@@ -230,6 +238,30 @@ describe('planArchive', () => {
expect(thrown).toMatchObject({ code: 'bad-request' })
expect((thrown as Error).message).toMatch(/no paths/)
})
// Regression: two `-`-leading names made GNU tar 1.35 execute them as
// options instead of operands. The guard is tool-independent.
it('refuses an entry name starting with "-" on both tools', async () => {
for (const tool of ['zip', 'tar'] as const) {
const spec = await specOf(tool)
const ws = join(PLAN_ROOT, 'ws')
for (const name of ['-dash.txt', '--long.txt']) {
const thrown = capture(() => planArchive([join(ws, name)], spec))
expect(thrown).toBeInstanceOf(SidebarError)
expect(thrown).toMatchObject({ code: 'bad-request' })
expect((thrown as Error).message).toMatch(/start with/)
}
}
})
it('refuses a leading-dash entry in a multi-selection too', async () => {
const spec = await specOf('tar')
const ws = join(PLAN_ROOT, 'ws')
const thrown = capture(() => planArchive([join(ws, '-dash.txt'), join(ws, 'ok.txt')], spec))
expect(thrown).toBeInstanceOf(SidebarError)
expect(thrown).toMatchObject({ code: 'bad-request' })
})
})
describe('archiveFileName', () => {
+4 -3
View File
@@ -642,13 +642,14 @@ describe('fs-search dispatch', () => {
runner: async () => { throw new Error('engine exploded') },
})
expect(await searchFiles(dir, 'util')).toEqual({ matches: ['src/util.ts'], dirs: [], truncated: false })
// The failed engine is disabled for the rest of the process.
// A single failure must NOT disable the engine: the next search retries
// it instead of permanently degrading to the slow walk.
let attempts = 0
setEngineHooks({
runner: async () => { attempts += 1; return { paths: [], dirs: [], truncated: false } },
runner: async () => { attempts += 1; throw new Error('engine exploded again') },
})
expect(await searchFiles(dir, 'util')).toEqual({ matches: ['src/util.ts'], dirs: [], truncated: false })
expect(attempts).toBe(0)
expect(attempts).toBe(1)
} finally {
removeTree(dir)
}
+91
View File
@@ -0,0 +1,91 @@
/**
* 用户给的路径是字面文件名:git 默认把 `a[1].txt` 里的 `[1]` 当 pathspec
* 通配符,会连 `a1.txt` 一起命中——丢弃改动不可恢复。这里钉住每个吃路径的
* 子命令都把 `--literal-pathspecs` 作为全局选项前置在子命令前,且原有的
* `--` 分隔与字面路径原样保留。
*
* 与 git-spawn.spec.ts 一样 mock 掉 spawn:只有拿到 argv 才能断言全局选项的
* 顺序,真实 git 只会把结果返回来。
*/
import { EventEmitter } from 'node:events'
import { PassThrough } from 'node:stream'
import { afterEach, describe, expect, it, vi } from 'vitest'
const { spawnMock } = vi.hoisted(() => ({ spawnMock: vi.fn() }))
vi.mock('node:child_process', () => ({ spawn: spawnMock }))
import { blame, diff, diffHead, discard, stage, unstage } from '../src/git.ts'
/** `a[1].txt` 是两平台都合法的良构方括号名;`a1.txt` 是它会被误伤的同伴。 */
const LITERAL = 'a[1].txt'
const PLAIN = 'a1.txt'
const CWD = '/repo'
afterEach(() => {
spawnMock.mockReset()
})
/** 假的 git 子进程:`rev-parse --show-toplevel` 回填仓库根,其余返回空。 */
function fakeGit(_file: string, args: string[]): EventEmitter {
const child = new EventEmitter()
const stdout = new PassThrough()
const stderr = new PassThrough()
Object.assign(child, { stdout, stderr, kill: vi.fn() })
const cwd = args[args.indexOf('-C') + 1] ?? ''
queueMicrotask(() => {
stdout.end(args.includes('rev-parse') ? `${cwd}\n` : '')
stderr.end()
child.emit('close', 0)
})
return child
}
const cases: { name: string; subcommand: string; run: () => Promise<unknown> }[] = [
{ name: 'discard', subcommand: 'checkout', run: () => discard(CWD, LITERAL) },
{ name: 'stage', subcommand: 'add', run: () => stage(CWD, LITERAL) },
{ name: 'unstage', subcommand: 'reset', run: () => unstage(CWD, LITERAL) },
{ name: 'diff (unstaged)', subcommand: 'diff', run: () => diff(CWD, LITERAL, false) },
{ name: 'diff (staged)', subcommand: 'diff', run: () => diff(CWD, LITERAL, true) },
{ name: 'diffHead', subcommand: 'diff', run: () => diffHead(CWD, LITERAL) },
{ name: 'blame', subcommand: 'blame', run: () => blame(CWD, LITERAL, 1, 1) },
]
describe('字面 pathspec(防止误伤同名文件)', () => {
for (const { name, subcommand, run } of cases) {
it(`${name}:--literal-pathspecs 前置在子命令前,且只带字面路径`, async () => {
spawnMock.mockImplementation(fakeGit)
await run()
// 目标命令是唯一带用户路径的那次 spawn(其余是仓库发现的 rev-parse)。
const argv = spawnMock.mock.calls
.map(call => call[1] as string[])
.find(args => args.includes(LITERAL))
expect(argv).toBeDefined()
const full = argv!
expect(full).toContain('--literal-pathspecs')
// 必须排在子命令之前,否则 git 把它当子命令参数、全局选项不生效。
expect(full.indexOf('--literal-pathspecs')).toBeLessThan(full.indexOf(subcommand))
// 原有的 `--` 分隔与字面路径不变,且路径是最后一个操作数。
expect(full).toContain('--')
expect(full.indexOf('--')).toBeLessThan(full.indexOf(LITERAL))
expect(full.at(-1)).toBe(LITERAL)
// 从未把 `a[1].txt` 展开/替换成 `a1.txt`。
expect(full).not.toContain(PLAIN)
})
}
it('全量操作(path 为 undefined)不引入多余的全局选项', async () => {
spawnMock.mockImplementation(fakeGit)
await Promise.all([
stage(CWD, undefined),
unstage(CWD, undefined),
diff(CWD, undefined, false),
diffHead(CWD, undefined),
])
for (const call of spawnMock.mock.calls) {
expect(call[1] as string[]).not.toContain('--literal-pathspecs')
}
})
})
+89 -1
View File
@@ -6,7 +6,7 @@ import { join } from 'node:path'
import { promisify } from 'node:util'
import { describe, expect, it } from 'vitest'
import { parseUnifiedDiff } from '../src/client/diff/rows.ts'
import { branches, checkout, currentBranch, log, parseLogLines, parseNumstat, parsePorcelainZ, parseStatusPorcelainV2Z, repoRoots, status } from '../src/git.ts'
import { branches, checkout, currentBranch, diff, discard, log, parseLogLines, parseNumstat, parsePorcelainZ, parseStatusPorcelainV2Z, repoRoots, stage, status, unstage } from '../src/git.ts'
import { removeTree } from './temp-tree.ts'
const execFileAsync = promisify(execFile)
@@ -685,3 +685,91 @@ describe('numstat line counts (#131)', () => {
}
})
})
/**
* 数据防误伤:`a[1].txt` 与 `a1.txt` 在 Windows / Linux 都是合法文件名,而
* git 默认把前者里的 `[1]` 当 pathspec 通配符,后者会被一起选中。丢弃改动
* 不可恢复,所以这里用真实 git 钉住「只动目标文件」。
*/
describe('字面 pathspec 不误伤同名文件', () => {
function repo(): string {
const root = mkdtempSync(join(tmpdir(), 'dsh-git-literal-'))
execFileSync('git', ['init', '-q'], { cwd: root })
execFileSync('git', ['config', 'user.email', 't@t'], { cwd: root })
execFileSync('git', ['config', 'user.name', 't'], { cwd: root })
// Windows 上默认 autocrlf 会把 checkout 回来的内容换成 CRLF。
execFileSync('git', ['config', 'core.autocrlf', 'false'], { cwd: root })
writeFileSync(join(root, 'a[1].txt'), 'base-A\n')
writeFileSync(join(root, 'a1.txt'), 'base-B\n')
execFileSync('git', ['add', '-A'], { cwd: root })
execFileSync('git', ['commit', '-q', '-m', 'base'], { cwd: root })
return root
}
const statusLines = (root: string): string => execFileSync(
'git', ['-c', 'core.quotePath=false', 'status', '--porcelain=v1'], { cwd: root, encoding: 'utf8' },
)
it('discard 只还原 a[1].txt,a1.txt 的改动保留', async () => {
const root = repo()
try {
writeFileSync(join(root, 'a[1].txt'), 'EDIT-A\n')
writeFileSync(join(root, 'a1.txt'), 'EDIT-B\n')
await discard(root, 'a[1].txt')
expect(readFileSync(join(root, 'a[1].txt'), 'utf8')).toBe('base-A\n')
expect(readFileSync(join(root, 'a1.txt'), 'utf8')).toBe('EDIT-B\n')
} finally {
removeTree(root)
}
})
it('stage 只暂存 a[1].txt', async () => {
const root = repo()
try {
writeFileSync(join(root, 'a[1].txt'), 'EDIT-A\n')
writeFileSync(join(root, 'a1.txt'), 'EDIT-B\n')
await stage(root, 'a[1].txt')
const rows = statusLines(root)
expect(rows).toContain('M a[1].txt')
expect(rows).toContain(' M a1.txt')
} finally {
removeTree(root)
}
})
it('unstage 只取消 a[1].txt 的暂存', async () => {
const root = repo()
try {
writeFileSync(join(root, 'a[1].txt'), 'EDIT-A\n')
writeFileSync(join(root, 'a1.txt'), 'EDIT-B\n')
execFileSync('git', ['add', '-A'], { cwd: root })
await unstage(root, 'a[1].txt')
const rows = statusLines(root)
expect(rows).toContain(' M a[1].txt')
expect(rows).toContain('M a1.txt')
} finally {
removeTree(root)
}
})
it('diff 只输出 a[1].txt 的补丁', async () => {
const root = repo()
try {
writeFileSync(join(root, 'a[1].txt'), 'EDIT-A\n')
writeFileSync(join(root, 'a1.txt'), 'EDIT-B\n')
const patch = await diff(root, 'a[1].txt', false)
expect(patch).toContain('a[1].txt')
expect(patch).not.toContain('a1.txt')
} finally {
removeTree(root)
}
})
})
+140 -14
View File
@@ -1,8 +1,9 @@
/**
* search-engines: the native-engine probe and runner behind fs.search.
* The probe is process-cached (verified binaries only); a runtime failure
* disables one engine without disturbing the others, while a TIMEOUT only
* degrades that one search. `normalizeEnginePaths` re-bases raw stdout lines
* The probe is process-cached (verified binaries only); a single runtime
* failure (or a timeout) only degrades that one search, so the next one can
* retry the engine — only repeated consecutive failures disable it, without
* disturbing the others. `normalizeEnginePaths` re-bases raw stdout lines
* onto the walk contract (root-relative, '/'-separated, no './' prefix) and
* `deriveRgMatches` supplies the directory hits `rg --files` cannot report.
* Child processes are exercised entirely through injected hooks — CI
@@ -212,9 +213,9 @@ describe('escapeGlob', () => {
})
// '{' is globset alternation syntax: unbalanced it breaks the glob parse
// (rg exits 2 → the engine looks broken and gets disabled process-wide),
// balanced 'a{b}' silently searches 'ab' instead of the literal. Both
// verified against real rg 15; '\{' is the accepted escape.
// (rg exits 2 → that engine run fails), balanced 'a{b}' silently searches
// 'ab' instead of the literal. Both verified against real rg 15; '\{' is the
// accepted escape.
it('escapes braces so alternation syntax cannot hijack a literal query', () => {
expect(escapeGlob('a{b}')).toBe('a\\{b\\}')
expect(escapeGlob('{')).toBe('\\{')
@@ -245,6 +246,32 @@ describe('engine argv symmetry', () => {
expect(argv[argv.length - 1]).toBe('.')
})
// Regression: `fd ... -foo .` made fd parse the query as an option. `--`
// must sit AFTER all options (and their values) and BEFORE the query, with
// the trailing `.` path still a positional.
it('fd argv puts `--` immediately before the query', () => {
const argv = fdArgv(10, '-foo')
const dash = argv.indexOf('--')
expect(dash).toBe(argv.length - 3)
expect(argv[dash + 1]).toBe('-foo') // literal, unescaped
expect(argv[dash + 2]).toBe('.')
// The last option's value precedes the separator; nothing after it is an option.
expect(argv[dash - 1]).toBe('11')
expect(argv.slice(0, dash)).toContain('--fixed-strings')
})
it('a `--`-leading query stays positional too', () => {
const argv = fdArgv(10, '--hidden')
expect(argv[argv.indexOf('--') + 1]).toBe('--hidden')
expect(argv[argv.length - 1]).toBe('.')
})
it('the `--type d` invocation keeps `--` before the pattern', () => {
const argv = fdArgv(10, '-foo', 'd')
expect(argv[argv.indexOf('--') + 1]).toBe('-foo')
expect(argv.indexOf('--type')).toBeLessThan(argv.indexOf('--'))
})
// fd cannot label its matches, so the directory subset comes from a second
// invocation restricted to directories. The filter must not disturb the
// sentinel/truncation contract of the main run.
@@ -437,8 +464,9 @@ describe('bundledRgCandidates', () => {
})
})
describe('probe cache and broken-disable', () => {
describe('probe cache and failure handling', () => {
afterEach(() => {
vi.useRealTimers()
resetEngines()
})
@@ -449,16 +477,51 @@ describe('probe cache and broken-disable', () => {
expect(calls).toBe(1)
})
it('usableEngines hides engines broken at runtime', async () => {
// Regression: one bad query used to add fd to the broken set forever, so
// every later search silently fell back to the slow plain walk.
it('a single runtime failure leaves the engine usable for the next search', async () => {
setEngineHooks({ prober: async () => [fdProbe, rgProbe] })
let calls = 0
setEngineHooks({
runner: async () => { throw new Error('boom') },
runner: async () => { calls += 1; throw new Error('boom') },
})
await runEngine(fdProbe, '/w', 'x', 10).catch(() => {
/* the failing runner above */
})
const usable = await usableEngines()
expect(usable.map(probe => probe.engine)).toEqual(['rg'])
expect((await usableEngines()).map(probe => probe.engine)).toEqual(['fd', 'rg'])
// The caller can actually try it again instead of being locked to the walk.
await runEngine(fdProbe, '/w', 'x', 10).catch(() => {})
expect(calls).toBe(2)
})
it('repeated consecutive failures still disable the engine', async () => {
setEngineHooks({ prober: async () => [fdProbe, rgProbe] })
setEngineHooks({ runner: async () => { throw new Error('boom') } })
// BROKEN_AFTER = 3: a genuinely dead binary must not slow every search,
// while a single failure (above) must not disable one.
for (let i = 0; i < 3; i += 1) {
await runEngine(fdProbe, '/w', 'x', 10).catch(() => {})
}
expect((await usableEngines()).map(probe => probe.engine)).toEqual(['rg'])
})
it('a successful run clears the consecutive-failure streak', async () => {
setEngineHooks({ prober: async () => [fdProbe] })
let fail = true
setEngineHooks({
runner: async () => {
if (fail) throw new Error('boom')
return { paths: [], dirs: [], truncated: false }
},
})
await runEngine(fdProbe, '/w', 'x', 10).catch(() => {})
await runEngine(fdProbe, '/w', 'x', 10).catch(() => {})
fail = false
await runEngine(fdProbe, '/w', 'x', 10)
// Two failures, a success, then one more: only one in a row, still usable.
fail = true
await runEngine(fdProbe, '/w', 'x', 10).catch(() => {})
expect((await usableEngines()).map(probe => probe.engine)).toEqual(['fd'])
})
// A timeout means THIS tree was too big — the broken-set is per-engine,
@@ -474,6 +537,68 @@ describe('probe cache and broken-disable', () => {
})
expect((await usableEngines()).map(probe => probe.engine)).toEqual(['fd'])
})
// A timeout must break the consecutive-failure streak like a success:
// otherwise the residual count from two earlier failures rolls into the
// next one and "fail, fail, timeout, fail" disables a healthy engine,
// contradicting "only repeated consecutive failures".
it('a timeout breaks the streak (fail, fail, timeout, fail does not disable)', async () => {
setEngineHooks({ prober: async () => [fdProbe, rgProbe] })
const outcomes = ['fail', 'fail', 'timeout', 'fail'] as const
let step = 0
setEngineHooks({
runner: async () => {
const outcome = outcomes[step]
step += 1
if (outcome === 'timeout') throw new EngineTimeoutError('search engine timed out')
throw new Error('boom')
},
})
for (let i = 0; i < outcomes.length; i += 1) {
await runEngine(fdProbe, '/w', 'x', 10).catch(() => {})
}
expect((await usableEngines()).map(probe => probe.engine)).toEqual(['fd', 'rg'])
})
// Concurrency: three failures can add `broken` while a fourth, in-flight
// request later succeeds. The success clears `failures` — it must also lift
// `broken`, or usableEngines() keeps filtering out an engine that recovered.
it('a success after the streak tripped BROKEN_AFTER re-enables the engine', async () => {
setEngineHooks({ prober: async () => [fdProbe, rgProbe] })
let call = 0
setEngineHooks({
runner: async () => {
call += 1
if (call <= 3) throw new Error('boom')
return { paths: [], dirs: [], truncated: false }
},
})
const calls = [
runEngine(fdProbe, '/w', 'x', 10),
runEngine(fdProbe, '/w', 'x', 10),
runEngine(fdProbe, '/w', 'x', 10),
runEngine(fdProbe, '/w', 'x', 10),
]
await Promise.allSettled(calls)
expect((await usableEngines()).map(probe => probe.engine)).toEqual(['fd', 'rg'])
})
// Disabling is not permanent: without the cooldown the only way back is a
// process restart, which is how a transient cause (a replaced binary, one
// EMFILE burst) used to cost the fast path for the rest of the session.
it('retries a disabled engine once the cooldown elapses', async () => {
vi.useFakeTimers()
vi.setSystemTime(0)
setEngineHooks({ prober: async () => [fdProbe, rgProbe] })
setEngineHooks({ runner: async () => { throw new Error('boom') } })
for (let i = 0; i < 3; i += 1) {
await runEngine(fdProbe, '/w', 'x', 10).catch(() => {})
}
expect((await usableEngines()).map(probe => probe.engine)).toEqual(['rg'])
vi.setSystemTime(60_000)
expect((await usableEngines()).map(probe => probe.engine)).toEqual(['fd', 'rg'])
})
})
/**
@@ -519,7 +644,7 @@ describe('real engines (only when installed)', () => {
// (verified against real rg 15.2.0: unescaped '*a[b]*' returns
// 'ab.ts', escaped '*a\[b\]*' returns 'a[b].ts'). Deliberately NOT an
// UNCLOSED 'a[b': rg refuses the glob outright ("unclosed character
// class", exit 2), the engine gets dropped as broken and the plain-walk
// class", exit 2), that engine run fails and the plain-walk
// fallback satisfies the assertion by accident.
const meta = process.platform === 'win32'
? { file: 'a[b].ts', decoy: 'ab.ts', query: 'a[b]' }
@@ -652,9 +777,10 @@ describe('streamLines settles on close, not exit', () => {
first.emit('exit', 0)
first.emit('close', 0)
// The --type d run dies: a rejection, which must reach runEngine's
// broken-marking instead of degrading into "zero directories".
// failure handling instead of degrading into "zero directories".
second.emit('error', new Error('fd dirs stream exploded'))
await expect(call).rejects.toThrow('fd dirs stream exploded')
expect((await usableEngines()).map(probe => probe.engine)).toEqual([])
// One failed run must not permanently drop fd: the next search can retry.
expect((await usableEngines()).map(probe => probe.engine)).toEqual(['fd'])
})
})
+204
View File
@@ -0,0 +1,204 @@
/**
* The task window's edit save is a CAS write: `expectedRevision` must be the
* revision the draft was OPENED against, not the live one the projection keeps
* pushing while the window stays open. Saving with the live revision makes the
* host's conflict check a no-op and silently overwrites a teammate's write.
*/
// @vitest-environment jsdom
import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'
import { createElement } from 'react'
import { createRoot, type Root } from 'react-dom/client'
import { act } from 'react-dom/test-utils'
import { TaskWindow } from '../src/client/TaskWindow.tsx'
import type { Context, SidebarTeamTaskView } from '../src/context-types.ts'
import { setupReactAct } from './test-utils.ts'
setupReactAct()
// vitest follows the OS locale; pin en-US so the button copy is English.
beforeAll(() => {
Object.defineProperty(window.navigator, 'language', { value: 'en-US', configurable: true })
})
const { teamsTaskUpdate } = vi.hoisted(() => ({
teamsTaskUpdate: vi.fn(async () => ({ ok: true })),
}))
vi.mock('../src/client/api.ts', async (importOriginal) => {
const actual = await importOriginal<typeof import('../src/client/api.ts')>()
return { ...actual, api: { ...actual.api, teamsTaskUpdate } }
})
function taskView(revision: number, subject: string): SidebarTeamTaskView {
return {
id: 't1',
revision,
subject,
description: 'body',
status: 'in_progress',
blockedBy: [],
writeScopes: [],
ready: true,
writeScopeWarnings: [],
}
}
let container: HTMLDivElement
let root: Root
/** Render — or RE-render in place — the one window, as the projection does
* when a teammate's write lands during an open edit. */
async function render(task: SidebarTeamTaskView): Promise<void> {
await act(async () => {
root.render(createElement(TaskWindow, {
rootId: 'root-1',
task,
members: [],
ctx: {} as Context,
onClose: () => {},
}))
})
}
/** One footer button by its copy (the window is body-portaled). */
function button(label: string): HTMLElement {
const found = [...document.querySelectorAll<HTMLElement>('button')]
.find(el => el.textContent?.trim() === label)
if (found === undefined) throw new Error(`button not found: ${label}`)
return found
}
afterEach(() => {
act(() => { root.unmount() })
container.remove()
document.body.innerHTML = ''
teamsTaskUpdate.mockClear()
})
describe('TaskWindow edit revision snapshot', () => {
beforeEach(() => {
container = document.createElement('div')
document.body.append(container)
root = createRoot(container)
})
it('saves against the revision present when editing opened, not the live one', async () => {
await render(taskView(1, 'First'))
act(() => { button('Edit').click() })
// A teammate's write lands while the draft is open: the projection hands
// over revision 2, but the draft still describes revision 1.
await render(taskView(2, 'Changed elsewhere'))
await act(async () => { button('Save').click() })
expect(teamsTaskUpdate).toHaveBeenCalledWith('root-1', expect.objectContaining({
taskId: 't1',
action: 'edit',
expectedRevision: 1,
}))
})
it('re-bases the snapshot when editing is reopened', async () => {
await render(taskView(1, 'First'))
act(() => { button('Edit').click() })
act(() => { button('Cancel').click() })
await render(taskView(3, 'Changed elsewhere'))
act(() => { button('Edit').click() })
await act(async () => { button('Save').click() })
expect(teamsTaskUpdate).toHaveBeenCalledWith('root-1', expect.objectContaining({
expectedRevision: 3,
}))
})
it('re-seeds the draft when Edit is reopened after the task changed', async () => {
await render(taskView(1, 'First'))
// A teammate's write lands while the window sits in the read-only view.
await render(taskView(2, 'Changed elsewhere'))
act(() => { button('Edit').click() })
// The edit box must show what the view shows: the draft and the CAS base
// have to describe the same read, or Save overwrites the teammate silently.
expect(document.querySelector<HTMLInputElement>('input[aria-label="Subject"]')!.value)
.toBe('Changed elsewhere')
await act(async () => { button('Save').click() })
expect(teamsTaskUpdate).toHaveBeenCalledWith('root-1', expect.objectContaining({
expectedRevision: 2,
subject: 'Changed elsewhere',
}))
})
it('waits for the projection before re-basing after a conflict', async () => {
await render(taskView(1, 'First'))
act(() => { button('Edit').click() })
teamsTaskUpdate
.mockImplementationOnce(async () => ({ ok: false, code: 'team-conflict', message: 'stale' }))
.mockImplementationOnce(async () => ({ ok: true }))
// The conflict comes back BEFORE the teammate's write reaches this window,
// so there is no newer revision to re-base onto yet.
await act(async () => { button('Save').click() })
expect(teamsTaskUpdate).toHaveBeenNthCalledWith(1, 'root-1', expect.objectContaining({
expectedRevision: 1,
}))
// The projection catches up; the next Save must use the new revision
// instead of re-submitting the one the server just rejected.
await render(taskView(2, 'Changed elsewhere'))
await act(async () => { button('Save').click() })
expect(teamsTaskUpdate).toHaveBeenNthCalledWith(2, 'root-1', expect.objectContaining({
expectedRevision: 2,
}))
})
it('re-bases after a conflict so the next Save commits, keeping the draft', async () => {
await render(taskView(1, 'First'))
act(() => { button('Edit').click() })
// The reader types a real draft into both fields.
await act(async () => {
const subject = document.querySelector<HTMLInputElement>('input[aria-label="Subject"]')!
const subjectSetter = Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype, 'value')?.set
subjectSetter?.call(subject, 'My draft')
subject.dispatchEvent(new Event('input', { bubbles: true }))
const area = document.querySelector<HTMLTextAreaElement>('textarea[aria-label="Description"]')!
const areaSetter = Object.getOwnPropertyDescriptor(window.HTMLTextAreaElement.prototype, 'value')?.set
areaSetter?.call(area, 'draft body')
area.dispatchEvent(new Event('input', { bubbles: true }))
})
// A teammate's write lands while the draft is open: projection → rev2.
await render(taskView(2, 'Changed elsewhere'))
// First Save carries the stale rev1 snapshot → rejected (409 team-conflict,
// which does NOT advance the revision). Second Save must use rev2 → ok.
teamsTaskUpdate
.mockImplementationOnce(async () => ({ ok: false, code: 'team-conflict', message: 'stale' }))
.mockImplementationOnce(async () => ({ ok: true }))
await act(async () => { button('Save').click() })
expect(teamsTaskUpdate).toHaveBeenNthCalledWith(1, 'root-1', expect.objectContaining({
action: 'edit',
expectedRevision: 1,
subject: 'My draft',
description: 'draft body',
}))
// The conflict is reported, but the draft is NOT discarded and editing is
// NOT left (the only exit used to throw away unsaved text): the textarea
// is still here with the reader's text, not the task's current content.
expect(document.body.textContent).toContain('The task changed elsewhere; refreshed')
const kept = document.querySelector<HTMLTextAreaElement>('textarea[aria-label="Description"]')!
expect(kept.value).toBe('draft body')
// Second Save now submits against the re-based rev2 and succeeds (the
// window returns to the read-only view, i.e. the Edit button is back).
await act(async () => { button('Save').click() })
expect(teamsTaskUpdate).toHaveBeenNthCalledWith(2, 'root-1', expect.objectContaining({
action: 'edit',
expectedRevision: 2,
subject: 'My draft',
description: 'draft body',
}))
expect(button('Edit')).toBeDefined()
})
})
+135
View File
@@ -12,6 +12,18 @@
* The second case pins the other side of the contract: a genuinely different
* document must still run the original file-switch reset (preview mode, no
* draft, clean editor, conflict cleared, new baseline) unchanged.
*
* The third case is a save still in flight: keystrokes made after the write
* was sent are NOT the bytes on disk, so the tab must stay dirty and keep its
* durable backup instead of declaring itself saved (which would let the next
* close/quit drop those edits silently).
*
* The fourth case is the cross-file save race (#3): a save sent for file A is
* still in flight when the viewer switches to file B — the [content, path]
* effect destroys A's view and points viewRef at B's. An expired result may
* only release the save lock (and adopt the server's mtime): it must not write
* A's text / save state into B's draft, while typing during a save of the
* CURRENT file still keeps that tab dirty (the third case above).
*/
// @vitest-environment jsdom
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
@@ -36,8 +48,18 @@ vi.mock('../src/client/api.ts', async (importOriginal) => {
}
})
const { clearDraftBackup } = vi.hoisted(() => ({ clearDraftBackup: vi.fn() }))
vi.mock('../src/client/editor-draft-backup.ts', async (importOriginal) => {
const actual = await importOriginal<typeof import('../src/client/editor-draft-backup.ts')>()
return { ...actual, clearDraftBackup: (...args: unknown[]) => clearDraftBackup(...args) }
})
const CONTENT = 'const a = 1\n'
const NEXT_CONTENT = 'const a = 2\n'
// Distinct markdown headings: the preview renders whichever document `draft`
// currently holds, so a leaked draft from file A is visible in the DOM.
const A_CONTENT = '# A-source-heading\n'
const B_CONTENT = '# B-clean-heading\n'
function viewerProps(overrides: Partial<FileViewerProps> = {}): FileViewerProps {
return {
@@ -112,6 +134,7 @@ function type(view: EditorView, insert: string): void {
beforeEach(() => {
fsWrite.mockReset()
fsWrite.mockResolvedValue({ ok: true, mtimeMs: 999 })
clearDraftBackup.mockClear()
})
afterEach(() => {
@@ -160,4 +183,116 @@ describe('TextEditor save baseline (#1059)', () => {
editor.unmount()
}
})
it('keeps typing done while the write is in flight unsaved', async () => {
let finish: ((value: { ok: true; mtimeMs: number }) => void) | undefined
fsWrite.mockImplementation(() => new Promise<{ ok: true; mtimeMs: number }>((resolve) => { finish = resolve }))
const editor = mountEditor()
try {
// Mount may decline a leftover draft backup (jsdom's confirm is a no-op);
// only the save callback's clear is under test here.
clearDraftBackup.mockClear()
const view = editor.view()
type(view, '// first\n')
await act(async () => { editor.controls().save() })
expect(editor.state().saveState).toBe('saving')
type(view, '// typed during save\n')
await act(async () => {
finish?.({ ok: true, mtimeMs: 999 })
await Promise.resolve()
await Promise.resolve()
})
expect(editor.state().dirty).toBe(true)
expect(editor.state().saveState).toBe('idle')
expect(clearDraftBackup).not.toHaveBeenCalled()
// The next save re-sends the live document against the NEW baseline.
fsWrite.mockResolvedValue({ ok: true, mtimeMs: 1000 })
await act(async () => { editor.controls().save() })
await act(async () => { await Promise.resolve() })
expect(fsWrite.mock.calls[1]![2]).toBe('// typed during save\n// first\n' + CONTENT)
expect(fsWrite.mock.calls[1]![3]).toBe(999)
} finally {
editor.unmount()
}
})
it('lets an in-flight save from the previous file expire without touching the new file', async () => {
let finish: ((value: { ok: true; mtimeMs: number }) => void) | undefined
fsWrite.mockImplementation(() => new Promise<{ ok: true; mtimeMs: number }>((resolve) => { finish = resolve }))
const editor = mountEditor()
try {
clearDraftBackup.mockClear()
const view = editor.view()
type(view, '// first\n')
await act(async () => { editor.controls().save() })
expect(editor.state().saveState).toBe('saving')
// A genuinely different document: the file-switch effect destroys the
// view the save captured and re-seats a clean one for NEXT_CONTENT.
editor.rerender({ content: NEXT_CONTENT, mtimeMs: 400 })
expect(editor.view().state.doc.toString()).toBe(NEXT_CONTENT)
expect(editor.state()).toMatchObject({ mode: 'preview', dirty: false, saveState: 'idle' })
clearDraftBackup.mockClear()
await act(async () => {
finish?.({ ok: true, mtimeMs: 999 })
await Promise.resolve()
await Promise.resolve()
})
// The result belongs to A: it must not declare B saved, drop B's
// durable backup, or move B's dirty/draft state.
expect(editor.state()).toMatchObject({ dirty: false, saveState: 'idle' })
expect(clearDraftBackup).not.toHaveBeenCalled()
// The save lock was released, so B can still save normally.
fsWrite.mockResolvedValue({ ok: true, mtimeMs: 1000 })
await act(async () => { editor.controls().save() })
await act(async () => { await Promise.resolve() })
expect(fsWrite).toHaveBeenCalledTimes(2)
expect(fsWrite.mock.calls[1]![2]).toBe(NEXT_CONTENT)
} finally {
editor.unmount()
}
})
it('does not publish the old file text as the new file draft when a save expires', async () => {
let finish: ((value: { ok: true; mtimeMs: number }) => void) | undefined
fsWrite.mockImplementation(() => new Promise<{ ok: true; mtimeMs: number }>((resolve) => { finish = resolve }))
const editor = mountEditor({
viewerId: 'markdown', path: '/p/a.md', title: 'a.md',
content: A_CONTENT, mtimeMs: 100,
})
try {
clearDraftBackup.mockClear()
act(() => { editor.controls().setMode('edit') })
const view = editor.view()
type(view, 'LEAK-FROM-A\n')
await act(async () => { editor.controls().save() })
expect(editor.state().saveState).toBe('saving')
// More keystrokes while the write is in flight: the old view's live
// document no longer equals the bytes that were sent, which is the
// branch that used to call setDraft(live).
type(view, 'MORE-FROM-A\n')
editor.rerender({ content: B_CONTENT, mtimeMs: 400 })
expect(editor.view().state.doc.toString()).toBe(B_CONTENT)
expect(editor.container.textContent).toContain('B-clean-heading')
expect(editor.state()).toMatchObject({ mode: 'preview', dirty: false, saveState: 'idle' })
clearDraftBackup.mockClear()
await act(async () => {
finish?.({ ok: true, mtimeMs: 999 })
await Promise.resolve()
await Promise.resolve()
})
// The preview still renders B's own content, not A's leaked text.
expect(editor.container.textContent).toContain('B-clean-heading')
expect(editor.container.textContent).not.toContain('MORE-FROM-A')
expect(editor.state()).toMatchObject({ dirty: false, saveState: 'idle' })
expect(clearDraftBackup).not.toHaveBeenCalled()
// The save lock was released, so B can still save normally.
fsWrite.mockResolvedValue({ ok: true, mtimeMs: 1000 })
await act(async () => { editor.controls().save() })
await act(async () => { await Promise.resolve() })
expect(fsWrite).toHaveBeenCalledTimes(2)
expect(fsWrite.mock.calls[1]![2]).toBe(B_CONTENT)
} finally {
editor.unmount()
}
})
})
+3
View File
@@ -54,6 +54,9 @@ export default defineConfig({
// list is the only thing vitest reads. Left out, `pnpm test` collects
// those stale copies and reports THEIR failures as ours.
'**/.delta/**',
// Same for the agent worktree lanes (and the reason `pnpm lint` needs
// the matching ignore): their spec copies would double-collect.
'**/.agents/worktrees/**',
'**/node_modules/**',
'**/dist/**',
'**/cypress/**',