mirror of
https://github.com/anomalyco/opencode.git
synced 2026-11-28 19:14:53 +00:00
fix(app): reload a file tree directory changed during its listing (#61814)
This commit is contained in:
parent
64ca766ff7
commit
e42ac691d5
6 changed files with 819 additions and 143 deletions
300
packages/app/src/workspaces/files/tree-machine.test.ts
Normal file
300
packages/app/src/workspaces/files/tree-machine.test.ts
Normal file
|
|
@ -0,0 +1,300 @@
|
|||
import { describe, expect, test } from "bun:test"
|
||||
import type { FileNode } from "@/runtime/server/types"
|
||||
import {
|
||||
canRefreshDirectory,
|
||||
createFileTreeState,
|
||||
DIRECTORY_LIST_TIMEOUT_MS,
|
||||
isDirectoryLoaded,
|
||||
isDirectoryLoading,
|
||||
selectDirectoryChildren,
|
||||
selectDirectoryError,
|
||||
transitionFileTree,
|
||||
type FileTreeEffect,
|
||||
type FileTreeEvent,
|
||||
type FileTreeState,
|
||||
} from "./tree-machine"
|
||||
|
||||
// The server ends directory paths with the platform separator (`FileSystem.list` in packages/core/src/filesystem.ts).
|
||||
const file = (path: string): FileNode => ({
|
||||
path,
|
||||
type: "file",
|
||||
name: path.split("/").at(-1) ?? path,
|
||||
absolute: `/repo/${path}`,
|
||||
ignored: false,
|
||||
})
|
||||
|
||||
const directory = (path: string): FileNode => ({
|
||||
path: `${path}/`,
|
||||
type: "directory",
|
||||
name: path.split("/").at(-1) ?? path,
|
||||
absolute: `/repo/${path}`,
|
||||
ignored: false,
|
||||
})
|
||||
|
||||
function replay(events: readonly FileTreeEvent[], state = createFileTreeState()) {
|
||||
return events.reduce<{ state: FileTreeState; effects: FileTreeEffect[] }>(
|
||||
(current, event) => {
|
||||
const result = transitionFileTree(current.state, event)
|
||||
|
||||
return { state: result.state, effects: [...current.effects, ...result.effects] }
|
||||
},
|
||||
{ state, effects: [] },
|
||||
)
|
||||
}
|
||||
|
||||
const dir = (state: FileTreeState, path: string) => (state.status === "active" ? state.dirs[path] : undefined)
|
||||
|
||||
const paths = (state: FileTreeState, path: string) => selectDirectoryChildren(state, path).map((node) => node.path)
|
||||
|
||||
const list = (path: string, attempt: number): FileTreeEffect => ({
|
||||
type: "list",
|
||||
dir: path,
|
||||
attempt,
|
||||
timeoutMs: DIRECTORY_LIST_TIMEOUT_MS,
|
||||
})
|
||||
|
||||
describe("file tree machine", () => {
|
||||
test("a forced reload during a listing runs one follow-up listing instead of joining it", () => {
|
||||
const started = replay([{ type: "list.requested", dir: "src", force: false }])
|
||||
expect(started.effects).toEqual([list("src", 1)])
|
||||
|
||||
const queued = replay(
|
||||
[
|
||||
{ type: "list.requested", dir: "src", force: true },
|
||||
{ type: "list.requested", dir: "src", force: true },
|
||||
],
|
||||
started.state,
|
||||
)
|
||||
|
||||
expect(queued.effects).toEqual([])
|
||||
expect(dir(queued.state, "src")).toMatchObject({ status: "loading", attempt: 1, dirty: true })
|
||||
expect(transitionFileTree(queued.state, { type: "list.requested", dir: "src", force: true }).state).toBe(
|
||||
queued.state,
|
||||
)
|
||||
|
||||
// The first read happened before `b.ts` was created: its result shows at once, and the follow-up reads again.
|
||||
const first = transitionFileTree(queued.state, {
|
||||
type: "list.loaded",
|
||||
dir: "src",
|
||||
attempt: 1,
|
||||
nodes: [file("src/a.ts")],
|
||||
})
|
||||
|
||||
expect(paths(first.state, "src")).toEqual(["src/a.ts"])
|
||||
expect(dir(first.state, "src")).toMatchObject({ status: "refreshing", attempt: 2, dirty: false })
|
||||
expect(first.effects).toEqual([list("src", 2)])
|
||||
|
||||
const second = transitionFileTree(first.state, {
|
||||
type: "list.loaded",
|
||||
dir: "src",
|
||||
attempt: 2,
|
||||
nodes: [file("src/a.ts"), file("src/b.ts")],
|
||||
})
|
||||
|
||||
expect(paths(second.state, "src")).toEqual(["src/a.ts", "src/b.ts"])
|
||||
expect(dir(second.state, "src")?.status).toBe("ready")
|
||||
expect(second.effects).toEqual([])
|
||||
})
|
||||
|
||||
test("a watcher change during a directory's first listing can reload it", () => {
|
||||
const loading = replay([{ type: "dir.expanded", dir: "src", list: true }]).state
|
||||
|
||||
expect(canRefreshDirectory(loading, "src")).toBe(true)
|
||||
expect(canRefreshDirectory(loading, "lib")).toBe(false)
|
||||
|
||||
const failed = replay(
|
||||
[
|
||||
{ type: "list.requested", dir: "lib", force: false },
|
||||
{ type: "list.failed", dir: "lib", attempt: 2, error: "boom" },
|
||||
],
|
||||
loading,
|
||||
).state
|
||||
|
||||
expect(canRefreshDirectory(failed, "lib")).toBe(false)
|
||||
|
||||
const queued = transitionFileTree(loading, { type: "list.requested", dir: "src", force: true })
|
||||
|
||||
const loaded = transitionFileTree(queued.state, {
|
||||
type: "list.loaded",
|
||||
dir: "src",
|
||||
attempt: 1,
|
||||
nodes: [file("src/a.ts")],
|
||||
})
|
||||
|
||||
expect(loaded.effects).toEqual([list("src", 2)])
|
||||
})
|
||||
|
||||
test("results from before a workspace reset never land in the new workspace", () => {
|
||||
const before = replay([{ type: "list.requested", dir: "", force: false }]).state
|
||||
const reset = transitionFileTree(before, { type: "reset" }).state
|
||||
expect(reset).toMatchObject({ epoch: 1, issued: 1 })
|
||||
|
||||
const after = transitionFileTree(reset, { type: "list.requested", dir: "", force: false })
|
||||
expect(after.effects).toEqual([list("", 2)])
|
||||
|
||||
const late: FileTreeEvent[] = [
|
||||
{ type: "list.loaded", dir: "", attempt: 1, nodes: [file("a.ts")] },
|
||||
{ type: "list.failed", dir: "", attempt: 1, error: "gone" },
|
||||
{ type: "list.timed-out", dir: "", attempt: 1 },
|
||||
]
|
||||
|
||||
late.forEach((event) => {
|
||||
const result = transitionFileTree(after.state, event)
|
||||
expect(result.state).toBe(after.state)
|
||||
expect(result.effects).toEqual([])
|
||||
})
|
||||
})
|
||||
|
||||
test("a failed reload keeps the listed entries without an error, and a failed first listing reports it", () => {
|
||||
const ready = replay([
|
||||
{ type: "list.requested", dir: "src", force: false },
|
||||
{ type: "list.loaded", dir: "src", attempt: 1, nodes: [file("src/a.ts")] },
|
||||
]).state
|
||||
|
||||
const reloaded = replay(
|
||||
[
|
||||
{ type: "list.requested", dir: "src", force: true },
|
||||
{ type: "list.failed", dir: "src", attempt: 2, error: "boom" },
|
||||
],
|
||||
ready,
|
||||
)
|
||||
|
||||
const entry = dir(reloaded.state, "src")
|
||||
expect(entry?.status).toBe("ready")
|
||||
expect(isDirectoryLoaded(entry)).toBe(true)
|
||||
expect(isDirectoryLoading(entry)).toBe(false)
|
||||
expect(selectDirectoryError(entry)).toBeUndefined()
|
||||
expect(paths(reloaded.state, "src")).toEqual(["src/a.ts"])
|
||||
expect(reloaded.effects).toEqual([list("src", 2)])
|
||||
|
||||
const failed = replay([
|
||||
{ type: "list.requested", dir: "src", force: false },
|
||||
{ type: "list.failed", dir: "src", attempt: 1, error: "boom" },
|
||||
])
|
||||
|
||||
expect(isDirectoryLoaded(dir(failed.state, "src"))).toBe(false)
|
||||
expect(selectDirectoryError(dir(failed.state, "src"))).toBe("boom")
|
||||
expect(failed.effects.at(-1)).toEqual({ type: "notify.error", message: "boom" })
|
||||
|
||||
// Opening the directory again retries it.
|
||||
expect(transitionFileTree(failed.state, { type: "dir.expanded", dir: "src", list: true }).effects).toEqual([
|
||||
list("src", 2),
|
||||
])
|
||||
})
|
||||
|
||||
test.each([
|
||||
["removed", [file("src/a.ts")]],
|
||||
["replaced by a file", [file("src/a.ts"), file("src/sub")]],
|
||||
])("a subdirectory %s drops its entries and its listing state", (_, next) => {
|
||||
const loaded = replay([
|
||||
{ type: "list.requested", dir: "src", force: false },
|
||||
{ type: "list.loaded", dir: "src", attempt: 1, nodes: [file("src/a.ts"), directory("src/sub")] },
|
||||
{ type: "dir.expanded", dir: "src/sub", list: true },
|
||||
{ type: "list.loaded", dir: "src/sub", attempt: 2, nodes: [file("src/sub/old.ts"), directory("src/sub/deep")] },
|
||||
{ type: "dir.expanded", dir: "src/sub/deep", list: true },
|
||||
]).state
|
||||
|
||||
const refreshed = replay(
|
||||
[
|
||||
{ type: "list.requested", dir: "src", force: true },
|
||||
{ type: "list.loaded", dir: "src", attempt: 4, nodes: next },
|
||||
],
|
||||
loaded,
|
||||
).state
|
||||
|
||||
expect(refreshed.status === "active" && Object.keys(refreshed.dirs).sort()).toEqual(["", "src"])
|
||||
expect(refreshed.status === "active" && Object.keys(refreshed.nodes).sort()).toEqual(
|
||||
next.map((node) => node.path).sort(),
|
||||
)
|
||||
|
||||
// The pruned in-flight listing of `src/sub/deep` lands nowhere.
|
||||
expect(
|
||||
transitionFileTree(refreshed, { type: "list.loaded", dir: "src/sub/deep", attempt: 3, nodes: [] }).state,
|
||||
).toBe(refreshed)
|
||||
|
||||
// A re-created directory lists again instead of showing as empty.
|
||||
expect(transitionFileTree(refreshed, { type: "dir.expanded", dir: "src/sub", list: true }).effects).toEqual([
|
||||
list("src/sub", 5),
|
||||
])
|
||||
})
|
||||
|
||||
test("a timeout ends the listing: a first listing fails, a reload keeps its entries, a queued reload runs", () => {
|
||||
const loading = replay([{ type: "list.requested", dir: "src", force: false }]).state
|
||||
const failed = transitionFileTree(loading, { type: "list.timed-out", dir: "src", attempt: 1 })
|
||||
expect(dir(failed.state, "src")).toEqual({ status: "failed", expanded: false, error: undefined })
|
||||
expect(failed.effects).toEqual([{ type: "notify.error", message: "" }])
|
||||
|
||||
const refreshing = replay(
|
||||
[
|
||||
{ type: "list.loaded", dir: "src", attempt: 1, nodes: [file("src/a.ts")] },
|
||||
{ type: "list.requested", dir: "src", force: true },
|
||||
],
|
||||
loading,
|
||||
).state
|
||||
|
||||
const kept = transitionFileTree(refreshing, { type: "list.timed-out", dir: "src", attempt: 2 })
|
||||
expect(dir(kept.state, "src")).toEqual({ status: "ready", expanded: false, children: ["src/a.ts"] })
|
||||
expect(kept.effects).toEqual([])
|
||||
|
||||
const queued = transitionFileTree(refreshing, { type: "list.requested", dir: "src", force: true }).state
|
||||
const retried = transitionFileTree(queued, { type: "list.timed-out", dir: "src", attempt: 2 })
|
||||
expect(dir(retried.state, "src")).toMatchObject({ status: "refreshing", attempt: 3, dirty: false })
|
||||
expect(retried.effects).toEqual([list("src", 3)])
|
||||
})
|
||||
|
||||
test("expanding and collapsing keep the listing and list only when asked", () => {
|
||||
const initial = createFileTreeState()
|
||||
|
||||
const filtered = transitionFileTree(initial, { type: "dir.expanded", dir: "src", list: false })
|
||||
expect(dir(filtered.state, "src")).toEqual({ status: "idle", expanded: true })
|
||||
expect(filtered.effects).toEqual([])
|
||||
expect(transitionFileTree(filtered.state, { type: "dir.expanded", dir: "src", list: false }).state).toBe(
|
||||
filtered.state,
|
||||
)
|
||||
|
||||
const collapsed = transitionFileTree(initial, { type: "dir.collapsed", dir: "src" }).state
|
||||
expect(dir(collapsed, "src")).toEqual({ status: "idle", expanded: false })
|
||||
expect(transitionFileTree(collapsed, { type: "dir.collapsed", dir: "src" }).state).toBe(collapsed)
|
||||
|
||||
const ready = replay(
|
||||
[
|
||||
{ type: "dir.expanded", dir: "src", list: true },
|
||||
{ type: "list.loaded", dir: "src", attempt: 1, nodes: [file("src/a.ts")] },
|
||||
{ type: "dir.collapsed", dir: "src" },
|
||||
],
|
||||
initial,
|
||||
).state
|
||||
|
||||
expect(paths(ready, "src")).toEqual(["src/a.ts"])
|
||||
|
||||
const reopened = transitionFileTree(ready, { type: "dir.expanded", dir: "src", list: true })
|
||||
expect(dir(reopened.state, "src")).toMatchObject({ status: "ready", expanded: true })
|
||||
expect(reopened.effects).toEqual([])
|
||||
expect(transitionFileTree(reopened.state, { type: "list.requested", dir: "src", force: false }).state).toBe(
|
||||
reopened.state,
|
||||
)
|
||||
})
|
||||
|
||||
test("an untouched tree ignores a reset, and a disposed tree ignores everything", () => {
|
||||
const initial = createFileTreeState()
|
||||
expect(transitionFileTree(initial, { type: "reset" }).state).toBe(initial)
|
||||
|
||||
const loading = replay([{ type: "list.requested", dir: "src", force: false }]).state
|
||||
const disposed = transitionFileTree(loading, { type: "disposed" }).state
|
||||
expect(disposed).toEqual({ status: "disposed" })
|
||||
expect(canRefreshDirectory(disposed, "src")).toBe(false)
|
||||
|
||||
const events: FileTreeEvent[] = [
|
||||
{ type: "list.loaded", dir: "src", attempt: 1, nodes: [file("src/a.ts")] },
|
||||
{ type: "list.failed", dir: "src", attempt: 1, error: "boom" },
|
||||
{ type: "list.requested", dir: "src", force: true },
|
||||
{ type: "reset" },
|
||||
]
|
||||
|
||||
events.forEach((event) => {
|
||||
const result = transitionFileTree(disposed, event)
|
||||
expect(result.state).toBe(disposed)
|
||||
expect(result.effects).toEqual([])
|
||||
})
|
||||
})
|
||||
})
|
||||
286
packages/app/src/workspaces/files/tree-machine.ts
Normal file
286
packages/app/src/workspaces/files/tree-machine.ts
Normal file
|
|
@ -0,0 +1,286 @@
|
|||
import type { FileNode } from "@/runtime/server/types"
|
||||
|
||||
/** Bounded fallback so a wedged server or network mount cannot leave a directory loading forever. */
|
||||
export const DIRECTORY_LIST_TIMEOUT_MS = 30_000
|
||||
|
||||
/**
|
||||
* One directory's listing lifecycle, keyed by its normalized path. `expanded` holds in every status: collapsing keeps
|
||||
* the listed entries, and filtered trees expand directories with `list: false` without listing them. `dirty` records
|
||||
* a forced reload that arrived while `attempt` was in flight, so one follow-up listing runs after it.
|
||||
*/
|
||||
export type DirectoryState =
|
||||
| { readonly status: "idle"; readonly expanded: boolean }
|
||||
| { readonly status: "loading"; readonly expanded: boolean; readonly attempt: number; readonly dirty: boolean }
|
||||
| { readonly status: "ready"; readonly expanded: boolean; readonly children: readonly string[] }
|
||||
| {
|
||||
readonly status: "refreshing"
|
||||
readonly expanded: boolean
|
||||
readonly children: readonly string[]
|
||||
readonly attempt: number
|
||||
readonly dirty: boolean
|
||||
}
|
||||
| { readonly status: "failed"; readonly expanded: boolean; readonly error?: string }
|
||||
|
||||
/**
|
||||
* The file tree of one workspace. `epoch` counts workspace resets; `issued` keeps counting across them, so a listing
|
||||
* that started before a reset or before its directory was pruned never matches a later attempt.
|
||||
*/
|
||||
export type FileTreeState =
|
||||
| {
|
||||
readonly status: "active"
|
||||
readonly epoch: number
|
||||
readonly issued: number
|
||||
readonly nodes: Readonly<Record<string, FileNode>>
|
||||
readonly dirs: Readonly<Record<string, DirectoryState>>
|
||||
}
|
||||
| { readonly status: "disposed" }
|
||||
|
||||
export type FileTreeEvent =
|
||||
| { readonly type: "list.requested"; readonly dir: string; readonly force: boolean }
|
||||
| { readonly type: "dir.expanded"; readonly dir: string; readonly list: boolean }
|
||||
| { readonly type: "dir.collapsed"; readonly dir: string }
|
||||
| {
|
||||
readonly type: "list.loaded"
|
||||
readonly dir: string
|
||||
readonly attempt: number
|
||||
readonly nodes: readonly FileNode[]
|
||||
}
|
||||
| { readonly type: "list.failed"; readonly dir: string; readonly attempt: number; readonly error: string }
|
||||
| { readonly type: "list.timed-out"; readonly dir: string; readonly attempt: number }
|
||||
| { readonly type: "reset" }
|
||||
| { readonly type: "disposed" }
|
||||
|
||||
export type FileTreeEffect =
|
||||
| { readonly type: "list"; readonly dir: string; readonly attempt: number; readonly timeoutMs: number }
|
||||
| { readonly type: "notify.error"; readonly message: string }
|
||||
|
||||
export type FileTreeTransition = { readonly state: FileTreeState; readonly effects: readonly FileTreeEffect[] }
|
||||
|
||||
type ActiveTree = Extract<FileTreeState, { status: "active" }>
|
||||
|
||||
type BusyDirectory = Extract<DirectoryState, { status: "loading" | "refreshing" }>
|
||||
|
||||
// Not frozen: the driver reconciles states into a Solid store, which writes into the objects it already holds.
|
||||
export function createFileTreeState(): FileTreeState {
|
||||
return { status: "active", epoch: 0, issued: 0, nodes: {}, dirs: { "": { status: "idle", expanded: true } } }
|
||||
}
|
||||
|
||||
export function transitionFileTree(state: FileTreeState, event: FileTreeEvent): FileTreeTransition {
|
||||
if (state.status === "disposed") return unchanged(state)
|
||||
|
||||
if (event.type === "disposed") return { state: { status: "disposed" }, effects: [] }
|
||||
|
||||
if (event.type === "reset") {
|
||||
if (isPristine(state)) return unchanged(state)
|
||||
|
||||
return {
|
||||
state: {
|
||||
status: "active",
|
||||
epoch: state.epoch + 1,
|
||||
issued: state.issued,
|
||||
nodes: {},
|
||||
dirs: { "": { status: "idle", expanded: true } },
|
||||
},
|
||||
effects: [],
|
||||
}
|
||||
}
|
||||
|
||||
const entry = state.dirs[event.dir]
|
||||
|
||||
if (event.type === "list.requested") {
|
||||
if (!entry || entry.status === "idle" || entry.status === "failed") {
|
||||
return startListing(state, event.dir, (attempt) => ({
|
||||
status: "loading",
|
||||
expanded: entry?.expanded ?? false,
|
||||
attempt,
|
||||
dirty: false,
|
||||
}))
|
||||
}
|
||||
|
||||
if (entry.status === "ready") {
|
||||
if (!event.force) return unchanged(state)
|
||||
|
||||
return startListing(state, event.dir, (attempt) => ({ ...entry, status: "refreshing", attempt, dirty: false }))
|
||||
}
|
||||
|
||||
if (!event.force || entry.dirty) return unchanged(state)
|
||||
|
||||
return withDirectory(state, event.dir, { ...entry, dirty: true })
|
||||
}
|
||||
|
||||
if (event.type === "dir.expanded") {
|
||||
if (event.list && (!entry || entry.status === "idle" || entry.status === "failed")) {
|
||||
return startListing(state, event.dir, (attempt) => ({ status: "loading", expanded: true, attempt, dirty: false }))
|
||||
}
|
||||
|
||||
if (entry?.expanded) return unchanged(state)
|
||||
|
||||
return withDirectory(state, event.dir, entry ? { ...entry, expanded: true } : { status: "idle", expanded: true })
|
||||
}
|
||||
|
||||
if (event.type === "dir.collapsed") {
|
||||
if (entry && !entry.expanded) return unchanged(state)
|
||||
|
||||
return withDirectory(state, event.dir, entry ? { ...entry, expanded: false } : { status: "idle", expanded: false })
|
||||
}
|
||||
|
||||
// A result for a superseded attempt, a pruned directory or an earlier workspace.
|
||||
if (!entry || (entry.status !== "loading" && entry.status !== "refreshing") || entry.attempt !== event.attempt) {
|
||||
return unchanged(state)
|
||||
}
|
||||
|
||||
if (event.type === "list.loaded") return applyListing(state, event.dir, entry, event.nodes)
|
||||
|
||||
// The queued reload runs before a failure is reported: the change that queued it may have fixed the directory.
|
||||
if (entry.dirty) {
|
||||
return startListing(state, event.dir, (attempt) => ({ ...entry, attempt, dirty: false }))
|
||||
}
|
||||
|
||||
// A failed reload keeps the entries it already shows; the directory reloads with the next change.
|
||||
if (entry.status === "refreshing") {
|
||||
return withDirectory(state, event.dir, { status: "ready", expanded: entry.expanded, children: entry.children })
|
||||
}
|
||||
|
||||
const error = event.type === "list.failed" ? event.error : undefined
|
||||
|
||||
return {
|
||||
state: withDirectory(state, event.dir, { status: "failed", expanded: entry.expanded, error }).state,
|
||||
effects: [{ type: "notify.error", message: error ?? "" }],
|
||||
}
|
||||
}
|
||||
|
||||
function applyListing(
|
||||
state: ActiveTree,
|
||||
dir: string,
|
||||
entry: BusyDirectory,
|
||||
listed: readonly FileNode[],
|
||||
): FileTreeTransition {
|
||||
const children = listed.map((node) => node.path)
|
||||
const byPath = new Map(listed.map((node) => [node.path, node]))
|
||||
const previous = entry.status === "refreshing" ? entry.children : []
|
||||
const removed = new Set(previous.filter((path) => !byPath.has(path)))
|
||||
|
||||
// A directory that disappeared or became a file takes its listed descendants and their directory states with it.
|
||||
const prunedRoots = previous
|
||||
.filter((path) => state.nodes[path]?.type === "directory" && byPath.get(path)?.type !== "directory")
|
||||
.map(treeKey)
|
||||
|
||||
const pruned = (path: string) => {
|
||||
const key = treeKey(path)
|
||||
|
||||
return prunedRoots.some((root) => key === root || key.startsWith(`${root}/`))
|
||||
}
|
||||
|
||||
const nodes = Object.fromEntries(Object.entries(state.nodes).filter(([path]) => !removed.has(path) && !pruned(path)))
|
||||
|
||||
listed.forEach((node) => {
|
||||
nodes[node.path] = node
|
||||
})
|
||||
|
||||
const dirs = Object.fromEntries(Object.entries(state.dirs).filter(([path]) => path === dir || !pruned(path)))
|
||||
|
||||
if (!entry.dirty) {
|
||||
dirs[dir] = { status: "ready", expanded: entry.expanded, children }
|
||||
|
||||
return { state: { ...state, nodes, dirs }, effects: [] }
|
||||
}
|
||||
|
||||
const attempt = state.issued + 1
|
||||
dirs[dir] = { status: "refreshing", expanded: entry.expanded, children, attempt, dirty: false }
|
||||
|
||||
return { state: { ...state, issued: attempt, nodes, dirs }, effects: [listEffect(dir, attempt)] }
|
||||
}
|
||||
|
||||
/**
|
||||
* Compares listed paths with directory keys. The server ends directory paths with the platform separator, and the
|
||||
* driver keys directories by `normalizeDir`, which turns Windows separators into `/`.
|
||||
*/
|
||||
function treeKey(path: string) {
|
||||
return path.replaceAll("\\", "/").replace(/\/+$/, "")
|
||||
}
|
||||
|
||||
function startListing(state: ActiveTree, dir: string, next: (attempt: number) => DirectoryState): FileTreeTransition {
|
||||
const attempt = state.issued + 1
|
||||
|
||||
return {
|
||||
state: { ...state, issued: attempt, dirs: { ...state.dirs, [dir]: next(attempt) } },
|
||||
effects: [listEffect(dir, attempt)],
|
||||
}
|
||||
}
|
||||
|
||||
function listEffect(dir: string, attempt: number): FileTreeEffect {
|
||||
return { type: "list", dir, attempt, timeoutMs: DIRECTORY_LIST_TIMEOUT_MS }
|
||||
}
|
||||
|
||||
function withDirectory(state: ActiveTree, dir: string, entry: DirectoryState): FileTreeTransition {
|
||||
return { state: { ...state, dirs: { ...state.dirs, [dir]: entry } }, effects: [] }
|
||||
}
|
||||
|
||||
function isPristine(state: ActiveTree) {
|
||||
const root = state.dirs[""]
|
||||
|
||||
return (
|
||||
Object.keys(state.nodes).length === 0 &&
|
||||
Object.keys(state.dirs).length === 1 &&
|
||||
root?.status === "idle" &&
|
||||
root.expanded
|
||||
)
|
||||
}
|
||||
|
||||
function unchanged(state: FileTreeState): FileTreeTransition {
|
||||
return { state, effects: [] }
|
||||
}
|
||||
|
||||
/*
|
||||
* The view selectors below read key presence (`children`, `attempt`, `error`) rather than `status`. Each key exists
|
||||
* in exactly the variants it names, and a Solid store reader re-runs only when its answer changes: a root that goes
|
||||
* idle, loading, then failed stays "not loaded" without waking the file tree's reload-when-unloaded check.
|
||||
*/
|
||||
|
||||
export function isDirectoryExpanded(entry: DirectoryState | undefined) {
|
||||
return entry?.expanded ?? false
|
||||
}
|
||||
|
||||
/** True for `ready` and `refreshing`. */
|
||||
export function isDirectoryLoaded(entry: DirectoryState | undefined) {
|
||||
return entry !== undefined && "children" in entry
|
||||
}
|
||||
|
||||
/** True for `loading` and `refreshing`. */
|
||||
export function isDirectoryLoading(entry: DirectoryState | undefined) {
|
||||
return entry !== undefined && "attempt" in entry
|
||||
}
|
||||
|
||||
export function selectDirectoryError(entry: DirectoryState | undefined) {
|
||||
return entry !== undefined && "error" in entry ? entry.error : undefined
|
||||
}
|
||||
|
||||
export function selectDirectoryChildren(state: FileTreeState, dir: string) {
|
||||
if (state.status !== "active") return []
|
||||
const entry = state.dirs[dir]
|
||||
|
||||
if (!entry || !("children" in entry)) return []
|
||||
|
||||
return entry.children.flatMap((path) => {
|
||||
const node = state.nodes[path]
|
||||
|
||||
return node ? [node] : []
|
||||
})
|
||||
}
|
||||
|
||||
export function selectTreeNode(state: FileTreeState, path: string) {
|
||||
return state.status === "active" ? state.nodes[path] : undefined
|
||||
}
|
||||
|
||||
/** Whether a watcher change should reload the directory: it is listed or being listed. */
|
||||
export function canRefreshDirectory(state: FileTreeState, dir: string) {
|
||||
if (state.status !== "active") return false
|
||||
const entry = state.dirs[dir]
|
||||
|
||||
return isDirectoryLoaded(entry) || isDirectoryLoading(entry)
|
||||
}
|
||||
|
||||
/** Whether a listing for the directory is in flight; `listDir` callers wait until it is not. */
|
||||
export function isDirectoryBusy(state: FileTreeState, dir: string) {
|
||||
return state.status === "active" && isDirectoryLoading(state.dirs[dir])
|
||||
}
|
||||
|
|
@ -1,13 +1,20 @@
|
|||
import { createStore, produce, reconcile } from "solid-js/store"
|
||||
import { getOwner, onCleanup, untrack } from "solid-js"
|
||||
import { createStore, reconcile, unwrap } from "solid-js/store"
|
||||
import type { FileNode } from "@/runtime/server/types"
|
||||
|
||||
type DirectoryState = {
|
||||
expanded: boolean
|
||||
loaded?: boolean
|
||||
loading?: boolean
|
||||
error?: string
|
||||
children?: string[]
|
||||
}
|
||||
import {
|
||||
canRefreshDirectory,
|
||||
createFileTreeState,
|
||||
isDirectoryBusy,
|
||||
isDirectoryExpanded,
|
||||
isDirectoryLoaded,
|
||||
isDirectoryLoading,
|
||||
selectDirectoryChildren,
|
||||
selectDirectoryError,
|
||||
selectTreeNode,
|
||||
transitionFileTree,
|
||||
type FileTreeEffect,
|
||||
type FileTreeEvent,
|
||||
} from "./tree-machine"
|
||||
|
||||
type TreeStoreOptions = {
|
||||
scope: () => string
|
||||
|
|
@ -17,159 +24,109 @@ type TreeStoreOptions = {
|
|||
}
|
||||
|
||||
export function createFileTreeStore(options: TreeStoreOptions) {
|
||||
const [tree, setTree] = createStore<{
|
||||
node: Record<string, FileNode>
|
||||
dir: Record<string, DirectoryState>
|
||||
}>({
|
||||
node: {},
|
||||
dir: { "": { expanded: true } },
|
||||
})
|
||||
const [tree, setTree] = createStore({ current: createFileTreeState() })
|
||||
const timers = new Map<number, ReturnType<typeof setTimeout>>()
|
||||
const waiters = new Map<string, Array<() => void>>()
|
||||
|
||||
const inflight = new Map<string, Promise<void>>()
|
||||
const dispatch = (event: FileTreeEvent) =>
|
||||
untrack(() => {
|
||||
const previous = unwrap(tree.current)
|
||||
const result = transitionFileTree(previous, event)
|
||||
|
||||
const reset = () => {
|
||||
inflight.clear()
|
||||
setTree("node", reconcile({}))
|
||||
setTree("dir", reconcile({}))
|
||||
setTree("dir", "", { expanded: true })
|
||||
if (result.state !== previous) {
|
||||
// Keyless reconcile writes only the fields that changed, so unchanged nodes and directories notify no reader.
|
||||
setTree("current", reconcile(result.state, { key: null }))
|
||||
|
||||
waiters.forEach((resolve, dir) => {
|
||||
if (isDirectoryBusy(result.state, dir)) return
|
||||
waiters.delete(dir)
|
||||
resolve.forEach((run) => run())
|
||||
})
|
||||
}
|
||||
|
||||
result.effects.forEach(run)
|
||||
})
|
||||
|
||||
const run = (effect: FileTreeEffect) => {
|
||||
if (effect.type === "notify.error") return options.onError(effect.message)
|
||||
|
||||
const settle = (event: Extract<FileTreeEvent, { attempt: number }>) => {
|
||||
clearTimeout(timers.get(event.attempt))
|
||||
timers.delete(event.attempt)
|
||||
dispatch(event)
|
||||
}
|
||||
|
||||
timers.set(
|
||||
effect.attempt,
|
||||
setTimeout(() => settle({ type: "list.timed-out", dir: effect.dir, attempt: effect.attempt }), effect.timeoutMs),
|
||||
)
|
||||
void Promise.try(() => options.list(effect.dir)).then(
|
||||
(nodes) => settle({ type: "list.loaded", dir: effect.dir, attempt: effect.attempt, nodes }),
|
||||
(error) =>
|
||||
settle({
|
||||
type: "list.failed",
|
||||
dir: effect.dir,
|
||||
attempt: effect.attempt,
|
||||
error: error instanceof Error ? error.message : String(error),
|
||||
}),
|
||||
)
|
||||
}
|
||||
|
||||
const ensureDir = (path: string) => {
|
||||
if (tree.dir[path]) return
|
||||
setTree("dir", path, { expanded: false })
|
||||
if (getOwner()) {
|
||||
onCleanup(() => {
|
||||
dispatch({ type: "disposed" })
|
||||
timers.forEach((timer) => clearTimeout(timer))
|
||||
timers.clear()
|
||||
})
|
||||
}
|
||||
|
||||
// Resolves once the directory has no listing in flight, so a forced reload resolves after its follow-up listing.
|
||||
const listDir = (input: string, opts?: { force?: boolean }) => {
|
||||
const dir = options.normalizeDir(input)
|
||||
ensureDir(dir)
|
||||
dispatch({ type: "list.requested", dir, force: Boolean(opts?.force) })
|
||||
|
||||
const current = tree.dir[dir]
|
||||
if (!isDirectoryBusy(unwrap(tree.current), dir)) return Promise.resolve()
|
||||
|
||||
if (!opts?.force && current?.loaded) return Promise.resolve()
|
||||
|
||||
const pending = inflight.get(dir)
|
||||
|
||||
if (pending) return pending
|
||||
|
||||
setTree(
|
||||
"dir",
|
||||
dir,
|
||||
produce((draft) => {
|
||||
draft.loading = true
|
||||
draft.error = undefined
|
||||
}),
|
||||
)
|
||||
|
||||
const directory = options.scope()
|
||||
|
||||
const promise = options
|
||||
.list(dir)
|
||||
.then((nodes) => {
|
||||
if (options.scope() !== directory) return
|
||||
const prevChildren = tree.dir[dir]?.children ?? []
|
||||
const nextChildren = nodes.map((node) => node.path)
|
||||
const nextSet = new Set(nextChildren)
|
||||
|
||||
setTree(
|
||||
"node",
|
||||
produce((draft) => {
|
||||
const removedDirs: string[] = []
|
||||
|
||||
for (const child of prevChildren) {
|
||||
if (nextSet.has(child)) continue
|
||||
const existing = draft[child]
|
||||
|
||||
if (existing?.type === "directory") removedDirs.push(child)
|
||||
delete draft[child]
|
||||
}
|
||||
|
||||
if (removedDirs.length > 0) {
|
||||
const keys = Object.keys(draft)
|
||||
|
||||
for (const key of keys) {
|
||||
for (const removed of removedDirs) {
|
||||
if (!key.startsWith(removed + "/")) continue
|
||||
delete draft[key]
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for (const node of nodes) {
|
||||
draft[node.path] = node
|
||||
}
|
||||
}),
|
||||
)
|
||||
|
||||
setTree(
|
||||
"dir",
|
||||
dir,
|
||||
produce((draft) => {
|
||||
draft.loaded = true
|
||||
draft.loading = false
|
||||
draft.children = nextChildren
|
||||
}),
|
||||
)
|
||||
})
|
||||
.catch((e) => {
|
||||
if (options.scope() !== directory) return
|
||||
setTree(
|
||||
"dir",
|
||||
dir,
|
||||
produce((draft) => {
|
||||
draft.loading = false
|
||||
draft.error = e.message
|
||||
}),
|
||||
)
|
||||
options.onError(e.message)
|
||||
})
|
||||
.finally(() => {
|
||||
inflight.delete(dir)
|
||||
})
|
||||
|
||||
inflight.set(dir, promise)
|
||||
|
||||
return promise
|
||||
return new Promise<void>((resolve) => waiters.set(dir, [...(waiters.get(dir) ?? []), resolve]))
|
||||
}
|
||||
|
||||
// `list: false` marks a directory expanded without fetching its children, for
|
||||
// trees whose nodes are synthesized from a filter; listing directories that
|
||||
// only exist on a diff's base branch fails and surfaces error toasts.
|
||||
const expandDir = (input: string, behavior?: { list?: boolean }) => {
|
||||
const dir = options.normalizeDir(input)
|
||||
ensureDir(dir)
|
||||
setTree("dir", dir, "expanded", true)
|
||||
|
||||
if (behavior?.list === false) return
|
||||
void listDir(dir)
|
||||
dispatch({ type: "dir.expanded", dir: options.normalizeDir(input), list: behavior?.list !== false })
|
||||
}
|
||||
|
||||
const collapseDir = (input: string) => {
|
||||
const dir = options.normalizeDir(input)
|
||||
ensureDir(dir)
|
||||
setTree("dir", dir, "expanded", false)
|
||||
dispatch({ type: "dir.collapsed", dir: options.normalizeDir(input) })
|
||||
}
|
||||
|
||||
// Getters keep each reader subscribed to the one field it reads. Reading `epoch` makes a workspace reset re-run every
|
||||
// reader, so the file tree lists the new root even when the old one never loaded.
|
||||
const dirState = (input: string) => {
|
||||
const dir = options.normalizeDir(input)
|
||||
const current = tree.current
|
||||
|
||||
return tree.dir[dir]
|
||||
}
|
||||
if (current.status !== "active") return undefined
|
||||
void current.epoch
|
||||
const entry = current.dirs[dir]
|
||||
|
||||
const children = (input: string) => {
|
||||
const dir = options.normalizeDir(input)
|
||||
const ids = tree.dir[dir]?.children
|
||||
if (!entry) return undefined
|
||||
|
||||
if (!ids) return []
|
||||
const out: FileNode[] = []
|
||||
|
||||
for (const id of ids) {
|
||||
const node = tree.node[id]
|
||||
|
||||
if (node) out.push(node)
|
||||
return {
|
||||
get expanded() {
|
||||
return isDirectoryExpanded(entry)
|
||||
},
|
||||
get loaded() {
|
||||
return isDirectoryLoaded(entry)
|
||||
},
|
||||
get loading() {
|
||||
return isDirectoryLoading(entry)
|
||||
},
|
||||
get error() {
|
||||
return selectDirectoryError(entry)
|
||||
},
|
||||
}
|
||||
|
||||
return out
|
||||
}
|
||||
|
||||
return {
|
||||
|
|
@ -177,9 +134,10 @@ export function createFileTreeStore(options: TreeStoreOptions) {
|
|||
expandDir,
|
||||
collapseDir,
|
||||
dirState,
|
||||
children,
|
||||
node: (path: string) => tree.node[path],
|
||||
isLoaded: (path: string) => Boolean(tree.dir[path]?.loaded),
|
||||
reset,
|
||||
children: (input: string) => selectDirectoryChildren(tree.current, options.normalizeDir(input)),
|
||||
node: (path: string) => selectTreeNode(tree.current, path),
|
||||
// Includes directories still loading, so a change during their first listing queues a reload.
|
||||
isLoaded: (path: string) => canRefreshDirectory(tree.current, options.normalizeDir(path)),
|
||||
reset: () => dispatch({ type: "reset" }),
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -80,10 +80,25 @@ describe("file watcher invalidation", () => {
|
|||
expect(refresh).toEqual(["src"])
|
||||
})
|
||||
|
||||
test("ignores invalid or git watcher updates", () => {
|
||||
test("refreshes the parent of a Windows path", () => {
|
||||
const refresh: string[] = []
|
||||
|
||||
invalidateFromWatcher(filesystemEvent(".git/index.lock", "change"), {
|
||||
invalidateFromWatcher(filesystemEvent("src\\sub\\new.ts", "add"), {
|
||||
normalize: (input) => input,
|
||||
hasFile: () => false,
|
||||
loadFile: () => {},
|
||||
node: () => undefined,
|
||||
isDirLoaded: (path) => path === "src/sub",
|
||||
refreshDir: (path) => refresh.push(path),
|
||||
})
|
||||
|
||||
expect(refresh).toEqual(["src/sub"])
|
||||
})
|
||||
|
||||
test.each([".git/index.lock", ".git\\index.lock"])("ignores git watcher update %p", (file) => {
|
||||
const refresh: string[] = []
|
||||
|
||||
invalidateFromWatcher(filesystemEvent(file, "change"), {
|
||||
normalize: (input) => input,
|
||||
hasFile: () => true,
|
||||
loadFile: () => {
|
||||
|
|
|
|||
|
|
@ -18,7 +18,7 @@ export function invalidateFromWatcher(event: WatcherEvent, ops: WatcherOps) {
|
|||
|
||||
if (!path) return
|
||||
|
||||
if (path.startsWith(".git/")) return
|
||||
if (path.startsWith(".git/") || path.startsWith(".git\\")) return
|
||||
|
||||
if (ops.hasFile(path) || ops.isOpen?.(path)) {
|
||||
ops.loadFile(path)
|
||||
|
|
@ -33,7 +33,8 @@ export function invalidateFromWatcher(event: WatcherEvent, ops: WatcherOps) {
|
|||
return
|
||||
}
|
||||
|
||||
const parent = path.split("/").slice(0, -1).join("/")
|
||||
// Paths keep the native separator, so a Windows event names `src\sub\a.ts`.
|
||||
const parent = path.split(/[/\\]/).slice(0, -1).join("/")
|
||||
|
||||
if (!ops.isDirLoaded(parent)) return
|
||||
|
||||
|
|
|
|||
116
packages/app/test-browser/file-tree-store.test.ts
Normal file
116
packages/app/test-browser/file-tree-store.test.ts
Normal file
|
|
@ -0,0 +1,116 @@
|
|||
import { afterEach, describe, expect, test, vi } from "bun:test"
|
||||
import { createComputed, createRoot } from "solid-js"
|
||||
import type { FileNode } from "@/runtime/server/types"
|
||||
import { createFileTreeStore } from "@/workspaces/files/tree-store"
|
||||
|
||||
// Runs under the browser build: the server build of Solid neither re-runs computations nor runs cleanups.
|
||||
|
||||
const file = (path: string): FileNode => ({ path, type: "file", name: path, absolute: `/repo/${path}`, ignored: false })
|
||||
|
||||
type Call = { dir: string; resolve: (nodes: FileNode[]) => void; reject: (error: Error) => void }
|
||||
|
||||
function setup(scope = () => "/repo") {
|
||||
const calls: Call[] = []
|
||||
const errors: string[] = []
|
||||
|
||||
return createRoot((dispose) => ({
|
||||
calls,
|
||||
errors,
|
||||
dispose,
|
||||
store: createFileTreeStore({
|
||||
scope,
|
||||
normalizeDir: (input) => input,
|
||||
list: (dir) => new Promise((resolve, reject) => calls.push({ dir, resolve, reject })),
|
||||
onError: (message) => errors.push(message),
|
||||
}),
|
||||
}))
|
||||
}
|
||||
|
||||
const flush = () => new Promise<void>((resolve) => setTimeout(resolve, 0))
|
||||
|
||||
const paths = (nodes: readonly FileNode[]) => nodes.map((node) => node.path)
|
||||
|
||||
afterEach(() => {
|
||||
vi.useRealTimers()
|
||||
})
|
||||
|
||||
describe("file tree store", () => {
|
||||
test("a forced reload during a listing resolves after a fresh listing", async () => {
|
||||
const tree = setup()
|
||||
void tree.store.listDir("src")
|
||||
const forced = tree.store.listDir("src", { force: true }).then(() => paths(tree.store.children("src")))
|
||||
const resolved: string[][] = []
|
||||
void forced.then((result) => resolved.push(result))
|
||||
expect(tree.calls.map((call) => call.dir)).toEqual(["src"])
|
||||
|
||||
tree.calls[0]!.resolve([file("src/a.ts")])
|
||||
await flush()
|
||||
expect(resolved).toEqual([])
|
||||
expect(paths(tree.store.children("src"))).toEqual(["src/a.ts"])
|
||||
expect(tree.calls.map((call) => call.dir)).toEqual(["src", "src"])
|
||||
|
||||
tree.calls[1]!.resolve([file("src/a.ts"), file("src/b.ts")])
|
||||
expect(await forced).toEqual(["src/a.ts", "src/b.ts"])
|
||||
tree.dispose()
|
||||
})
|
||||
|
||||
test("a listing from the previous workspace neither reports nor releases the new workspace's listing", async () => {
|
||||
const workspace = { directory: "/a" }
|
||||
const tree = setup(() => workspace.directory)
|
||||
void tree.store.listDir("")
|
||||
workspace.directory = "/b"
|
||||
tree.store.reset()
|
||||
void tree.store.listDir("")
|
||||
|
||||
tree.calls[0]!.reject(new Error("gone"))
|
||||
await flush()
|
||||
const joined = tree.store.listDir("")
|
||||
expect(tree.calls).toHaveLength(2)
|
||||
expect(tree.errors).toEqual([])
|
||||
|
||||
tree.calls[1]!.resolve([file("b.ts")])
|
||||
await joined
|
||||
expect(paths(tree.store.children(""))).toEqual(["b.ts"])
|
||||
tree.dispose()
|
||||
})
|
||||
|
||||
test("the root's loaded state wakes readers only when it changes or the workspace resets", async () => {
|
||||
const tree = setup()
|
||||
const reads: boolean[] = []
|
||||
|
||||
createRoot((dispose) => {
|
||||
createComputed(() => reads.push(tree.store.dirState("")?.loaded ?? false))
|
||||
void tree.store.listDir("")
|
||||
tree.calls[0]!.reject(new Error("boom"))
|
||||
|
||||
return dispose
|
||||
})
|
||||
|
||||
await flush()
|
||||
expect(tree.store.dirState("")?.error).toBe("boom")
|
||||
expect(tree.errors).toEqual(["boom"])
|
||||
expect(reads).toEqual([false])
|
||||
|
||||
tree.store.reset()
|
||||
expect(reads).toEqual([false, false])
|
||||
tree.dispose()
|
||||
})
|
||||
|
||||
test("a hung listing times out, and disposal cancels pending work", async () => {
|
||||
vi.useFakeTimers()
|
||||
const tree = setup()
|
||||
const hung = tree.store.listDir("src")
|
||||
vi.advanceTimersToNextTimer()
|
||||
await hung
|
||||
expect(tree.store.dirState("src")).toMatchObject({ loaded: false, loading: false })
|
||||
expect(tree.errors).toEqual([""])
|
||||
|
||||
const disposed = tree.store.listDir("lib")
|
||||
tree.dispose()
|
||||
await disposed
|
||||
vi.advanceTimersToNextTimer()
|
||||
tree.calls[1]!.reject(new Error("late"))
|
||||
await Promise.resolve()
|
||||
expect(tree.errors).toEqual([""])
|
||||
})
|
||||
})
|
||||
Loading…
Add table
Reference in a new issue