Skip to content

Commit 8951d75

Browse files
committed
projects: open the add project browser in the xdg projects dir
xdg-user-dirs 0.20 creates ~/Projects by default and records it as XDG_PROJECTS_DIR in user-dirs.dirs, but the Add Project browser always started in ~/ unless "Add project starts in" was set. The server now reads XDG_PROJECTS_DIR the way xdg-user-dir does and reports the directory as userProjectsRoot in its config when it exists. Web, desktop, and mobile start browsing there while the setting is empty, and Settings shows the default each environment will use.
1 parent d0918f1 commit 8951d75

10 files changed

Lines changed: 286 additions & 15 deletions

File tree

‎apps/mobile/src/features/projects/AddProjectScreen.tsx‎

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -98,6 +98,7 @@ interface EnvironmentOption {
9898
readonly platform: string;
9999
readonly machine: EnvironmentMachineKind;
100100
readonly baseDirectory: string | null;
101+
readonly userProjectsRoot: string | null;
101102
readonly newProjectsRoot: string | null;
102103
readonly connectionState: EnvironmentConnectionPhase;
103104
readonly connectionError: string | null;
@@ -300,10 +301,11 @@ function ProjectPathInput(props: {
300301
function useBrowsePathInput(environment: EnvironmentOption | null, pinnedDirectoryName = "") {
301302
const environmentId = environment?.environmentId ?? null;
302303
const environmentBaseDirectory = environment?.baseDirectory ?? null;
304+
const environmentUserProjectsRoot = environment?.userProjectsRoot ?? null;
303305
const clonePathCaseSensitive = !isWindowsPlatform(environment?.platform ?? "");
304306
const [pathInput, commitPathInput] = useState(() =>
305307
getCloneDestinationPath(
306-
getAddProjectInitialQuery(environmentBaseDirectory),
308+
getAddProjectInitialQuery(environmentBaseDirectory, environmentUserProjectsRoot),
307309
pinnedDirectoryName,
308310
),
309311
);
@@ -376,12 +378,18 @@ function useBrowsePathInput(environment: EnvironmentOption | null, pinnedDirecto
376378
previousEnvironmentIdRef.current = environmentId;
377379
setPathInput(
378380
getCloneDestinationPath(
379-
getAddProjectInitialQuery(environmentBaseDirectory),
381+
getAddProjectInitialQuery(environmentBaseDirectory, environmentUserProjectsRoot),
380382
pinnedDirectoryName,
381383
),
382384
);
383385
}
384-
}, [environmentBaseDirectory, environmentId, pinnedDirectoryName, setPathInput]);
386+
}, [
387+
environmentBaseDirectory,
388+
environmentId,
389+
environmentUserProjectsRoot,
390+
pinnedDirectoryName,
391+
setPathInput,
392+
]);
385393

