diff --git a/.github/workflows/lazurio-fork-ci.yml b/.github/workflows/lazurio-fork-ci.yml index 18ee37c8797fd..887ac61e096de 100644 --- a/.github/workflows/lazurio-fork-ci.yml +++ b/.github/workflows/lazurio-fork-ci.yml @@ -440,6 +440,11 @@ jobs: apps/web/src/components/ThreadNotificationCoordinator.tsx apps/web/src/state/entities.ts apps/web/src/hooks/useActiveProjectTarget.ts + # Buddy's window opens Buddy's thread when the Buddy folder appeared after the server + # started (LazurioPlatform#1179), proven in the real app. e2e finds scenarios only in + # scripts/scenarios/, beside the fixtures and the dependencies they import, so this new + # file is there; it starts its own stack with start-app.ts's exports, unchanged. + scripts/scenarios/buddy-window-opens-after-folder-appears.e2e.ts # A thread waiting on a question wakes whoever waits on it (row 39): t3_thread_wait's # untilQuestion in the contract and ThreadManagementService (listed above), and the # remote delegation follower that wakes the parent here, which the orchestrator keeps. diff --git a/apps/server/src/lazurio/agentCli.test.ts b/apps/server/src/lazurio/agentCli.test.ts index 96680c58accac..16107aa136c14 100644 --- a/apps/server/src/lazurio/agentCli.test.ts +++ b/apps/server/src/lazurio/agentCli.test.ts @@ -781,6 +781,7 @@ const buddyThreadRoute = (world: World) => Layer.mock(ProjectStore.ProjectStoreV2)({ list: () => Effect.succeed(world.buddyProjects), }), + Layer.mock(ProjectService.ProjectService)({}), NodeServices.layer, NodeCrypto.layer, ), diff --git a/apps/server/src/lazurio/buddySignal.ts b/apps/server/src/lazurio/buddySignal.ts index d2feaab4b39cf..b001fda317448 100644 --- a/apps/server/src/lazurio/buddySignal.ts +++ b/apps/server/src/lazurio/buddySignal.ts @@ -206,7 +206,7 @@ const buddyThreadId = Effect.fn("LazurioBuddySignal.threadId")(function* () { if (buddyFolder === undefined) return { kind: "absent", error: "not-buddy" } as const; const found = yield* findSharedBuddyThread(buddyFolder).pipe(Effect.result); if (found._tag === "Failure") - // Before the startup makes Buddy's project there is no thread either. + // Before the startup or the first window open makes Buddy's project there is no thread either. return found.failure.reason === "no-project" ? noThread : unavailable; return found.success.thread === null ? noThread diff --git a/apps/server/src/lazurio/buddySurface.testkit.ts b/apps/server/src/lazurio/buddySurface.testkit.ts index ebf5da4a57dae..f1a6093e735fe 100644 --- a/apps/server/src/lazurio/buddySurface.testkit.ts +++ b/apps/server/src/lazurio/buddySurface.testkit.ts @@ -38,6 +38,7 @@ import * as ProjectStore from "../orchestration-v2/ProjectStore.ts"; import * as ProviderTurnStartServiceTestkit from "../orchestration-v2/ProviderTurnStartService.testkit.ts"; import * as RuntimeLayer from "../orchestration-v2/runtimeLayer.ts"; import * as SqlitePersistence from "../persistence/Sqlite.ts"; +import * as ProjectEnrichmentService from "../project/ProjectEnrichmentService.ts"; import * as AntigravityInstallation from "../provider/AntigravityInstallation.ts"; import * as CodexInstallation from "../provider/CodexInstallation.ts"; import * as CodexManagedTokenBroker from "../provider/CodexManagedTokenBroker.ts"; @@ -51,6 +52,7 @@ import * as SourceControlProviderRegistry from "../sourceControl/SourceControlPr import * as VcsDriverRegistry from "../vcs/VcsDriverRegistry.ts"; import * as VcsProcess from "../vcs/VcsProcess.ts"; import { withBuddyInstance } from "./buddyPrompt.ts"; +import { layerMetadata, layerWorkspacePaths } from "./managedFolder.testkit.ts"; export const BUDDY = ProviderInstanceId.make("buddy"); export const buddyModel = { instanceId: BUDDY, model: "default" } satisfies ModelSelection; @@ -136,6 +138,13 @@ export const layerBuddyServer = Layer.mergeAll( ProjectStore.layer, RuntimeLayer.layerEventInfrastructure, ).pipe( + Layer.provideMerge( + RuntimeLayer.layerProjectService.pipe( + Layer.provide(ProjectEnrichmentService.layer), + Layer.provide(layerWorkspacePaths), + Layer.provide(layerMetadata), + ), + ), Layer.provide(McpSessionRegistryTestkit.layer), // Above the database, settings and gate, which instance hydration shares with the runtime. Layer.provide(layerProviderInstanceRegistry), diff --git a/apps/server/src/lazurio/buddySurfaceThread.test.ts b/apps/server/src/lazurio/buddySurfaceThread.test.ts index 28006744b3f1d..d6f5d80b924dd 100644 --- a/apps/server/src/lazurio/buddySurfaceThread.test.ts +++ b/apps/server/src/lazurio/buddySurfaceThread.test.ts @@ -14,8 +14,10 @@ import * as ServerConfig from "../config.ts"; import * as ServerSettings from "../serverSettings.ts"; import * as Orchestrator from "../orchestration-v2/Orchestrator.ts"; +import * as ProjectService from "../project/ProjectService.ts"; import { BUDDY, addProject, layerBuddyServer } from "./buddySurface.testkit.ts"; import { BUDDY_THREAD_ID, resolveBuddyThread } from "./buddySurfaceThread.ts"; +import { ensureManagedFolderProject } from "./managedFolderStartup.ts"; /** A home with Buddy's layer, `~/Lazurio/.agents/buddy`, in it. */ const makeHome = () => { @@ -321,9 +323,10 @@ describe("Buddy's thread", () => { }); it.live( - "answers no-project before the startup made Buddy's project, and not-buddy without one", + "answers no-project while the Buddy folder is absent, and not-buddy without one declared", () => { const { home, folder, buddy } = makeShared(); + NodeFS.rmSync(buddy, { recursive: true }); return Effect.gen(function* () { const reason = (exit: Exit.Exit) => Exit.isFailure(exit) ? JSON.stringify(exit.cause) : "succeeded"; @@ -332,6 +335,57 @@ describe("Buddy's thread", () => { "no-project", ); assert.include(reason(yield* Effect.exit(resolveBuddyThread())), "not-buddy"); + assert.lengthOf((yield* (yield* ProjectService.ProjectService).snapshot).projects, 0); + }).pipe( + Effect.provide(Layer.merge(layerBuddyServer, ServerSettings.layerTest())), + Effect.scoped, + Effect.provideService(HostProcess.Environment, { HOME: home }), + ); + }, + ); + + it.live( + "makes Buddy's project on the first visit when the Buddy folder appeared after the startup", + () => { + const { home, folder, buddy } = makeShared(); + NodeFS.rmSync(buddy, { recursive: true }); + return Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + const projects = yield* ProjectService.ProjectService; + const { bootstrapProjectId } = yield* withShared( + ensureManagedFolderProject, + folder, + buddy, + ); + const model = { instanceId: ProviderInstanceId.make("codex"), model: "gpt-6.1-sol" }; + yield* (yield* ServerSettings.ServerSettingsService).updateSettings({ + projectSettingsOverrides: { + [bootstrapProjectId!]: { defaultModelSelection: model }, + }, + }); + NodeFS.mkdirSync(buddy); + const [first, second] = yield* Effect.all( + [ + withShared(resolveBuddyThread(), folder, buddy), + withShared(resolveBuddyThread(), folder, buddy), + ], + { concurrency: 2 }, + ); + assert.deepStrictEqual(second, first); + const buddysProjects = (yield* projects.snapshot).projects.filter( + (project) => project.workspaceRoot === buddy, + ); + assert.deepStrictEqual( + buddysProjects.map((project) => [project.id, project.title, project.archivedAt]), + [[first.projectId, "Buddy", null]], + ); + const shell = yield* orchestrator.getThreadShell(first.threadId); + assert.strictEqual(shell?.projectId, first.projectId); + assert.deepStrictEqual(shell?.modelSelection, model); + assert.lengthOf( + (yield* orchestrator.getShellSnapshot({ projectId: first.projectId })).threads, + 1, + ); }).pipe( Effect.provide(Layer.merge(layerBuddyServer, ServerSettings.layerTest())), Effect.scoped, diff --git a/apps/server/src/lazurio/buddySurfaceThread.ts b/apps/server/src/lazurio/buddySurfaceThread.ts index 504ce0e0ede6e..7bae08e738b97 100644 --- a/apps/server/src/lazurio/buddySurfaceThread.ts +++ b/apps/server/src/lazurio/buddySurfaceThread.ts @@ -17,6 +17,7 @@ import * as DateTime from "effect/DateTime"; import * as Effect from "effect/Effect"; import * as Option from "effect/Option"; import * as Path from "effect/Path"; +import * as Result from "effect/Result"; import * as Schema from "effect/Schema"; import { resolveProjectSettings } from "@t3tools/shared/projectSettings"; @@ -30,6 +31,7 @@ import { buddyProjectFolder, isBuddySurfaceEnvironment, } from "./buddySurface.ts"; +import { ensureBuddyProjectIfPresent } from "./managedFolderStartup.ts"; export const BUDDY_THREAD_ROUTE = "/api/lazurio/buddy/thread"; @@ -110,7 +112,8 @@ const conflict = () => /** * Buddy GEN4 (plan LZD-0033, R3): on the shared Chat server Buddy's project is the one over the * declared Buddy folder, and Buddy's thread is its oldest root thread. Archiving one is - * refused and the startup brings archived ones back, so this is the conversation the person had. + * refused and making the project brings archived ones back, so this is the conversation the person + * had. */ const sharedBuddyProject = Effect.fn("LazurioBuddySurface.sharedBuddyProject")(function* ( buddyFolder: string, @@ -171,6 +174,24 @@ const keepBuddysThreadOpen = Effect.fn("LazurioBuddySurface.keepThreadOpen")(fun }); }, Effect.mapError(unavailable)); +/** + * `findSharedBuddyThread`, which first makes Buddy's project as the startup does when the Buddy + * folder appeared only after the startup ran. Of two first visits at once, one bootstrap loses to + * the other's on the folder's lock; that visit finds the other's project. + */ +const findSharedBuddyThreadMakingProject = Effect.fn( + "LazurioBuddySurface.findSharedThreadMakingProject", +)(function* (buddyFolder: string) { + const found = yield* findSharedBuddyThread(buddyFolder).pipe(Effect.result); + if (Result.isSuccess(found)) return found.success; + if (found.failure.reason !== "no-project") return yield* found.failure; + const made = yield* ensureBuddyProjectIfPresent(buddyFolder).pipe(Effect.result); + if (Result.isSuccess(made) && !made.success) return yield* found.failure; + const again = yield* findSharedBuddyThread(buddyFolder).pipe(Effect.result); + if (Result.isSuccess(again)) return again.success; + return yield* Result.isFailure(made) ? unavailable(made.failure) : again.failure; +}); + /** * Buddy's thread on the shared server, made on the project's default model the first time anyone * asks. Its id and command derive from the project, so two first visits make one thread. @@ -178,7 +199,7 @@ const keepBuddysThreadOpen = Effect.fn("LazurioBuddySurface.keepThreadOpen")(fun const resolveSharedBuddyThread = Effect.fn("LazurioBuddySurface.resolveSharedThread")(function* ( buddyFolder: string, ) { - const { project, thread } = yield* findSharedBuddyThread(buddyFolder); + const { project, thread } = yield* findSharedBuddyThreadMakingProject(buddyFolder); if (thread !== null) { yield* keepBuddysThreadOpen(thread); return { threadId: thread.id, projectId: project.projectId } satisfies BuddyThread; diff --git a/apps/server/src/lazurio/buddySurfaceThreadRoute.ts b/apps/server/src/lazurio/buddySurfaceThreadRoute.ts index adc74a7815d5e..c694bb01c78fd 100644 --- a/apps/server/src/lazurio/buddySurfaceThreadRoute.ts +++ b/apps/server/src/lazurio/buddySurfaceThreadRoute.ts @@ -1,11 +1,13 @@ /** * Lazurio overlay (root decision 0210, plan DEV-6676): `POST /api/lazurio/buddy/thread` finds or * makes Buddy's thread (buddySurfaceThread.ts) for the web surface and `t3 lazurio buddy thread`. - * Making it dispatches a command, so it needs the client's orchestration scopes. Errors: 404 + * Making it, or Buddy's project, dispatches a command, so it needs the client's orchestration scopes. Errors: 404 * `not-buddy`, 409 `no-project` or `thread-conflict`, 503 otherwise. */ import { AuthOrchestrationOperateScope, AuthOrchestrationReadScope } from "@t3tools/contracts"; +import * as SecureRandom from "effect/crypto/SecureRandom"; import * as Effect from "effect/Effect"; +import * as FileSystem from "effect/FileSystem"; import * as Option from "effect/Option"; import * as Path from "effect/Path"; import { HttpRouter, HttpServerResponse } from "effect/http"; @@ -13,6 +15,7 @@ import { HttpRouter, HttpServerResponse } from "effect/http"; import * as ServerConfig from "../config.ts"; import { OrchestratorV2 } from "../orchestration-v2/Orchestrator.ts"; import { ProjectStoreV2 } from "../orchestration-v2/ProjectStore.ts"; +import { ProjectService } from "../project/ProjectService.ts"; import { ServerSettingsService } from "../serverSettings.ts"; import { BUDDY_THREAD_ROUTE, resolveBuddyThread } from "./buddySurfaceThread.ts"; import { authenticateOverlayRoute } from "./routeAuth.ts"; @@ -31,6 +34,10 @@ export const layer = HttpRouter.use((router) => const projects = yield* ProjectStoreV2; const path = yield* Path.Path; const config = yield* ServerConfig.ServerConfig; + // Buddy's project, when the Buddy folder appeared after the startup (managedFolderStartup.ts). + const projectService = yield* ProjectService; + const random = yield* SecureRandom.SecureRandom; + const fileSystem = yield* FileSystem.FileSystem; // Only the shared server's first Buddy thread reads it; tests build this layer without one. const settings = yield* Effect.serviceOption(ServerSettingsService); yield* router.add( @@ -43,6 +50,9 @@ export const layer = HttpRouter.use((router) => Effect.provideService(ProjectStoreV2, projects), Effect.provideService(Path.Path, path), Effect.provideService(ServerConfig.ServerConfig, config), + Effect.provideService(ProjectService, projectService), + Effect.provideService(SecureRandom.SecureRandom, random), + Effect.provideService(FileSystem.FileSystem, fileSystem), Option.isSome(settings) ? Effect.provideService(ServerSettingsService, settings.value) : (effect) => effect, diff --git a/apps/server/src/lazurio/managedFolder.testkit.ts b/apps/server/src/lazurio/managedFolder.testkit.ts index 0f107fb088a66..9fb31dce5dbdd 100644 --- a/apps/server/src/lazurio/managedFolder.testkit.ts +++ b/apps/server/src/lazurio/managedFolder.testkit.ts @@ -63,13 +63,15 @@ export const layerManagedConfig = (lazurioFolder?: string, lazurioBuddyFolder?: })), ).pipe(Layer.provide(ServerConfig.layerTest(process.cwd(), { prefix: "t3-lazurio-folder-" }))); -const layerWorkspacePaths = Layer.succeed(WorkspacePaths.WorkspacePaths, { +/** Workspace roots as given, without the file system's say. */ +export const layerWorkspacePaths = Layer.succeed(WorkspacePaths.WorkspacePaths, { normalizeWorkspaceRoot: (workspaceRoot) => Effect.succeed(workspaceRoot.replace(/\/$/, "")), resolveRelativePathWithinRoot: ({ workspaceRoot, relativePath }) => Effect.succeed({ absolutePath: `${workspaceRoot}/${relativePath}`, relativePath }), }); -const layerMetadata = Layer.merge( +/** No repository identity and no favicon for any project. */ +export const layerMetadata = Layer.merge( Layer.succeed(RepositoryIdentityResolver.RepositoryIdentityResolver, { resolve: () => Effect.succeed(null), }), diff --git a/apps/server/src/lazurio/managedFolderGuards.ts b/apps/server/src/lazurio/managedFolderGuards.ts index c2135c49438c5..de6c93746799c 100644 --- a/apps/server/src/lazurio/managedFolderGuards.ts +++ b/apps/server/src/lazurio/managedFolderGuards.ts @@ -46,7 +46,8 @@ const threadInWorktree = /** * Upstream's project service from `live`, which in a managed Environment creates a project only for * the Folder, keeps it named Lazurio, in place and not archived, and moves no project. Buddy's project - * comes only from the startup's `bootstrap`, which no client, agent or CLI reaches, and stays as made. + * comes only from the `bootstrap` of the startup or of Buddy's thread route, which make it over the + * declared Buddy folder alone, and stays as made. */ export const guardProjects = (live: Layer.Layer) => Layer.effect( diff --git a/apps/server/src/lazurio/managedFolderStartup.ts b/apps/server/src/lazurio/managedFolderStartup.ts index f19b8a7970033..09dd242c870f6 100644 --- a/apps/server/src/lazurio/managedFolderStartup.ts +++ b/apps/server/src/lazurio/managedFolderStartup.ts @@ -1,7 +1,8 @@ /** * Lazurio overlay (LazurioPlatform F51): before the server takes commands, a managed Environment * adopts or creates the Folder's project (Lazurio), recorded for `t3 lazurio model`, and with a Buddy - * folder also Buddy's project, which only this path makes. Nothing edits state offline. + * folder also Buddy's project, which only this path and Buddy's thread route make (Buddy's folder can + * appear after the startup). Nothing edits state offline. */ import { CommandId, ProjectId } from "@t3tools/contracts"; import * as SecureRandom from "effect/crypto/SecureRandom"; @@ -41,14 +42,7 @@ export const ensureManagedFolderProject = Effect.gen(function* () { // Buddy's part never stops the Folder's Chat: a failure here is logged and the startup goes on. yield* Effect.gen(function* () { // A missing Buddy folder gets no project; one made earlier keeps its threads unarchived. - const fileSystemForBuddy = yield* Effect.serviceOption(FileSystem.FileSystem); - const exists = - Option.isNone(fileSystemForBuddy) || - (yield* fileSystemForBuddy.value - .exists(lazurioBuddyFolder) - .pipe(Effect.orElseSucceed(() => false))); - if (exists) yield* ensureBuddyProject(lazurioBuddyFolder); - else { + if (!(yield* ensureBuddyProjectIfPresent(lazurioBuddyFolder))) { const earlier = (yield* projects.snapshot).projects.find( (candidate) => candidate.workspaceRoot === lazurioBuddyFolder, ); @@ -74,7 +68,21 @@ export const ensureManagedFolderProject = Effect.gen(function* () { return { bootstrapProjectId: project.id, bootstrapProjectCreated: created }; }); -/** Buddy's project over the Buddy folder, adopted or created, keeping the name Buddy. */ +/** + * Buddy's project over the Buddy folder, adopted or created, keeping the name Buddy, when the folder + * exists; false when it does not. Without a file system (upstream's startup tests) it counts as there. + */ +export const ensureBuddyProjectIfPresent = Effect.fn( + "LazurioManagedFolder.ensureBuddyProjectIfPresent", +)(function* (buddyFolder: string) { + const fileSystem = yield* Effect.serviceOption(FileSystem.FileSystem); + const exists = + Option.isNone(fileSystem) || + (yield* fileSystem.value.exists(buddyFolder).pipe(Effect.orElseSucceed(() => false))); + if (exists) yield* ensureBuddyProject(buddyFolder); + return exists; +}); + const ensureBuddyProject = Effect.fn("LazurioManagedFolder.ensureBuddyProject")(function* ( buddyFolder: string, ) { diff --git a/scripts/scenarios/buddy-window-opens-after-folder-appears.e2e.ts b/scripts/scenarios/buddy-window-opens-after-folder-appears.e2e.ts new file mode 100644 index 0000000000000..55246ad18621f --- /dev/null +++ b/scripts/scenarios/buddy-window-opens-after-folder-appears.e2e.ts @@ -0,0 +1,150 @@ +// Lazurio overlay (LazurioPlatform#1179): a managed Environment whose Buddy folder appears only +// after its server started, as on a move from Buddy GEN3 to GEN4. It runs on its own dev stack, +// since the managed Folder would change every other scenario's server. +import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; +import * as NodeServices from "@effect/platform-node/NodeServices"; +import * as HostProcess from "@t3tools/shared/HostProcess"; +import * as NetService from "@t3tools/shared/Net"; +import { expect } from "e2e"; +import * as Deferred from "effect/Deferred"; +import * as Effect from "effect/Effect"; +import * as Fiber from "effect/Fiber"; +import * as FileSystem from "effect/FileSystem"; +import * as Path from "effect/Path"; +import * as Schedule from "effect/Schedule"; +import { FetchHttpClient, HttpClient, HttpClientResponse } from "effect/http"; + +import { APP_DIR, T3_HOME } from "../e2e.config.ts"; +import { ScenarioError } from "./shell.ts"; +import { prepareHome, start } from "./start-app.ts"; +import { runPromise, test, WEB } from "./t3.ts"; + +const HOME = `${T3_HOME}-buddy-window`; +const FOLDERS = `${T3_HOME}-buddy-window-folders`; +const FOLDER = `${FOLDERS}/Lazurio`; +const BUDDY_FOLDER = `${FOLDERS}/Buddy`; +// Mirror of BASE_WEB_PORT in dev-runner.ts, as start-app.ts mirrors it. +const BASE_WEB_PORT = 5733; + +/** + * The managed stack, running until interrupted: the app's server and Vite, started as start-app.ts + * starts them with its own `start` and `prepareHome`. `ready` gets the origin and pairing path. + */ +const runManagedStack = Effect.fn("scenario.buddyWindow.stack")(function* ( + ready: (stack: { readonly origin: string; readonly pairingPath: string }) => void, +) { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const net = yield* NetService.NetService; + const node = yield* HostProcess.ExecutablePath; + const hostEnvironment = yield* HostProcess.Environment; + yield* prepareHome(HOME); + yield* fs.remove(FOLDERS, { recursive: true, force: true }); + yield* fs.makeDirectory(FOLDER, { recursive: true }); + const webPort = yield* net.reserveLoopbackPort(); + const origin = `http://127.0.0.1:${webPort}`; + const ports = ["--port", String(yield* net.reserveLoopbackPort()), "--dev-url", origin]; + const devRunner = (mode: string, args: ReadonlyArray) => [ + "scripts/dev-runner.ts", + mode, + "--home-dir", + HOME, + "--no-seed", + ...args, + ]; + // Named in full: the shell that runs the scenario may be a managed Environment itself. + const env = { + PATH: `${path.join(HOME, "bin")}:${hostEnvironment.PATH ?? ""}`, + HOME: hostEnvironment.HOME, + ...(hostEnvironment.TMPDIR === undefined ? {} : { TMPDIR: hostEnvironment.TMPDIR }), + T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD: "0", + T3CODE_PORT_OFFSET: String(webPort - BASE_WEB_PORT), + T3CODE_LAZURIO_FOLDER: FOLDER, + T3CODE_LAZURIO_BUDDY_FOLDER: BUDDY_FOLDER, + // This origin is Buddy's window, so the whole page is Buddy's surface. + T3CODE_LAZURIO_BUDDY_ORIGIN: origin, + }; + // The server prints its pairing link after the startup made the Folder's project. + const pairing = yield* Deferred.make(); + const server = yield* start({ + cwd: APP_DIR, + command: node, + args: devRunner("dev:server", ports), + env: { ...env, T3CODE_DEV_ALLOWED_ORIGINS: origin }, + onLine: (line) => { + const url = /pairingUrl:\s*(\S+)/.exec(line)?.[1]; + if (url === undefined) return Effect.void; + const { pathname, search, hash } = new URL(url); + return Deferred.succeed(pairing, `${pathname}${search}${hash}`).pipe(Effect.asVoid); + }, + }); + const web = yield* start({ + cwd: APP_DIR, + command: node, + args: devRunner("dev:web", [...ports, "--", "--host", "127.0.0.1"]), + env, + onLine: () => Effect.void, + }); + const exited = Effect.raceFirst(server.exitCode, web.exitCode); + // The environment answers through Vite once both servers are up. + const up = Effect.gen(function* () { + const pairingPath = yield* Deferred.await(pairing); + yield* HttpClient.get(`${origin}/.well-known/t3/environment`).pipe( + Effect.flatMap(HttpClientResponse.filterStatusOk), + Effect.mapError(() => new ScenarioError({ message: "The managed stack is not up yet." })), + Effect.retry({ schedule: Schedule.spaced("1 second"), times: 300 }), + Effect.provide(FetchHttpClient.layer), + ); + return pairingPath; + }); + const stopped = exited.pipe( + Effect.flatMap((code) => + Effect.fail(new ScenarioError({ message: `The managed stack exited with ${code}.` })), + ), + ); + ready({ origin, pairingPath: yield* Effect.raceFirst(up, stopped) }); + return yield* exited; +}); + +function startManagedStack() { + const started = Promise.withResolvers<{ + readonly origin: string; + readonly pairingPath: string; + }>(); + const fiber = Effect.runFork( + runManagedStack(started.resolve).pipe( + Effect.scoped, + Effect.provide([NodeServices.layer, NodeCrypto.layer, NetService.layer]), + ), + ); + fiber.addObserver(() => started.reject(new Error("The managed stack stopped."))); + return { ready: started.promise, stop: () => Effect.runPromise(Fiber.interrupt(fiber)) }; +} + +test( + "Buddy's window opens Buddy's thread when the Buddy folder appeared after the server started", + WEB, + async ({ app, screen, browser }) => { + const stack = startManagedStack(); + try { + const { origin, pairingPath } = await stack.ready; + await runPromise( + Effect.flatMap(FileSystem.FileSystem, (fs) => fs.makeDirectory(BUDDY_FOLDER)), + ); + + await app.open(`${origin}${pairingPath}`); + await expect(browser).not.toHaveURL(/\/pair(?:[?#]|$)/, { timeout: 60_000 }); + const notReady = screen.getByText( + /^(Buddy is still being set up\.|Buddy se teprve instaluje\.)$/, + ); + const composer = screen.getByRole("textbox"); + await expect(notReady.or(composer)).toBeVisible({ timeout: 60_000 }); + await app.screenshot("buddy-window"); + + await expect(notReady).toBeHidden(); + await expect(composer).toBeVisible(); + } finally { + await stack.stop(); + } + }, +);