The best way to control Claude Code, Codex and more from any computer or phone

main
ts 222 lines 7.38 KB
Raw
1 import {
2 AuthFilesystemReadScope,
3 type FilesystemBrowseEntry,
4 WS_METHODS,
5 sessionGrantsScope,
6 type SessionGrantInput,
7 } from "@t3tools/contracts";
8 import { scoreQueryMatch } from "@t3tools/shared/searchRanking";
9 import { Atom } from "effect/reactivity";
10
11 import { mFallback, msg } from "gt-i18n";
12 import type { MFunctionType } from "gt-i18n/types";
13
14 import {
15 connectionErrorText,
16 type EnvironmentConnectionPhase,
17 type EnvironmentConnectionPresentation,
18 } from "../connection/presentation.ts";
19 import type { EnvironmentRegistry } from "../connection/registry.ts";
20 import {
21 canNavigateUp,
22 getBrowseDirectoryPath,
23 getBrowseLeafPathSegment,
24 getBrowseParentPath,
25 hasTrailingPathSeparator,
26 isFilesystemBrowseQuery,
27 } from "./projects.ts";
28 import { createEnvironmentRpcQueryAtomFamily } from "./runtime.ts";
29
30 const BROWSE_IDLE_TTL_MS = 5_000;
31
32 export function resolveFilesystemReadAccess(
33 input: {
34 readonly isCatalogReady: boolean;
35 readonly connection: Pick<
36 EnvironmentConnectionPresentation,
37 "phase" | "error" | "i18nError"
38 > | null;
39 readonly session: SessionGrantInput | null;
40 readonly sessionError: string | null;
41 },
42 resolve: MFunctionType = mFallback,
43 ) {
44 if (input.sessionError !== null) {
45 return { canReadFiles: false, isPending: false, error: input.sessionError };
46 }
47 if (input.session === null) {
48 // Wait for the catalog before interpreting a missing presentation as offline.
49 // Once ready, an offline environment cannot finish its session check.
50 const isPending =
51 !input.isCatalogReady ||
52 input.connection?.phase === "connected" ||
53 input.connection?.phase === "connecting" ||
54 input.connection?.phase === "reconnecting";
55 return {
56 canReadFiles: false,
57 isPending,
58 error: isPending
59 ? null
60 : ((input.connection === null ? null : connectionErrorText(input.connection, resolve)) ??
61 resolve(msg("This environment is not connected."))),
62 };
63 }
64 return {
65 canReadFiles: sessionGrantsScope(input.session, AuthFilesystemReadScope),
66 isPending: false,
67 error: null,
68 };
69 }
70
71 export function getFilesystemBrowsePath(query: string, platform = "", enabled = true) {
72 const isBrowsing = enabled && isFilesystemBrowseQuery(query, platform);
73 const directoryPath = isBrowsing ? getBrowseDirectoryPath(query) : "";
74 const filterQuery =
75 isBrowsing && !hasTrailingPathSeparator(query) ? getBrowseLeafPathSegment(query) : "";
76 const parentPath = isBrowsing ? getBrowseParentPath(directoryPath) : null;
77
78 return {
79 isBrowsing,
80 directoryPath,
81 filterQuery,
82 parentPath,
83 canBrowseUp: isBrowsing && canNavigateUp(directoryPath),
84 };
85 }
86
87 export function filterFilesystemBrowseEntries(
88 entries: ReadonlyArray<FilesystemBrowseEntry>,
89 query: string,
90 ) {
91 // macOS Finder stores names decomposed (NFD), while typed text is composed (NFC).
92 const normalizedQuery = query.normalize("NFC");
93 const lowerQuery = query.toLowerCase();
94 const lowerNormalizedQuery = normalizedQuery.toLowerCase();
95 const showHidden = query.startsWith(".");
96 const candidates = entries.filter((entry) => showHidden || !entry.name.startsWith("."));
97 const visibleEntries =
98 lowerQuery.length === 0
99 ? candidates
100 : candidates
101 .map((entry) => {
102 const options = {
103 // Position penalties stay under 1000 for 255-character names, so tiers never overlap.
104 query: lowerNormalizedQuery,
105 exactBase: 0,
106 prefixBase: 1000,
107 boundaryBase: 2000,
108 includesBase: 3000,
109 fuzzyBase: 4000,
110 boundaryMarkers: [" ", "-", "_", "."],
111 };
112 const rawScore = scoreQueryMatch({
113 ...options,
114 value: entry.name.toLowerCase(),
115 query: lowerQuery,
116 });
117 const normalizedScore = scoreQueryMatch({
118 ...options,
119 value: entry.name.normalize("NFC").toLowerCase(),
120 });
121 const score =
122 rawScore === null
123 ? normalizedScore
124 : normalizedScore === null
125 ? rawScore
126 : Math.min(rawScore, normalizedScore);
127 return { entry, score };
128 })
129 .filter((match): match is { entry: FilesystemBrowseEntry; score: number } => {
130 return match.score !== null;
131 })
132 .sort((left, right) => left.score - right.score)
133 .map((match) => match.entry);
134 const normalizedMatches = visibleEntries.filter(
135 (entry) => entry.name.normalize("NFC") === normalizedQuery,
136 );
137 const exactEntry =
138 query.length > 0
139 ? (visibleEntries.find((entry) => entry.name === query) ??
140 (normalizedMatches.length === 1 ? normalizedMatches[0] : null))
141 : null;
142
143 return { visibleEntries, exactEntry };
144 }
145
146 /** Shell-style Tab: a single match enters the directory, several extend to their common prefix. */
147 export function getFilesystemBrowseTabCompletion(
148 visibleEntries: ReadonlyArray<FilesystemBrowseEntry>,
149 filterQuery: string,
150 ): { readonly name: string; readonly isComplete: boolean } | null {
151 const lowerQuery = filterQuery.toLowerCase();
152 const lowerNormalizedQuery = filterQuery.normalize("NFC").toLowerCase();
153 const prefixEntries = visibleEntries.filter(
154 (entry) =>
155 entry.name.toLowerCase().startsWith(lowerQuery) ||
156 entry.name.normalize("NFC").toLowerCase().startsWith(lowerNormalizedQuery),
157 );
158 const [first, ...rest] = prefixEntries;
159 if (first === undefined) return null;
160 if (rest.length === 0) return { name: first.name, isComplete: true };
161 let prefix = Array.from(first.name);
162 for (const entry of rest) {
163 const characters = Array.from(entry.name);
164 let length = 0;
165 while (
166 length < prefix.length &&
167 prefix[length]?.toLowerCase() === characters[length]?.toLowerCase()
168 )
169 length += 1;
170 prefix = prefix.slice(0, length);
171 }
172 const name = prefix.join("");
173 const lowerName = name.toLowerCase();
174 return lowerName.length > lowerQuery.length &&
175 prefixEntries.every((entry) => entry.name.toLowerCase().startsWith(lowerName))
176 ? { name, isComplete: false }
177 : null;
178 }
179
180 export function createBrowseNavigationCoordinator() {
181 let generation = 0;
182
183 return {
184 invalidate: () => {
185 generation += 1;
186 },
187 run: async (load: () => Promise<void>, commit: () => void) => {
188 const navigationGeneration = ++generation;
189 await load();
190 if (navigationGeneration !== generation) {
191 return false;
192 }
193 commit();
194 return true;
195 },
196 };
197 }
198
199 export function canPreloadBrowsePath(
200 connectionPhase: EnvironmentConnectionPhase | null | undefined,
201 ): boolean {
202 return connectionPhase === "connected";
203 }
204
205 export function createFilesystemEnvironmentAtoms<R, E>(
206 runtime: Atom.AtomRuntime<EnvironmentRegistry | R, E>,
207 ) {
208 return {
209 getMetadata: createEnvironmentRpcQueryAtomFamily(runtime, {
210 label: "environment-data:filesystem:get-metadata",
211 tag: WS_METHODS.filesystemGetMetadata,
212 }),
213 browse: createEnvironmentRpcQueryAtomFamily(runtime, {
214 label: "environment-data:filesystem:browse",
215 tag: WS_METHODS.filesystemBrowse,
216 // A listing mirrors a directory that can change outside the app, so reopening a picker
217 // lists it again. The short TTL only keeps the old listing on screen while it refreshes.
218 idleTtlMs: BROWSE_IDLE_TTL_MS,
219 staleTimeMs: 0,
220 }),
221 };
222 }