386394
useEffect(
387395
() => () => {
@@ -411,6 +419,7 @@ function useEnvironmentOptions(): ReadonlyArray<EnvironmentOption> {
411419
platform: platformFromOs(config?.environment.platform.os ?? null),
412420
machine: resolveEnvironmentMachineKind(config ?? null),
413421
baseDirectory: config?.settings.addProjectBaseDirectory ?? null,
422+
userProjectsRoot: config?.userProjectsRoot ?? null,
414423
newProjectsRoot: config?.newProjectsRoot ?? null,
415424
connectionState: runtime?.connectionState ?? "available",
416425
connectionError: runtime?.connectionError ?? null,
Lines changed: 165 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,165 @@
1+
import * as NodeServices from "@effect/platform-node/NodeServices";
2+
import { describe, expect, it } from "@effect/vitest";
3+
import * as HostProcess from "@t3tools/shared/HostProcess";
4+
import * as Effect from "effect/Effect";
5+
import * as FileSystem from "effect/FileSystem";
6+
import * as Option from "effect/Option";
7+
import * as Path from "effect/Path";
8+
9+
import { parseXdgProjectsDir, resolveUserProjectsRoot } from "./userProjectsRoot.ts";
10+
11+
// Written by xdg-user-dirs-update 0.20 for a new account
12+
const GENERATED_USER_DIRS = `# This file is written by xdg-user-dirs-update
13+
# If you want to change or add directories, just edit the line you're
14+
# interested in. All local changes will be retained on the next run.
15+
# Format is XDG_xxx_DIR="$HOME/yyy", where yyy is a shell-escaped
16+
# homedir-relative path, or XDG_xxx_DIR="/yyy", where /yyy is an
17+
# absolute path. No other format is supported.
18+
#
19+
XDG_DESKTOP_DIR="$HOME/Desktop"
20+
XDG_DOWNLOAD_DIR="$HOME/Downloads"
21+
XDG_DOCUMENTS_DIR="$HOME/Documents"
22+
XDG_PROJECTS_DIR="$HOME/Projects"
23+
`;
24+
25+
describe("parseXdgProjectsDir", () => {
26+
it("reads the directory xdg-user-dirs-update writes", () => {
27+
expect(parseXdgProjectsDir(GENERATED_USER_DIRS)).toEqual(Option.some("~/Projects"));
28+
});
29+
30+
it("accepts the same values as xdg-user-dir", () => {
31+
const cases: ReadonlyArray<readonly [string, string]> = [
32+
['XDG_PROJECTS_DIR="/srv/code/"', "/srv/code"],
33+
['XDG_PROJECTS_DIR="$HOME/My Projects"', "~/My Projects"],
34+
['XDG_PROJECTS_DIR="$HOME/a\\"b"', '~/a"b'],
35+
['XDG_PROJECTS_DIR="$HOME/a\\\\b"', "~/a\\b"],
36+
['XDG_PROJECTS_DIR="$HOME/a\\$b"', "~/a$b"],
37+
['\t XDG_PROJECTS_DIR \t= \t"$HOME/code" trailing', "~/code"],
38+
['XDG_PROJECTS_DIR="$HOME/code', "~/code"],
39+
['XDG_PROJECTS_DIR="$HOME/"', "~"],
40+
['XDG_PROJECTS_DIR="/"', "/"],
41+
];
42+
for (const [line, root] of cases) {
43+
expect(parseXdgProjectsDir(line), line).toEqual(Option.some(root));
44+
}
45+
});
46+
47+
it("ignores lines xdg-user-dir ignores", () => {
48+
const lines = [
49+
"XDG_PROJECTS_DIR=$HOME/unquoted",
50+
'export XDG_PROJECTS_DIR="$HOME/exported"',
51+
'XDG_PROJECTS_DIR="${HOME}/braced"',
52+
'XDG_PROJECTS_DIR="$HOMEx/code"',
53+
'XDG_PROJECTS_DIR="relative/code"',
54+
'XDG_PROJECTS_DIR=""',
55+
'#XDG_PROJECTS_DIR="$HOME/commented"',
56+
'XDG_PROJECTS_DIRS="$HOME/other-key"',
57+
];
58+
for (const line of lines) {
59+
expect(parseXdgProjectsDir(line), line).toEqual(Option.none());
60+
}
61+
});
62+
63+
it("uses the last valid line", () => {
64+
expect(
65+
parseXdgProjectsDir(
66+
'XDG_PROJECTS_DIR="$HOME/first"\r\nXDG_PROJECTS_DIR="$HOME/second"\r\nXDG_PROJECTS_DIR=bad\r\n',
67+
),
68+
).toEqual(Option.some("~/second"));
69+
});
70+
});
71+
72+
it.layer(NodeServices.layer)("resolveUserProjectsRoot", (it) => {
73+
const makeHome = Effect.fn("makeHome")(function* (input: {
74+
readonly userDirs?: string;
75+
readonly directories?: ReadonlyArray<string>;
76+
}) {
77+
const fileSystem = yield* FileSystem.FileSystem;
78+
const path = yield* Path.Path;
79+
const home = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-user-projects-" });
80+
for (const directory of input.directories ?? []) {
81+
yield* fileSystem.makeDirectory(path.join(home, directory), { recursive: true });
82+
}
83+
if (input.userDirs !== undefined) {
84+
yield* fileSystem.makeDirectory(path.join(home, ".config"), { recursive: true });
85+
yield* fileSystem.writeFileString(
86+
path.join(home, ".config", "user-dirs.dirs"),
87+
input.userDirs,
88+
);
89+
}
90+
return home;
91+
});
92+
93+
const resolveFor = (
94+
home: string,
95+
options: { readonly platform?: NodeJS.Platform; readonly env?: NodeJS.ProcessEnv } = {},
96+
) =>
97+
resolveUserProjectsRoot().pipe(
98+
Effect.provideService(HostProcess.Platform, options.platform ?? "linux"),
99+
Effect.provideService(HostProcess.HomeDirectory, home),
100+
Effect.provideService(HostProcess.Environment, options.env ?? {}),
101+
);
102+
103+
it.effect("returns the Projects directory when it exists", () =>
104+
Effect.gen(function* () {
105+
const home = yield* makeHome({ userDirs: GENERATED_USER_DIRS, directories: ["Projects"] });
106+
107+
expect(yield* resolveFor(home)).toEqual(Option.some("~/Projects"));
108+
}),
109+
);
110+
111+
it.effect("returns none when the directory was deleted", () =>
112+
Effect.gen(function* () {
113+
const home = yield* makeHome({ userDirs: GENERATED_USER_DIRS });
114+
115+
expect(yield* resolveFor(home)).toEqual(Option.none());
116+
}),
117+
);
118+
119+
it.effect("returns none without user-dirs.dirs", () =>
120+
Effect.gen(function* () {
121+
const home = yield* makeHome({ directories: ["Projects"] });
122+
123+
expect(yield* resolveFor(home)).toEqual(Option.none());
124+
}),
125+
);
126+
127+
it.effect("returns none when the directory is disabled by pointing it at home", () =>
128+
Effect.gen(function* () {
129+
const home = yield* makeHome({ userDirs: 'XDG_PROJECTS_DIR="$HOME/"\n' });
130+
131+
expect(yield* resolveFor(home)).toEqual(Option.none());
132+
}),
133+
);
134+
135+
// user-dirs.dirs only takes POSIX absolute paths
136+
it.effect.skipIf(HostProcess.Platform.defaultValue() === "win32")(
137+
"reads user-dirs.dirs from an absolute XDG_CONFIG_HOME",
138+
() =>
139+
Effect.gen(function* () {
140+
const fileSystem = yield* FileSystem.FileSystem;
141+
const path = yield* Path.Path;
142+
const home = yield* makeHome({ directories: ["code", "config"] });
143+
yield* fileSystem.writeFileString(
144+
path.join(home, "config", "user-dirs.dirs"),
145+
`XDG_PROJECTS_DIR="${path.join(home, "code")}"\n`,
146+
);
147+
148+
expect(
149+
yield* resolveFor(home, { env: { XDG_CONFIG_HOME: path.join(home, "config") } }),
150+
).toEqual(Option.some(path.join(home, "code")));
151+
expect(yield* resolveFor(home, { env: { XDG_CONFIG_HOME: "config" } })).toEqual(
152+
Option.none(),
153+
);
154+
}),
155+
);
156+
157+
it.effect("returns none on Windows and macOS", () =>
158+
Effect.gen(function* () {
159+
const home = yield* makeHome({ userDirs: GENERATED_USER_DIRS, directories: ["Projects"] });
160+
161+
expect(yield* resolveFor(home, { platform: "win32" })).toEqual(Option.none());
162+
expect(yield* resolveFor(home, { platform: "darwin" })).toEqual(Option.none());
163+
}),
164+
);
165+
});
Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
import { expandHomePath } from "@t3tools/provider-core/server/pathExpansion";
2+
import * as HostProcess from "@t3tools/shared/HostProcess";
3+
import * as Effect from "effect/Effect";
4+
import * as FileSystem from "effect/FileSystem";
5+
import * as Option from "effect/Option";
6+
import * as Path from "effect/Path";
7+
8+
const PROJECTS_DIR_ASSIGNMENT = /^[ \t]*XDG_PROJECTS_DIR[ \t]*=[ \t]*"((?:[^"\\]|\\.)*)/;
9+
10+
/**
11+
* Reads `user-dirs.dirs` the way xdg-user-dirs' own `xdg-user-dir` does: the
12+
* value is quoted, starts with `$HOME` or `/`, a backslash keeps the next
13+
* character, and the last valid line wins. `$HOME` comes back as `~` so
14+
* clients show the directory the way they show the `~/` default.
15+
*/
16+
export function parseXdgProjectsDir(contents: string): Option.Option<string> {
17+
const roots = contents.split(/\r?\n/).flatMap((line) => {
18+
const quoted = PROJECTS_DIR_ASSIGNMENT.exec(line)?.[1];
19+
if (quoted === undefined) return [];
20+
const value = quoted.replace(/\\(.)/g, "$1");
21+
const root =
22+
value === "$HOME" || value.startsWith("$HOME/")
23+
? `~${value.slice("$HOME".length)}`
24+
: value.startsWith("/")
25+
? value
26+
: null;
27+
return root === null ? [] : [root.replace(/(?<=.)\/+$/, "")];
28+
});
29+
return Option.fromUndefinedOr(roots.at(-1));
30+
}
31+
32+
/**
33+
* The directory xdg-user-dirs names for projects, when it exists.
34+
* xdg-user-dirs does not recreate a directory the user deleted, and Windows
35+
* and macOS have no such directory.
36+
*/
37+
export const resolveUserProjectsRoot = Effect.fn("resolveUserProjectsRoot")(function* () {
38+
const platform = yield* HostProcess.Platform;
39+
if (platform === "win32" || platform === "darwin") return Option.none<string>();
40+
41+
const fileSystem = yield* FileSystem.FileSystem;
42+
const path = yield* Path.Path;
43+
const home = yield* HostProcess.HomeDirectory;
44+
const configHome = (yield* HostProcess.Environment).XDG_CONFIG_HOME;
45+
// The base directory spec says to ignore a relative XDG_CONFIG_HOME
46+
const configDir =
47+
configHome !== undefined && path.isAbsolute(configHome)
48+
? configHome
49+
: path.join(home, ".config");
50+
const root = Option.flatMap(
51+
yield* fileSystem.readFileString(path.join(configDir, "user-dirs.dirs")).pipe(Effect.option),
52+
parseXdgProjectsDir,
53+
);
54+
if (Option.isNone(root)) return root;
55+
56+
const absoluteRoot = path.resolve(expandHomePath(root.value, home));
57+
// Pointing a user directory at home is how xdg-user-dirs disables it
58+
if (absoluteRoot === path.resolve(home)) return Option.none<string>();
59+
const info = yield* fileSystem.stat(absoluteRoot).pipe(Effect.option);
60+
return Option.isSome(info) && info.value.type === "Directory" ? root : Option.none<string>();
61+
});

