import { AuthFilesystemReadScope, type FilesystemBrowseEntry, WS_METHODS, sessionGrantsScope, type SessionGrantInput, } from "@t3tools/contracts"; import { normalizeProjectPathForDispatch } from "@t3tools/shared/path"; import { scoreQueryMatch } from "@t3tools/shared/searchRanking"; import * as Effect from "effect/Effect"; import { Atom } from "effect/reactivity"; import { mFallback, msg } from "gt-i18n"; import type { MFunctionType } from "gt-i18n/types"; import { connectionErrorText, type EnvironmentConnectionPhase, type EnvironmentConnectionPresentation, } from "../connection/presentation.ts"; import type { EnvironmentRegistry } from "../connection/registry.ts"; import { canNavigateUp, ensureBrowseDirectoryPath, getBrowseDirectoryPath, getBrowseLeafPathSegment, getBrowseParentPath, hasTrailingPathSeparator, isFilesystemBrowseQuery, } from "./projects.ts"; import { createEnvironmentRpcCommand, createEnvironmentRpcQueryAtomFamily } from "./runtime.ts"; const BROWSE_IDLE_TTL_MS = 5_000; export function resolveFilesystemReadAccess( input: { readonly isCatalogReady: boolean; readonly connection: Pick< EnvironmentConnectionPresentation, "phase" | "error" | "i18nError" > | null; readonly session: SessionGrantInput | null; readonly sessionError: string | null; }, resolve: MFunctionType = mFallback, ) { if (input.sessionError !== null) { return { canReadFiles: false, isPending: false, error: input.sessionError }; } if (input.session === null) { // Wait for the catalog before interpreting a missing presentation as offline. // Once ready, an offline environment cannot finish its session check. const isPending = !input.isCatalogReady || input.connection?.phase === "connected" || input.connection?.phase === "connecting" || input.connection?.phase === "reconnecting"; return { canReadFiles: false, isPending, error: isPending ? null : ((input.connection === null ? null : connectionErrorText(input.connection, resolve)) ?? resolve(msg("This environment is not connected."))), }; } return { canReadFiles: sessionGrantsScope(input.session, AuthFilesystemReadScope), isPending: false, error: null, }; } export function getFilesystemBrowsePath(query: string, platform = "", enabled = true) { const isBrowsing = enabled && isFilesystemBrowseQuery(query, platform); // A bare drive has no separator, so it would otherwise filter its own listing by "D:". const browseQuery = /^[a-zA-Z]:$/.test(query) ? `${query}\\` : query; const directoryPath = isBrowsing ? getBrowseDirectoryPath(browseQuery) : ""; const filterQuery = isBrowsing && !hasTrailingPathSeparator(browseQuery) ? getBrowseLeafPathSegment(browseQuery) : ""; const parentPath = isBrowsing ? getBrowseParentPath(directoryPath) : null; return { isBrowsing, directoryPath, filterQuery, parentPath, canBrowseUp: isBrowsing && canNavigateUp(directoryPath), }; } export function filterFilesystemBrowseEntries( entries: ReadonlyArray, query: string, ) { // macOS Finder stores names decomposed (NFD), while typed text is composed (NFC). const normalizedQuery = query.normalize("NFC"); const lowerQuery = query.toLowerCase(); const lowerNormalizedQuery = normalizedQuery.toLowerCase(); const showHidden = query.startsWith("."); const candidates = entries.filter((entry) => showHidden || !entry.name.startsWith(".")); const visibleEntries = lowerQuery.length === 0 ? candidates : candidates .map((entry) => { const options = { // Position penalties stay under 1000 for 255-character names, so tiers never overlap. query: lowerNormalizedQuery, exactBase: 0, prefixBase: 1000, boundaryBase: 2000, includesBase: 3000, fuzzyBase: 4000, boundaryMarkers: [" ", "-", "_", "."], }; const rawScore = scoreQueryMatch({ ...options, value: entry.name.toLowerCase(), query: lowerQuery, }); const normalizedScore = scoreQueryMatch({ ...options, value: entry.name.normalize("NFC").toLowerCase(), }); const score = rawScore === null ? normalizedScore : normalizedScore === null ? rawScore : Math.min(rawScore, normalizedScore); return { entry, score }; }) .filter((match): match is { entry: FilesystemBrowseEntry; score: number } => { return match.score !== null; }) .sort((left, right) => left.score - right.score) .map((match) => match.entry); const normalizedMatches = visibleEntries.filter( (entry) => entry.name.normalize("NFC") === normalizedQuery, ); const exactEntry = query.length > 0 ? (visibleEntries.find((entry) => entry.name === query) ?? (normalizedMatches.length === 1 ? normalizedMatches[0] : null)) : null; return { visibleEntries, exactEntry }; } /** Shell-style Tab: a single match enters the directory, several extend to their common prefix. */ export function getFilesystemBrowseTabCompletion( visibleEntries: ReadonlyArray, filterQuery: string, ): { readonly name: string; readonly isComplete: boolean } | null { const lowerQuery = filterQuery.toLowerCase(); const lowerNormalizedQuery = filterQuery.normalize("NFC").toLowerCase(); const prefixEntries = visibleEntries.filter( (entry) => entry.name.toLowerCase().startsWith(lowerQuery) || entry.name.normalize("NFC").toLowerCase().startsWith(lowerNormalizedQuery), ); const [first, ...rest] = prefixEntries; if (first === undefined) return null; if (rest.length === 0) return { name: first.name, isComplete: true }; const rawName = sharedNamePrefix(prefixEntries, lowerQuery, (entryName) => entryName); if (rawName !== null) return { name: rawName, isComplete: false }; // A shared accented prefix spelled decomposed (macOS) and composed has no raw match; // compare composed forms, which must still extend the composed query. const composedName = sharedNamePrefix(prefixEntries, lowerNormalizedQuery, (entryName) => entryName.normalize("NFC"), ); return composedName?.toLowerCase().startsWith(lowerNormalizedQuery) ? { name: composedName, isComplete: false } : null; } function sharedNamePrefix( entries: ReadonlyArray, lowerQuery: string, spell: (name: string) => string, ): string | null { const [first, ...rest] = entries; if (first === undefined) return null; let prefix = Array.from(spell(first.name)); for (const entry of rest) { const characters = Array.from(spell(entry.name)); let length = 0; while ( length < prefix.length && prefix[length]?.toLowerCase() === characters[length]?.toLowerCase() ) length += 1; prefix = prefix.slice(0, length); if (prefix.length === 0) return null; } const name = prefix.join(""); const lowerName = name.toLowerCase(); return lowerName.length > lowerQuery.length && entries.every((entry) => spell(entry.name).toLowerCase().startsWith(lowerName)) ? name : null; } export function createBrowseNavigationCoordinator() { let generation = 0; return { invalidate: () => { generation += 1; }, run: async (load: () => Promise, commit: () => void) => { const navigationGeneration = ++generation; await load(); if (navigationGeneration !== generation) { return false; } commit(); return true; }, }; } export function canPreloadBrowsePath( connectionPhase: EnvironmentConnectionPhase | null | undefined, ): boolean { return connectionPhase === "connected"; } export function createFilesystemEnvironmentAtoms( runtime: Atom.AtomRuntime, ) { const browse = createEnvironmentRpcQueryAtomFamily(runtime, { label: "environment-data:filesystem:browse", tag: WS_METHODS.filesystemBrowse, // A listing mirrors a directory that can change outside the app, so reopening a picker // lists it again. The short TTL only keeps the old listing on screen while it refreshes. idleTtlMs: BROWSE_IDLE_TTL_MS, staleTimeMs: 0, }); return { getMetadata: createEnvironmentRpcQueryAtomFamily(runtime, { label: "environment-data:filesystem:get-metadata", tag: WS_METHODS.filesystemGetMetadata, }), browse, /** Home folders and mounted volumes; volumes come and go, so this refreshes after a while. */ places: createEnvironmentRpcQueryAtomFamily(runtime, { label: "environment-data:filesystem:places", tag: WS_METHODS.filesystemPlaces, idleTtlMs: 60_000, staleTimeMs: 30_000, }), searchDirectories: createEnvironmentRpcQueryAtomFamily(runtime, { label: "environment-data:filesystem:search-directories", tag: WS_METHODS.filesystemSearchDirectories, idleTtlMs: 10_000, staleTimeMs: 5_000, }), createDirectory: createEnvironmentRpcCommand(runtime, { label: "environment-data:filesystem:create-directory", tag: WS_METHODS.filesystemCreateDirectory, onSuccess: ({ environmentId, input }, registry, result) => Effect.sync(() => { const absoluteParent = getBrowseDirectoryPath(result.path); const parents = [ { path: input.parentPath, cwd: input.cwd }, { path: absoluteParent, cwd: input.cwd }, { path: absoluteParent, cwd: undefined }, ]; const cachedListings = new Set( parents.flatMap(({ path, cwd }) => [path, normalizeProjectPathForDispatch(path), ensureBrowseDirectoryPath(path)].map( (partialPath) => browse({ environmentId, input: { partialPath, cwd } }), ), ), ); for (const listing of cachedListings) registry.refresh(listing); }), }), /** Repositories under a folder and in its `.code-workspace` file, read from disk each time. */ scanFolders: createEnvironmentRpcQueryAtomFamily(runtime, { label: "environment-data:workspace:scan-folders", tag: WS_METHODS.workspaceScanFolders, staleTimeMs: 0, }), /** A project's tracked folders with what is on disk now: a repository, plain files, or gone. */ listFolders: createEnvironmentRpcQueryAtomFamily(runtime, { label: "environment-data:workspace:list-folders", tag: WS_METHODS.workspaceListFolders, staleTimeMs: 0, }), /** The task folder a thread's `worktreePath` belongs to, with each repository's worktree. */ taskFolder: createEnvironmentRpcQueryAtomFamily(runtime, { label: "environment-data:workspace:task-folder", tag: WS_METHODS.workspaceTaskFolder, staleTimeMs: 0, }), addTaskFolderRepository: createEnvironmentRpcCommand(runtime, { label: "environment-data:workspace:add-task-folder-repository", tag: WS_METHODS.workspaceAddTaskFolderRepository, }), /** A project's `worktreeLayout` commands as its `t3.json` holds them now, and whether each is approved. */ layoutCommands: createEnvironmentRpcQueryAtomFamily(runtime, { label: "environment-data:workspace:layout-commands", tag: WS_METHODS.workspaceLayoutCommands, staleTimeMs: 0, }), /** The same read as a one-off, for a check made as a worktree thread is about to start. */ readLayoutCommands: createEnvironmentRpcCommand(runtime, { label: "environment-data:workspace:read-layout-commands", tag: WS_METHODS.workspaceLayoutCommands, }), approveLayoutCommands: createEnvironmentRpcCommand(runtime, { label: "environment-data:workspace:approve-layout-commands", tag: WS_METHODS.workspaceApproveLayoutCommands, }), }; }