diff --git a/apps/server/src/config.ts b/apps/server/src/config.ts index 47e9fa237654a..121618c9c0c80 100644 --- a/apps/server/src/config.ts +++ b/apps/server/src/config.ts @@ -96,6 +96,8 @@ export class ServerConfig extends Context.Service< readonly lazurioFolder?: string; /** The Buddy folder beside the Folder, declared with it (`T3CODE_LAZURIO_BUDDY_FOLDER`). */ readonly lazurioBuddyFolder?: string; + /** Buddy's window's own origin, routed to this server (`T3CODE_LAZURIO_BUDDY_ORIGIN`). */ + readonly lazurioBuddyOrigin?: string; readonly lazurioToolsUrl?: string; readonly baseDir: string; readonly staticDir: string | undefined; diff --git a/apps/server/src/lazurio/buddyPrompt.test.ts b/apps/server/src/lazurio/buddyPrompt.test.ts index 92f306d2eb2ce..fe6170a7be56b 100644 --- a/apps/server/src/lazurio/buddyPrompt.test.ts +++ b/apps/server/src/lazurio/buddyPrompt.test.ts @@ -189,23 +189,29 @@ describe("the projection a provider turn gets", () => { }).pipe(Effect.provideService(HostProcess.Environment, BUDDY_ENV)), ); - it.effect("is upstream's for another instance of Buddy's T3 Code", () => + // Only Buddy's window adds a page record, so its page block reaches any provider (GEN4). + it.effect( + "is Buddy's for a message with a page record on any instance, also without the switch", + () => + Effect.gen(function* () { + for (const instanceId of [ProviderInstanceId.make("codex"), BUDDY]) { + const text = yield* projectComposerContextForProvider({ ...input, instanceId }); + assert.strictEqual(text, buddyProviderText(input)); + assert.include(text, "Kontext stránky"); + } + }).pipe(Effect.provideService(HostProcess.Environment, { T3CODE_LAZURIO_BUDDY: "true" })), + ); + + it.effect("is upstream's for a message without a page record on any other instance", () => Effect.gen(function* () { + const plain = { text: "Ahoj", records: [] }; const text = yield* projectComposerContextForProvider({ - ...input, + ...plain, instanceId: ProviderInstanceId.make("codex"), }); - assert.strictEqual(text, projectUpstream(input)); - assert.include(text, " - Effect.gen(function* () { - const text = yield* projectComposerContextForProvider({ ...input, instanceId: BUDDY }); - assert.strictEqual(text, projectUpstream(input)); - }).pipe(Effect.provideService(HostProcess.Environment, { T3CODE_LAZURIO_BUDDY: "true" })), - ); }); // What reaches the agent: the repository's mock ACP agent stands in for Hermes and logs every diff --git a/apps/server/src/lazurio/buddyPrompt.ts b/apps/server/src/lazurio/buddyPrompt.ts index e42762668fd90..d746f72634db7 100644 --- a/apps/server/src/lazurio/buddyPrompt.ts +++ b/apps/server/src/lazurio/buddyPrompt.ts @@ -131,7 +131,8 @@ export function buddyProviderText(input: { } /** - * The text a provider turn gets for a message: Buddy's projection for Buddy's instance, upstream's + * The text a provider turn gets for a message: Buddy's projection for Buddy's instance and for any + * message with a page record, which only Buddy's window adds (GEN4 on any provider); upstream's * for every other. */ export const projectComposerContextForProvider = Effect.fn( @@ -142,7 +143,7 @@ export const projectComposerContextForProvider = Effect.fn( readonly records: ReadonlyArray; }) { const environment = yield* HostProcess.Environment; - return isBuddyInstance(environment, input.instanceId) + return isBuddyInstance(environment, input.instanceId) || input.records.some(isPageRecord) ? buddyProviderText(input) : projectUpstream(input); }); diff --git a/apps/server/src/lazurio/buddySurfaceDays.ts b/apps/server/src/lazurio/buddySurfaceDays.ts index fc4dcafccba53..644e7ebd3934a 100644 --- a/apps/server/src/lazurio/buddySurfaceDays.ts +++ b/apps/server/src/lazurio/buddySurfaceDays.ts @@ -19,7 +19,9 @@ import { OrchestratorV2 } from "../orchestration-v2/Orchestrator.ts"; import { ActingSenders } from "./actingSenders.ts"; import { type ActingSendersRecord, personSeesMessage } from "./actingSenderVisibility.ts"; import { isBuddySurfaceEnvironment } from "./buddySurface.ts"; -import { BUDDY_THREAD_ID } from "./buddySurfaceThread.ts"; +import * as ServerConfig from "../config.ts"; +import { ProjectStoreV2 } from "../orchestration-v2/ProjectStore.ts"; +import { BUDDY_THREAD_ID, findSharedBuddyThread, sharedBuddyFolder } from "./buddySurfaceThread.ts"; import { authenticateOverlayRoute } from "./routeAuth.ts"; const BUDDY_DAYS_ROUTE = "/api/lazurio/buddy/days"; @@ -114,22 +116,39 @@ export const layer = HttpRouter.use((router) => // A handler sees only the request's context, so it takes the orchestrator from the layer's. const orchestrator = yield* OrchestratorV2; const senders = yield* ActingSenders; + const config = yield* ServerConfig.ServerConfig; + const projects = yield* ProjectStoreV2; yield* router.add( "GET", BUDDY_DAYS_ROUTE, Effect.gen(function* () { yield* authenticateOverlayRoute(AuthOrchestrationReadScope); - if (!isBuddySurfaceEnvironment(yield* HostProcess.Environment)) - return HttpServerResponse.jsonUnsafe({ error: "not-buddy" }, { status: 404 }); + // GEN3: the server's one thread; GEN4: Buddy's thread of the shared server. + let threadId = BUDDY_THREAD_ID; + if (!isBuddySurfaceEnvironment(yield* HostProcess.Environment)) { + const buddyFolder = yield* sharedBuddyFolder.pipe( + Effect.provideService(ServerConfig.ServerConfig, config), + ); + if (buddyFolder === undefined) + return HttpServerResponse.jsonUnsafe({ error: "not-buddy" }, { status: 404 }); + const found = yield* findSharedBuddyThread(buddyFolder).pipe( + Effect.provideService(OrchestratorV2, orchestrator), + Effect.provideService(ProjectStoreV2, projects), + Effect.option, + ); + const thread = Option.getOrUndefined(found)?.thread ?? null; + if (thread === null) return HttpServerResponse.jsonUnsafe({ days: [] }); + threadId = thread.id; + } const request = yield* HttpServerRequest.HttpServerRequest; const timeZone = timeZoneOf(new URL(request.url, "http://local").searchParams.get("tz")); - const shell = yield* orchestrator.getThreadShell(BUDDY_THREAD_ID).pipe(Effect.orDie); + const shell = yield* orchestrator.getThreadShell(threadId).pipe(Effect.orDie); if (shell === null) return HttpServerResponse.jsonUnsafe({ days: [] }); const records = yield* orchestrator - .getThreadRecords(BUDDY_THREAD_ID, ["messages"], { messageRoles: ["user"] }) + .getThreadRecords(threadId, ["messages"], { messageRoles: ["user"] }) .pipe(Effect.orDie); // As the web without the record: every message shows. - const answer = yield* senders.read(BUDDY_THREAD_ID).pipe(Effect.option); + const answer = yield* senders.read(threadId).pipe(Effect.option); const record = Option.match(answer, { onNone: () => null, onSome: ({ at, records }) => ({ diff --git a/apps/server/src/lazurio/buddySurfaceThread.test.ts b/apps/server/src/lazurio/buddySurfaceThread.test.ts index 0ed259a08b2ba..01b5ad22e721d 100644 --- a/apps/server/src/lazurio/buddySurfaceThread.test.ts +++ b/apps/server/src/lazurio/buddySurfaceThread.test.ts @@ -4,10 +4,14 @@ import * as NodeOS from "node:os"; import * as NodePath from "node:path"; import { assert, describe, it } from "@effect/vitest"; -import { CommandId, ProjectId } from "@t3tools/contracts"; +import { CommandId, ProjectId, ProviderInstanceId, ThreadId } from "@t3tools/contracts"; import * as HostProcess from "@t3tools/shared/HostProcess"; import * as Effect from "effect/Effect"; import * as Exit from "effect/Exit"; +import * as Layer from "effect/Layer"; + +import * as ServerConfig from "../config.ts"; +import * as ServerSettings from "../serverSettings.ts"; import * as Orchestrator from "../orchestration-v2/Orchestrator.ts"; import { BUDDY, addProject, layerBuddyServer } from "./buddySurface.testkit.ts"; @@ -203,4 +207,116 @@ describe("Buddy's thread", () => { ); }, ); + + describe("on the shared Chat server (GEN4, LZD-0033 R3)", () => { + /** A managed Folder and a Buddy folder beside it, as the Environment declares them. */ + const makeShared = () => { + const home = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "buddy-shared-home-")); + const folder = NodePath.join(home, "Lazurio"); + const buddy = NodePath.join(home, "Buddy"); + NodeFS.mkdirSync(folder); + NodeFS.mkdirSync(buddy); + return { home, folder, buddy }; + }; + const shared = (folder: string, buddy: string) => + Effect.map(ServerConfig.ServerConfig, (config) => ({ + ...config, + lazurioFolder: folder, + lazurioBuddyFolder: buddy, + })); + const withShared = (effect: Effect.Effect, folder: string, buddy: string) => + Effect.flatMap(shared(folder, buddy), (config) => + effect.pipe(Effect.provideService(ServerConfig.ServerConfig, config)), + ); + + it.live("makes one thread in Buddy's project on the Environment's default model", () => { + const { home, folder, buddy } = makeShared(); + return Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + const settings = yield* ServerSettings.ServerSettingsService; + // No Environment default yet: the Lazurio project's model (the Platform's recommendation). + const recommended = { instanceId: ProviderInstanceId.make("codex"), model: "gpt-6.1-sol" }; + yield* settings.updateSettings({ + projectSettingsOverrides: { + [ProjectId.make("project:lazurio")]: { defaultModelSelection: recommended }, + }, + }); + yield* addProject(ProjectId.make("project:lazurio"), folder); + yield* addProject(ProjectId.make("project:buddy"), buddy); + const [first, second] = yield* Effect.all( + [ + withShared(resolveBuddyThread(), folder, buddy), + withShared(resolveBuddyThread(), folder, buddy), + ], + { concurrency: 2 }, + ); + assert.deepStrictEqual(second, first); + assert.strictEqual(first.projectId, "project:buddy"); + const shell = yield* orchestrator.getThreadShell(first.threadId); + assert.deepStrictEqual(shell?.modelSelection, recommended); + assert.notStrictEqual(shell?.providerInstanceId, BUDDY); + const snapshot = yield* orchestrator.getShellSnapshot({ + projectId: ProjectId.make("project:buddy"), + }); + assert.lengthOf(snapshot.threads, 1); + }).pipe( + Effect.provide(Layer.merge(layerBuddyServer, ServerSettings.layerTest())), + Effect.scoped, + Effect.provideService(HostProcess.Environment, { HOME: home }), + ); + }); + + it.live("adopts the thread the project already has, whatever its provider", () => { + const { home, folder, buddy } = makeShared(); + return Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + yield* addProject(ProjectId.make("project:buddy"), buddy); + yield* orchestrator.dispatch({ + type: "thread.create", + createdBy: "user", + creationSource: "web", + commandId: CommandId.make("test:pilot-thread"), + threadId: ThreadId.make("pilot-thread"), + projectId: ProjectId.make("project:buddy"), + title: "Buddy", + modelSelection: { + instanceId: ProviderInstanceId.make("claudeAgent"), + model: "claude-model", + }, + runtimeMode: "full-access", + interactionMode: "default", + branch: null, + worktreePath: null, + }); + assert.deepStrictEqual(yield* withShared(resolveBuddyThread(), folder, buddy), { + threadId: ThreadId.make("pilot-thread"), + projectId: ProjectId.make("project:buddy"), + }); + }).pipe( + Effect.provide(Layer.merge(layerBuddyServer, ServerSettings.layerTest())), + Effect.scoped, + Effect.provideService(HostProcess.Environment, { HOME: home }), + ); + }); + + it.live( + "answers no-project before the startup made Buddy's project, and not-buddy without one", + () => { + const { home, folder, buddy } = makeShared(); + return Effect.gen(function* () { + const reason = (exit: Exit.Exit) => + Exit.isFailure(exit) ? JSON.stringify(exit.cause) : "succeeded"; + assert.include( + reason(yield* Effect.exit(withShared(resolveBuddyThread(), folder, buddy))), + "no-project", + ); + assert.include(reason(yield* Effect.exit(resolveBuddyThread())), "not-buddy"); + }).pipe( + Effect.provide(Layer.merge(layerBuddyServer, ServerSettings.layerTest())), + Effect.scoped, + Effect.provideService(HostProcess.Environment, { HOME: home }), + ); + }, + ); + }); }); diff --git a/apps/server/src/lazurio/buddySurfaceThread.ts b/apps/server/src/lazurio/buddySurfaceThread.ts index d978867802cc9..0c267fcfd48d6 100644 --- a/apps/server/src/lazurio/buddySurfaceThread.ts +++ b/apps/server/src/lazurio/buddySurfaceThread.ts @@ -9,11 +9,16 @@ import * as HostProcess from "@t3tools/shared/HostProcess"; import * as Context from "effect/Context"; import * as DateTime from "effect/DateTime"; import * as Effect from "effect/Effect"; +import * as Option from "effect/Option"; import * as Path from "effect/Path"; import * as Schema from "effect/Schema"; +import { resolveProjectSettings } from "@t3tools/shared/projectSettings"; + +import * as ServerConfig from "../config.ts"; import { OrchestratorV2 } from "../orchestration-v2/Orchestrator.ts"; import { ProjectStoreV2 } from "../orchestration-v2/ProjectStore.ts"; +import { ServerSettingsService } from "../serverSettings.ts"; import { BUDDY_PROVIDER_INSTANCE_ID, buddyProjectFolder, @@ -96,13 +101,123 @@ const conflict = () => detail: `A thread with Buddy's id "${BUDDY_THREAD_ID}" is not in Buddy's project on the instance "${BUDDY_PROVIDER_INSTANCE_ID}".`, }); +/** + * Buddy GEN4 (plan LZD-0033, R3): on the shared Chat server Buddy's project is the one over the + * declared Buddy folder, and Buddy's thread is its oldest root thread. Archiving one is + * refused and the startup brings archived ones back, so this is the conversation the person had. + */ +const sharedBuddyProject = Effect.fn("LazurioBuddySurface.sharedBuddyProject")(function* ( + buddyFolder: string, +) { + const projects = yield* (yield* ProjectStoreV2).list().pipe(Effect.mapError(unavailable)); + const project = projects.find((candidate) => candidate.workspaceRoot === buddyFolder); + if (project === undefined) + return yield* new BuddyThreadUnavailable({ + reason: "no-project", + detail: `Buddy's project ${buddyFolder} is not in this T3 Code yet.`, + }); + return project; +}); + +/** Buddy's thread on the shared server: the oldest root thread of Buddy's project, if any. */ +export const findSharedBuddyThread = Effect.fn("LazurioBuddySurface.findSharedThread")(function* ( + buddyFolder: string, +) { + const project = yield* sharedBuddyProject(buddyFolder); + const { threads } = yield* (yield* OrchestratorV2) + .getShellSnapshot({ projectId: project.projectId }) + .pipe(Effect.mapError(unavailable)); + const roots = threads.filter( + (thread) => + thread.projectId === project.projectId && + thread.lineage.parentThreadId === null && + thread.delegatedFrom === undefined, + ); + const oldest = roots.toSorted( + (left, right) => + DateTime.toEpochMillis(left.createdAt) - DateTime.toEpochMillis(right.createdAt), + )[0]; + return { project, thread: oldest ?? null }; +}); + +/** + * Buddy's thread on the shared server, made on the project's default model the first time anyone + * asks. Its id and command derive from the project, so two first visits make one thread. + */ +const resolveSharedBuddyThread = Effect.fn("LazurioBuddySurface.resolveSharedThread")(function* ( + buddyFolder: string, +) { + const { project, thread } = yield* findSharedBuddyThread(buddyFolder); + if (thread !== null) + return { threadId: thread.id, projectId: project.projectId } satisfies BuddyThread; + const settingsService = yield* Effect.serviceOption(ServerSettingsService); + if (Option.isNone(settingsService)) + return yield* new BuddyThreadUnavailable({ + reason: "unavailable", + detail: "This T3 Code cannot read its settings for Buddy's first thread.", + }); + const settings = yield* settingsService.value.getSettings.pipe(Effect.mapError(unavailable)); + // Buddy's project's own model, else the Environment's default, else the Lazurio project's, where + // a hosted Environment keeps the Platform's recommended model (modelRecommendation.ts). + const folder = (yield* ServerConfig.ServerConfig).lazurioFolder; + const folderProject = (yield* (yield* ProjectStoreV2) + .list() + .pipe(Effect.mapError(unavailable))).find((candidate) => candidate.workspaceRoot === folder); + const modelSelection = + resolveProjectSettings(settings, project.projectId).settings.defaultModelSelection ?? + (folderProject === undefined + ? null + : resolveProjectSettings(settings, folderProject.projectId).settings.defaultModelSelection); + if (modelSelection === null) + return yield* new BuddyThreadUnavailable({ + reason: "unavailable", + detail: "This Environment has no default model for Buddy's first thread.", + }); + const threadId = ThreadId.make(`lazurio-buddy:${project.projectId}`); + const orchestrator = yield* OrchestratorV2; + yield* orchestrator + .dispatch({ + type: "thread.create", + createdBy: "user", + creationSource: "server", + commandId: CommandId.make(`lazurio:buddy-thread:create:${project.projectId}`), + threadId, + projectId: project.projectId, + title: "Buddy", + modelSelection, + // Buddy works with the Osobní Prostředí's full rights (root decision 0210). + runtimeMode: "full-access", + interactionMode: "default", + branch: null, + worktreePath: null, + }) + .pipe(Effect.mapError(unavailable)); + const created = yield* orchestrator.getThreadShell(threadId).pipe(Effect.mapError(unavailable)); + if (created === null) + return yield* new BuddyThreadUnavailable({ + reason: "unavailable", + detail: "Buddy's thread was deleted.", + }); + return { threadId, projectId: project.projectId } satisfies BuddyThread; +}); + +/** The Buddy folder of a shared server that declares one (GEN4), or undefined. */ +export const sharedBuddyFolder = Effect.map(ServerConfig.ServerConfig, (config) => + typeof config.lazurioFolder === "string" && typeof config.lazurioBuddyFolder === "string" + ? config.lazurioBuddyFolder + : undefined, +); + /** Buddy's thread, made in Buddy's project the first time anyone asks. */ export const resolveBuddyThread = Effect.fn("LazurioBuddySurface.resolveThread")(function* () { - if (!isBuddySurfaceEnvironment(yield* HostProcess.Environment)) + if (!isBuddySurfaceEnvironment(yield* HostProcess.Environment)) { + const buddyFolder = yield* sharedBuddyFolder; + if (buddyFolder !== undefined) return yield* resolveSharedBuddyThread(buddyFolder); return yield* new BuddyThreadUnavailable({ reason: "not-buddy", detail: "This T3 Code is not Buddy's.", }); + } const orchestrator = yield* OrchestratorV2; const project = yield* buddyProject(); const existing = yield* orchestrator diff --git a/apps/server/src/lazurio/buddySurfaceThreadRoute.ts b/apps/server/src/lazurio/buddySurfaceThreadRoute.ts index def40e9201ece..adc74a7815d5e 100644 --- a/apps/server/src/lazurio/buddySurfaceThreadRoute.ts +++ b/apps/server/src/lazurio/buddySurfaceThreadRoute.ts @@ -6,12 +6,14 @@ */ import { AuthOrchestrationOperateScope, AuthOrchestrationReadScope } from "@t3tools/contracts"; import * as Effect from "effect/Effect"; +import * as Option from "effect/Option"; import * as Path from "effect/Path"; import { HttpRouter, HttpServerResponse } from "effect/http"; import * as ServerConfig from "../config.ts"; import { OrchestratorV2 } from "../orchestration-v2/Orchestrator.ts"; import { ProjectStoreV2 } from "../orchestration-v2/ProjectStore.ts"; +import { ServerSettingsService } from "../serverSettings.ts"; import { BUDDY_THREAD_ROUTE, resolveBuddyThread } from "./buddySurfaceThread.ts"; import { authenticateOverlayRoute } from "./routeAuth.ts"; @@ -29,6 +31,8 @@ export const layer = HttpRouter.use((router) => const projects = yield* ProjectStoreV2; const path = yield* Path.Path; const config = yield* ServerConfig.ServerConfig; + // Only the shared server's first Buddy thread reads it; tests build this layer without one. + const settings = yield* Effect.serviceOption(ServerSettingsService); yield* router.add( "POST", BUDDY_THREAD_ROUTE, @@ -39,6 +43,9 @@ export const layer = HttpRouter.use((router) => Effect.provideService(ProjectStoreV2, projects), Effect.provideService(Path.Path, path), Effect.provideService(ServerConfig.ServerConfig, config), + Option.isSome(settings) + ? Effect.provideService(ServerSettingsService, settings.value) + : (effect) => effect, Effect.map((thread) => HttpServerResponse.jsonUnsafe(thread)), Effect.catchTags({ BuddyThreadUnavailable: (error) => diff --git a/apps/server/src/lazurio/managedFolder.ts b/apps/server/src/lazurio/managedFolder.ts index 72e59b0db0fa8..9882624756a9f 100644 --- a/apps/server/src/lazurio/managedFolder.ts +++ b/apps/server/src/lazurio/managedFolder.ts @@ -13,6 +13,8 @@ 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 repositoryAtBuddyFolder = + "Buddy's folder holds Buddy's instructions and notes, so it does not become a repository."; const repositoryAtFolder = "The Lazurio Folder holds separate repositories, so it cannot become a repository itself."; @@ -49,7 +51,13 @@ export const makeFolderGuard = Effect.gen(function* () { folder === undefined ? Effect.succeed(null) : canonical(cwd).pipe( - Effect.map((path) => ((path ?? cwd) === folder ? repositoryAtFolder : null)), + Effect.map((path) => + (path ?? cwd) === folder + ? repositoryAtFolder + : buddyFolder !== undefined && (path ?? cwd) === buddyFolder + ? repositoryAtBuddyFolder + : null, + ), ), /** Whether `path` is the Folder itself; never without a managed Folder. */ isFolder: (path: string): Effect.Effect => @@ -68,11 +76,17 @@ export const makeFolderGuard = Effect.gen(function* () { export const managedFolderClientConfig = (config: { readonly lazurioFolder?: string; readonly lazurioBuddyFolder?: string; + readonly lazurioBuddyOrigin?: string; readonly lazurioToolsUrl?: string; }) => ({ ...(config.lazurioFolder === undefined ? {} : { lazurioFolder: config.lazurioFolder }), ...(config.lazurioFolder === undefined || config.lazurioBuddyFolder === undefined ? {} : { lazurioBuddyFolder: config.lazurioBuddyFolder }), + ...(config.lazurioFolder === undefined || + config.lazurioBuddyFolder === undefined || + config.lazurioBuddyOrigin === undefined + ? {} + : { lazurioBuddyOrigin: config.lazurioBuddyOrigin }), ...(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 0551b3c25f7dd..5343b931bb1a1 100644 --- a/apps/server/src/lazurio/managedFolderConfig.test.ts +++ b/apps/server/src/lazurio/managedFolderConfig.test.ts @@ -110,6 +110,48 @@ it.effect("declares the Buddy folder beside the Folder by its canonical path", ( }), ); +it.effect("declares Buddy's window origin only beside a Buddy folder, as a bare HTTPS origin", () => + Effect.gen(function* () { + const { folder, buddy } = makeFolder(); + const config = yield* resolveManagedFolderConfig.pipe( + withEnv({ + T3CODE_LAZURIO_FOLDER: folder, + T3CODE_LAZURIO_BUDDY_FOLDER: buddy, + T3CODE_LAZURIO_BUDDY_ORIGIN: "https://buddy.example.test", + }), + ); + assert.strictEqual(config.lazurioBuddyOrigin, "https://buddy.example.test"); + for (const [env, expected] of [ + [ + { + T3CODE_LAZURIO_FOLDER: folder, + T3CODE_LAZURIO_BUDDY_ORIGIN: "https://buddy.example.test", + }, + "T3CODE_LAZURIO_BUDDY_ORIGIN needs T3CODE_LAZURIO_BUDDY_FOLDER", + ], + [ + { + T3CODE_LAZURIO_FOLDER: folder, + T3CODE_LAZURIO_BUDDY_FOLDER: buddy, + T3CODE_LAZURIO_BUDDY_ORIGIN: "http://buddy.example.test", + }, + "must be a bare HTTPS origin", + ], + [ + { + T3CODE_LAZURIO_FOLDER: folder, + T3CODE_LAZURIO_BUDDY_FOLDER: buddy, + T3CODE_LAZURIO_BUDDY_ORIGIN: "https://buddy.example.test/chat", + }, + "must be a bare HTTPS origin", + ], + ] as const) { + const error = yield* resolveManagedFolderConfig.pipe(withEnv(env), Effect.flip); + assert.include(String(error), expected); + } + }), +); + it.effect("refuses a relative path, a file, an insecure or credentialed tools URL", () => Effect.gen(function* () { const { parent, folder, buddy } = makeFolder(); diff --git a/apps/server/src/lazurio/managedFolderConfig.ts b/apps/server/src/lazurio/managedFolderConfig.ts index 186a40892fef8..cf2321a44156e 100644 --- a/apps/server/src/lazurio/managedFolderConfig.ts +++ b/apps/server/src/lazurio/managedFolderConfig.ts @@ -25,6 +25,10 @@ const ManagedFolderEnv = Config.all({ Config.option, Config.map(Option.getOrUndefined), ), + buddyOrigin: Config.URL("T3CODE_LAZURIO_BUDDY_ORIGIN").pipe( + Config.option, + Config.map(Option.getOrUndefined), + ), toolsUrl: Config.URL("T3CODE_LAZURIO_TOOLS_URL").pipe( Config.option, Config.map(Option.getOrUndefined), @@ -117,6 +121,23 @@ export const resolveManagedFolderConfig = Effect.gen(function* () { env.buddyFolder === undefined ? undefined : yield* canonicalBuddyFolder(folder, env.buddyFolder); + // Buddy's window (LZD-0033 R3): its own HTTPS origin, which the gateway routes to this server. + if (env.buddyOrigin !== undefined) { + if (env.buddyFolder === undefined) + return yield* invalid("T3CODE_LAZURIO_BUDDY_ORIGIN needs T3CODE_LAZURIO_BUDDY_FOLDER."); + const url = env.buddyOrigin; + // HTTPS, or plain HTTP on a loopback host, where a developer runs both origins. + const loopback = ["localhost", "127.0.0.1", "[::1]"].includes(url.hostname); + if ( + (url.protocol !== "https:" && !(url.protocol === "http:" && loopback)) || + url.username || + url.password || + url.origin !== url.href.replace(/\/$/, "") + ) + return yield* invalid( + "T3CODE_LAZURIO_BUDDY_ORIGIN must be a bare HTTPS origin without credentials.", + ); + } if ( env.toolsUrl !== undefined && (env.toolsUrl.protocol !== "https:" || env.toolsUrl.username || env.toolsUrl.password) @@ -127,6 +148,7 @@ export const resolveManagedFolderConfig = Effect.gen(function* () { ? {} : { cwd: folder, lazurioFolder: folder, autoBootstrapProjectFromCwd: false }), ...(buddyFolder === undefined ? {} : { lazurioBuddyFolder: buddyFolder }), + ...(env.buddyOrigin === undefined ? {} : { lazurioBuddyOrigin: env.buddyOrigin.origin }), ...(env.toolsUrl === undefined ? {} : { lazurioToolsUrl: env.toolsUrl.toString() }), }; }); diff --git a/apps/server/src/lazurio/managedFolderVcs.test.ts b/apps/server/src/lazurio/managedFolderVcs.test.ts index f913edda919cf..710a7c037d977 100644 --- a/apps/server/src/lazurio/managedFolderVcs.test.ts +++ b/apps/server/src/lazurio/managedFolderVcs.test.ts @@ -9,7 +9,7 @@ import * as VcsProvisioningService from "../vcs/VcsProvisioningService.ts"; import { layerManagedConfig, makeFolderDirectories } from "./managedFolder.testkit.ts"; it.effect("never makes a managed Environment's Lazurio Folder a repository", () => { - const { folder, inside } = makeFolderDirectories(); + const { folder, inside, buddy } = makeFolderDirectories(); const calls: string[] = []; // Provisioning asks the driver only to make the repository. const driver = { @@ -24,6 +24,9 @@ it.effect("never makes a managed Environment's Lazurio Folder a repository", () refused.detail, "The Lazurio Folder holds separate repositories, so it cannot become a repository itself.", ); + // Buddy's folder beside it does not become one either (LZD-0033 R3). + const buddyRefused = yield* provisioning.initRepository({ cwd: buddy }).pipe(Effect.flip); + if (buddyRefused._tag !== "VcsUnsupportedOperationError") return assert.fail(buddyRefused._tag); yield* provisioning.initRepository({ cwd: inside }); assert.deepStrictEqual(calls, [inside]); }).pipe( @@ -32,7 +35,7 @@ it.effect("never makes a managed Environment's Lazurio Folder a repository", () Layer.provide( Layer.mock(VcsDriverRegistry.VcsDriverRegistry)({ get: () => Effect.succeed(driver) }), ), - Layer.provide(layerManagedConfig(folder)), + Layer.provide(layerManagedConfig(folder, buddy)), Layer.provide(NodeServices.layer), ), ), diff --git a/apps/web/index.html b/apps/web/index.html index 9b1dbc9f0981d..a451f722be3aa 100644 --- a/apps/web/index.html +++ b/apps/web/index.html @@ -748,7 +748,8 @@ } /* The right panel (RightPanelSheet.tsx, the one other sheet) takes the whole screen: no sliver of the conversation beside it. Its own toggle closes it, back to the conversation. */ - :root:has(lazurio-rail:defined) [data-slot="sheet-popup"]:not([data-mobile]) { + :root:has(lazurio-rail:defined) [data-slot="sheet-popup"]:not([data-mobile]), + :root:has([data-lazurio-buddy-surface]) [data-slot="sheet-popup"]:not([data-mobile]) { width: 100vw; min-width: 0; max-width: none; diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx index e5885cba3ff96..bcad4c43cee11 100644 --- a/apps/web/src/components/ChatView.tsx +++ b/apps/web/src/components/ChatView.tsx @@ -191,7 +191,7 @@ import { useBuddyChatShortcuts, useBuddyPage, useBuddyQueuedRunCount, - useBuddySurfaceMode, + useBuddyHermesControls, } from "../lazurio/BuddySurface"; import { BuddyPageChip } from "../lazurio/BuddySurfacePageChip"; import { @@ -599,9 +599,10 @@ export default function ChatView(props: ChatViewProps) { } return ids; })(); - // Lazurio overlay (plan DEV-6676): in Buddy's one conversation a follow-up steers by default, - // and queueing is the explicit alternative. - const buddySurface = useBuddySurfaceMode(environmentId) === true; + // Lazurio overlay (plan DEV-6676): in Hermes's one conversation (GEN3) a follow-up steers by + // default and the chat is only the conversation; Buddy's window on the shared server is a whole + // T3 thread (GEN4). + const buddySurface = useBuddyHermesControls(environmentId); // The page Buddy is asked from travels with the person's next message (buddySurfacePage.ts). const buddyPage = useBuddyPage(environmentId); const environmentSettings = useEnvironmentSettings(environmentId); diff --git a/apps/web/src/components/GitActionsControl.tsx b/apps/web/src/components/GitActionsControl.tsx index ea075af1d0837..44b6a3c14e40c 100644 --- a/apps/web/src/components/GitActionsControl.tsx +++ b/apps/web/src/components/GitActionsControl.tsx @@ -1550,7 +1550,12 @@ export default function GitActionsControl({ ); - if (!gitCwd || serverConfig?.lazurioFolder === gitCwd) return null; + if ( + !gitCwd || + serverConfig?.lazurioFolder === gitCwd || + serverConfig?.lazurioBuddyFolder === gitCwd + ) + return null; return ( <> diff --git a/apps/web/src/components/chat/ComposerControlsBar.tsx b/apps/web/src/components/chat/ComposerControlsBar.tsx index f133fbf8b623c..4d375247b93df 100644 --- a/apps/web/src/components/chat/ComposerControlsBar.tsx +++ b/apps/web/src/components/chat/ComposerControlsBar.tsx @@ -30,7 +30,7 @@ import { } from "./ComposerModelEffort"; import type { useComposerProviderModel } from "./useComposerProviderModel"; import { resolveComposerControlsOwnership } from "./composerControlsOwnership"; -import { BuddyComposerControls, useBuddySurfaceMode } from "../../lazurio/BuddySurface"; +import { BuddyComposerControls, useBuddyHermesControls } from "../../lazurio/BuddySurface"; /** * The composer footer controls: the model picker (which also holds effort, speed and @@ -148,10 +148,10 @@ export function ComposerControlsBar(props: { const controlSize = composerControlsCollapsed ? "xs" : "sm"; const applyThreadModelPick = useApplyThreadModelPick(); const applyRouteThreadModelPick = useStableCallback(() => applyThreadModelPick(routeThreadRef)); - // Lazurio overlay (plan DEV-6676): Buddy's chat offers no model, effort, access or mode, only - // Hermes's Normal / Fast switch (BuddySurface.tsx). It returns after the last hook. - const buddySurface = useBuddySurfaceMode(environmentId) === true; - if (buddySurface) return ; + // Lazurio overlay (plan DEV-6676): Hermes's chat (GEN3) offers no model, effort, access or mode, + // only Normal / Fast (BuddySurface.tsx); Buddy's window on the shared server keeps T3's picker. + const buddyHermes = useBuddyHermesControls(environmentId); + if (buddyHermes) return ; const traitsInput = resolveComposerTraitsInput({ provider: selectedProvider, instanceId: selectedInstanceId, diff --git a/apps/web/src/components/chat/MessagesTimeline.tsx b/apps/web/src/components/chat/MessagesTimeline.tsx index 693d668b7dd59..74e8a13c05ad0 100644 --- a/apps/web/src/components/chat/MessagesTimeline.tsx +++ b/apps/web/src/components/chat/MessagesTimeline.tsx @@ -26,6 +26,7 @@ import { buddySurfaceRows, useBuddyDayJump, useBuddyDayLines, + useBuddyHermesControls, useBuddySurfaceMode, } from "../../lazurio/BuddySurface"; import { buddyAnnouncementLevel } from "../../lazurio/buddySurfaceTimeline"; @@ -645,7 +646,9 @@ const ConversationTimeline = memo(function ConversationTimeline({ } } - const buddySurface = useBuddySurfaceMode(activeThreadEnvironmentId) === true; + // Hermes's quiet conversation (GEN3); Buddy's days and their jump in either Buddy surface. + const buddySurface = useBuddyHermesControls(activeThreadEnvironmentId); + const buddyDays = useBuddySurfaceMode(activeThreadEnvironmentId) === true; // Lazurio overlay (plan DEV-6676): Buddy's conversation filters its own rows // (buddySurfaceTimeline.ts), so "zen" would hide Buddy's messages between turns there. const preferredToolCallVisibility = useClientSettings((settings) => @@ -785,7 +788,7 @@ const ConversationTimeline = memo(function ConversationTimeline({ buddySurface, (isWorking || buddyBackgroundWork) && !awaitingUser, ); - const buddyDayLines = useBuddyDayLines(rows, buddySurface); + const buddyDayLines = useBuddyDayLines(rows, buddyDays); const matchedApprovalRequestIds = new Set(); for (const row of pendingApprovalRequestIds.size > 0 ? rows : []) { const entries = @@ -825,7 +828,7 @@ const ConversationTimeline = memo(function ConversationTimeline({ const viewportRef = useRef(null); const navigateTimeline = () => viewportRef.current?.navigate({ releasesFollow: true }); useBuddyDayJump({ - buddy: buddySurface, + buddy: buddyDays, rows, listRef, onManualNavigation: navigateTimeline, diff --git a/apps/web/src/lazurio/BuddySurface.tsx b/apps/web/src/lazurio/BuddySurface.tsx index 7934e0e6e4b51..8140d723ca573 100644 --- a/apps/web/src/lazurio/BuddySurface.tsx +++ b/apps/web/src/lazurio/BuddySurface.tsx @@ -19,7 +19,13 @@ import { useSyncExternalStore, } from "react"; +import { scopeThreadRef } from "@t3tools/client-runtime/environment"; +import type { EnvironmentId, ThreadId } from "@t3tools/contracts"; import { useComposerDraftStore } from "~/composerDraftStore"; +import { useThreadShell } from "~/state/entities"; +import { useEnvironmentShellStatus } from "~/state/shell"; +import { useEnvironmentThread } from "~/state/threads"; +import { isThreadRouteSnapshotAuthoritative, resolveThreadRouteRenderState } from "~/threadRoutes"; import type { ComposerControlsBar } from "~/components/chat/ComposerControlsBar"; import type { MessagesTimelineRow } from "~/components/chat/MessagesTimeline.logic"; import { ThreadDetailsPanel } from "~/components/chat/ThreadDetailsPanel"; @@ -42,18 +48,27 @@ import { buddySpeedSelection, type ChatShortcutsInput, isBuddySpeed, + isBuddyWindowOrigin, + leadsToBuddysThread, personsQueuedRuns, type QueueMessage, withoutUnusedShortcuts, } from "./buddySurfaceControls"; import { isPlainPrimaryClick } from "./environmentBrowser"; import { pageRecordOf } from "./buddySurfacePage"; +import { useLinkedUnlistedProjectIds } from "./unlistedRows"; import { BUDDY_WORKING_ROW, buddyConversationRows, buddyFailureOf } from "./buddySurfaceTimeline"; import { prefersCzech } from "./threadTabs"; import { useBuddyFrame } from "./useBuddyFrame"; +type BuddyConfig = { readonly lazurioBuddy?: true; readonly lazurioBuddyOrigin?: string } | null; + +/** Buddy's surface: Buddy's own T3 Code (GEN3), or Buddy's window on the shared server (GEN4). */ +const isBuddySurfaceConfig = (config: BuddyConfig) => + config?.lazurioBuddy === true || isBuddyWindowOrigin(config); + /** - * Buddy's T3 Code; null until the primary server's config is known, false without one. With + * Buddy's surface; null until the primary server's config is known, false without one. With * `environmentId`, only for that Environment: another Environment's thread is never Buddy's. */ export function useBuddySurfaceMode(environmentId?: string): boolean | null { @@ -61,12 +76,21 @@ export function useBuddySurfaceMode(environmentId?: string): boolean | null { const config = useAtomValue(primaryServerConfigAtom); if (primaryEnvironmentId === null) return false; if (environmentId !== undefined && environmentId !== primaryEnvironmentId) return false; - return config === null ? null : config.lazurioBuddy === true; + return config === null ? null : isBuddySurfaceConfig(config); +} + +/** + * Hermes's chat (GEN3 only): Normal / Fast instead of T3's model, effort and mode. Buddy's window on + * the shared server keeps T3's whole picker, as a Chat thread has it (GEN4). + */ +export function useBuddyHermesControls(environmentId?: string): boolean { + const config = useAtomValue(primaryServerConfigAtom); + return useBuddySurfaceMode(environmentId) === true && config?.lazurioBuddy === true; } -/** Buddy's T3 Code, read outside React when a command runs: false until the config is known. */ +/** Buddy's surface, read outside React when a command runs: false until the config is known. */ export const isBuddySurfaceNow = (): boolean => - appAtomRegistry.get(primaryServerConfigAtom)?.lazurioBuddy === true; + isBuddySurfaceConfig(appAtomRegistry.get(primaryServerConfigAtom)); const BUDDY_THREAD_ROUTE = "/api/lazurio/buddy/thread"; const BUDDY_DAYS_ROUTE = "/api/lazurio/buddy/days"; @@ -84,9 +108,7 @@ interface BuddyDay { * surface has none, since Buddy's thread is a conversation, not work in a checkout. */ export function BuddyThreadDetailsPanel(props: ComponentProps) { - return useBuddySurfaceMode(props.environmentId) === true ? null : ( - - ); + return useBuddyHermesControls(props.environmentId) ? null : ; } /** The surface's language: the host page's when framed, else the browser's. */ @@ -321,7 +343,7 @@ export function BuddyThreadErrorBanner({ environmentId, ...props }: ComponentProps & { readonly environmentId: string }) { - const buddy = useBuddySurfaceMode(environmentId) === true; + const buddy = useBuddyHermesControls(environmentId); const text = useCzech(buddy) ? TEXT.cs : TEXT.en; return buddy && props.error !== null ? ( @@ -433,7 +455,10 @@ export const buddyRightPanelState = (buddy: boolean, state: RightPanelState): Ri /** The chat's shortcuts, without those Buddy's surface has no use for there. */ export function useBuddyChatShortcuts(buddy: boolean, input: ChatShortcutsInput) { - useChatShortcuts(buddy ? withoutUnusedShortcuts(input) : input); + // Only Buddy's window on the shared server (GEN4) has a model and effort choice. + const surface = useBuddySurfaceMode() === true; + const hermes = useBuddyHermesControls(); + useChatShortcuts(buddy ? withoutUnusedShortcuts(input, surface && !hermes) : input); } /** @@ -446,7 +471,7 @@ export function useBuddyQueuedRuns, messages: ReadonlyArray | undefined, ): ReadonlyArray { - return useBuddySurfaceMode(environmentId) === true ? personsQueuedRuns(queued, messages) : queued; + return useBuddyHermesControls(environmentId) ? personsQueuedRuns(queued, messages) : queued; } /** @@ -458,7 +483,7 @@ export function useBuddyQueuedRunCount( runs: ReadonlyArray<{ readonly userMessageId: string }> | null, messages: ReadonlyArray | undefined, ): number { - const buddy = useBuddySurfaceMode(environmentId) === true; + const buddy = useBuddyHermesControls(environmentId); if (runs === null) return 0; if (!buddy) return runs.length; return personsQueuedRuns( @@ -672,12 +697,54 @@ export function useLeadsToBuddysThread( threadRef: { readonly environmentId: string; readonly threadId: string } | null, ): boolean { const buddy = useBuddySurfaceMode(threadRef?.environmentId) === true; + const hermes = useBuddyHermesControls(threadRef?.environmentId); const known = useSyncExternalStore(subscribeBuddyThread, () => buddyThreadId, noTarget); - return threadRef !== null && buddy && threadRef.threadId !== known; + const shell = useThreadShell( + threadRef === null + ? null + : scopeThreadRef(threadRef.environmentId as EnvironmentId, threadRef.threadId as ThreadId), + ); + const environmentId = (threadRef?.environmentId ?? null) as EnvironmentId | null; + // Buddy's project from the server's Buddy folder, known on a fresh load before `/` ever ran. + const buddyProjectIds = useLinkedUnlistedProjectIds(environmentId); + // Whether the server confirmed the thread missing, as ThreadRouteView decides it. + const shellStatus = useEnvironmentShellStatus(environmentId); + const asked = buddy && !hermes && shell === null && threadRef !== null; + const detail = useEnvironmentThread( + asked ? environmentId : null, + asked ? (threadRef.threadId as ThreadId) : null, + ); + const draftThread = useComposerDraftStore((store) => + asked + ? store.getDraftThreadByRef( + scopeThreadRef(threadRef.environmentId as EnvironmentId, threadRef.threadId as ThreadId), + ) + : null, + ); + if (threadRef === null || !buddy) return false; + const missing = + !hermes && + resolveThreadRouteRenderState({ + bootstrapComplete: isThreadRouteSnapshotAuthoritative(shellStatus), + serverThreadExists: shell !== null, + serverThreadDeleted: shell?.deletedAt != null, + unlistedThreadDetail: detail, + draftThreadExists: draftThread !== null, + }) === "missing"; + return leadsToBuddysThread({ + threadId: threadRef.threadId, + buddyThreadId: known, + hermes, + projectId: shell?.projectId, + missing, + buddyProjectIds, + }); } /** Asks the server for Buddy's thread: its id, or why there is none. */ -async function openBuddyThread(): Promise { +async function openBuddyThread(): Promise< + { readonly threadId: string; readonly projectId: string } | "not-ready" | "failed" +> { const response = await fetch(BUDDY_THREAD_ROUTE, { method: "POST", credentials: "same-origin", @@ -686,9 +753,11 @@ async function openBuddyThread(): Promise { }).catch(() => null); const body = (await response?.json().catch(() => null)) as { threadId?: string; + projectId?: string; error?: string; } | null; - if (response?.ok && typeof body?.threadId === "string") return body.threadId; + if (response?.ok && typeof body?.threadId === "string") + return { threadId: body.threadId, projectId: body.projectId ?? "" }; return body?.error === "no-project" ? "not-ready" : "failed"; } @@ -709,11 +778,11 @@ export function BuddySurfaceIndex() { setFailure({ attempt, outcome }); return; } - buddyThreadId = outcome; + buddyThreadId = outcome.threadId; for (const listener of buddyThreadListeners) listener(); void navigate({ to: "/$environmentId/$threadId", - params: { environmentId, threadId: outcome }, + params: { environmentId, threadId: outcome.threadId }, replace: true, }); }); diff --git a/apps/web/src/lazurio/buddySurfaceControls.test.ts b/apps/web/src/lazurio/buddySurfaceControls.test.ts index 6c6e82e1d9f39..810921621b4f0 100644 --- a/apps/web/src/lazurio/buddySurfaceControls.test.ts +++ b/apps/web/src/lazurio/buddySurfaceControls.test.ts @@ -10,7 +10,10 @@ import { buddySpeedOf, buddySpeedOption, buddySpeedSelection, + isBuddyWindowOrigin, + leadsToBuddysThread, personsQueuedRuns, + withoutUnusedShortcuts, } from "./buddySurfaceControls"; const BUDDY = ProviderInstanceId.make("buddy"); @@ -98,3 +101,67 @@ describe("Buddy's queue", () => { expect(personsQueuedRuns(queued, [{ id: "person", createdBy: "user" }])).toBe(queued); }); }); + +describe("Buddy's window on the shared server", () => { + it("is the page whose origin the server names for it, and nothing else", () => { + const config = { lazurioBuddyOrigin: "https://buddy.example.test" }; + expect(isBuddyWindowOrigin(config, "https://buddy.example.test")).toBe(true); + expect(isBuddyWindowOrigin(config, "https://t3code.example.test")).toBe(false); + expect(isBuddyWindowOrigin({}, "https://buddy.example.test")).toBe(false); + expect(isBuddyWindowOrigin(null, "https://buddy.example.test")).toBe(false); + }); +}); + +describe("a thread route in Buddy's surface", () => { + const buddyProjectIds = new Set(["buddy-project"]); + const route = (over: Partial[0]>) => + leadsToBuddysThread({ + threadId: "fork", + buddyThreadId: null, + hermes: false, + projectId: "buddy-project", + missing: false, + buddyProjectIds, + ...over, + }); + + it("keeps a fork or subagent of Buddy's project open on a fresh load, before Buddy's thread is known", () => { + expect(route({})).toBe(false); + expect(route({ buddyThreadId: "root" })).toBe(false); + }); + + it("waits for the thread and Buddy's project before it leads anywhere", () => { + expect(route({ projectId: undefined })).toBe(false); + expect(route({ projectId: "other", buddyProjectIds: new Set() })).toBe(false); + }); + + it("leads a thread the server confirmed missing to Buddy's, also before any thread exists", () => { + expect(route({ projectId: undefined, missing: true })).toBe(true); + expect(route({ projectId: undefined, missing: true, buddyProjectIds: new Set() })).toBe(true); + // Still loading is not missing: the route waits. + expect(route({ projectId: undefined, missing: false, buddyProjectIds: new Set() })).toBe(false); + }); + + it("leads another project's thread to Buddy's, and every other thread of Hermes's chat", () => { + expect(route({ projectId: "other" })).toBe(true); + expect(route({ hermes: true })).toBe(true); + expect(route({ hermes: true, threadId: "buddy", buddyThreadId: "buddy" })).toBe(false); + }); +}); + +describe("the chat's shortcuts in Buddy's surface", () => { + const binding = (command: string) => ({ command, shortcut: { key: "k" } }) as never; + const input = { + keybindings: [binding("modelPicker.toggle"), binding("terminal.toggle"), binding("chat.new")], + } as unknown as Parameters[0]; + const commands = (result: ReturnType) => + result.keybindings.map((entry) => entry.command); + + it("drop the model choice only in Hermes's chat, the panels in both", () => { + expect(commands(withoutUnusedShortcuts(input))).toEqual(["chat.new"]); + expect(commands(withoutUnusedShortcuts(input, true))).toEqual([ + "modelPicker.toggle", + "chat.new", + ]); + }); +}); diff --git a/apps/web/src/lazurio/buddySurfaceControls.ts b/apps/web/src/lazurio/buddySurfaceControls.ts index 33416aa909f84..1b048df51acb1 100644 --- a/apps/web/src/lazurio/buddySurfaceControls.ts +++ b/apps/web/src/lazurio/buddySurfaceControls.ts @@ -100,6 +100,8 @@ const UNUSED_SHORTCUTS: ReadonlySet = new Set([ ...PANEL_SHORTCUTS, ...CHOICE_SHORTCUTS, ]); +/** Buddy's window on the shared server keeps T3's picker, so only the panels go (GEN4). */ +const UNUSED_PANEL_SHORTCUTS: ReadonlySet = new Set(PANEL_SHORTCUTS); const NO_KEYBINDINGS: ResolvedKeybindingsConfig = []; @@ -111,10 +113,14 @@ export type ChatShortcutsInput = Parameters[0]; * them, not even the chat's guards that hold Mod+W for a closing terminal before any command runs, * so their keys reach the browser, as on any page that has no use for them. */ -export function withoutUnusedShortcuts(input: ChatShortcutsInput): ChatShortcutsInput { +export function withoutUnusedShortcuts( + input: ChatShortcutsInput, + keepsChoices = false, +): ChatShortcutsInput { + const unused = keepsChoices ? UNUSED_PANEL_SHORTCUTS : UNUSED_SHORTCUTS; return { ...input, - keybindings: input.keybindings.filter((binding) => !UNUSED_SHORTCUTS.has(binding.command)), + keybindings: input.keybindings.filter((binding) => !unused.has(binding.command)), scriptKeybindings: NO_KEYBINDINGS, }; } @@ -139,3 +145,33 @@ export function personsQueuedRuns if (!queued.some((run) => notThePersons.has(run.messageId))) return queued; return queued.filter((run) => !notThePersons.has(run.messageId)); } + +/** + * Whether a thread route leads to Buddy's thread: in GEN4 only another project's thread, decided + * once it and Buddy's project are known, or one the server confirmed missing, also on a server + * with no thread, where Chat's redirect home does not run. + */ +export function leadsToBuddysThread(input: { + readonly threadId: string; + readonly buddyThreadId: string | null; + readonly hermes: boolean; + readonly projectId: string | undefined; + readonly missing: boolean; + readonly buddyProjectIds: ReadonlySet; +}): boolean { + if (input.threadId === input.buddyThreadId) return false; + if (input.hermes || input.missing) return true; + if (input.projectId === undefined || input.buddyProjectIds.size === 0) return false; + return !input.buddyProjectIds.has(input.projectId); +} + +/** + * Whether this page is Buddy's window on the shared server (GEN4, plan LZD-0033 R3): the page's + * origin is the one the server names for Buddy's window. On Chat's origin it is Chat. + */ +export function isBuddyWindowOrigin( + config: { readonly lazurioBuddyOrigin?: string } | null | undefined, + origin: string = globalThis.location?.origin ?? "", +): boolean { + return config?.lazurioBuddyOrigin !== undefined && config.lazurioBuddyOrigin === origin; +} diff --git a/apps/web/src/lazurio/buddySurfaceTimeline.browser.test.tsx b/apps/web/src/lazurio/buddySurfaceTimeline.browser.test.tsx index f111e5a818af1..2a89931adf866 100644 --- a/apps/web/src/lazurio/buddySurfaceTimeline.browser.test.tsx +++ b/apps/web/src/lazurio/buddySurfaceTimeline.browser.test.tsx @@ -20,6 +20,7 @@ const surface = vi.hoisted(() => ({ buddy: true })); vi.mock(import("./BuddySurface"), async (original) => ({ ...(await original()), useBuddySurfaceMode: () => surface.buddy, + useBuddyHermesControls: () => surface.buddy, })); const setup = (buddy: boolean) => { diff --git a/docs/operations/lazurio-fork-release.md b/docs/operations/lazurio-fork-release.md index be51ed0420e0f..b3e952d764224 100644 --- a/docs/operations/lazurio-fork-release.md +++ b/docs/operations/lazurio-fork-release.md @@ -1254,6 +1254,36 @@ povrchu i s odkazy, `buddySurfaceTerminal.browser.test.tsx` skutečné kreslení rozhovorem, jen s náhradou za jeho emulátor, a `buddySurfaceRightPanel.browser.test.tsx` skutečný pravý panel T3. +### Okno Buddyho na společném serveru (Buddy GEN4) + +**Plán LZD-0033, řez R3.** Pro převedeného člověka otevírá okno Buddyho jedno +vlákno projektu Buddy ve společném serveru Chatu (viz Projekt Buddyho výše), +ne druhý server. Okno má dál vlastní origin `buddy.`, který brána +Prostředí u převedeného člověka vede na `t3code.service`. Server ho zná +z `T3CODE_LAZURIO_BUDDY_ORIGIN`: holý HTTPS origin, při vývoji i loopback přes +`http`, jen spolu s `T3CODE_LAZURIO_BUDDY_FOLDER`. Klientům ho posílá jako +`lazurioBuddyOrigin`. Web je v okně Buddyho právě tehdy, když se origin +stránky rovná `lazurioBuddyOrigin`; na originu Chatu je to Chat. Cookie +relace `__Host-` patří jednomu hostu a kontrola originu porovnává host, +takže okno má vlastní relaci a autentizace se nemění. + +- **Vlákno** je nejstarší kořenové vlákno projektu Buddy, které není + smazané (archivovat ho nejde). Když žádné není, trasa + `/api/lazurio/buddy/thread` ho založí na modelu projektu Buddy, jinak na + výchozím modelu Prostředí, jinak na modelu projektu Lazurio (doporučení + Platformy). Id i příkaz jsou odvozené z projektu, takže dvě první návštěvy + založí jedno vlákno. Dny čte trasa `/api/lazurio/buddy/days` z téhož vlákna. +- **Model:** skladatel má plný výběr poskytovatele, modelu a úsilí jako + vlákno Chatu a volba drží ve vlákně. Normální / Rychlý zůstává jen Hermesovi + (GEN3, `useBuddyHermesControls`). +- **Kontext stránky:** zpráva se záznamem stránky dostane český blok + stránky u kteréhokoli poskytovatele (`projectComposerContextForProvider`). + Záznam přidává jen okno Buddyho. +- **Beze změny pro GEN3:** server s `T3CODE_LAZURIO_BUDDY=1` má dál svoje + vlákno `buddy` na instanci `buddy`, stráže a výchozí nastavení. Žádný + z jeho obalů celého serveru (výchozí nastavení, propojení, checkpointy) + na společném serveru neběží. + ### Kdo jednal: Buddy a Delegace **Rozhodnutí 0210, večerní dodatek, bod 5 (řádek 27, plán DEV-6676).** Co Buddy napíše nebo diff --git a/packages/contracts/src/server.ts b/packages/contracts/src/server.ts index 1baa76049f2e7..5bf95e1c83466 100644 --- a/packages/contracts/src/server.ts +++ b/packages/contracts/src/server.ts @@ -693,6 +693,8 @@ export const ServerConfig = Schema.Struct({ lazurioFolder: Schema.optionalKey(TrimmedNonEmptyString), /** The Buddy folder beside it, the managed Environment's one other project. */ lazurioBuddyFolder: Schema.optionalKey(TrimmedNonEmptyString), + /** The origin of Buddy's window on this server; a client there shows Buddy's thread. */ + lazurioBuddyOrigin: 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 bee5645d82453..e5c5da049e82b 100644 --- a/scripts/lazurio-release-contract.test.mjs +++ b/scripts/lazurio-release-contract.test.mjs @@ -1170,7 +1170,7 @@ NodeTest.test("the managed Lazurio Folder keeps its seams", async () => { ); NodeAssert.match( source.gitActions, - /if \(!gitCwd \|\| serverConfig\?\.lazurioFolder === gitCwd\) return null;/, + /if \(\n\s+!gitCwd \|\|\n\s+serverConfig\?\.lazurioFolder === gitCwd \|\|\n\s+serverConfig\?\.lazurioBuddyFolder === gitCwd\n\s+\)\n\s+return null;/, ); before( source.welcome, @@ -1417,7 +1417,7 @@ NodeTest.test("the Lazurio shell slot survives a rebuild on a new upstream tag", // width in a narrow window with the shell present. NodeAssert.match( narrow, - /:root:has\(lazurio-rail:defined\) \[data-slot="sheet-popup"\]:not\(\[data-mobile\]\) \{\s*width: 100vw;\s*min-width: 0;\s*max-width: none;/, + /:root:has\(lazurio-rail:defined\) \[data-slot="sheet-popup"\]:not\(\[data-mobile\]\),\n\s+:root:has\(\[data-lazurio-buddy-surface\]\) \[data-slot="sheet-popup"\]:not\(\[data-mobile\]\) \{\s*width: 100vw;\s*min-width: 0;\s*max-width: none;/, ); NodeAssert.ok( page.indexOf("@media (max-width: 767px)") > page.search(/#root \{\s*box-sizing: border-box;/), @@ -3078,8 +3078,9 @@ NodeTest.test("Buddy keeps one conversation through its seams", async () => { layout, /\{toBuddysThread \? \(\n\s+\n\s+\) : shownTarget \? \(/, ); - NodeAssert.match(chat, /const buddySurface = useBuddySurfaceMode\(environmentId\) === true;/); - NodeAssert.doesNotMatch(chat, /useBuddySurfaceMode\(\)/); + // Hermes's one conversation (GEN3); Buddy's window on the shared server is a whole thread (GEN4). + NodeAssert.match(chat, /const buddySurface = useBuddyHermesControls\(environmentId\);/); + NodeAssert.doesNotMatch(chat, /useBuddyHermesControls\(\)/); NodeAssert.match(chat, /\? \{ \.\.\.environmentSettings, followUpBehavior: "steer" as const \}/); NodeAssert.match(chat, /const supportsConversationRollback =\n\s+!buddySurface &&/); // Buddy's thread keeps its provider session: upstream's /clear (a fresh session) is never offered there. @@ -3103,13 +3104,13 @@ NodeTest.test("Buddy keeps one conversation through its seams", async () => { NodeAssert.equal(timeline.match(/\buseBuddySurfaceMode\(/g)?.length, 1); NodeAssert.match( timeline, - /const buddySurface = useBuddySurfaceMode\(activeThreadEnvironmentId\) === true;\n[^]*?\n\s+const buddyDayLines = useBuddyDayLines\(rows, buddySurface\);/, + /const buddySurface = useBuddyHermesControls\(activeThreadEnvironmentId\);\n\s+const buddyDays = useBuddySurfaceMode\(activeThreadEnvironmentId\) === true;\n[^]*?\n\s+const buddyDayLines = useBuddyDayLines\(rows, buddyDays\);/, ); NodeAssert.match(timeline, /\n\s+workGroupViewState,\n\s+buddySurface,\n\s+\};/); // Since v0.1.3 the timeline navigates itself (pingdotgg/t3code#25463): the jump takes its navigateTimeline. NodeAssert.match( timeline, - /const navigateTimeline = \(\) => viewportRef\.current\?\.navigate\(\{ releasesFollow: true \}\);\n\s+useBuddyDayJump\(\{\n\s+buddy: buddySurface,\n\s+rows,\n\s+listRef,\n\s+onManualNavigation: navigateTimeline,\n\s+history: historyControls,\n\s+\}\);/, + /const navigateTimeline = \(\) => viewportRef\.current\?\.navigate\(\{ releasesFollow: true \}\);\n\s+useBuddyDayJump\(\{\n\s+buddy: buddyDays,\n\s+rows,\n\s+listRef,\n\s+onManualNavigation: navigateTimeline,\n\s+history: historyControls,\n\s+\}\);/, ); NodeAssert.match(timeline, /buddyDays: \[\.\.\.buddyDayLines\.keys\(\)\]\.join\(\),/); // Since v0.1.2 the rows live in their own files (pingdotgg/t3code#22674, pingdotgg/t3code#22677): the shared row state knows @@ -3376,13 +3377,12 @@ NodeTest.test("Buddy's chat reads like a chat with a friend through its seams", ); NodeAssert.equal(timeline.match(/ applyThreadModelPick\(routeThreadRef\)\);\n(?:\s+\/\/[^\n]*\n)*\s+const buddySurface = useBuddySurfaceMode\(environmentId\) === true;\n\s+if \(buddySurface\) return ;\n\s+const traitsInput = resolveComposerTraitsInput\(/, + /\n\s+const applyRouteThreadModelPick = useStableCallback\(\(\) => applyThreadModelPick\(routeThreadRef\)\);\n(?:\s+\/\/[^\n]*\n)*\s+const buddyHermes = useBuddyHermesControls\(environmentId\);\n\s+if \(buddyHermes\) return ;\n\s+const traitsInput = resolveComposerTraitsInput\(/, ); NodeAssert.doesNotMatch(composer, /buddyComposer\.hasControls/); // Buddy always works with full access: the web never asks Buddy's thread for another mode.