Skip to content
Merged
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
222 changes: 222 additions & 0 deletions apps/server/src/serverRuntimeStartup.test.ts
Original file line number Diff line number Diff line change
@@ -1,20 +1,50 @@
import { assert, it } from "@effect/vitest";
import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
import {
DEFAULT_SERVER_SETTINGS,
DEFAULT_MODEL,
ProjectId,
ProviderInstanceId,
ProviderDriverKind,
CommandId,
EnvironmentId,
type ServerLifecycleStreamEvent,
} from "@t3tools/contracts";
import { DEFAULT_SIGNAL_EXPORT } from "@t3tools/shared/observability";
import * as OtelEnvironment from "@t3tools/shared/otelEnvironment";
import { HttpServer } from "effect/http";
import * as NetAddress from "effect/net/NetAddress";
import * as Deferred from "effect/Deferred";
import * as Effect from "effect/Effect";
import * as Exit from "effect/Exit";
import * as Fiber from "effect/Fiber";
import * as Ref from "effect/Ref";
import * as Layer from "effect/Layer";
import * as Path from "effect/Path";

import * as GitVcsDriver from "./vcs/GitVcsDriver.ts";

import * as ServerConfig from "./config.ts";
import * as ServerRuntimeStartup from "./serverRuntimeStartup.ts";
import * as EnvironmentAuth from "./auth/EnvironmentAuth.ts";
import * as ServiceLauncherClient from "./cloud/serviceLauncherClient.ts";
import * as ServerEnvironment from "./environment/ServerEnvironment.ts";
import * as Keybindings from "./keybindings.ts";
import * as EffectWorker from "./orchestration-v2/EffectWorker.ts";
import * as LegacyV1ThreadImporter from "./orchestration-v2/legacy/LegacyV1ThreadImporter.ts";
import * as Orchestrator from "./orchestration-v2/Orchestrator.ts";
import * as ProjectStore from "./orchestration-v2/ProjectStore.ts";
import * as ProviderRuntimeRecovery from "./orchestration-v2/ProviderRuntimeRecoveryService.ts";
import * as ProviderSessionManager from "./orchestration-v2/ProviderSessionManager.ts";
import * as ThreadLaunch from "./orchestration-v2/ThreadLaunchService.ts";
import * as ThreadManagement from "./orchestration-v2/ThreadManagementService.ts";
import * as ExternalLauncher from "./process/externalLauncher.ts";
import * as ProjectService from "./project/ProjectService.ts";
import * as AgentAwarenessRelay from "./relay/AgentAwarenessRelay.ts";
import { ServerActivation } from "./serverActivation.ts";
import * as ServerLifecycleEvents from "./serverLifecycleEvents.ts";
import * as ServerSettings from "./serverSettings.ts";
import * as AnalyticsService from "./telemetry/AnalyticsService.ts";