‎apps/server/src/ws.ts‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -209,6 +209,7 @@ import * as ReviewService from "./review/ReviewService.ts";
209209
import * as ProjectEnrichmentService from "./project/ProjectEnrichmentService.ts";
210210
import * as ProjectService from "./project/ProjectService.ts";
211211
import * as ManagedProjectFolders from "./project/ManagedProjectFolders.ts";
212+
import { resolveUserProjectsRoot } from "./project/userProjectsRoot.ts";
212213
import { projectMutationOperation } from "./project/ProjectMutation.ts";
213214
import * as ProjectSetupScriptRunner from "./project/ProjectSetupScriptRunner.ts";
214215
import * as ProjectCloneTracker from "./project/ProjectCloneTracker.ts";
@@ -1667,6 +1668,7 @@ const layerWsRpc = (
16671668
const environment = yield* serverEnvironment.getDescriptor;
16681669
const auth = yield* serverAuth.getDescriptor();
16691670
const scratchWorkspaceRoot = yield* managedFolders.scratchRoot;
1671+
const userProjectsRoot = yield* resolveUserProjectsRoot();
16701672
const editorConfig = yield* resolveEditorConfig(
16711673
yield* resolveAvailableEditorsForConfig(externalLauncher.resolveAvailableEditors()),
16721674
resolveFileManagerRevealKindForConfig(externalLauncher.resolveFileManagerRevealKind()),
@@ -1710,6 +1712,10 @@ const layerWsRpc = (
17101712
onSome: (root) => ({ scratchWorkspaceRoot: root }),
17111713
}),
17121714
newProjectsRoot: managedFolders.namedProjectsRoot,
1715+
...Option.match(userProjectsRoot, {
1716+
onNone: () => ({}),
1717+
onSome: (root) => ({ userProjectsRoot: root }),
1718+
}),
17131719
};
17141720
});
17151721

