Skip to content

Commit 06e9794

Browse files
committed
fix(web): allow opening projects outside home directory
- Add directory parameter to /find/file endpoint - Extend File.search() to scan arbitrary directories - Parse absolute paths in dialog-select-directory component Fixes anomalyco#9795
1 parent d2fcdef commit 06e9794

3 files changed

Lines changed: 109 additions & 38 deletions

File tree

‎packages/app/src/components/dialog-select-directory.tsx‎

Lines changed: 54 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,17 @@ export function DialogSelectDirectory(props: DialogSelectDirectoryProps) {
1919
const dialog = useDialog()
2020

2121
const home = createMemo(() => sync.data.path.home)
22-
const root = createMemo(() => sync.data.path.home || sync.data.path.directory)
22+
23+
function isAbsolutePath(p: string) {
24+
return p.startsWith("/") || /^[a-zA-Z]:[\\/]/.test(p)
25+
}
26+
27+
function getParentPath(p: string) {
28+
const normalized = p.replace(/[\\/]+$/, "")
29+
const lastSlash = Math.max(normalized.lastIndexOf("/"), normalized.lastIndexOf("\\"))
30+
if (lastSlash <= 0) return "/"
31+
return normalized.slice(0, lastSlash)
32+
}
2333

2434
function join(base: string | undefined, rel: string) {
2535
const b = (base ?? "").replace(/[\\/]+$/, "")
@@ -29,61 +39,72 @@ export function DialogSelectDirectory(props: DialogSelectDirectoryProps) {
2939
return b + "/" + r
3040
}
3141

32-
function display(rel: string) {
33-
const full = join(root(), rel)
42+
function display(fullPath: string) {
3443
const h = home()
35-
if (!h) return full
36-
if (full === h) return "~"
37-
if (full.startsWith(h + "/") || full.startsWith(h + "\\")) {
38-
return "~" + full.slice(h.length)
44+
if (!h) return fullPath
45+
if (fullPath === h) return "~"
46+
if (fullPath.startsWith(h + "/") || fullPath.startsWith(h + "\\")) {
47+
return "~" + fullPath.slice(h.length)
3948
}
40-
return full
49+
return fullPath
4150
}
4251

43-
function normalizeQuery(query: string) {
52+
async function fetchDirs(filter: string) {
53+
const trimmed = filter.trim()
4454
const h = home()
4555

46-
if (!query) return query
47-
if (query.startsWith("~/")) return query.slice(2)
56+
// Determine search directory and query based on input
57+
let directory: string
58+
let query: string
4859

49-
if (h) {
50-
const lc = query.toLowerCase()
51-
const hc = h.toLowerCase()
52-
if (lc === hc || lc.startsWith(hc + "/") || lc.startsWith(hc + "\\")) {
53-
return query.slice(h.length).replace(/^[\\/]+/, "")
60+
if (isAbsolutePath(trimmed)) {
61+
// Check if path ends with / - user wants to see directory contents
62+
if (trimmed.endsWith("/") || trimmed.endsWith("\\")) {
63+
directory = trimmed.replace(/[\\/]+$/, "")
64+
query = ""
65+
} else {
66+
// Absolute path without trailing slash: use parent directory, search for basename
67+
directory = getParentPath(trimmed)
68+
const basename = trimmed.slice(directory.length).replace(/^[\\/]+/, "")
69+
query = basename
5470
}
71+
} else if (trimmed.startsWith("~/")) {
72+
// Home-relative path
73+
directory = h || "/"
74+
query = trimmed.slice(2)
75+
} else {
76+
// Relative query: search in home
77+
directory = h || "/"
78+
query = trimmed
5579
}
5680

57-
return query
58-
}
59-
60-
async function fetchDirs(query: string) {
61-
const directory = root()
6281
if (!directory) return [] as string[]
6382

6483
const results = await sdk.client.find
6584
.files({ directory, query, type: "directory", limit: 50 })
6685
.then((x) => x.data ?? [])
6786
.catch(() => [])
6887

69-
return results.map((x) => x.replace(/[\\/]+$/, ""))
88+
// Results are relative to directory - convert to absolute paths
89+
return results.map((x) => {
90+
const rel = x.replace(/[\\/]+$/, "")
91+
return join(directory, rel)
92+
})
7093
}
7194

7295
const directories = async (filter: string) => {
73-
const query = normalizeQuery(filter.trim())
74-
return fetchDirs(query)
96+
return fetchDirs(filter)
7597
}
7698

77-
function resolve(rel: string) {
78-
const absolute = join(root(), rel)
79-
props.onSelect(props.multiple ? [absolute] : absolute)
99+
function resolve(absolutePath: string) {
100+
props.onSelect(props.multiple ? [absolutePath] : absolutePath)
80101
dialog.close()
81102
}
82103

83104
return (
84105
<Dialog title={props.title ?? "Open project"}>
85106
<List
86-
search={{ placeholder: "Search folders", autofocus: true }}
107+
search={{ placeholder: "Search folders (use / for absolute paths)", autofocus: true }}
87108
emptyMessage="No folders found"
88109
items={directories}
89110
key={(x) => x}
@@ -92,17 +113,17 @@ export function DialogSelectDirectory(props: DialogSelectDirectoryProps) {
92113
resolve(path)
93114
}}
94115
>
95-
{(rel) => {
96-
const path = display(rel)
116+
{(absolutePath) => {
117+
const displayPath = display(absolutePath)
97118
return (
98119
<div class="w-full flex items-center justify-between rounded-md">
99120
<div class="flex items-center gap-x-3 grow min-w-0">
100-
<FileIcon node={{ path: rel, type: "directory" }} class="shrink-0 size-4" />
121+
<FileIcon node={{ path: absolutePath, type: "directory" }} class="shrink-0 size-4" />
101122
<div class="flex items-center text-14-regular min-w-0">
102123
<span class="text-text-weak whitespace-nowrap overflow-hidden overflow-ellipsis truncate min-w-0">
103-
{getDirectory(path)}
124+
{getDirectory(displayPath)}
104125
</span>
105-
<span class="text-text-strong whitespace-nowrap">{getFilename(path)}</span>
126+
<span class="text-text-strong whitespace-nowrap">{getFilename(displayPath)}</span>
106127
</div>
107128
</div>
108129
</div>

‎packages/opencode/src/file/index.ts‎

Lines changed: 51 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -369,13 +369,18 @@ export namespace File {
369369
})
370370
}
371371

372-
export async function search(input: { query: string; limit?: number; dirs?: boolean; type?: "file" | "directory" }) {
372+
export async function search(input: {
373+
query: string
374+
directory?: string
375+
limit?: number
376+
dirs?: boolean
377+
type?: "file" | "directory"
378+
}) {
373379
const query = input.query.trim()
374380
const limit = input.limit ?? 100
375381
const kind = input.type ?? (input.dirs === false ? "file" : "all")
376-
log.info("search", { query, kind })
377-
378-
const result = await state().then((x) => x.files())
382+
const searchDir = input.directory
383+
log.info("search", { query, kind, directory: searchDir })
379384

380385
const hidden = (item: string) => {
381386
const normalized = item.replaceAll("\\", "/").replace(/\/+$/, "")
@@ -393,6 +398,48 @@ export namespace File {
393398
}
394399
return [...visible, ...hiddenItems]
395400
}
401+
402+
// If a custom directory is provided, scan it directly instead of using cached results
403+
if (searchDir && searchDir !== Instance.directory) {
404+
const dirs = new Set<string>()
405+
const ignoreNested = new Set(["node_modules", "dist", "build", "target", "vendor"])
406+
const shouldIgnore = (name: string) => name.startsWith(".") && !preferHidden
407+
const shouldIgnoreNested = (name: string) => (name.startsWith(".") && !preferHidden) || ignoreNested.has(name)
408+
409+
try {
410+
const top = await fs.promises.readdir(searchDir, { withFileTypes: true }).catch(() => [] as fs.Dirent[])
411+
412+
for (const entry of top) {
413+
if (!entry.isDirectory()) continue
414+
if (shouldIgnore(entry.name)) continue
415+
dirs.add(entry.name + "/")
416+
417+
// Scan one level deeper
418+
const base = path.join(searchDir, entry.name)
419+
const children = await fs.promises.readdir(base, { withFileTypes: true }).catch(() => [] as fs.Dirent[])
420+
for (const child of children) {
421+
if (!child.isDirectory()) continue
422+
if (shouldIgnoreNested(child.name)) continue
423+
dirs.add(entry.name + "/" + child.name + "/")
424+
}
425+
}
426+
427+
const items = Array.from(dirs)
428+
if (!query) {
429+
return sortHiddenLast(items.toSorted()).slice(0, limit)
430+
}
431+
const searchLimit = !preferHidden ? limit * 20 : limit
432+
const sorted = fuzzysort.go(query, items, { limit: searchLimit }).map((r) => r.target)
433+
return sortHiddenLast(sorted).slice(0, limit)
434+
} catch (err) {
435+
log.error("search directory scan failed", { directory: searchDir, error: err })
436+
return []
437+
}
438+
}
439+
440+
// Use cached results for Instance.directory
441+
const result = await state().then((x) => x.files())
442+
396443
if (!query) {
397444
if (kind === "file") return result.files.slice(0, limit)
398445
return sortHiddenLast(result.dirs.toSorted()).slice(0, limit)

‎packages/opencode/src/server/routes/file.ts‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -62,19 +62,22 @@ export const FileRoutes = lazy(() =>
6262
validator(
6363
"query",
6464
z.object({
65-
query: z.string(),
65+
query: z.string().optional().default(""),
66+
directory: z.string().optional(),
6667
dirs: z.enum(["true", "false"]).optional(),
6768
type: z.enum(["file", "directory"]).optional(),
6869
limit: z.coerce.number().int().min(1).max(200).optional(),
6970
}),
7071
),
7172
async (c) => {
7273
const query = c.req.valid("query").query
74+
const directory = c.req.valid("query").directory
7375
const dirs = c.req.valid("query").dirs
7476
const type = c.req.valid("query").type
7577
const limit = c.req.valid("query").limit
7678
const results = await File.search({
7779
query,
80+
directory,
7881
limit: limit ?? 10,
7982
dirs: dirs !== "false",
8083
type,

0 commit comments

Comments
 (0)