it("uses the canonical Codex model for auto-bootstrap", () => {
assert.deepEqual(ServerRuntimeStartup.getAutoBootstrapThreadModelSelection(), {
Expand All @@ -23,6 +53,198 @@ it("uses the canonical Codex model for auto-bootstrap", () => {
});
});

it.effect.each([
"disabled-codex",
"disabled-default",
"launch-failure",
"project-failure",
] as const)("keeps bootstrap launch failures separate from project failures: %s", (scenario) =>
Effect.scoped(
Effect.gen(function* () {
const projectId = ProjectId.make("bootstrap-project");
const instanceId = ProviderInstanceId.make(
scenario === "disabled-default" ? "custom" : "codex",
);
const events: ServerLifecycleStreamEvent[] = [];
const recovery = {
terminalizedRuns: 0,
stoppedSessions: 0,
closedRequests: 0,
retiredEffects: 0,
requeuedEffects: 0,
};
const imports = { importedThreadCount: 0, importedMessageCount: 0 };
const dependencies = Layer.mergeAll(
NodeCrypto.layer,
Path.layer,
Layer.mock(ServerConfig.ServerConfig)({
...(yield* ServerConfig.deriveServerPaths("/bootstrap-project", undefined).pipe(
Effect.provide(Path.layer),
)),
baseDir: "/bootstrap-project",
logLevel: "Error",
traceMinLevel: "Info",
traceTimingEnabled: false,
traceBatchWindowMs: 200,
traceMaxBytes: 1024,
traceMaxFiles: 1,
otlpTracesUrl: undefined,
otlpMetricsUrl: undefined,
otlpLogsUrl: undefined,
otlpTracesExport: DEFAULT_SIGNAL_EXPORT,
otlpMetricsExport: DEFAULT_SIGNAL_EXPORT,
otlpLogsExport: DEFAULT_SIGNAL_EXPORT,
otelEnvironment: OtelEnvironment.none,
staticDir: undefined,
devAllowedOrigins: [],
desktopBootstrapToken: undefined,
logWebSocketEvents: false,
tailscaleServeEnabled: false,
tailscaleServePort: 443,
mode: "web",
cwd: "/bootstrap-project",
host: "localhost",
port: 3773,
devUrl: undefined,
noBrowser: true,
startupPresentation: "browser",
autoBootstrapProjectFromCwd: true,
}),
Layer.mock(Keybindings.Keybindings)({ start: Effect.void }),
Layer.mock(LegacyV1ThreadImporter.LegacyV1ThreadImporter)({
pendingThreadCount: Effect.succeed(0),
reconcileShells: Effect.succeed(imports),
importPendingTranscripts: Effect.succeed(imports),
}),
Layer.mock(ProviderRuntimeRecovery.ProviderRuntimeRecoveryService)({
recover: Effect.succeed(recovery),
prepareForShutdown: Effect.void,
reconcile: () => Effect.succeed(recovery),
}),
Layer.mock(Orchestrator.OrchestratorV2)({ recoverDelegatedTasks: Effect.void }),
Layer.mock(ProviderSessionManager.ProviderSessionManagerV2)({ shutdown: Effect.void }),
Layer.mock(AgentAwarenessRelay.AgentAwarenessRelay)({ start: () => Effect.void }),
Layer.mock(EffectWorker.OrchestrationEffectWorkerV2)({ runOnce: Effect.never }),
Layer.mock(ServerLifecycleEvents.ServerLifecycleEvents)({
publish: (event) =>
Effect.sync(() => {
const published = { ...event, sequence: events.length + 1 };
events.push(published);
return published;
}),
}),
Layer.mock(ServerSettings.ServerSettingsService)({
start: Effect.void,
getSettings: Effect.succeed({
...DEFAULT_SERVER_SETTINGS,
defaultModelSelection:
scenario === "disabled-default" ? { instanceId, model: "custom-model" } : null,
providerInstances: {
[instanceId]: {
driver: ProviderDriverKind.make("codex"),
enabled: false,
config: {},
},
},
}),
}),
Layer.mock(ServerEnvironment.ServerEnvironment)({
getDescriptor: Effect.succeed({
environmentId: EnvironmentId.make("bootstrap-environment"),
label: "Test environment",
platform: { os: "linux", arch: "x64" },
serverVersion: "0.0.0-test",
capabilities: { repositoryIdentity: true },
}),
}),
Layer.mock(ProjectStore.ProjectStoreV2)({}),
Layer.mock(ProjectService.ProjectService)({
bootstrap: () =>
scenario === "project-failure"
? Effect.die("project bootstrap failed")
: Effect.succeed({
created: true,
project: {
id: projectId,
title: "Project",
workspaceRoot: "/bootstrap-project",
repositoryIdentity: null,
faviconPath: null,
scripts: [],
createdAt: "2026-01-01T00:00:00Z",
updatedAt: "2026-01-01T00:00:00Z",
deletedAt: null,
defaultModelSelection:
scenario === "disabled-default"
? { instanceId, model: "custom-model" }
: null,
},
}),
}),
Layer.mock(ThreadManagement.ThreadManagementService)({
getShellSnapshot: () =>
Effect.succeed({
threads: [],
archivedThreads: [],
schemaVersion: 1,
snapshotSequence: 0,
}),
}),
Layer.mock(ThreadLaunch.ThreadLaunchService)({
launch: (input) => {
assert.equal(input.modelSelection.instanceId, instanceId);
return scenario === "launch-failure"
? Effect.fail(
new ThreadLaunch.ThreadLaunchError({
operation: "create-thread",
commandId: CommandId.make("bootstrap-command"),
projectId,
cause: "test launch failure",
}),
)
: Effect.fail(
new ThreadManagement.ThreadManagementProviderInstanceDisabledError({
projectId,
instanceId,
}),
);
},
}),
Layer.mock(ServiceLauncherClient.ServiceLauncherClient)({
managed: false,
prepareTrial: Effect.succeed(undefined),
}),
Layer.mock(GitVcsDriver.GitVcsDriver)({}),
Layer.mock(AnalyticsService.AnalyticsService)({}),
Layer.mock(EnvironmentAuth.EnvironmentAuth)({}),
Layer.mock(ExternalLauncher.ExternalLauncher)({}),
Layer.mock(HttpServer.HttpServer)({
address: NetAddress.inetAddressFromIpStringUnsafe("127.0.0.1", 3773),
}),
);
yield* Effect.gen(function* () {
const startup = yield* ServerRuntimeStartup.ServerRuntimeStartup;
yield* startup.markHttpListening;
const ready = yield* Effect.exit(startup.awaitCommandReady);
assert.equal(Exit.isSuccess(ready), scenario !== "project-failure");
const welcome = events.find((event) => event.type === "welcome");
if (scenario === "project-failure") {
assert.isUndefined(welcome);
} else {
assert.isDefined(welcome);
if (welcome?.type === "welcome") {
assert.equal(welcome.payload.bootstrapProjectId, projectId);
assert.isUndefined(welcome.payload.bootstrapThreadId);
}
}
}).pipe(
Effect.provide(ServerRuntimeStartup.layerWithOptions().pipe(Layer.provide(dependencies))),
Effect.provideService(ServerActivation, Effect.never),
);
}),
),
);

it.effect("starts without scanning or rebuilding projection history", () =>
Effect.gen(function* () {
const calls = yield* Ref.make<ReadonlyArray<string>>([]);
Expand Down
46 changes: 31 additions & 15 deletions apps/server/src/serverRuntimeStartup.ts
Original file line number Diff line number Diff line change
Expand Up @@ -285,22 +285,38 @@ const resolveAutoBootstrapWelcomeTargets = Effect.gen(function* () {
if (existingThread === undefined) {
const serverSettings = yield* ServerSettings.ServerSettingsService;
const settings = yield* serverSettings.getSettings;
const launched = yield* threadLaunch.launch({
commandId: CommandId.make(yield* randomUUID),
projectId: project.id,
title: "New thread",
modelSelection:
resolveProjectSettings(settings, project.id, project).settings.defaultModelSelection ??
threadModelSelection,
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: resolveProjectSettings(settings, project.id, project).settings
.defaultRuntimeMode,
workspaceStrategy: { type: "root" },
createdBy: "system",
creationSource: "server",
});
const launched = yield* threadLaunch
.launch({
commandId: CommandId.make(yield* randomUUID),
projectId: project.id,
title: "New thread",
modelSelection:
resolveProjectSettings(settings, project.id, project).settings.defaultModelSelection ??
threadModelSelection,
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: resolveProjectSettings(settings, project.id, project).settings
.defaultRuntimeMode,
workspaceStrategy: { type: "root" },
createdBy: "system",
creationSource: "server",
})
.pipe(
// The bootstrap thread is optional; its launch must not prevent opening the app.
Effect.catchTags({
ThreadManagementProviderInstanceDisabledError: (error) =>
Effect.logInfo("Skipped bootstrap thread because its provider instance is disabled", {
projectId: project.id,
instanceId: error.instanceId,
}).pipe(Effect.as(undefined)),
ThreadLaunchError: (error) =>
Effect.logWarning("Failed to launch bootstrap thread", {
projectId: project.id,
operation: error.operation,
}).pipe(Effect.as(undefined)),
}),
);
bootstrapProjectId = project.id;
bootstrapThreadId = launched.threadId;
bootstrapThreadId = launched?.threadId;
} else {
bootstrapProjectId = project.id;
bootstrapThreadId = existingThread.id;
Expand Down
Loading