Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

filesystem.ts

294 lines10.6 KB

1import {
2 AuthFilesystemReadScope,
3 type FilesystemBrowseEntry,
4 WS_METHODS,
5 sessionGrantsScope,
6 type SessionGrantInput,
7} from "@t3tools/contracts";
8import { request } from "../rpc/client.ts";
9import { scoreQueryMatch } from "@t3tools/shared/searchRanking";
10import { Atom } from "effect/reactivity";
11​
12import { mFallback, msg } from "gt-i18n";
13import type { M } from "gt-i18n";
14​
15import {
16 connectionErrorText,
17 type EnvironmentConnectionPhase,
18 type EnvironmentConnectionPresentation,
19} from "../connection/presentation.ts";
20import type { EnvironmentRegistry } from "../connection/registry.ts";
21import {
22 canNavigateUp,
23 collapsePosixRoot,
24 getBrowseDirectoryPath,
25 getBrowseLeafPathSegment,
26 getBrowseParentPath,
27 hasTrailingPathSeparator,
28 isFilesystemBrowseQuery,
29} from "./projects.ts";
30import {
31 createEnvironmentQueryAtomFamily,
32 createEnvironmentRpcCommand,
33 createEnvironmentRpcQueryAtomFamily,
34} from "./runtime.ts";
35​
36const BROWSE_IDLE_TTL_MS = 5_000;
37​
38export function resolveFilesystemReadAccess(
39 input: {
40 readonly isCatalogReady: boolean;
41 readonly connection: Pick<
42 EnvironmentConnectionPresentation,
43 "phase" | "error" | "i18nError"
44 > | null;
45 readonly session: SessionGrantInput | null;
46 readonly sessionError: string | null;
47 },
48 resolve: M = mFallback,
49) {
50 if (input.sessionError !== null) {
51 return { canReadFiles: false, isPending: false, error: input.sessionError };
52 }
53 if (input.session === null) {
54 // Wait for the catalog before interpreting a missing presentation as offline.
55 // Once ready, an offline environment cannot finish its session check.
56 const isPending =
57 !input.isCatalogReady ||
58 input.connection?.phase === "connected" ||
59 input.connection?.phase === "connecting" ||
60 input.connection?.phase === "reconnecting";
61 return {
62 canReadFiles: false,
63 isPending,
64 error: isPending
65 ? null
66 : ((input.connection === null ? null : connectionErrorText(input.connection, resolve)) ??
67 resolve(msg("This environment is not connected."))),
68 };
69 }
70 return {
71 canReadFiles: sessionGrantsScope(input.session, AuthFilesystemReadScope),
72 isPending: false,
73 error: null,
74 };
76​
77export function getFilesystemBrowsePath(query: string, platform = "", enabled = true) {
78 const isBrowsing = enabled && isFilesystemBrowseQuery(query, platform);
79 // A bare drive has no separator, so it would otherwise filter its own listing by "D:".
80 const browseQuery = /^[a-zA-Z]:$/.test(query) ? `${query}\\` : collapsePosixRoot(query, platform);
81 const directoryPath = isBrowsing ? getBrowseDirectoryPath(browseQuery) : "";
82 const filterQuery =
83 isBrowsing && !hasTrailingPathSeparator(browseQuery)
84 ? getBrowseLeafPathSegment(browseQuery)
85 : "";
86 const parentPath = isBrowsing ? getBrowseParentPath(directoryPath) : null;
87​
88 return {
89 isBrowsing,
90 directoryPath,
91 filterQuery,
92 parentPath,
93 canBrowseUp: isBrowsing && canNavigateUp(directoryPath),
94 };
96​
97export function filterFilesystemBrowseEntries(
98 entries: ReadonlyArray<FilesystemBrowseEntry>,
99 query: string,
100) {
101 // macOS Finder stores names decomposed (NFD), while typed text is composed (NFC).
102 const normalizedQuery = query.normalize("NFC");
103 const lowerQuery = query.toLowerCase();
104 const lowerNormalizedQuery = normalizedQuery.toLowerCase();
105 const showHidden = query.startsWith(".");
106 const candidates = entries.filter((entry) => showHidden || !entry.name.startsWith("."));
107 const visibleEntries =
108 lowerQuery.length === 0
109 ? candidates
110 : candidates
111 .map((entry) => {
112 const options = {
113 // Position penalties stay under 1000 for 255-character names, so tiers never overlap.
114 query: lowerNormalizedQuery,
115 exactBase: 0,
116 prefixBase: 1000,
117 boundaryBase: 2000,
118 includesBase: 3000,
119 fuzzyBase: 4000,
120 boundaryMarkers: [" ", "-", "_", "."],
121 };
122 const rawScore = scoreQueryMatch({
123 ...options,
124 value: entry.name.toLowerCase(),
125 query: lowerQuery,
126 });
127 const normalizedScore = scoreQueryMatch({
128 ...options,
129 value: entry.name.normalize("NFC").toLowerCase(),
130 });
131 const score =
132 rawScore === null
133 ? normalizedScore
134 : normalizedScore === null
135 ? rawScore
136 : Math.min(rawScore, normalizedScore);
137 return { entry, score };
138 })
139 .filter((match): match is { entry: FilesystemBrowseEntry; score: number } => {
140 return match.score !== null;
141 })
142 .sort((left, right) => left.score - right.score)
143 .map((match) => match.entry);
144 const normalizedMatches = visibleEntries.filter(
145 (entry) => entry.name.normalize("NFC") === normalizedQuery,
146 );
147 const exactEntry =
148 query.length > 0
149 ? (visibleEntries.find((entry) => entry.name === query) ??
150 (normalizedMatches.length === 1 ? normalizedMatches[0] : null))
151 : null;
152​
153 return { visibleEntries, exactEntry };
155​
156/** Shell-style Tab: a single match enters the directory, several extend to their common prefix. */
157export function getFilesystemBrowseTabCompletion(
158 visibleEntries: ReadonlyArray<FilesystemBrowseEntry>,
159 filterQuery: string,
160): { readonly name: string; readonly isComplete: boolean } | null {
161 const lowerQuery = filterQuery.toLowerCase();
162 const lowerNormalizedQuery = filterQuery.normalize("NFC").toLowerCase();
163 const prefixEntries = visibleEntries.filter(
164 (entry) =>
165 entry.name.toLowerCase().startsWith(lowerQuery) ||
166 entry.name.normalize("NFC").toLowerCase().startsWith(lowerNormalizedQuery),
167 );
168 const [first, ...rest] = prefixEntries;
169 if (first === undefined) return null;
170 if (rest.length === 0) return { name: first.name, isComplete: true };
171 const rawName = sharedNamePrefix(prefixEntries, lowerQuery, (entryName) => entryName);
172 if (rawName !== null) return { name: rawName, isComplete: false };
173 // A shared accented prefix spelled decomposed (macOS) and composed has no raw match;
174 // compare composed forms, which must still extend the composed query.
175 const composedName = sharedNamePrefix(prefixEntries, lowerNormalizedQuery, (entryName) =>
176 entryName.normalize("NFC"),
177 );
178 return composedName?.toLowerCase().startsWith(lowerNormalizedQuery)
179 ? { name: composedName, isComplete: false }
180 : null;
182​
183function sharedNamePrefix(
184 entries: ReadonlyArray<FilesystemBrowseEntry>,
185 lowerQuery: string,
186 spell: (name: string) => string,
187): string | null {
188 const [first, ...rest] = entries;
189 if (first === undefined) return null;
190 let prefix = Array.from(spell(first.name));
191 for (const entry of rest) {
192 const characters = Array.from(spell(entry.name));
193 let length = 0;
194 while (
195 length < prefix.length &&
196 prefix[length]?.toLowerCase() === characters[length]?.toLowerCase()
197 )
198 length += 1;
199 prefix = prefix.slice(0, length);
200 if (prefix.length === 0) return null;
201 }
202 const name = prefix.join("");
203 const lowerName = name.toLowerCase();
204 return lowerName.length > lowerQuery.length &&
205 entries.every((entry) => spell(entry.name).toLowerCase().startsWith(lowerName))
206 ? name
207 : null;
209​
210export function createBrowseNavigationCoordinator() {
211 let generation = 0;
212​
213 return {
214 invalidate: () => {
215 generation += 1;
216 },
217 run: async (load: () => Promise<void>, commit: () => void) => {
218 const navigationGeneration = ++generation;
219 await load();
220 if (navigationGeneration !== generation) {
221 return false;
222 }
223 commit();
224 return true;
225 },
226 };
228​
229export function canPreloadBrowsePath(
230 connectionPhase: EnvironmentConnectionPhase | null | undefined,
231): boolean {
232 return connectionPhase === "connected";
234​
235export function createFilesystemEnvironmentAtoms<R, E>(
236 runtime: Atom.AtomRuntime<EnvironmentRegistry | R, E>,
237) {
238 return {
239 getMetadata: createEnvironmentRpcQueryAtomFamily(runtime, {
240 label: "environment-data:filesystem:get-metadata",
241 tag: WS_METHODS.filesystemGetMetadata,
242 }),
243 workspaceRecovery: createEnvironmentQueryAtomFamily(runtime, {
244 label: "environment-data:filesystem:workspace-recovery",
245 execute: ({ path }: { readonly path: string; readonly failureKey: string }) =>
246 request(WS_METHODS.filesystemGetMetadata, { paths: [path] }),
247 }),
248 browse: createEnvironmentRpcQueryAtomFamily(runtime, {
249 label: "environment-data:filesystem:browse",
250 tag: WS_METHODS.filesystemBrowse,
251 // A listing mirrors a directory that can change outside the app, so reopening a picker
252 // lists it again. The short TTL only keeps the old listing on screen while it refreshes.
253 idleTtlMs: BROWSE_IDLE_TTL_MS,
254 staleTimeMs: 0,
255 }),
256 /** Repositories under a folder and in its `.code-workspace` file, read from disk each time. */
257 scanFolders: createEnvironmentRpcQueryAtomFamily(runtime, {
258 label: "environment-data:workspace:scan-folders",
259 tag: WS_METHODS.workspaceScanFolders,
260 staleTimeMs: 0,
261 }),
262 /** A project's tracked folders with what is on disk now: a repository, plain files, or gone. */
263 listFolders: createEnvironmentRpcQueryAtomFamily(runtime, {
264 label: "environment-data:workspace:list-folders",
265 tag: WS_METHODS.workspaceListFolders,
266 staleTimeMs: 0,
267 }),
268 /** The task folder a thread's `worktreePath` belongs to, with each repository's worktree. */
269 taskFolder: createEnvironmentRpcQueryAtomFamily(runtime, {
270 label: "environment-data:workspace:task-folder",
271 tag: WS_METHODS.workspaceTaskFolder,
272 staleTimeMs: 0,
273 }),
274 addTaskFolderRepository: createEnvironmentRpcCommand(runtime, {
275 label: "environment-data:workspace:add-task-folder-repository",
276 tag: WS_METHODS.workspaceAddTaskFolderRepository,
277 }),
278 /** A project's `worktreeLayout` commands as its `t3.json` holds them now, and whether each is approved. */
279 layoutCommands: createEnvironmentRpcQueryAtomFamily(runtime, {
280 label: "environment-data:workspace:layout-commands",
281 tag: WS_METHODS.workspaceLayoutCommands,
282 staleTimeMs: 0,
283 }),
284 /** The same read as a one-off, for a check made as a worktree thread is about to start. */
285 readLayoutCommands: createEnvironmentRpcCommand(runtime, {
286 label: "environment-data:workspace:read-layout-commands",
287 tag: WS_METHODS.workspaceLayoutCommands,
288 }),
289 approveLayoutCommands: createEnvironmentRpcCommand(runtime, {
290 label: "environment-data:workspace:approve-layout-commands",
291 tag: WS_METHODS.workspaceApproveLayoutCommands,
292 }),
293 };