Repository navigation
Expand file tree
/
Copy pathinventory.ts
More file actions
67 lines (64 loc) · 2.61 KB
/
Copy pathinventory.ts
File metadata and controls
67 lines (64 loc) · 2.61 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
import type { QueryClient } from "@tanstack/solid-query"
import type { WorktreeDirectory } from "@opencode/client/promise"
import type { ServerApi } from "@/runtime/server/api"
import type { ServerScope } from "@/runtime/server/scope"
import type { Project } from "@/runtime/server/types"
import { sameDirectory } from "./paths"
export function worktreeInventoryKey(scope: ServerScope, projectID: string) {
return [scope, "worktree", projectID] as const
}
// Project metadata arrives without worktrees; a loaded inventory supplies the workspace list.
export function withWorktreeInventory(project: Project, worktrees: readonly WorktreeDirectory[] | undefined): Project {
if (!worktrees) return project
return {
...project,
worktrees: [...worktrees],
sandboxes: worktrees
.map((item) => item.directory)
.filter((directory) => !sameDirectory(project.worktree, directory)),
}
}
// Reads use saved inventory; explicit demand also discovers external worktree changes.
export function createWorktreeInventory(input: {
scope: ServerScope
queryClient: QueryClient
api: () => Pick<ServerApi["worktree"], "list" | "refresh">
updated: (projectID: string, worktrees: WorktreeDirectory[]) => void
}) {
const options = (projectID: string) => ({
queryKey: worktreeInventoryKey(input.scope, projectID),
queryFn: () =>
input
.api()
.list({ projectID })
.then((items) => {
input.updated(projectID, items)
return items
}),
// `worktree.updated` and reconnect invalidation drive refreshes; time alone does not re-list.
staleTime: Infinity,
gcTime: Infinity,
retry: false,
})
return {
cached: (projectID: string) =>
input.queryClient.getQueryData<WorktreeDirectory[]>(worktreeInventoryKey(input.scope, projectID)),
load: async (projectID: string) => {
const discover = !input.queryClient.getQueryState(worktreeInventoryKey(input.scope, projectID))
const items = await input.queryClient.fetchQuery(options(projectID)).catch(() => undefined)
if (discover) {
// The worktree.updated event re-reads inventory only when discovery actually changes it.
void input
.api()
.refresh({ projectID })
.catch(() => undefined)
}
return items
},
// Only inventories some view already demanded are refreshed.
refresh: (projectID: string) => {
if (!input.queryClient.getQueryState(worktreeInventoryKey(input.scope, projectID))) return Promise.resolve()
return input.queryClient.fetchQuery({ ...options(projectID), staleTime: 0 }).catch(() => undefined)
},
}
}