Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
55 changes: 55 additions & 0 deletions apps/server/src/orchestration-v2/ProviderSessionManager.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ import { TestClock } from "effect/testing";
import { HttpServer } from "effect/http";

import { ProviderWorkspaceMissingError } from "../provider/Errors.ts";
import * as ServerConfig from "../config.ts";
import * as ServerEnvironment from "../environment/ServerEnvironment.ts";
import * as ProjectService from "../project/ProjectService.ts";
import * as McpProviderSession from "@t3tools/provider-core/server/mcpSession";
Expand Down Expand Up @@ -492,6 +493,7 @@ function layerTest(input: {
readonly scopeCloseReached?: Deferred.Deferred<void>;
readonly serverSettingsLayer?: ReturnType<typeof ServerSettings.layerTest>;
readonly projectServiceLayer?: Layer.Layer<ProjectService.ProjectService>;
readonly baseDir?: string;
}) {
const layerConfiguredEventSink =
input.flakyReleaseWrites !== undefined
Expand Down Expand Up @@ -574,6 +576,13 @@ function layerTest(input: {
layerTestStores,
...(input.serverSettingsLayer === undefined ? [] : [input.serverSettingsLayer]),
...(input.projectServiceLayer === undefined ? [] : [input.projectServiceLayer]),
...(input.baseDir === undefined
? []
: [
Layer.succeed(ServerConfig.ServerConfig, {
baseDir: input.baseDir,
} as ServerConfig.ServerConfig["Service"]),
]),
),
),
),
Expand Down Expand Up @@ -3736,6 +3745,52 @@ it.effect.each(["missing", "file"] as const)(
}).pipe(Effect.provide(NodeServices.layer)),
);

it.effect.each(["scratch", "outside-scratch"] as const)(
"recreates a missing %s workspace only inside the scratch root",
(location) =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const root = yield* fileSystem.makeTempDirectoryScoped();
const scratchRoot = `${root}/scratch`;
yield* fileSystem.makeDirectory(scratchRoot);
const cwd =
location === "scratch" ? `${scratchRoot}/2026-11-07-thread-161f3ded` : `${root}/project`;
const state = yield* Ref.make(emptyState);
yield* Effect.gen(function* () {
const manager = yield* ProviderSessionManager.ProviderSessionManagerV2;
const eventSink = yield* EventSink.EventSinkV2;
const idAllocator = yield* IdAllocator.IdAllocatorV2;
const threadId = ThreadId.make(`thread-${location}-recreate`);
const providerSessionId = yield* idAllocator.allocate.providerSession({
providerInstanceId: modelSelection.instanceId,
threadId,
});
yield* eventSink.write({
events: [
yield* makeThreadCreatedEvent({ idAllocator, threadId, now: yield* DateTime.now }),
],
});
const result = yield* manager
.open({
threadId,
providerSessionId,
modelSelection,
runtimePolicy: { ...runtimePolicy, cwd },
})
.pipe(Effect.exit);
if (location === "scratch") {
assert.isTrue(Exit.isSuccess(result));
assert.equal((yield* fileSystem.stat(cwd)).type, "Directory");
assert.equal((yield* Ref.get(state)).openCount, 1);
} else {
assert.isTrue(Exit.isFailure(result));
assert.isFalse(yield* fileSystem.exists(cwd));
assert.equal((yield* Ref.get(state)).openCount, 0);
}
}).pipe(Effect.provide(layerTest({ state, idleTimeoutMs: 60_000, baseDir: root })));
}).pipe(Effect.provide(NodeServices.layer)),
);

it.effect(
"rejects a deleted workspace before reusing a live session without changing its state",
() =>
Expand Down
30 changes: 29 additions & 1 deletion apps/server/src/orchestration-v2/ProviderSessionManager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ import * as FiberSet from "effect/FiberSet";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Path from "effect/Path";
import * as Queue from "effect/Queue";
import * as Ref from "effect/Ref";
import * as Schedule from "effect/Schedule";
Expand All @@ -42,6 +43,7 @@ import {
} from "../observability/Metrics.ts";
import { ProviderWorkspaceMissingError } from "../provider/Errors.ts";
import * as ProjectService from "../project/ProjectService.ts";
import * as ServerConfig from "../config.ts";
import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderSessions";
import * as ServerSettings from "../serverSettings.ts";
import * as McpSessionRegistry from "../mcp/McpSessionRegistry.ts";
Expand Down Expand Up @@ -340,6 +342,32 @@ export const layerWithOptions = (
/** Unreadable settings must preserve explicit browser-access opt-outs. */
const serverSettings = yield* Effect.serviceOption(ServerSettings.ServerSettingsService);
const projectService = yield* Effect.serviceOption(ProjectService.ProjectService);
const serverConfig = yield* Effect.serviceOption(ServerConfig.ServerConfig);
/**
* A scratch thread's folder is disposable and owned by T3, so cleanup may remove it while
* the thread lives on. Recreate it empty instead of failing the session open; any other
* missing workspace (projects, worktrees) still fails, since an empty folder would mislead.
*/
const pathService = yield* Effect.serviceOption(Path.Path);
const recreateMissingScratchWorkspace = Effect.fn(
"ProviderSessionManagerV2.recreateMissingScratchWorkspace",
)(
function* (cwd: string) {
if (Option.isNone(serverConfig) || Option.isNone(pathService)) return false;
const path = pathService.value;
// Same root ManagedProjectFolders creates scratch thread folders in.
const scratchRoot = path.resolve(serverConfig.value.baseDir, "scratch");
const resolved = path.resolve(cwd);
if (path.dirname(resolved) !== scratchRoot) return false;
if (yield* fileSystem.exists(resolved)) return false;
yield* fileSystem.makeDirectory(resolved, { recursive: true });
yield* Effect.logInfo("orchestration-v2.driver-session.scratch-workspace-recreated", {
cwd: resolved,
});
return true;
},
Effect.orElseSucceed(() => false),
);
const eventSink = yield* EventSink.EventSinkV2;
const commandOutput = yield* CommandOutputHub.CommandOutputHub;
const idAllocator = yield* IdAllocator.IdAllocatorV2;
Expand Down Expand Up @@ -2127,7 +2155,7 @@ export const layerWithOptions = (
Effect.map((stat) => stat.type === "Directory"),
Effect.catch((error) => Effect.succeed(error.reason._tag !== "NotFound")),
);
if (!workspaceIsDirectory) {
if (!workspaceIsDirectory && !(yield* recreateMissingScratchWorkspace(cwd))) {
return yield* new ProviderWorkspaceMissingError({
threadId: input.threadId,
cwd,
Expand Down
Loading