‎apps/web/src/components/CommandPalette.tsx‎

Lines changed: 5 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ import { visibleThreadPullRequests } from "@t3tools/shared/threadPullRequests";
66
import { scopeProjectRef, scopeThreadRef } from "@t3tools/client-runtime/environment";
77
import {
88
canCreateProjectInEnvironment,
9+
getAddProjectInitialQuery,
910
getCloneDestinationBrowsePath,
1011
getCloneDestinationPath,
1112
getCloneDirectoryName,
@@ -139,7 +140,6 @@ import { useThreadSearch } from "../state/queries";
139140
import { resolveThreadActionProjectRef, startNewThreadFromContext } from "../lib/chatThreadActions";
140141
import {
141142
appendBrowsePathSegment,
142-
ensureBrowseDirectoryPath,
143143
findProjectByPath,
144144
getBrowseDirectoryPath,
145145
hasTrailingPathSeparator,
@@ -966,12 +966,10 @@ function OpenCommandPaletteDialog(props: {
966966
const paletteMode = getCommandPaletteMode({ currentView, isBrowsing });
967967
const getAddProjectInitialQueryForEnvironment = (environmentId: EnvironmentId | null): string => {
968968
const environment = environments.find((candidate) => candidate.environmentId === environmentId);
969-
const environmentSettings = environment?.serverConfig?.settings ?? null;
970-
const baseDirectory = environmentSettings?.addProjectBaseDirectory?.trim() ?? "";
971-
if (baseDirectory.length === 0) {
972-
return "~/";
973-
}
974-
return ensureBrowseDirectoryPath(baseDirectory);
969+
return getAddProjectInitialQuery(
970+
environment?.serverConfig?.settings.addProjectBaseDirectory,
971+
environment?.serverConfig?.userProjectsRoot,
972+
);
975973
};
976974

977975
const { projectCwdById, projectByKey, projectTitleById } = useProjectLookups();

‎apps/web/src/components/settings/SettingsPanels.tsx‎

Lines changed: 19 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@ import {
1717
type SidebarProjectGroupingMode,
1818
} from "@t3tools/contracts";
1919
import { scopeThreadRef } from "@t3tools/client-runtime/environment";
20+
import { getAddProjectInitialQuery } from "@t3tools/client-runtime/operations/projects";
2021
import { presentThreadShell } from "@t3tools/client-runtime/state/shell";
2122
import {
2223
isAtomCommandInterrupted,
@@ -2119,6 +2120,14 @@ export function GeneralSettingsPanel() {
21192120
const backgroundActivityProfileOption = resolveBackgroundActivityProfileOption(settings);
21202121
const mixedBackgroundActivity = useScopedSettingsMixed(["backgroundActivity"]);
21212122
const mixedAddProjectBaseDirectory = useScopedSettingsMixed(["addProjectBaseDirectory"]);
2123+
const addProjectDefaultQueries = new Set(
2124+
connectedEnvironments.map((target) =>
2125+
getAddProjectInitialQuery(null, target.serverConfig?.userProjectsRoot),
2126+
),
2127+
);
2128+
// Each environment in scope can have its own projects directory
2129+
const addProjectDefaultQuery =
2130+
addProjectDefaultQueries.size > 1 ? null : (Array.from(addProjectDefaultQueries)[0] ?? "~/");
21222131
const mixedTextGenerationModel = useScopedSettingsMixed(["textGenerationModelSelection"]);
21232132
const backgroundActivityDescription =
21242133
backgroundActivityProfileOption === "advanced"
@@ -2967,7 +2976,11 @@ export function GeneralSettingsPanel() {
29672976
serverScoped
29682977
settingKeys={["addProjectBaseDirectory"]}
29692978
{...searchableSetting("add-project-starts-in")}
2970-
description='Leave empty to use "~/" when the Add Project browser opens.'
2979+
description={
2980+
addProjectDefaultQuery === null
2981+
? "Leave empty to start in each environment's projects directory, or its home directory."
2982+
: `Leave empty to use "${addProjectDefaultQuery}" when the Add Project browser opens.`
2983+
}
29712984
resetAction={
29722985
settings.addProjectBaseDirectory !==
29732986
DEFAULT_UNIFIED_SETTINGS.addProjectBaseDirectory ? (
@@ -2987,7 +3000,11 @@ export function GeneralSettingsPanel() {
29873000
className="w-full sm:w-72"
29883001
value={mixedAddProjectBaseDirectory ? "" : settings.addProjectBaseDirectory}
29893002
onCommit={(next) => updateSettings({ addProjectBaseDirectory: next })}
2990-
placeholder={mixedAddProjectBaseDirectory ? "Mixed" : "~/"}
3003+
placeholder={
3004+
mixedAddProjectBaseDirectory || addProjectDefaultQuery === null
3005+
? "Mixed"
3006+
: addProjectDefaultQuery
3007+
}
29913008
spellCheck={false}
29923009
aria-label="Add project base directory"
29933010
/>

‎apps/web/src/lib/projectPaths.ts‎

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
export {
22
appendBrowsePathSegment,
33
canNavigateUp,
4-
ensureBrowseDirectoryPath,
54
findProjectByPath,
65
getBrowseDirectoryPath,
76
getBrowseLeafPathSegment,

0 commit comments

Comments
 (0)