diff --git a/.github/workflows/lazurio-fork-ci.yml b/.github/workflows/lazurio-fork-ci.yml index 32a162b6e6a09..2198984de6739 100644 --- a/.github/workflows/lazurio-fork-ci.yml +++ b/.github/workflows/lazurio-fork-ci.yml @@ -416,6 +416,21 @@ jobs: # admits, a copy of APPLICATION_PUBLIC_PATHS in HumanAndMachine-ai/Machines (row 34, # root decision 0157). packages/client-runtime/src/lazurio/workspaceGateway.test.ts + # Buddy's project beside the managed Folder (LZD-0033, row 15): the web leaves it and its + # threads out of lists, the archive and pull request rows, not out of point reads, so a + # link to its thread opens. The logic is in the overlay module; the project, thread and + # archive atoms and their web wiring carry one hook each. + packages/client-runtime/src/lazurio/unlistedProjects.ts + packages/client-runtime/src/lazurio/unlistedProjects.test.ts + packages/client-runtime/src/state/projectEntities.ts + packages/client-runtime/src/state/threadShell.ts + packages/client-runtime/src/state/archivedThreads.ts + apps/web/src/state/threads.ts + apps/web/src/lib/archivedThreadsState.ts + apps/web/src/components/pullRequest/PullRequestThreadLinks.tsx + apps/web/src/components/ThreadNotificationCoordinator.tsx + apps/web/src/state/entities.ts + apps/web/src/hooks/useActiveProjectTarget.ts ) unexpected="$(git diff --name-only "$UPSTREAM_SHA..HEAD" | grep -E '^(apps|packages|scripts)/' | diff --git a/apps/server/src/config.ts b/apps/server/src/config.ts index 361db4134f286..f8b6393e868c6 100644 --- a/apps/server/src/config.ts +++ b/apps/server/src/config.ts @@ -93,6 +93,8 @@ export class ServerConfig extends Context.Service< readonly cwd: string; /** Opt-in hosted Folder entry contract, declared by Machines. */ readonly lazurioFolder?: string; + /** The Buddy folder beside the Folder, declared with it (`T3CODE_LAZURIO_BUDDY_FOLDER`). */ + readonly lazurioBuddyFolder?: string; readonly lazurioToolsUrl?: string; readonly baseDir: string; readonly staticDir: string | undefined; diff --git a/apps/server/src/lazurio/managedFolder.testkit.ts b/apps/server/src/lazurio/managedFolder.testkit.ts index 5143d4105cd90..0f107fb088a66 100644 --- a/apps/server/src/lazurio/managedFolder.testkit.ts +++ b/apps/server/src/lazurio/managedFolder.testkit.ts @@ -19,7 +19,8 @@ import * as WorkspacePaths from "../workspace/WorkspacePaths.ts"; /** * A managed Environment on disk: its Folder, a repository inside it, one beside it (an earlier - * project), a symlink to the Folder, and where its database goes. + * project), the Buddy folder beside it and a symlink to it, a symlink to the Folder, and where its + * database goes. */ export const makeFolderDirectories = () => { const parent = NodeFS.realpathSync( @@ -29,19 +30,36 @@ export const makeFolderDirectories = () => { const inside = NodePath.join(folder, "organizations", "example"); const repository = NodePath.join(parent, "repository"); const link = NodePath.join(parent, "link-to-Lazurio"); + const buddy = NodePath.join(parent, "Buddy"); + const buddyLink = NodePath.join(parent, "link-to-Buddy"); NodeFS.mkdirSync(inside, { recursive: true }); NodeFS.mkdirSync(repository); + NodeFS.mkdirSync(buddy); NodeFS.symlinkSync(folder, link); - return { parent, folder, inside, repository, link, database: NodePath.join(parent, "db.sqlite") }; + NodeFS.symlinkSync(buddy, buddyLink); + return { + parent, + folder, + inside, + repository, + link, + buddy, + buddyLink, + database: NodePath.join(parent, "db.sqlite"), + }; }; -/** The test server config, with `lazurioFolder` as `T3CODE_LAZURIO_FOLDER` would set it. */ -export const layerManagedConfig = (lazurioFolder?: string) => +/** + * The test server config, with `lazurioFolder` and `lazurioBuddyFolder` as `T3CODE_LAZURIO_FOLDER` + * and `T3CODE_LAZURIO_BUDDY_FOLDER` would set them. + */ +export const layerManagedConfig = (lazurioFolder?: string, lazurioBuddyFolder?: string) => Layer.effect( ServerConfig.ServerConfig, Effect.map(ServerConfig.ServerConfig, (config) => ({ ...config, ...(lazurioFolder === undefined ? {} : { lazurioFolder }), + ...(lazurioBuddyFolder === undefined ? {} : { lazurioBuddyFolder }), })), ).pipe(Layer.provide(ServerConfig.layerTest(process.cwd(), { prefix: "t3-lazurio-folder-" }))); @@ -65,6 +83,7 @@ const layerMetadata = Layer.merge( export const layerProjects = (input: { readonly persistence: Layer.Layer; readonly lazurioFolder?: string; + readonly lazurioBuddyFolder?: string; }) => RuntimeLayer.layerProjectService.pipe( Layer.provideMerge(ProjectEnrichmentService.layer), @@ -72,6 +91,6 @@ export const layerProjects = (input: { Layer.provideMerge(layerMetadata), Layer.provideMerge(input.persistence), Layer.provideMerge(ServerSettings.layerTest()), - Layer.provideMerge(layerManagedConfig(input.lazurioFolder)), + Layer.provideMerge(layerManagedConfig(input.lazurioFolder, input.lazurioBuddyFolder)), Layer.provideMerge(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)), ); diff --git a/apps/server/src/lazurio/managedFolder.ts b/apps/server/src/lazurio/managedFolder.ts index 0b81c3c256850..72e59b0db0fa8 100644 --- a/apps/server/src/lazurio/managedFolder.ts +++ b/apps/server/src/lazurio/managedFolder.ts @@ -1,14 +1,16 @@ /** - * Lazurio overlay (LazurioPlatform F51): with `T3CODE_LAZURIO_FOLDER` a hosted Environment's chats - * start in its Lazurio Folder. This is an entry-context contract, not a filesystem sandbox: agents - * start at the Folder and can then work in its repositories with their normal tools. Without the - * variable nothing here refuses anything. + * Lazurio overlay (LazurioPlatform F51): with `T3CODE_LAZURIO_FOLDER` chats start in the Lazurio + * Folder, an entry context, not a sandbox; `T3CODE_LAZURIO_BUDDY_FOLDER` adds Buddy's folder beside it + * (LZD-0033). Without the Folder nothing here refuses anything. */ import * as Effect from "effect/Effect"; import * as FileSystem from "effect/FileSystem"; import * as ServerConfig from "../config.ts"; +/** The name the server's startup gives Buddy's project (managedFolderStartup.ts). */ +export const BUDDY_PROJECT_TITLE = "Buddy"; + const turnOutsideFolder = "Agents in this Environment work in its Lazurio Folder. Start a new chat in the Lazurio project."; const repositoryAtFolder = @@ -17,23 +19,30 @@ const repositoryAtFolder = /** * The guard of the session manager, the VCS service and the model recommendation route, read once * from the server config: the Folder, why an agent turn or a new repository is refused in a - * managed Environment, or null, and whether a path names the Folder. A path counts as the Folder - * when it resolves to it, symlinks followed. + * managed Environment, or null, and whether a path names the Folder or the Buddy folder. A path + * counts as one when it resolves to it, symlinks followed. */ export const makeFolderGuard = Effect.gen(function* () { - const { lazurioFolder: folder } = yield* ServerConfig.ServerConfig; + const { lazurioFolder: folder, lazurioBuddyFolder } = yield* ServerConfig.ServerConfig; + // Only beside a Folder: the config never sets one alone, and a test's mock answers with a function. + const buddyFolder = + folder !== undefined && typeof lazurioBuddyFolder === "string" ? lazurioBuddyFolder : undefined; const fs = yield* FileSystem.FileSystem; /** `path` with its symlinks resolved, or null when it does not resolve. */ const canonical = (path: string) => fs.realPath(path).pipe(Effect.orElseSucceed(() => null)); return { /** The Folder's canonical path; undefined when the Environment is not managed. */ folder, - /** An agent turn runs only in the Folder itself; anywhere else, or nowhere, is refused. */ + /** The Buddy folder's canonical path; undefined unless declared beside the Folder. */ + buddyFolder, + /** An agent turn runs only in the Folder or the Buddy folder itself; anywhere else, or nowhere, is refused. */ turnRefusal: (cwd: string | null | undefined): Effect.Effect => folder === undefined ? Effect.succeed(null) : (cwd == null ? Effect.succeed(null) : canonical(cwd)).pipe( - Effect.map((path) => (path === folder ? null : turnOutsideFolder)), + Effect.map((path) => + path === folder || (path !== null && path === buddyFolder) ? null : turnOutsideFolder, + ), ), /** The Folder holds repositories, so it never becomes one; a path that does not resolve is compared as it is. */ repositoryRefusal: (cwd: string): Effect.Effect => @@ -47,14 +56,23 @@ export const makeFolderGuard = Effect.gen(function* () { folder === undefined ? Effect.succeed(false) : canonical(path).pipe(Effect.map((resolved) => resolved === folder)), + /** Whether `path` is the Buddy folder itself; never without one. */ + isBuddyFolder: (path: string): Effect.Effect => + buddyFolder === undefined + ? Effect.succeed(false) + : canonical(path).pipe(Effect.map((resolved) => resolved === buddyFolder)), }; }); /** The managed Folder in the config the server gives its clients (`server.getConfig`), if any. */ export const managedFolderClientConfig = (config: { readonly lazurioFolder?: string; + readonly lazurioBuddyFolder?: string; readonly lazurioToolsUrl?: string; }) => ({ ...(config.lazurioFolder === undefined ? {} : { lazurioFolder: config.lazurioFolder }), + ...(config.lazurioFolder === undefined || config.lazurioBuddyFolder === undefined + ? {} + : { lazurioBuddyFolder: config.lazurioBuddyFolder }), ...(config.lazurioToolsUrl === undefined ? {} : { lazurioToolsUrl: config.lazurioToolsUrl }), }); diff --git a/apps/server/src/lazurio/managedFolderConfig.test.ts b/apps/server/src/lazurio/managedFolderConfig.test.ts index 8d80acbcf5d62..0551b3c25f7dd 100644 --- a/apps/server/src/lazurio/managedFolderConfig.test.ts +++ b/apps/server/src/lazurio/managedFolderConfig.test.ts @@ -31,7 +31,11 @@ const makeFolder = () => { NodeFS.mkdirSync(folder); const link = NodePath.join(parent, "link-to-Lazurio"); NodeFS.symlinkSync(folder, link); - return { parent, folder, link }; + const buddy = NodePath.join(parent, "Buddy"); + NodeFS.mkdirSync(buddy); + const buddyLink = NodePath.join(parent, "link-to-Buddy"); + NodeFS.symlinkSync(buddy, buddyLink); + return { parent, folder, link, buddy, buddyLink }; }; it.effect( @@ -62,14 +66,77 @@ it.effect("makes the Folder's canonical path the cwd, without a cwd bootstrap", }), ); +it.effect("declares the Buddy folder beside the Folder by its canonical path", () => + Effect.gen(function* () { + const { folder, buddy, buddyLink } = makeFolder(); + assert.deepStrictEqual( + yield* resolveManagedFolderConfig.pipe( + withEnv({ T3CODE_LAZURIO_FOLDER: folder, T3CODE_LAZURIO_BUDDY_FOLDER: buddyLink }), + ), + { + cwd: folder, + lazurioFolder: folder, + autoBootstrapProjectFromCwd: false, + lazurioBuddyFolder: buddy, + }, + ); + // Missing (not made yet, or removed): Chat still starts and the path stays, so an earlier + // Buddy project stays unlisted. A sibling whose name starts with two dots is still beside. + // A link whose target was removed still names the target, the root its project was made with. + const target = NodePath.join(NodePath.dirname(folder), "Buddy-target"); + const dangling = NodePath.join(NodePath.dirname(folder), "Buddy-link"); + NodeFS.symlinkSync(target, dangling); + assert.strictEqual( + (yield* resolveManagedFolderConfig.pipe( + withEnv({ T3CODE_LAZURIO_FOLDER: folder, T3CODE_LAZURIO_BUDDY_FOLDER: dangling }), + )).lazurioBuddyFolder, + target, + ); + const dotsSibling = NodePath.join(NodePath.dirname(folder), "..Buddy"); + NodeFS.mkdirSync(dotsSibling); + for (const declared of [`${buddy}-missing`, dotsSibling]) { + assert.deepStrictEqual( + yield* resolveManagedFolderConfig.pipe( + withEnv({ T3CODE_LAZURIO_FOLDER: folder, T3CODE_LAZURIO_BUDDY_FOLDER: declared }), + ), + { + cwd: folder, + lazurioFolder: folder, + autoBootstrapProjectFromCwd: false, + lazurioBuddyFolder: declared, + }, + ); + } + }), +); + it.effect("refuses a relative path, a file, an insecure or credentialed tools URL", () => Effect.gen(function* () { - const { parent, folder } = makeFolder(); + const { parent, folder, buddy } = makeFolder(); const file = NodePath.join(parent, "not-a-folder"); NodeFS.writeFileSync(file, ""); + const insideFolder = NodePath.join(folder, ".agents", "buddy"); + NodeFS.mkdirSync(insideFolder, { recursive: true }); + const dotsInsideFolder = NodePath.join(folder, "..buddy"); + NodeFS.mkdirSync(dotsInsideFolder); + NodeFS.mkdirSync(NodePath.join(folder, "..x")); + const beside = "T3CODE_LAZURIO_BUDDY_FOLDER must be beside the Lazurio Folder"; for (const [env, expected] of [ [{ T3CODE_LAZURIO_FOLDER: "Lazurio" }, "T3CODE_LAZURIO_FOLDER must be an absolute"], [{ T3CODE_LAZURIO_FOLDER: file }, "T3CODE_LAZURIO_FOLDER must be a directory"], + [ + { T3CODE_LAZURIO_BUDDY_FOLDER: buddy }, + "T3CODE_LAZURIO_BUDDY_FOLDER needs T3CODE_LAZURIO_FOLDER", + ], + [ + { T3CODE_LAZURIO_FOLDER: folder, T3CODE_LAZURIO_BUDDY_FOLDER: "Buddy" }, + "T3CODE_LAZURIO_BUDDY_FOLDER must be an absolute", + ], + [{ T3CODE_LAZURIO_FOLDER: folder, T3CODE_LAZURIO_BUDDY_FOLDER: folder }, beside], + [{ T3CODE_LAZURIO_FOLDER: folder, T3CODE_LAZURIO_BUDDY_FOLDER: insideFolder }, beside], + [{ T3CODE_LAZURIO_FOLDER: folder, T3CODE_LAZURIO_BUDDY_FOLDER: dotsInsideFolder }, beside], + [{ T3CODE_LAZURIO_FOLDER: `${folder}/..x`, T3CODE_LAZURIO_BUDDY_FOLDER: folder }, beside], + [{ T3CODE_LAZURIO_FOLDER: folder, T3CODE_LAZURIO_BUDDY_FOLDER: parent }, beside], [ { T3CODE_LAZURIO_FOLDER: folder, T3CODE_LAZURIO_TOOLS_URL: "http://launchpad.test/" }, "T3CODE_LAZURIO_TOOLS_URL must be an HTTPS URL", diff --git a/apps/server/src/lazurio/managedFolderConfig.ts b/apps/server/src/lazurio/managedFolderConfig.ts index 05d3c326b8e81..186a40892fef8 100644 --- a/apps/server/src/lazurio/managedFolderConfig.ts +++ b/apps/server/src/lazurio/managedFolderConfig.ts @@ -1,8 +1,7 @@ /** - * Lazurio overlay (LazurioPlatform F51): `T3CODE_LAZURIO_FOLDER`, an absolute existing directory - * whose canonical path becomes the cwd and `lazurioFolder` (no project bootstraps from the cwd), and - * `T3CODE_LAZURIO_TOOLS_URL`, an HTTPS page without credentials for connecting agent accounts. - * Unset, both leave upstream's config as it is. + * Lazurio overlay (LazurioPlatform F51): `T3CODE_LAZURIO_FOLDER` (its canonical path becomes the cwd + * and `lazurioFolder`), `T3CODE_LAZURIO_BUDDY_FOLDER` (Buddy's folder beside it, LZD-0033) and + * `T3CODE_LAZURIO_TOOLS_URL` (HTTPS, no credentials). Unset, each leaves upstream's config alone. */ import * as Config from "effect/Config"; import * as Effect from "effect/Effect"; @@ -22,6 +21,10 @@ const ManagedFolderEnv = Config.all({ Config.option, Config.map(Option.getOrUndefined), ), + buddyFolder: Config.String("T3CODE_LAZURIO_BUDDY_FOLDER").pipe( + Config.option, + Config.map(Option.getOrUndefined), + ), toolsUrl: Config.URL("T3CODE_LAZURIO_TOOLS_URL").pipe( Config.option, Config.map(Option.getOrUndefined), @@ -30,22 +33,90 @@ const ManagedFolderEnv = Config.all({ /** The declared Folder's canonical path: absolute, existing, a directory, symlinks resolved. */ const canonicalFolder = Effect.fn("LazurioManagedFolder.canonicalFolder")(function* ( + variable: "T3CODE_LAZURIO_FOLDER" | "T3CODE_LAZURIO_BUDDY_FOLDER", declared: string, ) { const fs = yield* FileSystem.FileSystem; const path = yield* Path.Path; if (!path.isAbsolute(declared)) - return yield* invalid("T3CODE_LAZURIO_FOLDER must be an absolute existing directory."); + return yield* invalid(`${variable} must be an absolute existing directory.`); const root = yield* fs.realPath(declared); const info = yield* fs.stat(root); - if (info.type !== "Directory") - return yield* invalid("T3CODE_LAZURIO_FOLDER must be a directory."); + if (info.type !== "Directory") return yield* invalid(`${variable} must be a directory.`); + return root; +}); + +/** + * Where a missing path would be once made: links followed, also dangling ones, and the deepest + * existing ancestor resolved, so a project created through a link keeps its root after a restart. + */ +const canonicalMissing = Effect.fn("LazurioManagedFolder.canonicalMissing")(function* ( + declared: string, +) { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + let current = path.resolve(declared); + const rest: Array = []; + for (let hop = 0; hop < 40; hop++) { + const target = yield* fs.readLink(current).pipe(Effect.option); + if (Option.isSome(target)) { + current = path.resolve(path.dirname(current), target.value); + continue; + } + if (yield* fs.exists(current).pipe(Effect.orElseSucceed(() => false))) + return path.join(yield* fs.realPath(current), ...rest); + const parent = path.dirname(current); + if (parent === current) break; + rest.unshift(path.basename(current)); + current = parent; + } + return path.resolve(declared); +}); + +/** Whether `inner` is `outer` or lies under it, compared by whole path components. */ +const within = (path: Path.Path, outer: string, inner: string) => { + const relative = path.relative(outer, inner); + return ( + relative === "" || + (relative !== ".." && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative)) + ); +}; + +/** + * The Buddy folder's canonical path, beside the Folder (not inside or around it), so its agents + * load its own instructions. A missing folder keeps its declared path, so Chat runs and an earlier + * Buddy project stays unlisted; nothing resolves to it, so no turn runs there. + */ +const canonicalBuddyFolder = Effect.fn("LazurioManagedFolder.canonicalBuddyFolder")(function* ( + folder: string | undefined, + declared: string, +) { + if (folder === undefined) + return yield* invalid("T3CODE_LAZURIO_BUDDY_FOLDER needs T3CODE_LAZURIO_FOLDER."); + const path = yield* Path.Path; + const fs = yield* FileSystem.FileSystem; + const root = + path.isAbsolute(declared) && + !(yield* fs.exists(declared).pipe(Effect.orElseSucceed(() => false))) + ? yield* canonicalMissing(declared) + : yield* canonicalFolder("T3CODE_LAZURIO_BUDDY_FOLDER", declared); + if (within(path, folder, root) || within(path, root, folder)) + return yield* invalid( + "T3CODE_LAZURIO_BUDDY_FOLDER must be beside the Lazurio Folder, not inside it or around it.", + ); return root; }); export const resolveManagedFolderConfig = Effect.gen(function* () { const env = yield* ManagedFolderEnv; - const folder = env.folder === undefined ? undefined : yield* canonicalFolder(env.folder); + const folder = + env.folder === undefined + ? undefined + : yield* canonicalFolder("T3CODE_LAZURIO_FOLDER", env.folder); + const buddyFolder = + env.buddyFolder === undefined + ? undefined + : yield* canonicalBuddyFolder(folder, env.buddyFolder); if ( env.toolsUrl !== undefined && (env.toolsUrl.protocol !== "https:" || env.toolsUrl.username || env.toolsUrl.password) @@ -55,6 +126,7 @@ export const resolveManagedFolderConfig = Effect.gen(function* () { ...(folder === undefined ? {} : { cwd: folder, lazurioFolder: folder, autoBootstrapProjectFromCwd: false }), + ...(buddyFolder === undefined ? {} : { lazurioBuddyFolder: buddyFolder }), ...(env.toolsUrl === undefined ? {} : { lazurioToolsUrl: env.toolsUrl.toString() }), }; }); diff --git a/apps/server/src/lazurio/managedFolderGuards.test.ts b/apps/server/src/lazurio/managedFolderGuards.test.ts index b7d521a7fc3a8..1553dfa878445 100644 --- a/apps/server/src/lazurio/managedFolderGuards.test.ts +++ b/apps/server/src/lazurio/managedFolderGuards.test.ts @@ -43,6 +43,10 @@ const threadElsewhere = "Start a new chat in the Lazurio project. Agents in this Environment work in its Lazurio Folder; your earlier chats stay here as history."; const threadInWorktree = "Chats in this Environment start in the Lazurio Folder, without a separate worktree."; +const buddyThreadUnknown = + "This Environment could not check whether this thread is Buddy's, so it stays as it is. Try again."; +const buddyThreadKept = + "Buddy's threads belong to this Environment, like its project: they are not archived or deleted."; const turnOutsideFolder = "Agents in this Environment work in its Lazurio Folder. Start a new chat in the Lazurio project."; @@ -153,6 +157,74 @@ describe("projects in a managed Environment", () => { }); }); + it.effect("take Buddy's project only from the startup's bootstrap, and keep it", () => { + const { folder, buddy, buddyLink } = makeFolderDirectories(); + const bootstrapBuddy = Effect.flatMap(ProjectService.ProjectService, (projects) => + projects.bootstrap({ + commandId: CommandId.make("bootstrap-buddy"), + projectId: ProjectId.make("buddy"), + title: "Buddy", + workspaceRoot: buddyLink, + }), + ); + // Separate provides: layers memoize across a nested one. + const withoutBuddy = Effect.gen(function* () { + // Without a declared Buddy folder it is any other folder. + assert.strictEqual( + yield* projectRefusal(bootstrapBuddy), + "In this Environment, the Lazurio project is the Lazurio Folder itself.", + ); + }).pipe( + Effect.provide( + layerProjects({ persistence: SqlitePersistence.layerMemory, lazurioFolder: folder }), + ), + ); + const withBuddy = Effect.gen(function* () { + const projects = yield* ProjectService.ProjectService; + // Clients, agents and the CLI create projects, and get only the Folder's. + assert.strictEqual( + yield* projectRefusal( + projects.create({ + commandId: CommandId.make("create-buddy"), + projectId: ProjectId.make("buddy-created"), + title: "Buddy", + workspaceRoot: buddy, + }), + ), + "In this Environment, the Lazurio project is the Lazurio Folder itself.", + ); + const { project } = yield* bootstrapBuddy; + assert.strictEqual(project.workspaceRoot, buddy); + const kept = + "Buddy's project belongs to this Environment: it keeps its name and cannot be archived or removed."; + let updates = 0; + const update = (change: { title?: string; archived?: boolean; pinned?: boolean }) => + projects.update({ + commandId: CommandId.make(`update-buddy-${++updates}`), + projectId: project.id, + ...change, + }); + assert.strictEqual(yield* projectRefusal(update({ title: "Chat" })), kept); + assert.strictEqual(yield* projectRefusal(update({ archived: true })), kept); + assert.strictEqual( + yield* projectRefusal( + projects.delete({ commandId: CommandId.make("delete-buddy"), projectId: project.id }), + ), + kept, + ); + yield* update({ title: "Buddy", pinned: true }); + }).pipe( + Effect.provide( + layerProjects({ + persistence: SqlitePersistence.layerMemory, + lazurioFolder: folder, + lazurioBuddyFolder: buddy, + }), + ), + ); + return Effect.andThen(withoutBuddy, withBuddy); + }); + it.effect("are upstream's without T3CODE_LAZURIO_FOLDER", () => { const { parent, repository } = makeFolderDirectories(); return Effect.gen(function* () { @@ -178,8 +250,11 @@ describe("projects in a managed Environment", () => { }); describe("orchestration commands in a managed Environment", () => { - const { folder } = makeFolderDirectories(); + const { folder, buddy } = makeFolderDirectories(); const folderProject = ProjectId.make("project-lazurio"); + const buddyProject = ProjectId.make("project-buddy"); + const buddyThread = ThreadId.make("thread-buddy"); + const unreadableThread = ThreadId.make("thread-unreadable"); const historyProject = ProjectId.make("project-history"); const folderThread = ThreadId.make("thread-lazurio"); const historyThread = ThreadId.make("thread-history"); @@ -187,17 +262,19 @@ describe("orchestration commands in a managed Environment", () => { const threads = new Map([ [folderThread, { projectId: folderProject, worktreePath: null }], [historyThread, { projectId: historyProject, worktreePath: null }], + [buddyThread, { projectId: buddyProject, worktreePath: null }], [worktreeThread, { projectId: folderProject, worktreePath: `${folder}-worktree` }], ]); const roots = new Map([ [folderProject, folder], [historyProject, "/home/person/older-repository"], + [buddyProject, buddy], ]); const modelSelection = { instanceId: ProviderInstanceId.make("codex"), model: "gpt-6.1-sol" }; const creation = { createdBy: "user", creationSource: "web" } as const; /** The decorated orchestrator over a stand-in that records what reached it. */ - const withOrchestrator = (lazurioFolder: string | undefined) => { + const withOrchestrator = (lazurioFolder: string | undefined, lazurioBuddyFolder?: string) => { const reached: Array = []; const layer = LazurioManagedFolder.guardCommands( Layer.mock(Orchestrator.OrchestratorV2)({ @@ -206,7 +283,10 @@ describe("orchestration commands in a managed Environment", () => { reached.push(command.commandId); return { sequence: reached.length, storedEvents: [] }; }), - getThreadShell: (threadId) => Effect.succeed((threads.get(threadId) ?? null) as never), + getThreadShell: (threadId) => + threadId === unreadableThread + ? Effect.fail(new Error("projection unavailable") as never) + : Effect.succeed((threads.get(threadId) ?? null) as never), }), ).pipe( Layer.provide( @@ -219,7 +299,7 @@ describe("orchestration commands in a managed Environment", () => { ), }), ), - Layer.provide(layerManagedConfig(lazurioFolder)), + Layer.provide(layerManagedConfig(lazurioFolder, lazurioBuddyFolder)), Layer.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)), ); return { reached, layer }; @@ -291,6 +371,18 @@ describe("orchestration commands in a managed Environment", () => { interactionMode: "default", ...(workspaceStrategy === undefined ? {} : { workspaceStrategy }), }) satisfies OrchestrationV2ServerCommand; + const organize = ( + id: string, + type: "thread.archive" | "thread.delete", + threadId: ThreadId, + onlyIfUnused?: boolean, + ) => + ({ + type, + commandId: CommandId.make(id), + threadId, + ...(onlyIfUnused === undefined ? {} : { onlyIfUnused }), + }) as OrchestrationV2ServerCommand; const moveThread = (id: string, worktreePath: string | null) => ({ type: "thread.metadata.update", @@ -310,6 +402,9 @@ describe("orchestration commands in a managed Environment", () => { createThread("create-folder", folderProject, null), ), "create elsewhere": yield* refusalOf(createThread("create-history", historyProject, null)), + "create in Buddy's undeclared folder": yield* refusalOf( + createThread("create-buddy", buddyProject, null), + ), "create in a worktree": yield* refusalOf( createThread("create-worktree", folderProject, `${folder}-worktree`), ), @@ -334,6 +429,7 @@ describe("orchestration commands in a managed Environment", () => { assert.deepStrictEqual(refusals, { "create in the Folder": null, "create elsewhere": threadElsewhere, + "create in Buddy's undeclared folder": threadElsewhere, "create in a worktree": threadElsewhere, "message in the Folder": null, "launch in the Folder": null, @@ -362,6 +458,57 @@ describe("orchestration commands in a managed Environment", () => { }).pipe(Effect.provide(layer)); }); + it.effect("keep threads in Buddy's project root too, once its folder is declared", () => { + const { reached, layer } = withOrchestrator(folder, buddy); + return Effect.gen(function* () { + const refusals = { + create: yield* refusalOf(createThread("create-buddy", buddyProject, null)), + "create in a worktree": yield* refusalOf( + createThread("create-buddy-worktree", buddyProject, `${buddy}-worktree`), + ), + message: yield* refusalOf(message("message-buddy", buddyThread)), + "launch into a worktree": yield* refusalOf( + message("launch-buddy-worktree", buddyThread, { type: "worktree", baseRef: "main" }), + ), + fork: yield* refusalOf(fork("fork-buddy", buddyThread)), + archive: yield* refusalOf(organize("archive-buddy", "thread.archive", buddyThread)), + delete: yield* refusalOf(organize("delete-buddy", "thread.delete", buddyThread)), + "delete if unused": yield* refusalOf( + organize("delete-unused-buddy", "thread.delete", buddyThread, true), + ), + "archive a Chat thread": yield* refusalOf( + organize("archive-folder", "thread.archive", folderThread), + ), + "archive an unreadable thread": yield* refusalOf( + organize("archive-unreadable", "thread.archive", unreadableThread), + ), + "create elsewhere": yield* refusalOf(createThread("create-history", historyProject, null)), + "message to history": yield* refusalOf(message("message-history", historyThread)), + }; + assert.deepStrictEqual(refusals, { + create: null, + "create in a worktree": threadElsewhere, + message: null, + "launch into a worktree": threadInWorktree, + fork: null, + archive: buddyThreadKept, + delete: buddyThreadKept, + "delete if unused": null, + "archive a Chat thread": null, + "archive an unreadable thread": buddyThreadUnknown, + "create elsewhere": threadElsewhere, + "message to history": threadElsewhere, + }); + assert.deepStrictEqual(reached, [ + "create-buddy", + "message-buddy", + "fork-buddy", + "delete-unused-buddy", + "archive-folder", + ]); + }).pipe(Effect.provide(layer)); + }); + it.effect("are upstream's without T3CODE_LAZURIO_FOLDER", () => { const { reached, layer } = withOrchestrator(undefined); return Effect.gen(function* () { @@ -384,7 +531,7 @@ describe("agent sessions in a managed Environment", () => { const claude = { instanceId: ProviderInstanceId.make("claudeAgent"), model: "claude-model" }; /** The decorated session manager over a stand-in provider that records each session it opens. */ - const withSessions = (lazurioFolder: string | undefined) => { + const withSessions = (lazurioFolder: string | undefined, lazurioBuddyFolder?: string) => { const opened: Array = []; const layer = LazurioManagedFolder.guardTurns( Layer.mock(ProviderSessionManager.ProviderSessionManagerV2)({ @@ -395,7 +542,7 @@ describe("agent sessions in a managed Environment", () => { }), }), ).pipe( - Layer.provide(layerManagedConfig(lazurioFolder)), + Layer.provide(layerManagedConfig(lazurioFolder, lazurioBuddyFolder)), Layer.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)), ); return { opened, layer }; @@ -427,12 +574,12 @@ describe("agent sessions in a managed Environment", () => { ]; it.effect.each(providers)("open for $provider only in the Folder itself", ({ selection }) => { - const { folder, link, inside, repository } = makeFolderDirectories(); + const { folder, link, inside, repository, buddy } = makeFolderDirectories(); const { opened, layer } = withSessions(folder); return Effect.gen(function* () { assert.isNull(yield* open(selection, folder)); assert.isNull(yield* open(selection, link)); - for (const elsewhere of [inside, repository, `${folder}-missing`, null]) { + for (const elsewhere of [inside, repository, buddy, `${folder}-missing`, null]) { assert.deepStrictEqual(yield* open(selection, elsewhere), { instanceId: selection.instanceId, cause: turnOutsideFolder, @@ -443,6 +590,25 @@ describe("agent sessions in a managed Environment", () => { }).pipe(Effect.provide(layer)); }); + it.effect.each(providers)( + "open for $provider in the declared Buddy folder too, and nowhere else new", + ({ selection }) => { + const { folder, buddy, buddyLink, inside, repository } = makeFolderDirectories(); + const { opened, layer } = withSessions(folder, buddy); + return Effect.gen(function* () { + for (const allowed of [folder, buddy, buddyLink]) + assert.isNull(yield* open(selection, allowed)); + for (const elsewhere of [inside, repository, `${buddy}/inside`, null]) { + assert.deepStrictEqual(yield* open(selection, elsewhere), { + instanceId: selection.instanceId, + cause: turnOutsideFolder, + }); + } + assert.deepStrictEqual(opened, [folder, buddy, buddyLink]); + }).pipe(Effect.provide(layer)); + }, + ); + it.effect.each(providers)( "refuse $provider in a Folder path that now leads elsewhere", ({ selection }) => { diff --git a/apps/server/src/lazurio/managedFolderGuards.ts b/apps/server/src/lazurio/managedFolderGuards.ts index 087d109003ae8..31170b728c464 100644 --- a/apps/server/src/lazurio/managedFolderGuards.ts +++ b/apps/server/src/lazurio/managedFolderGuards.ts @@ -22,7 +22,7 @@ import * as ProviderSessionManager from "../orchestration-v2/ProviderSessionMana import * as ManagedProjectFolders from "../project/ManagedProjectFolders.ts"; import * as ProjectService from "../project/ProjectService.ts"; import * as TriageService from "../triage/TriageService.ts"; -import { makeFolderGuard } from "./managedFolder.ts"; +import { BUDDY_PROJECT_TITLE, makeFolderGuard } from "./managedFolder.ts"; const projectElsewhere = "In this Environment, the Lazurio project is the Lazurio Folder itself."; const projectMoved = @@ -31,15 +31,22 @@ const projectRenamed = "This project keeps the name Lazurio."; const projectRemoved = "The Lazurio project belongs to this Environment and cannot be removed."; const triageUnavailable = "This Environment does not triage issues against upstream T3 Code."; const projectArchived = "The Lazurio project belongs to this Environment and cannot be archived."; +const buddyThreadUnknown = + "This Environment could not check whether this thread is Buddy's, so it stays as it is. Try again."; +const buddyThreadKept = + "Buddy's threads belong to this Environment, like its project: they are not archived or deleted."; +const buddyProjectChanged = + "Buddy's project belongs to this Environment: it keeps its name and cannot be archived or removed."; + const threadElsewhere = "Start a new chat in the Lazurio project. Agents in this Environment work in its Lazurio Folder; your earlier chats stay here as history."; const threadInWorktree = "Chats in this Environment start in the Lazurio Folder, without a separate worktree."; /** - * Upstream's project service from `live`, which in a managed Environment creates or adopts a - * project only for the Folder (a path that resolves to the Folder names it), keeps the Folder's - * project named Lazurio, in place and not archived, and moves no project to another folder. + * 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. */ export const guardProjects = (live: Layer.Layer) => Layer.effect( @@ -47,7 +54,7 @@ export const guardProjects = (live: Layer.Layer @@ -58,10 +65,10 @@ export const guardProjects = (live: Layer.Layer + const rootOf = (projectId: ProjectId) => projects .getById(projectId) - .pipe(Effect.map(Option.exists((project) => project.workspaceRoot === folder))); + .pipe(Effect.map((project) => Option.getOrUndefined(project)?.workspaceRoot)); // The Folder's project always has the Folder's canonical path as its root. const inFolder = < A extends { readonly projectId: ProjectId; readonly workspaceRoot: string }, @@ -73,13 +80,24 @@ export const guardProjects = (live: Layer.Layer( + input: A, + ) => + buddyFolder === undefined + ? inFolder(input) + : Effect.flatMap(guard.isBuddyFolder(input.workspaceRoot), (isBuddy) => + isBuddy ? Effect.succeed({ ...input, workspaceRoot: buddyFolder }) : inFolder(input), + ); return ProjectService.ProjectService.of({ ...projects, create: Effect.fn("LazurioManagedFolder.createProject")((input) => Effect.flatMap(inFolder(input), projects.create), ), bootstrap: Effect.fn("LazurioManagedFolder.bootstrapProject")((input) => - Effect.flatMap(inFolder(input), projects.bootstrap), + Effect.flatMap(inFolderOrBuddy(input), projects.bootstrap), ), update: Effect.fn("LazurioManagedFolder.updateProject")(function* (input) { if (input.workspaceRoot !== undefined) { @@ -90,36 +108,48 @@ export const guardProjects = (live: Layer.Layer - Effect.flatMap(isFolderProject(input.projectId), (isFolder) => - isFolder ? refuse(input.projectId, projectRemoved) : projects.delete(input), - ), - ), + delete: Effect.fn("LazurioManagedFolder.deleteProject")(function* (input) { + const root = yield* rootOf(input.projectId); + if (root === folder) return yield* refuse(input.projectId, projectRemoved); + if (buddyFolder !== undefined && root === buddyFolder) + return yield* refuse(input.projectId, buddyProjectChanged); + return yield* projects.delete(input); + }), }); }), ).pipe(Layer.provide(live)); /** * Why a managed Environment refuses an orchestration command, or null: new threads, messages and - * forks belong to the Folder project's root, and no thread moves into a worktree. A command whose - * thread is gone is left to upstream, which answers for it. + * forks belong to the root of the Folder's or the Buddy folder's project, and no thread moves into + * a worktree. A command whose thread is gone is left to upstream, which answers for it. */ +const buddyRefusal = (buddy: boolean | null) => + buddy === null ? buddyThreadUnknown : buddy ? buddyThreadKept : null; + const commandRefusal = ( command: OrchestrationV2ServerCommand, state: { readonly isFolderProject: (projectId: ProjectId) => Effect.Effect; readonly isInFolderRoot: (threadId: ThreadId) => Effect.Effect; + /** Whether the thread is in Buddy's project; null when that could not be read. */ + readonly isBuddyThread: (threadId: ThreadId) => Effect.Effect; }, ): Effect.Effect => { const unless = (allowed: Effect.Effect, refusal: string) => @@ -142,6 +172,13 @@ const commandRefusal = ( } case "thread.fork": return unless(state.isInFolderRoot(command.sourceThreadId), threadElsewhere); + // An archived or deleted Buddy thread would leave the tasks it runs elsewhere listed in Chat. + case "thread.archive": + return Effect.map(state.isBuddyThread(command.threadId), buddyRefusal); + case "thread.delete": + return command.onlyIfUnused === true + ? Effect.succeed(null) + : Effect.map(state.isBuddyThread(command.threadId), buddyRefusal); case "delegated_task.request": return Effect.succeed( command.workspaceStrategy === undefined || command.workspaceStrategy.type === "root" @@ -155,8 +192,8 @@ const commandRefusal = ( /** * Upstream's orchestrator from `live`, which in a managed Environment rejects a command that would - * start a thread, a message or a fork outside the Folder project's root, or move a thread into a - * worktree, before it is decided. Every command passes `dispatch`, so this holds for clients, + * start a thread, a message or a fork outside the Folder's or the Buddy folder's project root, or + * move a thread into a worktree, before it is decided. Every command passes `dispatch`, so this holds for clients, * agents, scheduled tasks and the server's own launches alike. */ export const guardCommands = (live: Layer.Layer) => @@ -164,13 +201,20 @@ export const guardCommands = (live: Layer.Layer projects.get(projectId).pipe( - Effect.map(Option.exists((project) => project.workspaceRoot === folder)), + Effect.map( + Option.exists( + (project) => + project.workspaceRoot === folder || + (buddyFolder !== undefined && project.workspaceRoot === buddyFolder), + ), + ), Effect.orElseSucceed(() => false), ); const isInFolderRoot = (threadId: ThreadId) => @@ -184,19 +228,38 @@ export const guardCommands = (live: Layer.Layer false), ); + const isBuddyThread = (threadId: ThreadId) => + buddyFolder === undefined + ? Effect.succeed(false) + : orchestrator.getThreadShell(threadId).pipe( + Effect.flatMap((thread) => + thread === null + ? Effect.succeed(false) + : projects + .get(thread.projectId) + .pipe( + Effect.map( + Option.exists((project) => project.workspaceRoot === buddyFolder), + ), + ), + ), + Effect.orElseSucceed(() => null), + ); return Orchestrator.OrchestratorV2.of({ ...orchestrator, dispatch: Effect.fn("LazurioManagedFolder.dispatch")((command) => - Effect.flatMap(commandRefusal(command, { isFolderProject, isInFolderRoot }), (refusal) => - refusal === null - ? orchestrator.dispatch(command) - : Effect.fail( - new Orchestrator.OrchestratorCommandRejectedError({ - commandId: command.commandId, - commandType: command.type, - cause: refusal, - }), - ), + Effect.flatMap( + commandRefusal(command, { isFolderProject, isInFolderRoot, isBuddyThread }), + (refusal) => + refusal === null + ? orchestrator.dispatch(command) + : Effect.fail( + new Orchestrator.OrchestratorCommandRejectedError({ + commandId: command.commandId, + commandType: command.type, + cause: refusal, + }), + ), ), ), }); @@ -205,8 +268,8 @@ export const guardCommands = (live: Layer.Layer( diff --git a/apps/server/src/lazurio/managedFolderStartup.test.ts b/apps/server/src/lazurio/managedFolderStartup.test.ts index 4c416ccfdba1b..41ad52ee53fa9 100644 --- a/apps/server/src/lazurio/managedFolderStartup.test.ts +++ b/apps/server/src/lazurio/managedFolderStartup.test.ts @@ -1,9 +1,14 @@ -import { CommandId, ProjectId } from "@t3tools/contracts"; +// @effect-diagnostics nodeBuiltinImport:off - the Buddy folder is a real directory, removed in one case. +import * as NodeFS from "node:fs"; + +import { CommandId, ProjectId, ThreadId } from "@t3tools/contracts"; import { assert, it } from "@effect/vitest"; import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; import * as ServerConfig from "../config.ts"; +import * as Orchestrator from "../orchestration-v2/Orchestrator.ts"; import * as SqlitePersistence from "../persistence/Sqlite.ts"; import * as ProjectService from "../project/ProjectService.ts"; import { layerProjects, makeFolderDirectories } from "./managedFolder.testkit.ts"; @@ -88,3 +93,163 @@ it.effect( }); }, ); + +it.effect("with a Buddy folder declared, also creates Buddy's project once, named Buddy", () => { + const { folder, buddy } = makeFolderDirectories(); + return Effect.gen(function* () { + const first = yield* ensureManagedFolderProject; + yield* ensureManagedFolderProject; + const projects = (yield* (yield* ProjectService.ProjectService).snapshot).projects; + assert.deepStrictEqual( + projects.map((project) => [project.title, project.workspaceRoot]).toSorted(), + [ + ["Buddy", buddy], + ["Lazurio", folder], + ], + ); + // The Platform's model recommendation stays the Folder project's alone. + const { stateDir } = yield* ServerConfig.ServerConfig; + assert.strictEqual( + Option.getOrThrow(yield* readModelRecommendationRecord(stateDir)).projectId, + first.bootstrapProjectId, + ); + }).pipe( + Effect.provide( + layerProjects({ + persistence: SqlitePersistence.layerMemory, + lazurioFolder: folder, + lazurioBuddyFolder: buddy, + }), + ), + ); +}); + +it.effect("restarts without the Buddy folder: Chat starts and Buddy's project stays", () => { + const { folder, buddy, database } = makeFolderDirectories(); + const persistence = SqlitePersistence.layerFromPath(database); + const managed = layerProjects({ persistence, lazurioFolder: folder, lazurioBuddyFolder: buddy }); + const projectsByTitle = Effect.gen(function* () { + const { projects } = yield* (yield* ProjectService.ProjectService).snapshot; + return projects.map((project) => [project.title, project.workspaceRoot]).toSorted(); + }); + return Effect.gen(function* () { + yield* Effect.andThen(ensureManagedFolderProject, projectsByTitle).pipe( + Effect.provide(managed), + ); + yield* Effect.sync(() => NodeFS.rmSync(buddy, { recursive: true })); + assert.deepStrictEqual( + yield* Effect.andThen(ensureManagedFolderProject, projectsByTitle).pipe( + Effect.provide(managed), + ), + [ + ["Buddy", buddy], + ["Lazurio", folder], + ], + ); + }); +}); + +it.effect("re-enabling the Buddy folder brings Buddy's archived threads back, nothing else", () => { + const { folder, buddy } = makeFolderDirectories(); + const unarchived: Array = []; + // A thread archived while the folder was not declared, and an archived Chat thread. + const orchestrator = Layer.mock(Orchestrator.OrchestratorV2)({ + getShellSnapshot: (options) => + Effect.succeed({ + schemaVersion: 1, + snapshotSequence: 1, + threads: [], + archivedThreads: [ + { id: ThreadId.make("buddy-archived"), projectId: options?.projectId }, + { id: ThreadId.make("chat-archived"), projectId: ProjectId.make("lazurio") }, + ], + } as never), + dispatch: (command) => + Effect.sync(() => { + if (command.type === "thread.unarchive") unarchived.push(command.threadId); + return { sequence: unarchived.length, storedEvents: [] }; + }), + }); + return Effect.gen(function* () { + yield* ensureManagedFolderProject; + assert.deepStrictEqual(unarchived, ["buddy-archived"]); + }).pipe( + Effect.provide( + Layer.merge( + orchestrator, + layerProjects({ + persistence: SqlitePersistence.layerMemory, + lazurioFolder: folder, + lazurioBuddyFolder: buddy, + }), + ), + ), + ); +}); + +it.effect( + "with the Buddy folder gone, its earlier project still gets its archived threads back", + () => { + const { folder, buddy, database } = makeFolderDirectories(); + const persistence = SqlitePersistence.layerFromPath(database); + const unarchived: Array = []; + const orchestrator = Layer.mock(Orchestrator.OrchestratorV2)({ + getShellSnapshot: (options) => + Effect.succeed({ + schemaVersion: 1, + snapshotSequence: 1, + threads: [], + archivedThreads: [{ id: ThreadId.make("buddy-archived"), projectId: options?.projectId }], + } as never), + dispatch: (command) => + Effect.sync(() => { + if (command.type === "thread.unarchive") unarchived.push(command.threadId); + return { sequence: unarchived.length, storedEvents: [] }; + }), + }); + const managed = (lazurioBuddyFolder?: string) => + Layer.merge( + orchestrator, + layerProjects({ + persistence, + lazurioFolder: folder, + ...(lazurioBuddyFolder === undefined ? {} : { lazurioBuddyFolder }), + }), + ); + return Effect.gen(function* () { + yield* ensureManagedFolderProject.pipe(Effect.provide(managed(buddy))); + // Turned off, the thread archived and the folder removed, then turned on again. + yield* ensureManagedFolderProject.pipe(Effect.provide(managed())); + yield* Effect.sync(() => NodeFS.rmSync(buddy, { recursive: true })); + unarchived.length = 0; + yield* ensureManagedFolderProject.pipe(Effect.provide(managed(buddy))); + assert.deepStrictEqual(unarchived, ["buddy-archived"]); + }); + }, +); + +it.effect("a failure in Buddy's part leaves the Folder's project and Chat starting", () => { + const { folder, buddy } = makeFolderDirectories(); + const orchestrator = Layer.mock(Orchestrator.OrchestratorV2)({ + getShellSnapshot: () => Effect.fail(new Error("projection unavailable") as never), + }); + return Effect.gen(function* () { + const started = yield* ensureManagedFolderProject; + const projects = (yield* (yield* ProjectService.ProjectService).snapshot).projects; + assert.strictEqual( + projects.find((project) => project.id === started.bootstrapProjectId)?.workspaceRoot, + folder, + ); + }).pipe( + Effect.provide( + Layer.merge( + orchestrator, + layerProjects({ + persistence: SqlitePersistence.layerMemory, + lazurioFolder: folder, + lazurioBuddyFolder: buddy, + }), + ), + ), + ); +}); diff --git a/apps/server/src/lazurio/managedFolderStartup.ts b/apps/server/src/lazurio/managedFolderStartup.ts index c3f29b518c8a4..f19b8a7970033 100644 --- a/apps/server/src/lazurio/managedFolderStartup.ts +++ b/apps/server/src/lazurio/managedFolderStartup.ts @@ -1,7 +1,7 @@ /** * Lazurio overlay (LazurioPlatform F51): before the server takes commands, a managed Environment - * adopts or creates the Folder's project (named Lazurio) through upstream's project service and - * records it for `t3 lazurio model`. The server is the only writer; nothing edits state offline. + * 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. */ import { CommandId, ProjectId } from "@t3tools/contracts"; import * as SecureRandom from "effect/crypto/SecureRandom"; @@ -10,12 +10,14 @@ import * as FileSystem from "effect/FileSystem"; import * as Option from "effect/Option"; import * as ServerConfig from "../config.ts"; +import * as Orchestrator from "../orchestration-v2/Orchestrator.ts"; import * as ProjectService from "../project/ProjectService.ts"; +import { BUDDY_PROJECT_TITLE } from "./managedFolder.ts"; import { recordFolderProject } from "./modelRecommendation.ts"; /** The Folder's project, adopted or created; the welcome event names it. */ export const ensureManagedFolderProject = Effect.gen(function* () { - const { lazurioFolder, stateDir } = yield* ServerConfig.ServerConfig; + const { lazurioFolder, lazurioBuddyFolder, stateDir } = yield* ServerConfig.ServerConfig; // Upstream's startup tests mock the config, and a mock answers a field it lacks, such as this // one, with a function: only a path is a Folder. if (typeof lazurioFolder !== "string") return {}; @@ -35,6 +37,32 @@ export const ensureManagedFolderProject = Effect.gen(function* () { title: "Lazurio", }); } + if (typeof lazurioBuddyFolder === "string") { + // 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 { + const earlier = (yield* projects.snapshot).projects.find( + (candidate) => candidate.workspaceRoot === lazurioBuddyFolder, + ); + if (earlier !== undefined) yield* restoreBuddyThreads(earlier.id); + } + }).pipe( + Effect.catchCause((cause) => + Effect.logWarning( + "Lazurio could not prepare Buddy's project; Chat starts without it.", + cause, + ), + ), + ); + } // A server always runs on the platform's file system. Upstream's startup tests build this phase // without one, so it is read here rather than added to the startup's requirements. const fileSystem = yield* Effect.serviceOption(FileSystem.FileSystem); @@ -45,3 +73,52 @@ 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. */ +const ensureBuddyProject = Effect.fn("LazurioManagedFolder.ensureBuddyProject")(function* ( + buddyFolder: string, +) { + const projects = yield* ProjectService.ProjectService; + const random = yield* SecureRandom.SecureRandom; + const id = yield* random.uuidV4(); + const { project } = yield* projects.bootstrap({ + commandId: CommandId.make(`lazurio-buddy-project:${id}`), + projectId: ProjectId.make(id), + title: BUDDY_PROJECT_TITLE, + workspaceRoot: buddyFolder, + }); + if (project.title !== BUDDY_PROJECT_TITLE || (project.archivedAt ?? null) !== null) { + yield* projects.update({ + commandId: CommandId.make(`lazurio-buddy-project-title:${id}`), + projectId: project.id, + title: BUDDY_PROJECT_TITLE, + archived: false, + }); + } + yield* restoreBuddyThreads(project.id); +}); + +/** + * Buddy's threads are never archived (managedFolderGuards.ts); one archived while the folder was not + * declared comes back, so the tasks it runs elsewhere follow a live parent again. + */ +const restoreBuddyThreads = Effect.fn("LazurioManagedFolder.restoreBuddyThreads")(function* ( + projectId: ProjectId, +) { + const orchestrator = yield* Effect.serviceOption(Orchestrator.OrchestratorV2); + if (Option.isNone(orchestrator)) return; + const random = yield* SecureRandom.SecureRandom; + const id = yield* random.uuidV4(); + const { archivedThreads } = yield* orchestrator.value.getShellSnapshot({ + location: "archive", + projectId, + }); + for (const thread of archivedThreads) { + if (thread.projectId !== projectId) continue; + yield* orchestrator.value.dispatch({ + type: "thread.unarchive", + commandId: CommandId.make(`lazurio-buddy-unarchive:${id}:${thread.id}`), + threadId: thread.id, + }); + } +}); diff --git a/apps/server/src/lazurio/modelRecommendation.test.ts b/apps/server/src/lazurio/modelRecommendation.test.ts index 634b6125f74ec..81023e47427ce 100644 --- a/apps/server/src/lazurio/modelRecommendation.test.ts +++ b/apps/server/src/lazurio/modelRecommendation.test.ts @@ -134,6 +134,14 @@ it.effect("the settings writer applies recommendations and keeps the person's ow selection: second, }); + // Another project's model, such as Buddy's (LZD-0033), is never the recommendation's. + yield* settings.updateSettings({ + projectSettingsOverrides: { [historyProject]: { defaultModelSelection: personal } }, + }); + yield* apply(first); + yield* apply(second); + assert.deepStrictEqual(folderModel(yield* settings.getSettings, historyProject), personal); + // The person's own model for the project stays, and so does their Environment default. yield* settings.updateSettings({ defaultModelSelection: claude, diff --git a/apps/server/src/serverRuntimeStartup.ts b/apps/server/src/serverRuntimeStartup.ts index 628b2ff6a5cef..861f61356f147 100644 --- a/apps/server/src/serverRuntimeStartup.ts +++ b/apps/server/src/serverRuntimeStartup.ts @@ -574,7 +574,10 @@ const make = Effect.fn("serverRuntimeStartup.make")(function* (options?: Startup yield* Effect.logInfo("V2 orchestration recovery completed", recovery); const managedWelcome = yield* runStartupPhase( "lazurio.project", - ensureManagedFolderProject.pipe(Effect.provideService(SecureRandom.SecureRandom, random)), + ensureManagedFolderProject.pipe( + Effect.provideService(SecureRandom.SecureRandom, random), + Effect.provideService(Orchestrator.OrchestratorV2, orchestrator), + ), ); // Runs after activation: the status check fetches every enabled project's // remote, and awaiting it here held command readiness for that long. diff --git a/apps/web/src/components/CommandPalette.tsx b/apps/web/src/components/CommandPalette.tsx index c08eb868b0e93..77753344dabf4 100644 --- a/apps/web/src/components/CommandPalette.tsx +++ b/apps/web/src/components/CommandPalette.tsx @@ -1,4 +1,5 @@ import { everyEnvironmentManaged, offeredInProjectPicker } from "../lazurio/managedFolder"; +import { listedLinkedRows, useLinkedUnlistedProjectIds } from "../lazurio/unlistedRows"; import { ThreadContextDragGhost } from "./chat/ThreadContextDragGhost"; import { threadPullRequestLinkMode } from "@t3tools/client-runtime/thread-pull-request-compatibility"; import { visibleThreadPullRequests } from "@t3tools/shared/threadPullRequests"; @@ -422,6 +423,7 @@ function OpenCommandPaletteDialog(props: { const linkedEnvironmentId = linkedThreadSearch?.linkedThreads?.environmentId ?? null; const hidingAnywhere = useAnyEnvironmentHiding(); const linkedThreadRefs = useEnvironmentThreadRefs(linkedEnvironmentId); + const linkedUnlistedProjectIds = useLinkedUnlistedProjectIds(linkedEnvironmentId); const [searchState, dispatchSearch] = useReducer(reduceCommandPaletteSearchState, null, () => { const view = props.initialContext ? null : openIntentView(props.openIntent); return view @@ -1803,7 +1805,7 @@ function OpenCommandPaletteDialog(props: { ? buildLinkedThreadActionItems({ ...linkedThreadSearch.linkedThreads, threads: visibleLinkedThreads( - linkedThreadSearch.linkedThreads.threads, + listedLinkedRows(linkedThreadSearch.linkedThreads.threads, linkedUnlistedProjectIds), linkedThreadSearch.linkedThreads.environmentId, linkedThreadRefs, hiddenKeys, diff --git a/apps/web/src/components/ThreadNotificationCoordinator.tsx b/apps/web/src/components/ThreadNotificationCoordinator.tsx index 2051d4ad633a8..0353492bc9dd6 100644 --- a/apps/web/src/components/ThreadNotificationCoordinator.tsx +++ b/apps/web/src/components/ThreadNotificationCoordinator.tsx @@ -86,10 +86,11 @@ export function startThreadNotifications( if (remaining.length === 0) openToasts.delete(key); else openToasts.set(key, remaining); }; + // Lazurio overlay (LZD-0033): Buddy's unlisted threads notify no more than tag-hidden ones. // A notification shown before the tag filter turned on must not stay on screen. While hiding, // one whose thread left the live list (archived) cannot be judged, so it closes too. const closeHiddenPending = () => { - const hidden = registry.get(environmentThreadShells.hiddenThreadKeysAtom); + const hidden = registry.get(environmentThreadShells.listHiddenThreadKeysAtom); const live = registry.get(environmentThreadShells.anyEnvironmentHidingAtom) ? new Set(registry.get(environmentThreadShells.threadRefsAtom).map(threadKey)) : null; @@ -121,7 +122,7 @@ export function startThreadNotifications( const { thread, status } = state; if ( registry - .get(environmentThreadShells.hiddenThreadKeysAtom) + .get(environmentThreadShells.listHiddenThreadKeysAtom) .has(threadKey({ environmentId, threadId: thread.id })) ) return; @@ -411,7 +412,7 @@ export function startThreadNotifications( }, ); const unsubscribeHidden = [ - registry.subscribe(environmentThreadShells.hiddenThreadKeysAtom, closeHiddenPending), + registry.subscribe(environmentThreadShells.listHiddenThreadKeysAtom, closeHiddenPending), registry.subscribe(environmentThreadShells.anyEnvironmentHidingAtom, closeHiddenPending), registry.subscribe(environmentThreadShells.threadRefsAtom, closeHiddenPending), ]; diff --git a/apps/web/src/components/pullRequest/PullRequestThreadLinks.tsx b/apps/web/src/components/pullRequest/PullRequestThreadLinks.tsx index a5b9ce5a3c24c..918651b03deb0 100644 --- a/apps/web/src/components/pullRequest/PullRequestThreadLinks.tsx +++ b/apps/web/src/components/pullRequest/PullRequestThreadLinks.tsx @@ -20,6 +20,8 @@ import { useVisibleThreadShells, } from "~/state/entities"; import { pullRequestEnvironment } from "~/state/pullRequests"; +import { listedLinkedRows } from "~/lazurio/unlistedRows"; +import { environmentProjects } from "~/state/projects"; import { environmentThreadShells } from "~/state/threads"; import { useEnvironmentQuery } from "~/state/query"; import { useThreadSearch } from "~/state/queries"; @@ -68,7 +70,11 @@ function EnabledPullRequestThreadLinks({ const currentThreadRef = thread === null ? null : threadRef; const linking = usePullRequestLinking(environmentId); const linkedHere = linking.isLinked(thread, url); - const hiddenKeys = useAtomValue(environmentThreadShells.hiddenThreadKeysAtom); + // Lazurio overlay (LZD-0033): Buddy's threads stay out of linked-thread rows too. + const hiddenKeys = useAtomValue(environmentThreadShells.listHiddenThreadKeysAtom); + const unlistedProjectIds = useAtomValue( + environmentProjects.unlistedProjectIdsAtom(environmentId), + ); const hidingAnywhere = useAnyEnvironmentHiding(); const loadedThreadRefs = useEnvironmentThreadRefs(environmentId); const relations = useEnvironmentQuery( @@ -118,7 +124,10 @@ function EnabledPullRequestThreadLinks({ if (parsed === null || (!linkedHere && !linking.canLink(url))) return null; const linkedThreads = visibleLinkedThreads( - linking.mode === "multiple" ? ((relations.data ?? lastRelations)?.threads ?? []) : [], + listedLinkedRows( + linking.mode === "multiple" ? ((relations.data ?? lastRelations)?.threads ?? []) : [], + unlistedProjectIds, + ), environmentId, loadedThreadRefs, hiddenKeys, diff --git a/apps/web/src/hooks/useActiveProjectTarget.ts b/apps/web/src/hooks/useActiveProjectTarget.ts index d90c91ca95351..a9d04ca0943ec 100644 --- a/apps/web/src/hooks/useActiveProjectTarget.ts +++ b/apps/web/src/hooks/useActiveProjectTarget.ts @@ -1,7 +1,7 @@ -import { scopeThreadRef } from "@t3tools/client-runtime/environment"; +import { scopeProjectRef, scopeThreadRef } from "@t3tools/client-runtime/environment"; import type { EnvironmentId, ScopedThreadRef } from "@t3tools/contracts"; -import { useProjects } from "~/state/entities"; +import { useProject } from "~/state/entities"; import { useHandleNewThread } from "./useHandleNewThread"; @@ -14,15 +14,12 @@ export interface ActiveProjectTarget { export function useActiveProjectTarget(): ActiveProjectTarget | null { const { activeDraftThread, activeThread } = useHandleNewThread(); - const projects = useProjects(); const thread = activeThread ?? activeDraftThread; const threadId = activeThread?.id ?? activeDraftThread?.threadId; - const project = thread - ? projects.find( - (candidate) => - candidate.environmentId === thread.environmentId && candidate.id === thread.projectId, - ) - : null; + // A point read: lists leave out Buddy's project (LZD-0033), its thread still has a project. + const project = useProject( + thread ? scopeProjectRef(thread.environmentId, thread.projectId) : null, + ); const cwd = thread?.worktreePath ?? project?.workspaceRoot; if (!thread || !threadId || !project || !cwd) return null; diff --git a/apps/web/src/lazurio/unlistedRows.test.ts b/apps/web/src/lazurio/unlistedRows.test.ts new file mode 100644 index 0000000000000..2c0c413471300 --- /dev/null +++ b/apps/web/src/lazurio/unlistedRows.test.ts @@ -0,0 +1,18 @@ +import { ProjectId, ThreadId } from "@t3tools/contracts"; +import { describe, expect, it } from "vite-plus/test"; + +import { listedLinkedRows } from "./unlistedRows"; + +describe("a pull request's linked threads in a managed Environment", () => { + it("leave out Buddy's threads, archived ones too", () => { + const buddy = ProjectId.make("buddy"); + const lazurio = ProjectId.make("lazurio"); + const rows = [ + { id: ThreadId.make("chat"), projectId: lazurio, archivedAt: null }, + { id: ThreadId.make("buddy-live"), projectId: buddy, archivedAt: null }, + { id: ThreadId.make("buddy-archived"), projectId: buddy, archivedAt: "2026-11-17T12:00:00Z" }, + ]; + expect(listedLinkedRows(rows, new Set([buddy])).map(({ id }) => id)).toEqual(["chat"]); + expect(listedLinkedRows(rows, new Set())).toBe(rows); + }); +}); diff --git a/apps/web/src/lazurio/unlistedRows.ts b/apps/web/src/lazurio/unlistedRows.ts new file mode 100644 index 0000000000000..5382a55aa4c55 --- /dev/null +++ b/apps/web/src/lazurio/unlistedRows.ts @@ -0,0 +1,33 @@ +import { useAtomValue } from "@effect/atom-react"; +import type { EnvironmentId, ProjectId } from "@t3tools/contracts"; +import { Atom } from "effect/reactivity"; + +import { environmentProjects } from "../state/projects"; + +const NO_PROJECTS = Atom.make((): ReadonlySet => new Set()).pipe( + Atom.withLabel("lazurio-no-unlisted-projects"), +); + +/** Buddy's project in `environmentId`, the one pull request rows leave out; none without one. */ +export function useLinkedUnlistedProjectIds( + environmentId: EnvironmentId | null, +): ReadonlySet { + return useAtomValue( + environmentId === null + ? NO_PROJECTS + : environmentProjects.unlistedProjectIdsAtom(environmentId), + ); +} + +/** + * Lazurio overlay (LZD-0033): a pull request's linked-thread rows without the threads of Buddy's + * project, archived ones too. The rows carry their project, the live shell does not hold them. + */ +export function listedLinkedRows( + rows: ReadonlyArray, + unlistedProjectIds: ReadonlySet, +): ReadonlyArray { + return unlistedProjectIds.size === 0 + ? rows + : rows.filter((row) => !unlistedProjectIds.has(row.projectId)); +} diff --git a/apps/web/src/lib/archivedThreadsState.ts b/apps/web/src/lib/archivedThreadsState.ts index fbd17226cefc8..c5b4e721472e9 100644 --- a/apps/web/src/lib/archivedThreadsState.ts +++ b/apps/web/src/lib/archivedThreadsState.ts @@ -4,10 +4,15 @@ import { createArchivedThreadSnapshotsAtomFamily, makeArchivedThreadsEnvironmentKey, } from "@t3tools/client-runtime/state/threads"; +import { enabledEnvironmentIds } from "@t3tools/client-runtime/state/connections"; import type { EnvironmentId } from "@t3tools/contracts"; +import { Atom } from "effect/reactivity"; + +import { environmentCatalog } from "../connection/catalog"; import { orchestrationEnvironment } from "../state/orchestration"; import { serverEnvironment } from "../state/server"; +import { environmentProjects } from "../state/projects"; import { environmentThreadShells } from "../state/threads"; import { appAtomRegistry } from "../rpc/atomRegistry"; @@ -21,9 +26,16 @@ function archivedSnapshotAtom(environmentId: EnvironmentId) { const archivedSnapshotsAtom = createArchivedThreadSnapshotsAtomFamily({ getSnapshotAtom: archivedSnapshotAtom, hiddenThreadTagsAtom: serverEnvironment.hiddenThreadTagsAtom, - hiddenThreadKeysAtom: environmentThreadShells.hiddenThreadKeysAtom, + // Lazurio overlay (LZD-0033): live and archived threads of Buddy's project stay out too. + hiddenThreadKeysAtom: environmentThreadShells.listHiddenThreadKeysAtom, liveThreadRefsAtom: environmentThreadShells.threadRefsAtom, anyEnvironmentHidingAtom: environmentThreadShells.anyEnvironmentHidingAtom, + unlistedProjectIdsAtom: environmentProjects.unlistedProjectIdsAtom, + unlistedEnvironmentIdsAtom: Atom.make((get) => + Array.from(enabledEnvironmentIds(get(environmentCatalog.catalogValueAtom))).filter( + (environmentId) => get(environmentProjects.unlistedProjectIdsAtom(environmentId)).size > 0, + ), + ), labelPrefix: "web:archived-thread-snapshots", }); diff --git a/apps/web/src/state/entities.ts b/apps/web/src/state/entities.ts index 19c0736779897..be4a099b2597c 100644 --- a/apps/web/src/state/entities.ts +++ b/apps/web/src/state/entities.ts @@ -112,9 +112,9 @@ export function useAnyEnvironmentHiding(): boolean { return useAtomValue(environmentThreadShells.anyEnvironmentHidingAtom); } -/** Keys of threads the tag filter hides from display, by `threadKey`. */ +/** Keys of threads the tag filter hides from display, and Buddy's unlisted ones (LZD-0033). */ export function useHiddenThreadKeys(): ReadonlySet { - return useAtomValue(environmentThreadShells.hiddenThreadKeysAtom); + return useAtomValue(environmentThreadShells.listHiddenThreadKeysAtom); } /** Thread shells minus those the tag filter hides, for lists that show threads to the user. */ diff --git a/apps/web/src/state/threads.ts b/apps/web/src/state/threads.ts index 6d2ce2a07c90b..4c83c269be166 100644 --- a/apps/web/src/state/threads.ts +++ b/apps/web/src/state/threads.ts @@ -18,6 +18,7 @@ import { AsyncResult, Atom } from "effect/reactivity"; import { environmentCatalog } from "../connection/catalog"; import { connectionAtomRuntime } from "../connection/runtime"; +import { environmentProjects } from "./projects"; import { serverEnvironment } from "./server"; import { environmentShell } from "./shell"; @@ -41,6 +42,7 @@ export const environmentThreadShells = createEnvironmentThreadShellAtoms({ catalogValueAtom: environmentCatalog.catalogValueAtom, snapshotAtom: threadEnvironment.snapshotAtom, hiddenThreadTagsAtom: serverEnvironment.hiddenThreadTagsAtom, + unlistedProjectIdsAtom: environmentProjects.unlistedProjectIdsAtom, }); export const childThreadApprovalsAtom = createChildThreadApprovalsAtom({ childThreadInputsAtom: environmentThreadShells.childThreadInputsAtom, diff --git a/docs/operations/lazurio-fork-release.md b/docs/operations/lazurio-fork-release.md index 4e8740ac83929..39562fd693429 100644 --- a/docs/operations/lazurio-fork-release.md +++ b/docs/operations/lazurio-fork-release.md @@ -774,6 +774,52 @@ odkaz vede na hostovanou aplikaci upstreamu s textem zadání v adrese a na spravovaném Environmentu vlákno neotevře. Co dělá odkaz, který přesto přijde, popisuje [specifikace overlaye](./lazurio-overlay.md#odkazy-na-zadání-upstreamu). +**Projekt Buddyho (plán LZD-0033, řez R1).** `T3CODE_LAZURIO_BUDDY_FOLDER` +určí vedle složky Lazuria kanonickou existující složku Buddyho; bez +`T3CODE_LAZURIO_FOLDER` ji server odmítne, stejně jako složku uvnitř Folderu +nebo složku, která Folder obsahuje (porovnává celé složky cesty, takže +`Lazurio/..buddy` leží uvnitř). Chybějící složka Chat nezastaví: server běží +a projekt nezakládá. V konfiguraci zůstane cesta, kde by složka byla (odkazy +i visící se přečtou, nejhlubší existující předek se kanonizuje), takže +dřívější projekt Buddyho zůstane nevypsaný a tahy v něm stráže odmítnou. Projekt nad ní je vnitřní věc Lazuria, ne +funkce Chatu: založí ho jen start serveru (`ProjectService.bootstrap`, jméno +Buddy), kam žádný klient, agent ani CLI nedosáhne. `create` ho dál odmítne +(`t3 project add`, `t3_project_create` i web) a přejmenování, archivaci +a smazání odmítne stráž projektů. Vlákna, zprávy, forky a tahy agenta stráže +pouští v kořeni složky Buddyho jako v kořeni Folderu, bez worktree. Doporučený +model Platformy zůstává jen modelem projektu Lazurio, takže přepis modelu +projektu Buddyho Lazurio nepřepíše. Server pošle složku klientům +(`lazurioBuddyFolder` v `server.getConfig`). Web projekt vynechá ze všech +seznamů projektů a jeho vlákna i s podřízenými vlákny a úlohami, které pro ně +běží v jiném Environmentu, ze seznamů, palety, hledání, archivu (Settings → +Archived threads; archivy Environmentů s projektem Buddyho se čtou i mimo +zvolený rozsah, aby úloha následovala rodiče archivovaného jinde) a vláken +propojených s pull requestem (řádky nesou projekt, takže vypadnou i +archivované), a to i v paletě a panelu vztahů; neposílá ani oznámení. Vlákno +otevřené odkazem čte svůj projekt přímo, takže výběr souborů a hledání v něm +fungují. Chyba v části startu, která patří Buddymu, se jen zaloguje a Chat +složky Lazurio naběhne bez projektu Buddyho. Vlákna projektu +Buddyho stráž příkazů nearchivuje ani nemaže (kromě nepoužitého vlákna, +`onlyIfUnused`), stejně jako jeho projekt. Vlákno archivované v době, +kdy proměnná nastavená nebyla, vrátí start serveru z archivu, i když +složka Buddyho mezitím zmizela a projekt se jen najde podle cesty. Úloha, kterou vlákno Buddyho +spustilo v jiném Environmentu, tak má rodiče vždy v živém shellu a ze seznamů +vypadne s ním. Na rozdíl od vláken skrytých filtrem štítků je otevře přímý odkaz +`//`. Agenti Chatu Buddyho vlákno přes MCP dál vidí +(`t3_thread_list`, `t3_project_list`); server ho neskrývá, protože Buddy vlákna +Chatu vidět musí. Oficiální desktop a mobil projekt ukážou jako běžný, protože +skrytí je ve webovém klientu a client-runtime overlaye. Bez proměnné se nic +nemění a Buddyho T3 Code GEN3 (`T3CODE_LAZURIO_BUDDY=1`) ji nedostává. +Logika vynechání je v modulu overlaye +`packages/client-runtime/src/lazurio/unlistedProjects.ts`. Atomy projektů, +vláken a archivu upstreamu (`projectEntities.ts`, `threadShell.ts`, +`archivedThreads.ts`) a jejich zapojení ve webu (`state/threads.ts`, +`lib/archivedThreadsState.ts`, `pullRequest/PullRequestThreadLinks.tsx`, +`ThreadNotificationCoordinator.tsx`, `state/entities.ts` a +`hooks/useActiveProjectTarget.ts`, filtr +řádků je v `apps/web/src/lazurio/unlistedRows.ts`) +nesou po jednom háčku. Proto jsou v allowlistu i s modulem a jeho testem. + Kód spravované složky žije ve složkách overlaye (`apps/*/src/lazurio/`); upstream soubory nesou jen háčky o několika řádcích. Kontraktní test je hlídá („the managed Lazurio Folder keeps its seams“) a `apps/server/src/lazurio/cli.test.ts` diff --git a/packages/client-runtime/src/lazurio/unlistedProjects.test.ts b/packages/client-runtime/src/lazurio/unlistedProjects.test.ts new file mode 100644 index 0000000000000..dabcba19e77c3 --- /dev/null +++ b/packages/client-runtime/src/lazurio/unlistedProjects.test.ts @@ -0,0 +1,217 @@ +import { + EnvironmentId, + ProjectId, + type ServerConfig, + ThreadId, + type OrchestrationV2ArchivedShellSnapshot, + type OrchestrationV2ShellSnapshot, +} from "@t3tools/contracts"; +import * as Option from "effect/Option"; +import { AsyncResult, Atom, AtomRegistry } from "effect/reactivity"; +import { describe, expect, it } from "vite-plus/test"; + +import { PrimaryConnectionTarget } from "../connection/model.ts"; +import { v2Project, v2ShellSnapshot, v2ThreadShell } from "../state/orchestrationV2TestFixtures.ts"; +import { + createArchivedThreadSnapshotsAtomFamily, + makeArchivedThreadsEnvironmentKey, +} from "../state/archivedThreads.ts"; +import { threadKey } from "../state/entities.ts"; +import { createEnvironmentProjectAtoms } from "../state/projectEntities.ts"; +import { createEnvironmentThreadShellAtoms } from "../state/threadShell.ts"; + +const environmentId = EnvironmentId.make("local"); +const remoteEnvironmentId = EnvironmentId.make("remote"); +const buddyProject = { + ...v2Project, + id: ProjectId.make("buddy"), + workspaceRoot: "/home/person/Buddy", +}; +const buddyThread = { ...v2ThreadShell, id: ThreadId.make("buddy"), projectId: buddyProject.id }; +const buddyChild = { + ...buddyThread, + id: ThreadId.make("buddy-child"), + projectId: v2ThreadShell.projectId, + lineage: { + ...buddyThread.lineage, + parentThreadId: buddyThread.id, + relationshipToParent: "subagent" as const, + }, +}; + +// A task another environment runs for Buddy's thread. +const remoteTask = { + ...v2ThreadShell, + id: ThreadId.make("remote-task"), + delegatedFrom: { environmentId, threadId: buddyThread.id, title: "Buddy" }, +}; + +function makeHarness() { + const snapshotAtom = Atom.family((id: EnvironmentId) => + Atom.make( + id === environmentId + ? { + ...v2ShellSnapshot, + projects: [v2Project, buddyProject], + threads: [v2ThreadShell, buddyThread, buddyChild], + } + : { ...v2ShellSnapshot, projects: [v2Project], threads: [remoteTask] }, + ), + ); + const configAtom = Atom.family((_environmentId: EnvironmentId) => + Atom.make | null>(null), + ); + const catalogValueAtom = Atom.make({ + isReady: true, + entries: new Map( + [environmentId, remoteEnvironmentId].map((id) => [ + id, + { + target: new PrimaryConnectionTarget({ + environmentId: id, + label: id, + httpBaseUrl: `https://${id}.example.test`, + wsBaseUrl: `wss://${id}.example.test`, + }), + profile: Option.none(), + enabled: true, + }, + ]), + ), + }); + const projects = createEnvironmentProjectAtoms({ + catalogValueAtom, + snapshotAtom, + serverConfigValueAtom: configAtom, + }); + const threads = createEnvironmentThreadShellAtoms({ + catalogValueAtom, + snapshotAtom, + hiddenThreadTagsAtom: () => Atom.make(null), + unlistedProjectIdsAtom: projects.unlistedProjectIdsAtom, + }); + return { registry: AtomRegistry.make(), projects, threads, configAtom }; +} + +describe("Buddy's project in a managed Environment", () => { + it("stays out of project and thread lists, with its subagents, and still opens", () => { + const { registry, projects, threads, configAtom } = makeHarness(); + try { + const ids = (list: ReadonlyArray<{ readonly id: string }>) => list.map(({ id }) => id); + const ref = { environmentId, projectId: buddyProject.id }; + // Without a declared Buddy folder it is listed as upstream lists it. + expect(ids(registry.get(projects.projectsAtom))).toEqual([ + v2Project.id, + buddyProject.id, + v2Project.id, + ]); + expect(ids(registry.get(threads.visibleThreadShellsAtom))).toHaveLength(4); + + registry.set(configAtom(environmentId), { lazurioBuddyFolder: buddyProject.workspaceRoot }); + expect(ids(registry.get(projects.projectsAtom))).toEqual([v2Project.id, v2Project.id]); + // Its subagent and the task another environment runs for it leave the lists too. + expect(ids(registry.get(threads.navigationThreadShellsAtom))).toEqual([v2ThreadShell.id]); + expect(ids(registry.get(threads.visibleThreadShellsAtom))).toEqual([v2ThreadShell.id]); + expect(ids(registry.get(threads.quietThreadShellsAtom))).toEqual([v2ThreadShell.id]); + // Linked-thread rows of a pull request read the same set. + expect([...registry.get(threads.listHiddenThreadKeysAtom)].toSorted()).toEqual( + [ + threadKey({ environmentId, threadId: buddyThread.id }), + threadKey({ environmentId, threadId: buddyChild.id }), + threadKey({ environmentId: remoteEnvironmentId, threadId: remoteTask.id }), + ].toSorted(), + ); + // Point reads find it, and it is not tag-hidden, which the thread route keeps closed. + expect(registry.get(projects.projectAtom(ref))?.workspaceRoot).toBe( + buddyProject.workspaceRoot, + ); + expect(registry.get(threads.threadShellsAtom)).toHaveLength(4); + expect(registry.get(threads.hiddenThreadKeysAtom).size).toBe(0); + } finally { + registry.dispose(); + } + }); + + it("stays out of the archive, with archived children of its live thread", () => { + const { registry, projects, threads, configAtom } = makeHarness(); + const archivedBuddy = { ...buddyThread, id: ThreadId.make("archived-buddy") }; + const archivedChild = { + ...buddyChild, + id: ThreadId.make("archived-child"), + lineage: { ...buddyChild.lineage, parentThreadId: buddyThread.id }, + }; + const archivedOther = { ...v2ThreadShell, id: ThreadId.make("archived-other") }; + const archive = createArchivedThreadSnapshotsAtomFamily({ + getSnapshotAtom: () => + Atom.make( + AsyncResult.success({ + schemaVersion: 1, + snapshotSequence: 1, + projects: [v2Project, buddyProject], + threads: [archivedBuddy, archivedChild, archivedOther], + }), + ), + hiddenThreadTagsAtom: () => Atom.make(null), + hiddenThreadKeysAtom: threads.listHiddenThreadKeysAtom, + liveThreadRefsAtom: threads.threadRefsAtom, + anyEnvironmentHidingAtom: threads.anyEnvironmentHidingAtom, + unlistedProjectIdsAtom: projects.unlistedProjectIdsAtom, + labelPrefix: "test:unlisted-archive", + }); + try { + registry.set(configAtom(environmentId), { lazurioBuddyFolder: buddyProject.workspaceRoot }); + const [entry] = registry.get( + archive(makeArchivedThreadsEnvironmentKey([environmentId])), + ).snapshots; + expect(entry?.snapshot.threads.map(({ id }) => id)).toEqual([archivedOther.id]); + } finally { + registry.dispose(); + } + }); + + it("keeps a task archived elsewhere out when its archived Buddy parent is in another archive", () => { + const { registry, projects, threads, configAtom } = makeHarness(); + const archivedBuddy = { ...buddyThread, id: ThreadId.make("archived-buddy") }; + const archivedTask = { + ...v2ThreadShell, + id: ThreadId.make("archived-remote-task"), + delegatedFrom: { environmentId, threadId: archivedBuddy.id, title: "Buddy" }, + }; + const archivedRemote = { ...v2ThreadShell, id: ThreadId.make("archived-remote") }; + const page = ( + threadsOnPage: OrchestrationV2ArchivedShellSnapshot["threads"], + ): OrchestrationV2ArchivedShellSnapshot => ({ + schemaVersion: 1, + snapshotSequence: 1, + projects: [v2Project, buddyProject], + threads: threadsOnPage, + }); + const archive = createArchivedThreadSnapshotsAtomFamily({ + getSnapshotAtom: (id) => + Atom.make( + AsyncResult.success( + id === environmentId ? page([archivedBuddy]) : page([archivedTask, archivedRemote]), + ), + ), + hiddenThreadTagsAtom: () => Atom.make(null), + hiddenThreadKeysAtom: threads.listHiddenThreadKeysAtom, + liveThreadRefsAtom: threads.threadRefsAtom, + anyEnvironmentHidingAtom: threads.anyEnvironmentHidingAtom, + unlistedProjectIdsAtom: projects.unlistedProjectIdsAtom, + unlistedEnvironmentIdsAtom: Atom.make([environmentId]), + labelPrefix: "test:unlisted-archive-elsewhere", + }); + try { + registry.set(configAtom(environmentId), { lazurioBuddyFolder: buddyProject.workspaceRoot }); + // Scoped to the remote environment only, with no tag filter anywhere. + expect(registry.get(threads.anyEnvironmentHidingAtom)).toBe(false); + const { snapshots } = registry.get( + archive(makeArchivedThreadsEnvironmentKey([remoteEnvironmentId])), + ); + expect(snapshots.map(({ environmentId: id }) => id)).toEqual([remoteEnvironmentId]); + expect(snapshots[0]?.snapshot.threads.map(({ id }) => id)).toEqual([archivedRemote.id]); + } finally { + registry.dispose(); + } + }); +}); diff --git a/packages/client-runtime/src/lazurio/unlistedProjects.ts b/packages/client-runtime/src/lazurio/unlistedProjects.ts new file mode 100644 index 0000000000000..7662842f85f30 --- /dev/null +++ b/packages/client-runtime/src/lazurio/unlistedProjects.ts @@ -0,0 +1,89 @@ +/** + * Lazurio overlay (LZD-0033): Buddy's project, over the Buddy folder a managed Environment declares + * (`lazurioBuddyFolder`), is Lazurio's own. Lists leave it and its threads out; point reads, and so + * a link to one of its threads, still find them. Tag-hidden threads stay closed, these do not. + */ +import type { EnvironmentId, OrchestrationV2ThreadShell, ProjectId } from "@t3tools/contracts"; + +import { threadKey } from "../state/entities.ts"; +import { hiddenThreadKeys, NO_HIDDEN_THREADS } from "../state/threadTagFilter.ts"; + +export const NO_UNLISTED_PROJECT_IDS: ReadonlySet = new Set(); + +/** The projects lists leave out: the one over the declared Buddy folder, if any. */ +export function unlistedProjectIds( + projects: ReadonlyArray<{ readonly id: ProjectId; readonly workspaceRoot: string }>, + buddyFolder: string | undefined, +): ReadonlySet { + if (buddyFolder === undefined) return NO_UNLISTED_PROJECT_IDS; + const ids = projects.flatMap((project) => + project.workspaceRoot === buddyFolder ? [project.id] : [], + ); + return ids.length === 0 ? NO_UNLISTED_PROJECT_IDS : new Set(ids); +} + +const sameKeys = (a: ReadonlySet, b: ReadonlySet) => + a === b || (a.size === b.size && [...a].every((key) => b.has(key))); +export const sameProjectIds = (a: ReadonlySet, b: ReadonlySet) => + sameKeys(a, b); +export const sameThreadKeys = (a: ReadonlySet, b: ReadonlySet) => sameKeys(a, b); + +/** + * Keys of threads in unlisted projects, with the subagents, side chats and tasks under them, also + * those another environment runs for them: pass every enabled environment, most with no projects. + */ +export function unlistedThreadKeys( + environments: ReadonlyArray<{ + readonly environmentId: EnvironmentId; + readonly projectIds: ReadonlySet; + readonly threads: ReadonlyArray< + Pick + >; + }>, +): ReadonlySet { + const inProjects = new Set(); + for (const { environmentId, projectIds, threads } of environments) { + for (const thread of threads) { + if (projectIds.has(thread.projectId)) + inProjects.add(threadKey({ environmentId, threadId: thread.id })); + } + } + if (inProjects.size === 0) return NO_HIDDEN_THREADS; + // Not hiding anywhere: a child whose parent is not loaded stays listed, as upstream lists it. + return hiddenThreadKeys( + environments.map(({ environmentId, threads }) => ({ + environmentId, + threads, + hiddenTags: null, + })), + inProjects, + ); +} + +/** Keys of archived threads in unlisted projects; the archive's own pass hides their children. */ +export function unlistedArchivedThreadKeys( + environments: ReadonlyArray<{ + readonly environmentId: EnvironmentId; + readonly projectIds: ReadonlySet; + readonly threads: ReadonlyArray>; + }>, +): ReadonlySet { + const keys = new Set(); + for (const { environmentId, projectIds, threads } of environments) { + for (const thread of threads) { + if (projectIds.has(thread.projectId)) + keys.add(threadKey({ environmentId, threadId: thread.id })); + } + } + return keys.size === 0 ? NO_HIDDEN_THREADS : keys; +} + +/** What lists leave out: tag-hidden threads and unlisted ones. */ +export function listHiddenKeys( + hidden: ReadonlySet, + unlisted: ReadonlySet, +): ReadonlySet { + if (unlisted.size === 0) return hidden; + if (hidden.size === 0) return unlisted; + return new Set([...hidden, ...unlisted]); +} diff --git a/packages/client-runtime/src/state/archivedThreads.ts b/packages/client-runtime/src/state/archivedThreads.ts index 067a913d018b4..dce2e3154665e 100644 --- a/packages/client-runtime/src/state/archivedThreads.ts +++ b/packages/client-runtime/src/state/archivedThreads.ts @@ -1,6 +1,7 @@ import { EnvironmentId, type OrchestrationV2ArchivedShellSnapshot, + type ProjectId, type ScopedThreadRef, } from "@t3tools/contracts"; import * as Arr from "effect/Array"; @@ -10,6 +11,11 @@ import { AsyncResult, Atom } from "effect/reactivity"; import { threadKey } from "./entities.ts"; import { hiddenThreadKeys, type TagFilteredEnvironment } from "./threadTagFilter.ts"; +import { + listHiddenKeys, + NO_UNLISTED_PROJECT_IDS, + unlistedArchivedThreadKeys, +} from "../lazurio/unlistedProjects.ts"; export interface ArchivedSnapshotEntry { readonly environmentId: EnvironmentId; @@ -56,6 +62,12 @@ export function createArchivedThreadSnapshotsAtomFamily(options: { readonly liveThreadRefsAtom: Atom.Atom>; /** Whether any connected environment hides tags, including ones outside this archive's scope. */ readonly anyEnvironmentHidingAtom: Atom.Atom; + /** Lazurio overlay (LZD-0033): projects whose archived threads, and their children, stay out. */ + readonly unlistedProjectIdsAtom?: ( + environmentId: EnvironmentId, + ) => Atom.Atom>; + /** Environments with unlisted projects, whose archives are read so tasks follow parents there. */ + readonly unlistedEnvironmentIdsAtom?: Atom.Atom>; readonly labelPrefix: string; }) { return Atom.family((environmentKey: string) => @@ -85,12 +97,40 @@ export function createArchivedThreadSnapshotsAtomFamily(options: { } } + // Lazurio overlay (LZD-0033): archives outside the scope that hold unlisted projects join the + // pass only, so a task follows a parent archived there. + const traversed = [...snapshots]; + for (const environmentId of options.unlistedEnvironmentIdsAtom + ? get(options.unlistedEnvironmentIdsAtom) + : []) { + if (environments.some((environment) => environment.environmentId === environmentId)) + continue; + const result = get(options.getSnapshotAtom(environmentId)); + isLoading ||= result.waiting; + const snapshot = AsyncResult.getOrElse(result, () => null); + if (snapshot !== null) traversed.push({ environmentId, snapshot }); + environments.push({ + environmentId, + threads: snapshot?.threads ?? [], + hiddenTags: get(options.hiddenThreadTagsAtom(environmentId)), + }); + } + // One pass over every environment's page, so archived tasks follow parents archived elsewhere. // Any connected machine may hide an unloaded parent, so the global flag decides, not the scope. const hidingAnywhere = get(options.anyEnvironmentHidingAtom); + const unlisted = unlistedArchivedThreadKeys( + traversed.map(({ environmentId, snapshot }) => ({ + environmentId, + projectIds: options.unlistedProjectIdsAtom + ? get(options.unlistedProjectIdsAtom(environmentId)) + : NO_UNLISTED_PROJECT_IDS, + threads: snapshot.threads, + })), + ); const hidden = hiddenThreadKeys( environments, - get(options.hiddenThreadKeysAtom), + listHiddenKeys(get(options.hiddenThreadKeysAtom), unlisted), hidingAnywhere ? new Set(get(options.liveThreadRefsAtom).map(threadKey)) : undefined, hidingAnywhere, ); diff --git a/packages/client-runtime/src/state/projectEntities.ts b/packages/client-runtime/src/state/projectEntities.ts index 313f845797e97..83f7e2e5fb48f 100644 --- a/packages/client-runtime/src/state/projectEntities.ts +++ b/packages/client-runtime/src/state/projectEntities.ts @@ -11,6 +11,7 @@ import { Atom } from "effect/reactivity"; import type { EnvironmentProject } from "./models.ts"; import { scopeProject } from "./models.ts"; import { isScratchProject } from "./projects.ts"; +import { sameProjectIds, unlistedProjectIds } from "../lazurio/unlistedProjects.ts"; import { type EnvironmentCatalogState, enabledEnvironmentIds } from "./connections.ts"; import { arrayElementsEqual, parseProjectKey, projectKey, projectRefsEqual } from "./entities.ts"; @@ -24,7 +25,7 @@ export function createEnvironmentProjectAtoms(input: { ) => Atom.Atom; readonly serverConfigValueAtom?: ( environmentId: EnvironmentId, - ) => Atom.Atom | null>; + ) => Atom.Atom | null>; }) { const environmentProjectsAtom = Atom.family((environmentId: EnvironmentId) => Atom.make( @@ -43,13 +44,28 @@ export function createEnvironmentProjectAtoms(input: { }).pipe(Atom.withLabel(`environment-project-index:${environmentId}`)), ); + // Lazurio overlay (LZD-0033): Buddy's project stays out of the lists below, not out of point reads. + const unlistedProjectIdsAtom = Atom.family((environmentId: EnvironmentId) => + Atom.make((get) => + unlistedProjectIds( + get(environmentProjectsAtom(environmentId)), + input.serverConfigValueAtom + ? get(input.serverConfigValueAtom(environmentId))?.lazurioBuddyFolder + : undefined, + ), + ).pipe( + Atom.withEquality(sameProjectIds), + Atom.withLabel(`environment-unlisted-projects:${environmentId}`), + ), + ); + const environmentProjectRefsAtom = Atom.family((environmentId: EnvironmentId) => { let previous: ReadonlyArray = []; return Atom.make((get) => { - const next = get(environmentProjectsAtom(environmentId)).map((project) => ({ - environmentId, - projectId: project.id, - })); + const unlisted = get(unlistedProjectIdsAtom(environmentId)); + const next = get(environmentProjectsAtom(environmentId)).flatMap((project) => + unlisted.has(project.id) ? [] : [{ environmentId, projectId: project.id }], + ); if (projectRefsEqual(previous, next)) { return previous; } @@ -133,6 +149,7 @@ export function createEnvironmentProjectAtoms(input: { projectRefsAtom, projectsAtom, projectConfigsReadyAtom, + unlistedProjectIdsAtom, projectAtom: (ref: ScopedProjectRef) => projectAtomFamily(projectKey(ref)), }; } diff --git a/packages/client-runtime/src/state/threadShell.ts b/packages/client-runtime/src/state/threadShell.ts index f5ced761c5665..2ea11f7aeaaa2 100644 --- a/packages/client-runtime/src/state/threadShell.ts +++ b/packages/client-runtime/src/state/threadShell.ts @@ -17,6 +17,12 @@ import { Atom } from "effect/reactivity"; import type { EnvironmentThreadShell, PendingSubagentRequest } from "./models.ts"; import { presentThreadShell, threadRuntimeIsActive } from "./models.ts"; import { hiddenThreadKeys, NO_HIDDEN_THREADS } from "./threadTagFilter.ts"; +import { + listHiddenKeys, + NO_UNLISTED_PROJECT_IDS, + sameThreadKeys, + unlistedThreadKeys, +} from "../lazurio/unlistedProjects.ts"; import { type EnvironmentCatalogState, enabledEnvironmentIds } from "./connections.ts"; import { arrayElementsEqual, @@ -209,6 +215,10 @@ export function createEnvironmentThreadShellAtoms(input: { readonly hiddenThreadTagsAtom: ( environmentId: EnvironmentId, ) => Atom.Atom | null>; + /** Lazurio overlay (LZD-0033): projects whose threads, and their children, lists leave out. */ + readonly unlistedProjectIdsAtom?: ( + environmentId: EnvironmentId, + ) => Atom.Atom>; }) { // Point reads and aggregate lists share values without keeping an atom alive // for every listed thread. Replaced source objects can be collected. @@ -626,6 +636,26 @@ export function createEnvironmentThreadShellAtoms(input: { return next; }).pipe(Atom.withLabel("environment-hidden-thread-keys")); + // Lazurio overlay (LZD-0033): lists leave out unlisted projects' threads; the route still opens them. + const unlistedThreadKeysAtom = Atom.make((get) => { + const environments = Array.from(enabledEnvironmentIds(get(input.catalogValueAtom)), (id) => ({ + environmentId: id, + projectIds: input.unlistedProjectIdsAtom ? get(input.unlistedProjectIdsAtom(id)) : null, + })); + if (!environments.some(({ projectIds }) => projectIds !== null && projectIds.size > 0)) + return NO_HIDDEN_THREADS; + return unlistedThreadKeys( + environments.map(({ environmentId, projectIds }) => ({ + environmentId, + projectIds: projectIds ?? NO_UNLISTED_PROJECT_IDS, + threads: get(environmentThreadsAtom(environmentId)), + })), + ); + }).pipe(Atom.withEquality(sameThreadKeys), Atom.withLabel("environment-unlisted-thread-keys")); + const listHiddenThreadKeysAtom = Atom.make((get) => + listHiddenKeys(get(hiddenThreadKeysAtom), get(unlistedThreadKeysAtom)), + ).pipe(Atom.withLabel("environment-list-hidden-thread-keys")); + const anyEnvironmentHidingAtom = Atom.make((get) => Array.from(enabledEnvironmentIds(get(input.catalogValueAtom))).some( (environmentId) => get(input.hiddenThreadTagsAtom(environmentId)) !== null, @@ -636,7 +666,7 @@ export function createEnvironmentThreadShellAtoms(input: { let previousVisibleThreadShells: ReadonlyArray = []; const visibleThreadShellsAtom = Atom.make((get) => { const threads = get(threadShellsAtom); - const hidden = get(hiddenThreadKeysAtom); + const hidden = get(listHiddenThreadKeysAtom); if (hidden.size === 0) return threads; const next = threads.filter( (thread) => @@ -652,7 +682,7 @@ export function createEnvironmentThreadShellAtoms(input: { let previousQuietThreadShells: ReadonlyArray = []; const quietThreadShellsAtom = Atom.make((get) => { const next: EnvironmentThreadShell[] = []; - const hidden = get(hiddenThreadKeysAtom); + const hidden = get(listHiddenThreadKeysAtom); for (const ref of get(threadRefsAtom)) { if (hidden.has(threadKey(ref))) continue; const shell = get(quietThreadShellAtomFamily(threadKey(ref))); @@ -695,7 +725,7 @@ export function createEnvironmentThreadShellAtoms(input: { const navigationThreadShellsAtom = Atom.make((get) => { const next: EnvironmentThreadShell[] = []; const underParent = get(delegatedUnderParentAtom); - const hidden = get(hiddenThreadKeysAtom); + const hidden = get(listHiddenThreadKeysAtom); for (const environmentId of enabledEnvironmentIds(get(input.catalogValueAtom))) { const subagentRequests = get(pendingSubagentRequestsAtom(environmentId)); for (const thread of get(environmentThreadsAtom(environmentId))) { @@ -723,6 +753,7 @@ export function createEnvironmentThreadShellAtoms(input: { threadShellsAtom, visibleThreadShellsAtom, hiddenThreadKeysAtom, + listHiddenThreadKeysAtom, anyEnvironmentHidingAtom, quietThreadShellsAtom, navigationThreadShellsAtom, diff --git a/packages/contracts/src/server.ts b/packages/contracts/src/server.ts index 7b7ea27348d39..ff5baa60f056e 100644 --- a/packages/contracts/src/server.ts +++ b/packages/contracts/src/server.ts @@ -610,6 +610,8 @@ export type ServerEventLoopStall = typeof ServerEventLoopStall.Type; export const ServerConfig = Schema.Struct({ /** The one initial project of a managed Lazurio Environment. Older clients still follow server enforcement. */ lazurioFolder: Schema.optionalKey(TrimmedNonEmptyString), + /** The Buddy folder beside it, the managed Environment's one other project. */ + lazurioBuddyFolder: Schema.optionalKey(TrimmedNonEmptyString), lazurioToolsUrl: Schema.optionalKey(TrimmedNonEmptyString), /** Buddy's own T3 Code (T3CODE_LAZURIO_BUDDY=1): the web shows Buddy's one conversation. */ lazurioBuddy: Schema.optionalKey(Schema.Literal(true)), diff --git a/scripts/lazurio-release-contract.test.mjs b/scripts/lazurio-release-contract.test.mjs index 4dce8c8c88c99..93546a0737f6c 100644 --- a/scripts/lazurio-release-contract.test.mjs +++ b/scripts/lazurio-release-contract.test.mjs @@ -1062,7 +1062,7 @@ NodeTest.test("the managed Lazurio Folder keeps its seams", async () => { // decorator is an Effect.fn with its own span (effectFnOpportunity is an error). NodeAssert.match( source.guards, - /dispatch: Effect\.fn\("LazurioManagedFolder\.dispatch"\)\(\(command\) =>\n\s+Effect\.flatMap\(commandRefusal\(command, \{ isFolderProject, isInFolderRoot \}\), \(refusal\) =>\n\s+refusal === null\n\s+\? orchestrator\.dispatch\(command\)/, + /dispatch: Effect\.fn\("LazurioManagedFolder\.dispatch"\)\(\(command\) =>\n\s+Effect\.flatMap\(\n\s+commandRefusal\(command, \{ isFolderProject, isInFolderRoot, isBuddyThread \}\),\n\s+\(refusal\) =>\n\s+refusal === null\n\s+\? orchestrator\.dispatch\(command\)/, ); NodeAssert.match( source.guards, @@ -1074,7 +1074,8 @@ NodeTest.test("the managed Lazurio Folder keeps its seams", async () => { ); NodeAssert.match( source.guards, - /bootstrap: Effect\.fn\("LazurioManagedFolder\.bootstrapProject"\)\(\(input\) =>\n\s+Effect\.flatMap\(inFolder\(input\), projects\.bootstrap\),/, + // Only the startup bootstraps, so only it can make Buddy's project (LZD-0033); create cannot. + /bootstrap: Effect\.fn\("LazurioManagedFolder\.bootstrapProject"\)\(\(input\) =>\n\s+Effect\.flatMap\(inFolderOrBuddy\(input\), projects\.bootstrap\),/, ); NodeAssert.match(source.guards, /scratchRoot: Effect\.succeedNone,/); NodeAssert.match(source.vcs, /const lazurioFolderGuard = yield\* makeFolderGuard;/);