Skip to content

Commit c610e40

Browse files
committed
fix(server): make projectless thread directory configurable
1 parent 125b619 commit c610e40

8 files changed

Lines changed: 172 additions & 15 deletions

File tree

‎apps/server/src/cli/config.test.ts‎

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -120,6 +120,37 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
120120
);
121121
});
122122

123+
it.effect("resolves the configured Scratch directory relative to the host cwd", () =>
124+
Effect.gen(function* () {
125+
const fs = yield* FileSystem.FileSystem;
126+
const path = yield* Path.Path;
127+
const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-scratch-config-" });
128+
const homeDir = yield* HostProcess.HomeDirectory;
129+
for (const [value, expected] of [
130+
[undefined, undefined],
131+
["", undefined],
132+
[" ", undefined],
133+
["~/projectless", path.join(homeDir, "projectless")],
134+
["./projectless", path.resolve("projectless")],
135+
[path.join(baseDir, "chats"), path.join(baseDir, "chats")],
136+
] as const) {
137+
const config = yield* resolveServerConfig(minimalDesktopFlags(baseDir), Option.none()).pipe(
138+
Effect.provide(
139+
Layer.merge(
140+
NetService.layer,
141+
ConfigProvider.layer(
142+
ConfigProvider.fromEnv({
143+
env: value === undefined ? {} : { T3CODE_SCRATCH_DIR: value },
144+
}),
145+
),
146+
),
147+
),
148+
);
149+
expect(config.scratchDir).toBe(expected);
150+
}
151+
}),
152+
);
153+
123154
it.effect("keeps stale records and supervised startup out of the manual launch preflight", () =>
124155
Effect.gen(function* () {
125156
const fs = yield* FileSystem.FileSystem;

‎apps/server/src/cli/config.ts‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -130,6 +130,10 @@ const EnvServerConfig = Config.all({
130130
port: Config.Port("T3CODE_PORT").pipe(Config.option, Config.map(Option.getOrUndefined)),
131131
host: Config.String("T3CODE_HOST").pipe(Config.option, Config.map(Option.getOrUndefined)),
132132
t3Home: Config.String("T3CODE_HOME").pipe(Config.option, Config.map(Option.getOrUndefined)),
133+
scratchDir: Config.String("T3CODE_SCRATCH_DIR").pipe(
134+
Config.option,
135+
Config.map(Option.getOrUndefined),
136+
),
133137
devUrl: Config.URL("VITE_DEV_SERVER_URL").pipe(Config.option, Config.map(Option.getOrUndefined)),
134138
devAllowedOrigins: Config.String("T3CODE_DEV_ALLOWED_ORIGINS").pipe(
135139
Config.withDefault(""),
@@ -326,6 +330,9 @@ export const resolveServerConfig = Effect.fn("config.resolveServerConfig")(funct
326330
);
327331
const rawCwd = Option.getOrElse(normalizedFlags.cwd, () => process.cwd());
328332
const cwd = path.resolve(yield* expandHomePath(rawCwd.trim()));
333+
const scratchDir = env.scratchDir?.trim()
334+
? path.resolve(yield* expandHomePath(env.scratchDir.trim()))
335+
: undefined;
329336
const derivedPaths = yield* ServerConfig.deriveServerPaths(baseDir, devUrl, {
330337
baseDirIsExplicit: Option.isSome(explicitBaseDir),
331338
});
@@ -484,6 +491,7 @@ export const resolveServerConfig = Effect.fn("config.resolveServerConfig")(funct
484491
cwd,
485492
baseDir,
486493
...derivedPaths,
494+
...(scratchDir === undefined ? {} : { scratchDir }),
487495
serverTracePath,
488496
host,
489497
...(privateNetworkOnly ? { privateNetworkOnly } : {}),

‎apps/server/src/config.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -88,6 +88,7 @@ export class ServerConfig extends Context.Service<
8888
readonly privateNetworkOnly?: boolean | undefined;
8989
readonly cwd: string;
9090
readonly baseDir: string;
91+
readonly scratchDir?: string | undefined;
9192
readonly staticDir: string | undefined;
9293
readonly devUrl: URL | undefined;
9394
readonly devAuthToken?: Redacted.Redacted<string> | undefined;

‎apps/server/src/project/AgentSessionScanner.test.ts‎

Lines changed: 26 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,7 @@ interface ScannerTestInput {
4848
readonly codexHomePath: string;
4949
readonly importedWorkspaceRoots?: ReadonlyArray<string>;
5050
readonly configBaseDir?: string;
51+
readonly scratchDir?: string;
5152
readonly providerInstances?: ContractServerSettings["providerInstances"];
5253
}
5354

@@ -68,9 +69,18 @@ const layerScannerTest = (input: ScannerTestInput) =>
6869
...input.providerInstances,
6970
},
7071
}),
71-
ServerConfig.layerTest(
72-
input.claudeHomePath,
73-
input.configBaseDir ?? { prefix: "t3code-scanner-config-" },
72+
Layer.effect(
73+
ServerConfig.ServerConfig,
74+
ServerConfig.ServerConfig.pipe(
75+
Effect.map((config) => ({ ...config, scratchDir: input.scratchDir })),
76+
),
77+
).pipe(
78+
Layer.provide(
79+
ServerConfig.layerTest(
80+
input.claudeHomePath,
81+
input.configBaseDir ?? { prefix: "t3code-scanner-config-" },
82+
),
83+
),
7484
),
7585
layerProjectStore(input.importedWorkspaceRoots ?? []),
7686
),
@@ -667,18 +677,28 @@ it.layer(NodeServices.layer)("AgentSessionScanner", (it) => {
667677
}),
668678
);
669679

670-
it.effect("excludes the home directory, temporary root, and T3 data directory", () =>
680+
it.effect("excludes home, temporary, data, and configured Scratch directories", () =>
671681
Effect.gen(function* () {
672682
const path = yield* Path.Path;
673683
const claudeHomePath = yield* makeTempDir("t3code-claude-home-");
674684
const codexHomePath = yield* makeTempDir("t3code-codex-home-");
675685
const configBaseDir = yield* makeTempDir("t3code-scanner-base-");
676-
const workspace = yield* makeTempDir("t3code-workspace-");
686+
const scratchDir = yield* makeTempDir("t3code-scanner-custom-");
687+
const workspace = `${scratchDir}-project`;
688+
const fs = yield* FileSystem.FileSystem;
689+
yield* fs.makeDirectory(workspace);
690+
yield* Effect.addFinalizer(() =>
691+
fs.remove(workspace, { recursive: true }).pipe(Effect.orDie),
692+
);
693+
const chat = path.join(scratchDir, "chat");
694+
yield* fs.makeDirectory(chat);
677695

678696
for (const [index, cwd] of [
679697
NodeOS.homedir(),
680698
NodeOS.tmpdir(),
681699
configBaseDir,
700+
scratchDir,
701+
chat,
682702
workspace,
683703
].entries()) {
684704
yield* writeTranscript({
@@ -688,7 +708,7 @@ it.layer(NodeServices.layer)("AgentSessionScanner", (it) => {
688708
});
689709
}
690710

691-
const result = yield* runScan({ claudeHomePath, codexHomePath, configBaseDir });
711+
const result = yield* runScan({ claudeHomePath, codexHomePath, configBaseDir, scratchDir });
692712

693713
expect(result.candidates.map((candidate) => candidate.path)).toEqual([workspace]);
694714
}),

‎apps/server/src/project/AgentSessionScanner.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -643,6 +643,7 @@ export const make = Effect.gen(function* () {
643643
const excludedProjectAncestors = [
644644
path.join(homeDir, "Downloads"),
645645
path.join(homeDir, "Documents", "Codex"),
646+
...(serverConfig.scratchDir === undefined ? [] : [path.resolve(serverConfig.scratchDir)]),
646647
];
647648

648649
const isExcludedProjectPath = (candidatePath: string) =>

‎apps/server/src/project/ManagedProjectFolders.test.ts‎

Lines changed: 60 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -51,6 +51,7 @@ const layerEnrichment = ProjectEnrichmentService.layer.pipe(
5151
const layerRealGit = GitVcsDriver.layer.pipe(Layer.provide(VcsProcess.layer));
5252

5353
interface HarnessOptions {
54+
readonly scratchDir?: string;
5455
readonly vcsProcess?: Layer.Layer<VcsProcess.VcsProcess>;
5556
readonly git?: Layer.Layer<GitVcsDriver.GitVcsDriver>;
5657
readonly projects?: (
@@ -75,7 +76,14 @@ const layer = (baseDir: string, options?: HarnessOptions) =>
7576
Layer.provideMerge(options?.git ?? layerRealGit),
7677
Layer.provideMerge(SqlitePersistence.layerMemory),
7778
Layer.provideMerge(ServerSettings.layerTest()),
78-
Layer.provideMerge(ServerConfig.layerTest(baseDir, baseDir)),
79+
Layer.provideMerge(
80+
Layer.effect(
81+
ServerConfig.ServerConfig,
82+
ServerConfig.ServerConfig.pipe(
83+
Effect.map((config) => ({ ...config, scratchDir: options?.scratchDir })),
84+
),
85+
).pipe(Layer.provide(ServerConfig.layerTest(baseDir, baseDir))),
86+
),
7987
Layer.provideMerge(NodeServices.layer),
8088
);
8189

@@ -259,6 +267,57 @@ it.effect("gives each Scratch thread its own folder, named from its message", ()
259267
),
260268
);
261269

270+
it.effect("uses a configured directory without changing the Scratch project", () =>
271+
Effect.gen(function* () {
272+
const fs = yield* FileSystem.FileSystem;
273+
const path = yield* Path.Path;
274+
const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-scratch-custom-" });
275+
const baseDir = path.join(root, "data");
276+
const scratchDir = path.join(root, "custom", "chats");
277+
yield* Effect.gen(function* () {
278+
const scratch = yield* ManagedProjectFolders.ManagedProjectFolders;
279+
const projects = yield* ProjectService.ProjectService;
280+
const { projectId } = yield* scratch.ensureScratchProject;
281+
const project = Option.getOrThrow(yield* projects.getById(projectId));
282+
assert.equal(project.workspaceRoot, path.join(baseDir, "scratch"));
283+
assert.isTrue(yield* scratch.isScratchProject(projectId));
284+
const folders = yield* Effect.forEach(
285+
["thread:a:12345678", "thread:b:12345678"],
286+
(threadId) =>
287+
scratch.folderForThread({ projectId, threadId: ThreadId.make(threadId), text: "Hello" }),
288+
);
289+
const paths = folders.map(Option.getOrThrow);
290+
assert.equal(new Set(paths).size, 2);
291+
for (const folder of paths) {
292+
assert.equal(path.dirname(folder), scratchDir);
293+
assert.isTrue(yield* fs.exists(folder));
294+
}
295+
assert.deepEqual(yield* fs.readDirectory(project.workspaceRoot), []);
296+
}).pipe(Effect.provide(layer(baseDir, { scratchDir })));
297+
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
298+
);
299+
300+
it.effect("rejects a configured Scratch directory inside a Git checkout", () =>
301+
Effect.gen(function* () {
302+
const fs = yield* FileSystem.FileSystem;
303+
const path = yield* Path.Path;
304+
const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-scratch-custom-repo-" });
305+
const checkout = path.join(root, "repo");
306+
yield* fs.makeDirectory(checkout);
307+
yield* git(checkout, ["init", "--quiet"]);
308+
const scratchDir = path.join(checkout, "missing", "chats");
309+
yield* Effect.gen(function* () {
310+
const scratch = yield* ManagedProjectFolders.ManagedProjectFolders;
311+
assert.isTrue(Option.isNone(yield* scratch.scratchRoot));
312+
assert.equal(
313+
(yield* Effect.flip(scratch.ensureScratchProject))._tag,
314+
"ScratchUnavailableError",
315+
);
316+
assert.isFalse(yield* fs.exists(scratchDir));
317+
}).pipe(Effect.provide(layer(path.join(root, "data"), { scratchDir })));
318+
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
319+
);
320+
262321
it.effect("leaves threads in other projects alone", () =>
263322
withScratch(({ baseDir }) =>
264323
Effect.gen(function* () {

‎apps/server/src/project/ManagedProjectFolders.ts‎

Lines changed: 23 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -230,13 +230,27 @@ const make = Effect.gen(function* () {
230230
}
231231
});
232232

233-
// Scratch inside a checkout would inherit its git status and checkpoints; require a data dir outside work trees.
233+
// Both the project root and thread folders must stay outside checkouts to avoid inheriting Git state.
234234
const [probe, invalidate] = yield* Effect.cachedInvalidateWithTTL(
235-
gitWorkflow.isRepository(config.baseDir).pipe(
236-
Effect.catchIf(isGitMissing, () => Effect.succeed(false)),
237-
Effect.map((isRepository) =>
238-
isRepository ? Option.none<string>() : Option.some(path.resolve(config.baseDir, "scratch")),
239-
),
235+
Effect.gen(function* () {
236+
const directories = [config.baseDir];
237+
if (config.scratchDir !== undefined) {
238+
let existing = config.scratchDir;
239+
while (!(yield* fileSystem.exists(existing))) {
240+
const parent = path.dirname(existing);
241+
if (parent === existing) break;
242+
existing = parent;
243+
}
244+
directories.push(existing);
245+
}
246+
for (const directory of directories) {
247+
const isRepository = yield* gitWorkflow
248+
.isRepository(directory)
249+
.pipe(Effect.catchIf(isGitMissing, () => Effect.succeed(false)));
250+
if (isRepository) return Option.none<string>();
251+
}
252+
return Option.some(path.resolve(config.baseDir, "scratch"));
253+
}).pipe(
240254
Effect.catchCause((cause) =>
241255
Cause.hasInterrupts(cause) ? Effect.interrupt : Effect.succeed(Option.none<string>()),
242256
),
@@ -320,12 +334,13 @@ const make = Effect.gen(function* () {
320334
const root = yield* scratchRoot;
321335
if (Option.isNone(root)) return Option.none();
322336
if (!(yield* isScratchRoot(input.projectId, root.value))) return Option.none();
337+
const threadRoot = config.scratchDir ?? root.value;
323338
const date = DateTime.formatIso(yield* DateTime.now).slice(0, 10);
324339
const words = folderWords(input.text);
325340
const id = input.threadId.toLowerCase().replace(/[^a-z0-9]/g, "");
326341
const folderFor = (idPart: string) =>
327-
path.join(root.value, [date, words, idPart].filter(Boolean).join("-"));
328-
yield* makeScratchFolder(root.value);
342+
path.join(threadRoot, [date, words, idPart].filter(Boolean).join("-"));
343+
yield* makeScratchFolder(threadRoot);
329344
const fullFolder = folderFor(id);
330345
return yield* claimFreeFolder(
331346
(attempt) =>

‎docs/user/providers-codex.md‎

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,28 @@ T3 Code can use your installed Codex and its existing login. Run `codex login`
2525
on the environment's machine to sign in. [Provider setup](./install.md#providers)
2626
covers installation and custom configuration.
2727

28+
## Projectless threads in other Codex clients
29+
30+
Codex clients sharing the same Codex home can display T3 Code's **No project**
31+
threads as separate projects. To choose where new projectless threads work, set
32+
`T3CODE_SCRATCH_DIR` on the machine running the T3 server and restart it. For
33+
Codex clients that recognize dated folders under `~/Documents/Codex`, start with:
34+
35+
```bash
36+
T3CODE_SCRATCH_DIR="$HOME/Documents/Codex" t3
37+
```
38+
39+
For a background service, set the variable in its
40+
[service environment file](./background-service.md). Desktop launches must inherit
41+
the variable too; setting it only in a provider's environment does not configure
42+
the T3 server.
43+
44+
Choose a dedicated directory outside Git repositories. The setting applies to all
45+
new projectless threads on that server. Existing threads keep their directories
46+
and files. Unset the variable to use the default T3 scratch directory for new
47+
threads again. Codex's directory recognition can change between releases, and
48+
this does not reclassify older threads in Codex.
49+
2850
## Use multiple accounts
2951

3052
Add another ChatGPT account in **Settings → Providers**, then select the account

0 commit comments

Comments
 (0)