Open History to see the last commit
1import {
2 CommandId,
3 DEFAULT_MODEL_BY_PROVIDER,
4 DEFAULT_PROVIDER_INTERACTION_MODE,
5 type ModelSelection,
6 ProjectId,
7 ThreadId,
8} from "@workbench/contracts";
9import {
10 Data,
11 Deferred,
12 Effect,
13 Exit,
14 Layer,
15 Option,
16 Path,
17 Queue,
18 Ref,
19 Scope,
20 Context,
21 Console,
22} from "effect";
23
24import { ServerConfig } from "./config.ts";
25import { Keybindings } from "./keybindings.ts";
26import { Open } from "./open.ts";
27import { OrchestrationEngineService } from "./orchestration/Services/OrchestrationEngine.ts";
28import { ProjectionSnapshotQuery } from "./orchestration/Services/ProjectionSnapshotQuery.ts";
29import { OrchestrationReactor } from "./orchestration/Services/OrchestrationReactor.ts";
30import { ServerLifecycleEvents } from "./serverLifecycleEvents.ts";
31import { ServerSettingsService } from "./serverSettings.ts";
32import { ServerEnvironment } from "./environment/Services/ServerEnvironment.ts";
33import { AnalyticsService } from "./telemetry/Services/AnalyticsService.ts";
34import { ServerAuth } from "./auth/Services/ServerAuth.ts";
35import { ProviderSessionReaper } from "./provider/Services/ProviderSessionReaper.ts";
36import {
37 formatHeadlessServeOutput,
38 formatHostForUrl,
39 isWildcardHost,
40 issueHeadlessServeAccessInfo,
41} from "./startupAccess.ts";
42
43export class ServerRuntimeStartupError extends Data.TaggedError("ServerRuntimeStartupError")<{
44 readonly message: string;
45 readonly cause?: unknown;
46}> {}
47
48export interface ServerRuntimeStartupShape {
49 readonly awaitCommandReady: Effect.Effect<void, ServerRuntimeStartupError>;
50 readonly markHttpListening: Effect.Effect<void>;
51 readonly enqueueCommand: <A, E>(
52 effect: Effect.Effect<A, E>,
53 ) => Effect.Effect<A, E | ServerRuntimeStartupError>;
54}
55
56export class ServerRuntimeStartup extends Context.Service<
57 ServerRuntimeStartup,
58 ServerRuntimeStartupShape
59>()("t3/serverRuntimeStartup") {}
60
61interface QueuedCommand {
62 readonly run: Effect.Effect<void, never>;
63}
64
65type CommandReadinessState = "pending" | "ready" | ServerRuntimeStartupError;
66
67interface CommandGate {
68 readonly awaitCommandReady: Effect.Effect<void, ServerRuntimeStartupError>;
69 readonly signalCommandReady: Effect.Effect<void>;
70 readonly failCommandReady: (error: ServerRuntimeStartupError) => Effect.Effect<void>;
71 readonly enqueueCommand: <A, E>(
72 effect: Effect.Effect<A, E>,
73 ) => Effect.Effect<A, E | ServerRuntimeStartupError>;
74}
75
76const settleQueuedCommand = <A, E>(deferred: Deferred.Deferred<A, E>, exit: Exit.Exit<A, E>) =>
77 Exit.isSuccess(exit)
78 ? Deferred.succeed(deferred, exit.value)
79 : Deferred.failCause(deferred, exit.cause);
80
81export const makeCommandGate = Effect.gen(function* () {
82 const commandReady = yield* Deferred.make<void, ServerRuntimeStartupError>();
83 const commandQueue = yield* Queue.unbounded<QueuedCommand>();
84 const commandReadinessState = yield* Ref.make<CommandReadinessState>("pending");
85
86 const commandWorker = Effect.forever(
87 Queue.take(commandQueue).pipe(Effect.flatMap((command) => command.run)),
88 );
89 yield* Effect.forkScoped(commandWorker);
90
91 return {
92 awaitCommandReady: Deferred.await(commandReady),
93 signalCommandReady: Effect.gen(function* () {
94 yield* Ref.set(commandReadinessState, "ready");
95 yield* Deferred.succeed(commandReady, undefined).pipe(Effect.orDie);
96 }),
97 failCommandReady: (error) =>
98 Effect.gen(function* () {
99 yield* Ref.set(commandReadinessState, error);
100 yield* Deferred.fail(commandReady, error).pipe(Effect.orDie);
101 }),
102 enqueueCommand: <A, E>(effect: Effect.Effect<A, E>) =>
103 Effect.gen(function* () {
104 const readinessState = yield* Ref.get(commandReadinessState);
105 if (readinessState === "ready") {
106 return yield* effect;
107 }
108 if (readinessState !== "pending") {
109 return yield* readinessState;
110 }
111
112 const result = yield* Deferred.make<A, E | ServerRuntimeStartupError>();
113 yield* Queue.offer(commandQueue, {
114 run: Deferred.await(commandReady).pipe(
115 Effect.flatMap(() => effect),
116 Effect.exit,
117 Effect.flatMap((exit) => settleQueuedCommand(result, exit)),
118 ),
119 });
120 return yield* Deferred.await(result);
121 }),
122 } satisfies CommandGate;
123});
124
125export const recordStartupHeartbeat = Effect.gen(function* () {
126 const analytics = yield* AnalyticsService;
127 const projectionSnapshotQuery = yield* ProjectionSnapshotQuery;
128
129 const { threadCount, projectCount } = yield* projectionSnapshotQuery.getCounts().pipe(
130 Effect.catch((cause) =>
131 Effect.logWarning("failed to gather startup projection counts for telemetry", {
132 cause,
133 }).pipe(
134 Effect.as({
135 threadCount: 0,
136 projectCount: 0,
137 }),
138 ),
139 ),
140 );
141
142 yield* analytics.record("server.boot.heartbeat", {
143 threadCount,
144 projectCount,
145 });
146});
147
148export const launchStartupHeartbeat = recordStartupHeartbeat.pipe(
149 Effect.annotateSpans({ "startup.phase": "heartbeat.record" }),
150 Effect.withSpan("server.startup.heartbeat.record"),
151 Effect.ignoreCause({ log: true }),
152 Effect.forkScoped,
153 Effect.asVoid,
154);
155
156export const getAutoBootstrapDefaultModelSelection = (): ModelSelection => ({
157 provider: "codex",
158 model: DEFAULT_MODEL_BY_PROVIDER.codex,
159});
160
161export const resolveWelcomeBase = Effect.gen(function* () {
162 const serverConfig = yield* ServerConfig;
163 const segments = serverConfig.cwd.split(/[/\\]/).filter(Boolean);
164 const projectName = segments[segments.length - 1] ?? "project";
165
166 return {
167 cwd: serverConfig.cwd,
168 projectName,
169 } as const;
170});
171
172export const resolveAutoBootstrapWelcomeTargets = Effect.gen(function* () {
173 const serverConfig = yield* ServerConfig;
174 const projectionReadModelQuery = yield* ProjectionSnapshotQuery;
175 const orchestrationEngine = yield* OrchestrationEngineService;
176 const path = yield* Path.Path;
177
178 let bootstrapProjectId: ProjectId | undefined;
179 let bootstrapThreadId: ThreadId | undefined;
180
181 if (serverConfig.autoBootstrapProjectFromCwd) {
182 yield* Effect.gen(function* () {
183 const existingProject = yield* projectionReadModelQuery.getActiveProjectByWorkspaceRoot(
184 serverConfig.cwd,
185 );
186 let nextProjectId: ProjectId;
187 let nextProjectDefaultModelSelection: ModelSelection;
188
189 if (Option.isNone(existingProject)) {
190 const createdAt = new Date().toISOString();
191 nextProjectId = ProjectId.make(crypto.randomUUID());
192 const bootstrapProjectTitle = path.basename(serverConfig.cwd) || "project";
193 nextProjectDefaultModelSelection = getAutoBootstrapDefaultModelSelection();
194 yield* orchestrationEngine.dispatch({
195 type: "project.create",
196 commandId: CommandId.make(crypto.randomUUID()),
197 projectId: nextProjectId,
198 title: bootstrapProjectTitle,
199 workspaceRoot: serverConfig.cwd,
200 defaultModelSelection: nextProjectDefaultModelSelection,
201 createdAt,
202 });
203 } else {
204 nextProjectId = existingProject.value.id;
205 nextProjectDefaultModelSelection =
206 existingProject.value.defaultModelSelection ?? getAutoBootstrapDefaultModelSelection();
207 }
208
209 const existingThreadId =
210 yield* projectionReadModelQuery.getFirstActiveThreadIdByProjectId(nextProjectId);
211 if (Option.isNone(existingThreadId)) {
212 const createdAt = new Date().toISOString();
213 const createdThreadId = ThreadId.make(crypto.randomUUID());
214 yield* orchestrationEngine.dispatch({
215 type: "thread.create",
216 commandId: CommandId.make(crypto.randomUUID()),
217 threadId: createdThreadId,
218 projectId: nextProjectId,
219 title: "New thread",
220 modelSelection: nextProjectDefaultModelSelection,
221 interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
222 runtimeMode: "full-access",
223 branch: null,
224 worktreePath: null,
225 createdAt,
226 });
227 bootstrapProjectId = nextProjectId;
228 bootstrapThreadId = createdThreadId;
229 } else {
230 bootstrapProjectId = nextProjectId;
231 bootstrapThreadId = existingThreadId.value;
232 }
233 });
234 }
235
236 return {
237 ...(bootstrapProjectId ? { bootstrapProjectId } : {}),
238 ...(bootstrapThreadId ? { bootstrapThreadId } : {}),
239 } as const;
240});
241
242const resolveStartupBrowserTarget = Effect.gen(function* () {
243 const serverConfig = yield* ServerConfig;
244 const serverAuth = yield* ServerAuth;
245 const localUrl = `http://localhost:${serverConfig.port}`;
246 const bindUrl =
247 serverConfig.host && !isWildcardHost(serverConfig.host)
248 ? `http://${formatHostForUrl(serverConfig.host)}:${serverConfig.port}`
249 : localUrl;
250 const baseTarget = serverConfig.devUrl?.toString() ?? bindUrl;
251 return yield* Effect.succeed(serverConfig.mode === "desktop" ? baseTarget : undefined).pipe(
252 Effect.flatMap((target) =>
253 target ? Effect.succeed(target) : serverAuth.issueStartupPairingUrl(baseTarget),
254 ),
255 );
256});
257
258const maybeOpenBrowser = (target: string) =>
259 Effect.gen(function* () {
260 const serverConfig = yield* ServerConfig;
261 if (serverConfig.noBrowser) {
262 return;
263 }
264 const { openBrowser } = yield* Open;
265
266 yield* openBrowser(target).pipe(
267 Effect.catch(() =>
268 Effect.logInfo("browser auto-open unavailable", {
269 hint: `Open ${target} in your browser.`,
270 }),
271 ),
272 );
273 });
274
275const runStartupPhase = <A, E, R>(phase: string, effect: Effect.Effect<A, E, R>) =>
276 effect.pipe(
277 Effect.annotateSpans({ "startup.phase": phase }),
278 Effect.withSpan(`server.startup.${phase}`),
279 );
280
281export const makeServerRuntimeStartup = Effect.gen(function* () {
282 const serverConfig = yield* ServerConfig;
283 const keybindings = yield* Keybindings;
284 const orchestrationReactor = yield* OrchestrationReactor;
285 const providerSessionReaper = yield* ProviderSessionReaper;
286 const lifecycleEvents = yield* ServerLifecycleEvents;
287 const serverSettings = yield* ServerSettingsService;
288 const serverEnvironment = yield* ServerEnvironment;
289
290 const commandGate = yield* makeCommandGate;
291 const httpListening = yield* Deferred.make<void>();
292 const reactorScope = yield* Scope.make("sequential");
293
294 yield* Effect.addFinalizer(() => Scope.close(reactorScope, Exit.void));
295
296 const startup = Effect.gen(function* () {
297 yield* Effect.logDebug("startup phase: starting keybindings runtime");
298 yield* runStartupPhase(
299 "keybindings.start",
300 keybindings.start.pipe(
301 Effect.catch((error) =>
302 Effect.logWarning("failed to start keybindings runtime", {
303 path: error.configPath,
304 detail: error.detail,
305 cause: error.cause,
306 }),
307 ),
308 Effect.forkScoped,
309 ),
310 );
311
312 yield* Effect.logDebug("startup phase: starting server settings runtime");
313 yield* runStartupPhase(
314 "settings.start",
315 serverSettings.start.pipe(
316 Effect.catch((error) =>
317 Effect.logWarning("failed to start server settings runtime", {
318 path: error.settingsPath,
319 detail: error.detail,
320 cause: error.cause,
321 }),
322 ),
323 Effect.forkScoped,
324 ),
325 );
326
327 yield* Effect.logDebug("startup phase: starting orchestration reactors");
328 yield* runStartupPhase(
329 "reactors.start",
330 Effect.gen(function* () {
331 yield* orchestrationReactor.start().pipe(Scope.provide(reactorScope));
332 yield* providerSessionReaper.start().pipe(Scope.provide(reactorScope));
333 }),
334 );
335
336 const welcomeBase = yield* resolveWelcomeBase;
337 const environment = yield* serverEnvironment.getDescriptor;
338 yield* Effect.logDebug("startup phase: preparing welcome payload");
339 yield* Effect.logDebug("startup phase: publishing welcome event", {
340 environmentId: environment.environmentId,
341 cwd: welcomeBase.cwd,
342 projectName: welcomeBase.projectName,
343 });
344 yield* runStartupPhase(
345 "welcome.publish",
346 lifecycleEvents.publish({
347 version: 1,
348 type: "welcome",
349 payload: {
350 environment,
351 ...welcomeBase,
352 },
353 }),
354 );
355
356 if (serverConfig.autoBootstrapProjectFromCwd) {
357 yield* Effect.forkScoped(
358 runStartupPhase(
359 "welcome.autobootstrap",
360 Effect.gen(function* () {
361 const bootstrapTargets = yield* resolveAutoBootstrapWelcomeTargets;
362 if (!bootstrapTargets.bootstrapProjectId && !bootstrapTargets.bootstrapThreadId) {
363 return;
364 }
365
366 yield* Effect.logDebug("startup phase: publishing bootstrapped welcome event", {
367 environmentId: environment.environmentId,
368 cwd: welcomeBase.cwd,
369 projectName: welcomeBase.projectName,
370 bootstrapProjectId: bootstrapTargets.bootstrapProjectId,
371 bootstrapThreadId: bootstrapTargets.bootstrapThreadId,
372 });
373 yield* lifecycleEvents.publish({
374 version: 1,
375 type: "welcome",
376 payload: {
377 environment,
378 ...welcomeBase,
379 ...bootstrapTargets,
380 },
381 });
382 }).pipe(
383 Effect.catch((cause) =>
384 Effect.logWarning("startup auto-bootstrap welcome failed", {
385 cause,
386 }),
387 ),
388 ),
389 ),
390 );
391 }
392 }).pipe(
393 Effect.annotateSpans({
394 "server.mode": serverConfig.mode,
395 "server.port": serverConfig.port,
396 "server.host": serverConfig.host ?? "default",
397 }),
398 Effect.withSpan("server.startup", { kind: "server", root: true }),
399 );
400
401 yield* Effect.forkScoped(
402 Effect.gen(function* () {
403 const startupExit = yield* Effect.exit(startup);
404 if (Exit.isFailure(startupExit)) {
405 const error = new ServerRuntimeStartupError({
406 message: "Server runtime startup failed before command readiness.",
407 cause: startupExit.cause,
408 });
409 yield* Effect.logError("server runtime startup failed", { cause: startupExit.cause });
410 yield* commandGate.failCommandReady(error);
411 return;
412 }
413
414 yield* Effect.logDebug("Accepting commands");
415 yield* commandGate.signalCommandReady;
416 yield* Effect.logDebug("startup phase: waiting for http listener");
417 yield* runStartupPhase("http.wait", Deferred.await(httpListening));
418 yield* Effect.logDebug("startup phase: publishing ready event");
419 yield* runStartupPhase(
420 "ready.publish",
421 lifecycleEvents.publish({
422 version: 1,
423 type: "ready",
424 payload: {
425 at: new Date().toISOString(),
426 environment: yield* serverEnvironment.getDescriptor,
427 },
428 }),
429 );
430
431 yield* Effect.logDebug("startup phase: recording startup heartbeat");
432 yield* launchStartupHeartbeat;
433 if (serverConfig.startupPresentation === "headless") {
434 yield* Effect.logDebug("startup phase: headless access info");
435 const accessInfo = yield* issueHeadlessServeAccessInfo();
436 yield* runStartupPhase(
437 "headless.output",
438 Console.log(formatHeadlessServeOutput(accessInfo)),
439 );
440 } else {
441 yield* Effect.logDebug("startup phase: browser open check");
442 const startupBrowserTarget = yield* resolveStartupBrowserTarget;
443 if (serverConfig.mode !== "desktop") {
444 yield* Effect.logInfo(
445 "Authentication required. Open Workbench using the pairing URL.",
446 ).pipe(Effect.annotateLogs({ pairingUrl: startupBrowserTarget }));
447 }
448 yield* runStartupPhase("browser.open", maybeOpenBrowser(startupBrowserTarget));
449 }
450 yield* Effect.logDebug("startup phase: complete");
451 }),
452 );
453
454 return {
455 awaitCommandReady: commandGate.awaitCommandReady,
456 markHttpListening: Deferred.succeed(httpListening, undefined),
457 enqueueCommand: commandGate.enqueueCommand,
458 } satisfies ServerRuntimeStartupShape;
459});
460
461export const ServerRuntimeStartupLive = Layer.effect(
462 ServerRuntimeStartup,
463 makeServerRuntimeStartup,
464);